@odoo/o-spreadsheet 16.3.22 → 16.3.25

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)},r=function(e,...t){return new n(e,t)};class n 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,r("Circular reference"))}}class u extends c{constructor(){super(a.InvalidReference,r("Invalid reference"))}}class g extends c{constructor(e){super(a.NotAvailable,e||r("Data not available"),e?l.error:l.silent)}}class p extends c{constructor(e){super(a.UnknownFunction,r('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",re="#00A04A",ne="#DC6965",ae=.4,le=["'","*","?","/","\\","[","]"],ce=/'|\*|\?|\/|\\|\[|\]/,he="|",de=r("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,r=0){this.jsDate=new Date(Date.UTC(e,t,o,i,s,r,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,r=3===i.length;let n=Number(i[0]),a=s?Number(i[1]):0,l=r?Number(i[2]):0,c=r?"hh:mm:ss":"hh:mm";if(t||o)c+=" a";else if(!s)return null;n>=12&&t?n-=12:n<12&&o&&(n+=12),a+=Math.floor(l/60),l%=60,n+=Math.floor(a/60),a%=60,n>=24&&(c="hhhh:mm:ss");return{value:n/24+a/1440+l/86400,format:c,jsDate:new be(1899,11,30,n,a,l)}}return null}(o[0]),null===t)return null;e=e.replace(o[0],"").trim()}let i;const s=e.match(xe),r=e.match(ye);if(s||r){let t;if(s?(t=s[0],i=Ae(t,"mdy")):(t=r[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,r=o?2:0,n=Number(t[i]),a=Number(t[s]),l=2===t[i].length&&n<10||2===t[s].length&&a<10,c=t[r]?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[r]):Ee,h=new be(c,n-1,a),d=e.match(/\/|-|\s/)[0];if(h.getMonth()!==n-1||h.getDate()!==a)return null;const u=h.getTime()-ve.getTime();let g=l?`mm${d}dd`:`m${d}d`;return t[r]&&(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),r=Math.round(24*(i-s/24)*60),n=Math.round(24*(i-s/24-r/24/60)*60*60);return o.setHours(s),o.setMinutes(r),o.setSeconds(n),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(),r=e.getDate(),n=new be(i,s+t,1);return o&&r===Ne(e)||r>Ne(n)?n.setDate(Ne(n)):n.setDate(r),n}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 r=i.getDate(),n=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===r&&(r=30),30===r&&31===n&&(n=30),1===a&&r===(De(c)?29:28)&&(r=30,1===l&&n===(De(h)?29:28)&&(n=30)),d=c+(30*a+r)/360,u=h+(30*l+n)/360;break;case 1:let o=365;const i=c===h;if(!i&&!(c+1===h)||!i&&a<l||!i&&a===l&&r<n){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===n)&&(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===r&&(r=30),31===n&&(n=30),d=c+(30*a+r)/360,u=h+(30*l+n)/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(),r=e.getDate(),n=t.getDate();return s>i||s===i&&n>=r?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 rt(e,t){return`[${e}](${t})`}function nt(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:Math.max(...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 e===t;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):""}const Rt=/rgba?\(|\s+|\)/gi,Tt=/^#([A-F\d]{2}){3,4}$/,At=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function Ot(e){return Mt(e.toString(16).padStart(6,"0"))}function Mt(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(Rt,"").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}`),!Tt.test(t))throw new Error(`invalid color input: ${e}`);return t}function Nt(e){try{return Mt(e),!0}catch(e){return!1}}const _t=e=>e>=0&&e<=255;function Ft(e,t,o,i=1){if(!_t(e)||!_t(t)||!_t(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 Dt(e){let{r:t,g:o,b:i}=kt(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 Lt(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 kt(e){let t,o,i,s;if(7===(e=Mt(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 Pt(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,r=0,n=0;return 0<=e.h&&e.h<60?(s=t,r=o,n=0):60<=e.h&&e.h<120?(s=o,r=t,n=0):120<=e.h&&e.h<180?(s=0,r=t,n=o):180<=e.h&&e.h<240?(s=0,r=o,n=t):240<=e.h&&e.h<300?(s=o,r=0,n=t):300<=e.h&&e.h<360&&(s=t,r=0,n=o),s=Math.round(255*(s+i)),r=Math.round(255*(r+i)),n=Math.round(255*(n+i)),{a:e.a,r:s,g:r,b:n}}function Ut(e){const t=e.r/255,o=e.g/255,i=e.b/255;let s=Math.min(t,o,i),r=Math.max(t,o,i),n=r-s,a=0,l=0,c=0;return a=0==n?0:r==t?(o-i)/n%6:r==o?(i-t)/n+2:(t-o)/n+4,a=Math.round(60*a),a<0&&(a+=360),c=(r+s)/2,l=0==n?0:n/(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 Vt(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Vt(Math.floor(e/26)-1)+Vt(e%26)}const zt={};for(const e of"ABCDEFGHIJKLMNOPQRSTUVWXYZ"){const t=e.charCodeAt(0)-64;zt[e]=t,zt[e.toLowerCase()]=t}function Bt(e){let t=-1;let o=1;for(let i=e.length-1;i>=0;i--){t+=zt[e[i]]*o,o*=26}return t}function Ht(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function $t(e){return e>="0"&&e<="9"}function Wt(e){let t;e=e.trim();for(let o=0;o<e.length;o++){const i=e[o];if(!t){if("$"===i&&0===o||Ht(i))continue;t=o}if(!$t(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=Bt(o),r=Number(i)-1;if(isNaN(r))throw new Error(`Invalid cell description: ${e}`);return{col:s,row:r}}function Gt(e,t,o={colFixed:!1,rowFixed:!1}){return(o.colFixed?"$":"")+Vt(e)+(o.rowFixed?"$":"")+String(t+1)}const qt=140,Zt=20,jt=.035;function Yt(e){return Zt+(qt-Zt)*Math.exp(-jt*(e-1))}const Xt=/(^-?\d+(\.?\d*(e\d+)?)?|^-?\.\d+)(?!\w|!)/,Kt="(\\s*(\\d+(,\\d{3,})*(\\.\\d*)?)|(\\.\\d+))(e(\\+|-)?\\d+)?(\\s*%)?",Qt="(\\s*-)?",Jt="(\\s*[\\$€])?",eo="^(("+[Qt+Jt+Kt,Qt+Kt+Jt,Jt+Qt+Kt].join(")|(")+"))$",to=new RegExp(eo,"i");function oo(e){return!!e&&to.test(e.trim())}const io=/[,\$€]+/g;function so(e){e=e.replace(io,"");let t=Number(e);return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}function ro(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 r=Math.ceil(s),n=Math.floor(s);return i[r]*(s-n)+i[n]*(r-s)}const no=20,ao=11,lo=/(\d+?)(?=(\d{3})+(?!\d)|$)/g,co=/0/g,ho={0:r("January"),1:r("February"),2:r("March"),3:r("April"),4:r("May"),5:r("June"),6:r("July"),7:r("August"),8:r("September"),9:r("October"),10:r("November"),11:r("December")},uo={0:r("Sunday"),1:r("Monday"),2:r("Tuesday"),3:r("Wednesday"),4:r("Thursday"),5:r("Friday"),6:r("Saturday")},go={};function po(e){let t=go[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 r=e.substring(t,i);Eo(r)?o.push({type:"DATE",format:r}):o.push({type:"NUMBER",format:_o(r)})}t=i}return o}(e),go[e]=t),t}function mo(e,t){switch(typeof e){case"string":return e;case"boolean":return e?"TRUE":"FALSE";case"number":t||(t=Ro(e));return function(e,t){if("DATE"===t[0].type)return xo(e,t[0].format);let o=e<0?"-":"";for(let i of t)switch(i.type){case"NUMBER":o+=fo(Math.abs(e),i.format);break;case"STRING":o+=i.format}return o}(e,po(t));case"object":return"0"}}function fo(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}=vo(e,o);let r=function(e,t,o){const i="0"===e?"":e;let s=i;const r=t.length-i.length;if(r>0){const e=(t.substring(0,r).match(co)||[]).length;s="0".repeat(e)+s}o&&(s=s.match(lo)?.join(",")||s);return s}(i,t.integerPart,t.thousandsSeparator);return void 0!==t.decimalPart&&(r+="."+function(e,t){let o=e;if(t.length-e.length>0){const i=(t.substring(e.length,t.length+1).match(co)||[]).length;o+="0".repeat(i)}return o}(s||"",t.decimalPart)),t.isPercent&&(r+="%"),r}const bo=[];function vo(e,t=no){const o=e.toString();if(o.includes("e"))return function(e,t=no){let o=bo[t];o||(o=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),bo[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),r=o.substring(i+1);if(0===t)return Number(r[0])>=5&&(s=(Number(s)+1).toString()),{integerDigits:s,decimalDigits:void 0};if(r.length>t){const{integerDigits:e,decimalDigits:o}=function(e,t){let o="0",i=e,s=e.slice(0,t);const r=t;if(Number(e[r])<5)return{integerDigits:o,decimalDigits:s};const n=s.match(Co)?.[0]||"",a=(Number(s)+1).toString(),l=s.slice(n.length),c=a.length>l.length;c&&!n?(o="1",i=void 0):i=c?n.slice(0,-1)+a:n+a;return{integerDigits:o,decimalDigits:i}}(r,t);r=o,"0"!==e&&(s=(Number(s)+Number(e)).toString())}return{integerDigits:s,decimalDigits:So(r||"")}}function So(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const Co=/^0+/;function Eo(e){if(!wo.has(e[0]))return!1;try{return xo(1,e),!0}catch(e){return!1}}const wo=new Set(["h","m","y","d"]);function xo(e,t){const o=Oe(e),i=t.indexOf("h");let s="",r="";return i>0?(s=yo(o,t.substring(0,i-1)),r=Io(o,t.substring(i))):0===i?r=Io(o,t):i<0&&(s=yo(o,t)),s+(s&&r?" ":"")+r}function yo(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 uo[e.getDay()].slice(0,3);case"dddd":return uo[e.getDay()];case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return ho[e.getMonth()].slice(0,3);case"mmmm":return ho[e.getMonth()];case"mmmmm":return ho[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 Io(e,t){let o=t.split(/:|\s/);const i=e.getHours(),s="a"===o[o.length-1];let r=i,n="";return s&&(r=0===r?12:r>12?r-12:r,n=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 r.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(":")+n}function Ro(e){let{integerDigits:t,decimalDigits:o}=vo(e);if(!o)return"0";const i=t.replace("-","").length;if(i+2>ao)return"0";const s=ao-i-1;return({decimalDigits:o}=vo(e,Math.min(s,o.length))),o?"0."+"0".repeat(o.length):"0"}function To(e){if(et(e)){return Te(e).format}if(!oo(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 Ao(e,t,o){return Do(po(e||"#,##0").map((e=>"NUMBER"===e.type?[{...e,format:{...e.format,magnitude:t,decimalPart:void 0}},{type:"STRING",format:o}]:e)).flat())}function Oo(e,t){const o=po(e).map((e=>"NUMBER"===e.type?{...e,format:Mo(e.format,t)}:e)),i=Do(o);return go[i]=o,i}function Mo(e,t){const o={...e},i=Math.sign(t),s=o.decimalPart?.length||0,r=Math.min(Math.max(0,s+i),no);return o.decimalPart="0".repeat(r),""===o.decimalPart&&delete o.decimalPart,o}const No=/,*?$/;function _o(e){if(function(e){return Boolean(e.replace(Fo,""))}(e=e.trim()))throw new Error(`Invalid number format: ${e}`);const t=e.includes("%"),o=e.match(No)?.[0]||"",i=o?1e3**o.length:1;let s=e.slice(0,e.length-(o.length||0));const r=s.includes(",");if(/\..*,/.test(s))throw new Error("A format can't contain ',' symbol in the decimal part");s=s.replace("%","").replace(",","");const n=s.match(/[\%|,]/);if(n)throw new Error(`A format can only contain a single '${n[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:r,decimalPart:l,magnitude:i}:{integerPart:a,isPercent:t,thousandsSeparator:r,magnitude:i}}const Fo=/[,#0.%]/g;function Do(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 Lo=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),ko=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),Po=new RegExp(/^\$?([A-Z]{1,3})+$/,"i"),Uo=new RegExp(/^\$?([0-9]{1,7})+$/,"i"),Vo=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),zo=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),Bo=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[Lo.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 Ho(e){return Vo.test(e)}function $o(e){return zo.test(e)}function Wo(e){return Po.test(e)}function Go(e){return Uo.test(e)}function qo(e){return ko.test(e)}function Zo(e){const t=e.split("!"),o=t.pop();return{sheetName:He(t.join("!"))||void 0,xc:o}}class jo{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 jo?e:new jo(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(r("Bad zone format"))}static getRangeParts(e,t){const o=e.split(":").map((e=>{const t=$o(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 jo({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 Yo(e,t,o){const i=o.sheetId===e?t:o.sheetId;return o.clone({sheetId:i})}function Xo(e,t,o){return o?e.getRangeFromSheetXC(t,o):void 0}function Ko(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,r=0;for(let n=0;n<s;n++)t[n]===e[r]?(r++,i+=100+i-n/200):i=0,o+=i;return r===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 Qo(e){const t=[];for(let o=0;o<e;o++){const e={cells:{}};t.push(e)}return t}class Jo{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 ei(e){const t=function(e){let t,o,i,s,r;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 n=!1,a=!1,l=!1;const c=t[0],h=t[1]&&t[1];if(Ho(c))s=r=Bt(c),o=i=0,n=!0;else if($o(c))o=i=parseInt(c,10)-1,s=r=0,a=!0;else{const e=Wt(c);s=r=e.col,o=i=e.row,l=!0}if(2===t.length)if(Ho(h))r=Bt(h),n=!0;else if($o(h))i=parseInt(h,10)-1,a=!0;else{const e=Wt(h);r=e.col,i=e.row,o=n?i:o,s=a?r:s,l=!0}if(n&&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:n?void 0:i,right:a?void 0:r};return l=l&&(a||n),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 ti(e){const t=ei(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function oi(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 ii(e){const{top:t,bottom:o,left:i,right:s}=e,n="hasHeader"in e&&e.hasHeader,a=t===o&&i===s;if(void 0===o&&void 0!==s)return 0!==t||n?`${Gt(i,t)}:${Vt(s)}`:`${Vt(i)}:${Vt(s)}`;if(void 0===s&&void 0!==o)return 0!==i||n?`${Gt(i,t)}:${o+1}`:`${t+1}:${o+1}`;if(void 0!==o&&void 0!==s)return a?Gt(i,t):`${Gt(i,t)}:${Gt(s,o)}`;throw new Error(r("Bad zone format"))}function si(e,t,o,i,s){const r="left"===t?"columns":"rows",n="before"===i?o-1:o,a=e["left"===t?"right":"bottom"];return e[t]<=n&&a&&a>n?Si(e,r,"RESIZE",s):n<e[t]?Si(e,r,"MOVE",s):{...e}}function ri(e,t,o,i,s){const r="left"===t?"columns":"rows",n="before"===i?o-1:o,a="left"===t?"right":"bottom";return e[t]<=n&&e[a]>n?Si(e,r,"RESIZE",s):n<e[t]?Si(e,r,"MOVE",s):{...e}}function ni(e,t,o){const i="left"===t?"right":"bottom";let s=e[t],r=e[i];for(let n of o.sort(((e,t)=>t-e)))e[t]>n&&(s--,r--),e[t]<n&&e[i]>=n&&r--;return{...e,[t]:s,[i]:r}}function ai(e,t,o){const i="left"===t?"right":"bottom";let s=e[t],r=e[i];const n=e[i];for(let i of o.sort(((e,t)=>t-e)))e[t]>i&&(s--,void 0!==r&&r--),void 0!==n&&void 0!==r&&e[t]<=i&&n>=i&&r--;if(!(void 0!==r&&s>r))return{...e,[t]:s,[i]:r}}function li(...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 ci(e,t){if(di(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 hi(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function di(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function ui(e,t,o){const{left:i,right:s,top:r,bottom:n}=o;return e>=i&&e<=s&&t>=r&&t<=n}function gi(e,t){return hi(li(t,e),t)}function pi(e,t){const o=e.map(ei),i=t.map(ti),s=Math.max(...o.concat(i).map((e=>e.bottom||0))),r=Math.max(...o.concat(i).map((e=>e.right||0))),n=o.map((e=>({...e,bottom:void 0===e.bottom?s+1:e.bottom,right:void 0===e.right?r+1:e.right}))),a=i.map((e=>({...e,bottom:void 0===e.bottom?s+1:e.bottom,right:void 0===e.right?r+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}`)))}(n.map(vi).flat(),a.map(vi).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=wi(t);for(const{col:e,row:t}of o)if(!ui(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=wi({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=mi(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)?li(e,t):e),o.shift());t.push(e)}return mi(t)}(c).map((e=>({...e,bottom:e.bottom===s+1?void 0:e.bottom,right:e.right===r+1?void 0:e.right}))).map(ii)}function mi(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=>gi(e,t)))||o.push(e)}return o.reverse()}function fi(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function bi(e){const{numberOfCols:t,numberOfRows:o}=fi(e);return 1===t||1===o}function vi(e){const t=[],[o,i]=[e.right,e.left].sort(((e,t)=>e-t)),[s,r]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of Ke(o,i+1))for(const o of Ke(s,r+1))t.push({col:e,row:o});return t}function Si(e,t,o,i){const s="both"===t?i[0]:"columns"===t?i:0,r="both"===t?i[1]:"rows"===t?i:0,n="hasHeader"in e&&e.hasHeader;let a;a=!function(e){return void 0===e.bottom}(e)||n?!(xi(e)&&!n)||"columns"!==t:"rows"!==t;const l={...e};return a&&"MOVE"===o&&(l.left+=s,l.top+=r),void 0!==l.right&&(l.right+=s),void 0!==l.bottom&&(l.bottom+=r),l}function Ci(e,t){let o,i;const{left:s,right:r,top:n,bottom:a}=e,{left:l,right:c,top:h,bottom:d}=t;return o=l!=s?l:c!=r?c:l,i=h!=n?h:d!=a?d:h,{col:o,row:i}}function Ei(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 wi(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function xi(e){return void 0===e.right}function yi(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function Ii(...e){return e.length<2||1===pi(e.map(ii),[]).length}class Ri 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})}}Ri.props={figure:Object};const Ti={};let Ai=0;function Oi(e,...t){const o="__sheet__"+Ai++;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 r(e,t){const i=[];for(const s of o[e]){let n=t&&t+" "+s||s;n.includes("&")&&(n=s.replace(/&/g,t||"")),e<o.length-1&&(n=r(e+1,n)),i.push(n)}return i.join(", ")}function n(){s.length&&(i.push(r(0)+" {"),i.push(...s),i.push("}"),s=[])}for(;t.length;){let e=t.shift();"}"===e?(n(),o.pop()):("{"===t[0]&&(n(),o.push(e.split(/\s*,\s*/)),t.shift()),";"===t[0]&&s.push(" "+e+";"))}return i.join("\n")}(t),Ti[e]=o}(o,String.raw(e,...t)),function(e){const t=Ti[e];t.setAttribute("component",e),document.head.appendChild(t)}(o),o}function Mi({strikethrough:e,underline:t}){return e||t?`${e?"line-through":""} ${t?"underline":""}`:"none"}function Ni(e){const t=_i(e);return e?(e.fillColor&&(t.background=e.fillColor),t):t}function _i(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 Fi(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>`${e}:${t};`)).join(" ")}const Di=1.2;Oi`
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:Math.max(...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 e===t;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):""}const Rt=/rgba?\(|\s+|\)/gi,Tt=/^#([A-F\d]{2}){3,4}$/,At=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function Ot(e){return Mt(e.toString(16).padStart(6,"0"))}function Mt(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(Rt,"").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}`),!Tt.test(t))throw new Error(`invalid color input: ${e}`);return t}function Nt(e){try{return Mt(e),!0}catch(e){return!1}}const _t=e=>e>=0&&e<=255;function Ft(e,t,o,i=1){if(!_t(e)||!_t(t)||!_t(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 Dt(e){let{r:t,g:o,b:i}=kt(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 Lt(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 kt(e){let t,o,i,s;if(7===(e=Mt(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 Pt(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 Ut(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 Vt(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Vt(Math.floor(e/26)-1)+Vt(e%26)}const zt={};for(const e of"ABCDEFGHIJKLMNOPQRSTUVWXYZ"){const t=e.charCodeAt(0)-64;zt[e]=t,zt[e.toLowerCase()]=t}function Bt(e){let t=-1;let o=1;for(let i=e.length-1;i>=0;i--){t+=zt[e[i]]*o,o*=26}return t}function Ht(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function $t(e){return e>="0"&&e<="9"}function Wt(e){let t;e=e.trim();for(let o=0;o<e.length;o++){const i=e[o];if(!t){if("$"===i&&0===o||Ht(i))continue;t=o}if(!$t(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=Bt(o),n=Number(i)-1;if(isNaN(n))throw new Error(`Invalid cell description: ${e}`);return{col:s,row:n}}function Gt(e,t,o={colFixed:!1,rowFixed:!1}){return(o.colFixed?"$":"")+Vt(e)+(o.rowFixed?"$":"")+String(t+1)}const qt=140,Zt=20,jt=.035;function Yt(e){return Zt+(qt-Zt)*Math.exp(-jt*(e-1))}const Xt=/(^-?\d+(\.?\d*(e\d+)?)?|^-?\.\d+)(?!\w|!)/,Kt="(\\s*(\\d+(,\\d{3,})*(\\.\\d*)?)|(\\.\\d+))(e(\\+|-)?\\d+)?(\\s*%)?",Qt="(\\s*-)?",Jt="(\\s*[\\$€])?",eo="^(("+[Qt+Jt+Kt,Qt+Kt+Jt,Jt+Qt+Kt].join(")|(")+"))$",to=new RegExp(eo,"i");function oo(e){return!!e&&to.test(e.trim())}const io=/[,\$€]+/g;function so(e){e=e.replace(io,"");let t=Number(e);return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}function no(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 ro=20,ao=11,lo=/(\d+?)(?=(\d{3})+(?!\d)|$)/g,co=/0/g,ho={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")},uo={0:n("Sunday"),1:n("Monday"),2:n("Tuesday"),3:n("Wednesday"),4:n("Thursday"),5:n("Friday"),6:n("Saturday")},go={};function po(e){let t=go[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);Eo(n)?o.push({type:"DATE",format:n}):o.push({type:"NUMBER",format:_o(n)})}t=i}return o}(e),go[e]=t),t}function mo(e,t){switch(typeof e){case"string":return e.includes('\\"')?e.replace(/\\"/g,'"'):e;case"boolean":return e?"TRUE":"FALSE";case"number":t||(t=Ro(e));return function(e,t){if("DATE"===t[0].type)return xo(e,t[0].format);let o=e<0?"-":"";for(let i of t)switch(i.type){case"NUMBER":o+=fo(Math.abs(e),i.format);break;case"STRING":o+=i.format}return o}(e,po(t));case"object":return"0"}}function fo(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}=vo(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(co)||[]).length;s="0".repeat(e)+s}o&&(s=s.match(lo)?.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(co)||[]).length;o+="0".repeat(i)}return o}(s||"",t.decimalPart)),t.isPercent&&(n+="%"),n}const bo=[];function vo(e,t=ro){const o=e.toString();if(o.includes("e"))return function(e,t=ro){let o=bo[t];o||(o=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),bo[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(Co)?.[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:So(n||"")}}function So(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const Co=/^0+/;function Eo(e){if(!wo.has(e[0]))return!1;try{return xo(1,e),!0}catch(e){return!1}}const wo=new Set(["h","m","y","d"]);function xo(e,t){const o=Oe(e),i=t.indexOf("h");let s="",n="";return i>0?(s=yo(o,t.substring(0,i-1)),n=Io(o,t.substring(i))):0===i?n=Io(o,t):i<0&&(s=yo(o,t)),s+(s&&n?" ":"")+n}function yo(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 uo[e.getDay()].slice(0,3);case"dddd":return uo[e.getDay()];case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return ho[e.getMonth()].slice(0,3);case"mmmm":return ho[e.getMonth()];case"mmmmm":return ho[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 Io(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 Ro(e){let{integerDigits:t,decimalDigits:o}=vo(e);if(!o)return"0";const i=t.replace("-","").length;if(i+2>ao)return"0";const s=ao-i-1;return({decimalDigits:o}=vo(e,Math.min(s,o.length))),o?"0."+"0".repeat(o.length):"0"}function To(e){if(et(e)){return Te(e).format}if(!oo(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 Ao(e,t,o){const i=po(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 Do(s)}function Oo(e,t){const o=po(e).map((e=>"NUMBER"===e.type?{...e,format:Mo(e.format,t)}:e)),i=Do(o);return go[i]=o,i}function Mo(e,t){const o={...e},i=Math.sign(t),s=o.decimalPart?.length||0,n=Math.min(Math.max(0,s+i),ro);return o.decimalPart="0".repeat(n),""===o.decimalPart&&delete o.decimalPart,o}const No=/,*?$/;function _o(e){if(function(e){return Boolean(e.replace(Fo,""))}(e=e.trim()))throw new Error(`Invalid number format: ${e}`);const t=e.includes("%"),o=e.match(No)?.[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 Fo=/[,#0.%]/g;function Do(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 Lo=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),ko=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),Po=new RegExp(/^\$?([A-Z]{1,3})+$/,"i"),Uo=new RegExp(/^\$?([0-9]{1,7})+$/,"i"),Vo=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),zo=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),Bo=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[Lo.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 Ho(e){return Vo.test(e)}function $o(e){return zo.test(e)}function Wo(e){return Po.test(e)}function Go(e){return Uo.test(e)}function qo(e){return ko.test(e)}function Zo(e){const t=e.split("!"),o=t.pop();return{sheetName:He(t.join("!"))||void 0,xc:o}}class jo{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 jo?e:new jo(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=$o(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 jo({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 Yo(e,t,o){const i=o.sheetId===e?t:o.sheetId;return o.clone({sheetId:i})}function Xo(e,t,o){return o?e.getRangeFromSheetXC(t,o):void 0}function Ko(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 Qo(e){const t=[];for(let o=0;o<e;o++){const e={cells:{}};t.push(e)}return t}class Jo{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 ei(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(Ho(c))s=n=Bt(c),o=i=0,r=!0;else if($o(c))o=i=parseInt(c,10)-1,s=n=0,a=!0;else{const e=Wt(c);s=n=e.col,o=i=e.row,l=!0}if(2===t.length)if(Ho(h))n=Bt(h),r=!0;else if($o(h))i=parseInt(h,10)-1,a=!0;else{const e=Wt(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 ti(e){const t=ei(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function oi(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 ii(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?`${Gt(i,t)}:${Vt(s)}`:`${Vt(i)}:${Vt(s)}`;if(void 0===s&&void 0!==o)return 0!==i||r?`${Gt(i,t)}:${o+1}`:`${t+1}:${o+1}`;if(void 0!==o&&void 0!==s)return a?Gt(i,t):`${Gt(i,t)}:${Gt(s,o)}`;throw new Error(n("Bad zone format"))}function si(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?Si(e,n,"RESIZE",s):r<e[t]?Si(e,n,"MOVE",s):{...e}}function ni(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?Si(e,n,"RESIZE",s):r<e[t]?Si(e,n,"MOVE",s):{...e}}function ri(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 ai(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 li(...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 ci(e,t){if(di(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 hi(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function di(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function ui(e,t,o){const{left:i,right:s,top:n,bottom:r}=o;return e>=i&&e<=s&&t>=n&&t<=r}function gi(e,t){return hi(li(t,e),t)}function pi(e,t){const o=e.map(ei),i=t.map(ti),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(vi).flat(),a.map(vi).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=wi(t);for(const{col:e,row:t}of o)if(!ui(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=wi({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=mi(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)?li(e,t):e),o.shift());t.push(e)}return mi(t)}(c).map((e=>({...e,bottom:e.bottom===s+1?void 0:e.bottom,right:e.right===n+1?void 0:e.right}))).map(ii)}function mi(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=>gi(e,t)))||o.push(e)}return o.reverse()}function fi(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function bi(e){const{numberOfCols:t,numberOfRows:o}=fi(e);return 1===t||1===o}function vi(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 Si(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?!(xi(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 Ci(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 Ei(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 wi(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function xi(e){return void 0===e.right}function yi(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function Ii(...e){return e.length<2||1===pi(e.map(ii),[]).length}class Ri 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})}}Ri.props={figure:Object};const Ti={};let Ai=0;function Oi(e,...t){const o="__sheet__"+Ai++;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),Ti[e]=o}(o,String.raw(e,...t)),function(e){const t=Ti[e];t.setAttribute("component",e),document.head.appendChild(t)}(o),o}function Mi({strikethrough:e,underline:t}){return e||t?`${e?"line-through":""} ${t?"underline":""}`:"none"}function Ni(e){const t=_i(e);return e?(e.fillColor&&(t.background=e.fillColor),t):t}function _i(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 Fi(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>`${e}:${t};`)).join(" ")}const Di=1.2;Oi`
2
2
  div.o-scorecard {
3
3
  font-family: ${j};
4
4
  user-select: none;
@@ -50,7 +50,7 @@
50
50
  }
51
51
  }
52
52
  }
53
- `;class Li 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 Dt(this.backgroundColor)>.3?"#525252":"#C8C8C8"}get figure(){return this.props.figure}get chartStyle(){return Fi({padding:`${this.chartPadding}px`,background:this.backgroundColor})}get chartContentStyle(){return Fi({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 r=(s+t)/2,n=o(r),a=0;for(;Math.abs(n-e)>i&&a<20;)n>=e?t=(s+t)/2:s=(s+t)/2,r=(s+t)/2,n=o(r),a++;return r}(e,o,(e=>t.getElementWidth(e,this.ctx,this)))/o;const s=(new Pi).getElementMaxFontSize(this.getDrawableHeight(),this)*i,r=(new ki).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:r}),baselineValueStyle:this.getTextStyle({fontSize:r,cellStyle:this.runtime.baselineStyle,color:this.runtime.baselineColor||this.secondaryFontColor}),baselineDescrStyle:this.getTextStyle({fontSize:.9*r,color:this.secondaryFontColor})}}getTextStyle(e){const t=_i(e.cellStyle);return t["font-size"]=`${e.fontSize}px`,t.display="inline-block",!t.color&&e.color&&(t.color=e.color),Fi(t)}getDrawableHeight(){const e=2*this.chartPadding;let t=this.props.figure.height-e;return t-=this.title?18*Di:0,t}getWidestElement(){const e=new ki,t=new Pi;return e.getElementWidth(.35,this.ctx,this)>t.getElementWidth(.65,this.ctx,this)?e:t}}class ki{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 r=t.measureText(s).width;return t.font=`${.9*e}px ${j}`,r+=t.measureText(o.baselineDescr).width,r}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.35*e:0)/Di}}class Pi{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)/Di}}Li.props={figure:Object};class Ui{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 Vi(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const zi=new Ui;function Bi(e,t){return{url:e=Vi(e),label:t||e,isExternal:!0,isUrlEditable:!0}}zi.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)||r("Invalid sheet")},open(e,t){const o=ht(e);t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:o})},sequence:0});const Hi={createLink:Bi,match:e=>st(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function $i(e){return zi.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((t=>t.match(e)))||Hi}function Wi(e,t){return $i(e.url).urlRepresentation(e.url,t)}function Gi(e,t){$i(e.url).open(e.url,t)}function qi(e){if("string"==typeof e){if(it(e)){const{label:t,url:o}=nt(e);return $i(o).createLink(o,t)}return st(e)?Bi(e):void 0}}const Zi=["number","string","boolean","undefined"];function ji(e,t){if(!e())throw new Error(t)}const Yi=e=>r("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function Xi(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(oo(e)||""===e)return so(e);const t=Te(e);if(t)return t.value;throw new Error(Yi(e));default:return 0}}function Ki(e){if(""===e)throw new Error(Yi(e));return Xi(e)}function Qi(e){return Math.trunc(Ki(e))}function Ji(e){ji((()=>e>=1),r("The function [[FUNCTION_NAME]] expects a number value to be greater than or equal to 1, but receives %s.",e.toString()))}function es(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}const ts=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 os(e){return"string"==typeof e?ts(e):e}const is=e=>r("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function ss(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(is(e))}return!1;case"number":return!!e;default:return!1}}function rs(e){return Oe(Xi(e))}function ns(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 as(e,t){ns(e,t,t)}function ls(e,t){ns(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(Ki(e))}))}function cs(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 r=0;r<o;r++)for(let o=0;o<e;o++)s=t(s,i[o][r])}else s=o(s,i);return s}function hs(e,t,o){return cs(e,t,t,o)}function ds(e,t,o){return cs(e,((e,o)=>"number"==typeof o?t(e,o):e),((e,o)=>t(e,Ki(o))),o)}function us(e,t,o){return cs(e,((e,o)=>null!=o?t(e,"number"==typeof o?o:"boolean"==typeof o?Xi(o):0):e),((e,o)=>t(e,Xi(o))),o)}function gs(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(is(e));return ss(e)}(e))))}function ps(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)),oo(i)?i=Xi(i):"TRUE"!==i&&"FALSE"!==i||(i=ss(i));const r={operator:o,operand:i};return"string"==typeof i&&(t&&(i+="*"),r.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)),r}function ms(e,t){const{operator:o,operand:i}=t;if(void 0===e||void 0===i)return!1;if("number"==typeof i&&"="===o)return es(e)===es(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 fs(e,t,o=!1){const i=e.length;if(i%2==1)throw new Error(r("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const s=e[0].length,n=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!==n)throw new Error(r("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=es(e[t+1]);a.push(ps(l,o))}for(let o=0;o<s;o++)for(let s=0;s<n;s++){let r=!0;for(let t=0;t<i-1;t+=2){if(r=ms(e[t][o][s],a[t/2]),!r)break}r&&t(o,s)}}function bs(e,t){return os(e[0][t])}function vs(e,t){return os(e[t][0])}function Ss(e,t,o,i,s,r){if(null==t)return-1;const n=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=r(e,h),u=typeof d;g<h&&n!==u;)h--,d=r(e,h),u=typeof d;u===n&&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 Cs(e,t,o,i,s,r=!1){if(null==t)return-1;const n=r?(e,t)=>s(e,i-t-1):s;let a,l=-1;for(let s=0;s<i;s++){const c=n(e,s);if(c===t)return r?i-s-1:s;"nextSmaller"===o?(!a&&Es(t,c)>=0||Es(t,c)>=0&&Es(c,a)>0)&&(a=c,l=s):"nextGreater"===o&&(!a&&Es(t,c)<=0||Es(t,c)<=0&&Es(c,a)<0)&&(a=c,l=s)}return r?i-l-1:l}function Es(e,t){let o=Zi.indexOf(typeof e)-Zi.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 ws,xs;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(ws||(ws={})),function(e){e.PlainText="text/plain",e.Html="text/html"}(xs||(xs={}));const ys=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),Is=new Set([...ys,"DUPLICATE_SHEET","EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT"]),Rs=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"]),Ts=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 As(e){return Ts.has(e.type)}class Os{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new Os}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var Ms;e.CommandResult=void 0,(Ms=e.CommandResult||(e.CommandResult={}))[Ms.Success=0]="Success",Ms[Ms.CancelledForUnknownReason=1]="CancelledForUnknownReason",Ms[Ms.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",Ms[Ms.MergeIsDestructive=3]="MergeIsDestructive",Ms[Ms.CellIsMerged=4]="CellIsMerged",Ms[Ms.InvalidTarget=5]="InvalidTarget",Ms[Ms.EmptyUndoStack=6]="EmptyUndoStack",Ms[Ms.EmptyRedoStack=7]="EmptyRedoStack",Ms[Ms.NotEnoughElements=8]="NotEnoughElements",Ms[Ms.NotEnoughSheets=9]="NotEnoughSheets",Ms[Ms.MissingSheetName=10]="MissingSheetName",Ms[Ms.DuplicatedSheetName=11]="DuplicatedSheetName",Ms[Ms.DuplicatedSheetId=12]="DuplicatedSheetId",Ms[Ms.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",Ms[Ms.WrongSheetMove=14]="WrongSheetMove",Ms[Ms.WrongSheetPosition=15]="WrongSheetPosition",Ms[Ms.InvalidAnchorZone=16]="InvalidAnchorZone",Ms[Ms.SelectionOutOfBound=17]="SelectionOutOfBound",Ms[Ms.TargetOutOfSheet=18]="TargetOutOfSheet",Ms[Ms.WrongCutSelection=19]="WrongCutSelection",Ms[Ms.WrongPasteSelection=20]="WrongPasteSelection",Ms[Ms.WrongPasteOption=21]="WrongPasteOption",Ms[Ms.WrongFigurePasteOption=22]="WrongFigurePasteOption",Ms[Ms.EmptyClipboard=23]="EmptyClipboard",Ms[Ms.EmptyRange=24]="EmptyRange",Ms[Ms.InvalidRange=25]="InvalidRange",Ms[Ms.InvalidZones=26]="InvalidZones",Ms[Ms.InvalidSheetId=27]="InvalidSheetId",Ms[Ms.InvalidFigureId=28]="InvalidFigureId",Ms[Ms.InputAlreadyFocused=29]="InputAlreadyFocused",Ms[Ms.MaximumRangesReached=30]="MaximumRangesReached",Ms[Ms.InvalidChartDefinition=31]="InvalidChartDefinition",Ms[Ms.InvalidDataSet=32]="InvalidDataSet",Ms[Ms.InvalidLabelRange=33]="InvalidLabelRange",Ms[Ms.InvalidScorecardKeyValue=34]="InvalidScorecardKeyValue",Ms[Ms.InvalidScorecardBaseline=35]="InvalidScorecardBaseline",Ms[Ms.InvalidGaugeDataRange=36]="InvalidGaugeDataRange",Ms[Ms.EmptyGaugeRangeMin=37]="EmptyGaugeRangeMin",Ms[Ms.GaugeRangeMinNaN=38]="GaugeRangeMinNaN",Ms[Ms.EmptyGaugeRangeMax=39]="EmptyGaugeRangeMax",Ms[Ms.GaugeRangeMaxNaN=40]="GaugeRangeMaxNaN",Ms[Ms.GaugeRangeMinBiggerThanRangeMax=41]="GaugeRangeMinBiggerThanRangeMax",Ms[Ms.GaugeLowerInflectionPointNaN=42]="GaugeLowerInflectionPointNaN",Ms[Ms.GaugeUpperInflectionPointNaN=43]="GaugeUpperInflectionPointNaN",Ms[Ms.GaugeLowerBiggerThanUpper=44]="GaugeLowerBiggerThanUpper",Ms[Ms.InvalidAutofillSelection=45]="InvalidAutofillSelection",Ms[Ms.WrongComposerSelection=46]="WrongComposerSelection",Ms[Ms.MinBiggerThanMax=47]="MinBiggerThanMax",Ms[Ms.LowerBiggerThanUpper=48]="LowerBiggerThanUpper",Ms[Ms.MidBiggerThanMax=49]="MidBiggerThanMax",Ms[Ms.MinBiggerThanMid=50]="MinBiggerThanMid",Ms[Ms.FirstArgMissing=51]="FirstArgMissing",Ms[Ms.SecondArgMissing=52]="SecondArgMissing",Ms[Ms.MinNaN=53]="MinNaN",Ms[Ms.MidNaN=54]="MidNaN",Ms[Ms.MaxNaN=55]="MaxNaN",Ms[Ms.ValueUpperInflectionNaN=56]="ValueUpperInflectionNaN",Ms[Ms.ValueLowerInflectionNaN=57]="ValueLowerInflectionNaN",Ms[Ms.MinInvalidFormula=58]="MinInvalidFormula",Ms[Ms.MidInvalidFormula=59]="MidInvalidFormula",Ms[Ms.MaxInvalidFormula=60]="MaxInvalidFormula",Ms[Ms.ValueUpperInvalidFormula=61]="ValueUpperInvalidFormula",Ms[Ms.ValueLowerInvalidFormula=62]="ValueLowerInvalidFormula",Ms[Ms.InvalidSortZone=63]="InvalidSortZone",Ms[Ms.WaitingSessionConfirmation=64]="WaitingSessionConfirmation",Ms[Ms.MergeOverlap=65]="MergeOverlap",Ms[Ms.TooManyHiddenElements=66]="TooManyHiddenElements",Ms[Ms.Readonly=67]="Readonly",Ms[Ms.InvalidViewportSize=68]="InvalidViewportSize",Ms[Ms.InvalidScrollingDirection=69]="InvalidScrollingDirection",Ms[Ms.FigureDoesNotExist=70]="FigureDoesNotExist",Ms[Ms.InvalidConditionalFormatId=71]="InvalidConditionalFormatId",Ms[Ms.InvalidCellPopover=72]="InvalidCellPopover",Ms[Ms.EmptyTarget=73]="EmptyTarget",Ms[Ms.InvalidFreezeQuantity=74]="InvalidFreezeQuantity",Ms[Ms.FrozenPaneOverlap=75]="FrozenPaneOverlap",Ms[Ms.ValuesNotChanged=76]="ValuesNotChanged",Ms[Ms.InvalidFilterZone=77]="InvalidFilterZone",Ms[Ms.FilterOverlap=78]="FilterOverlap",Ms[Ms.FilterNotFound=79]="FilterNotFound",Ms[Ms.MergeInFilter=80]="MergeInFilter",Ms[Ms.NonContinuousTargets=81]="NonContinuousTargets",Ms[Ms.DuplicatedFigureId=82]="DuplicatedFigureId",Ms[Ms.InvalidSelectionStep=83]="InvalidSelectionStep",Ms[Ms.DuplicatedChartId=84]="DuplicatedChartId",Ms[Ms.ChartDoesNotExist=85]="ChartDoesNotExist",Ms[Ms.InvalidHeaderIndex=86]="InvalidHeaderIndex",Ms[Ms.InvalidQuantity=87]="InvalidQuantity",Ms[Ms.MoreThanOneColumnSelected=88]="MoreThanOneColumnSelected",Ms[Ms.EmptySplitSeparator=89]="EmptySplitSeparator",Ms[Ms.SplitWillOverwriteContent=90]="SplitWillOverwriteContent",Ms[Ms.NoSplitSeparatorInSelection=91]="NoSplitSeparatorInSelection",Ms[Ms.NoActiveSheet=92]="NoActiveSheet",Ms[Ms.NoChanges=93]="NoChanges";const Ns=["thin","medium","thick","dashed","dotted"];var _s,Fs;function Ds(e,t){return ks(Ls(e||""),t)}function Ls(e){if(e.startsWith("="))throw new Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);return oo(e)||et(e)?Xi(e):function(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}(e)?"TRUE"===e.toUpperCase():e}function ks(e,t){const o=qi(e);return o?{...Ps(Ls(o.label),t||To(o.label)),link:o}:Ps(e,t)}function Ps(e,t){try{for(const o of Bs){const i=o(e,t);if(i)return i}return function(e,t){return{type:ws.text,value:e,format:t,isAutoSummable:!0,defaultAlign:"left",formattedValue:mo(e,t)}}((e||"").toString(),t)}catch(t){return zs((e||"").toString(),new c(a.GenericError,t.message||de))}}function Us(e,t){return{type:ws.number,value:e||0,format:t,isAutoSummable:!0,defaultAlign:"right",formattedValue:mo(e,t)}}!function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(_s||(_s={})),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"}(Fs||(Fs={}));const Vs={type:ws.empty,value:"",format:void 0,isAutoSummable:!0,defaultAlign:"left",formattedValue:""};function zs(e,t){return{type:ws.error,value:t.errorType,error:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:t.errorType}}const Bs=[function(e,t){if(""===e)return function(e){return void 0===e?Vs:{type:ws.empty,value:"",format:e,isAutoSummable:!0,defaultAlign:"left",formattedValue:""}}(t)},function(e,t){if(t&&"number"==typeof e&&Eo(t))return function(e,t){const o=mo(e,t);return{type:ws.number,value:e,format:t,isAutoSummable:!1,defaultAlign:"right",formattedValue:o}}(e,t)},function(e,t){return"number"==typeof e?Us(e,t):null===e?Us(0,t):void 0},function(e,t){if("boolean"==typeof e)return function(e,t){const o=e?"TRUE":"FALSE";return{type:ws.boolean,value:e,format:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:o}}(e,t)}],Hs=new Ui;Hs.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=mo(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:Ds(t.cell?.content,t.cell?.format).formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,o,i)=>{e.current+=e.increment;let s=0,r=0;switch(i){case"up":s=0,r=-e.current;break;case"down":s=0,r=e.current;break;case"left":s=-e.current,r=0;break;case"right":s=e.current,r=0}const n=t.cell;if(!n||!n.isFormula)return{cellData:{}};const a=t.sheetId,l=o.createAdaptedRanges(n.dependencies,s,r,a),c=o.buildFormulaContent(a,n,l);return{cellData:{border:t.border,style:n.style,format:n.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});const $s=new Ui,Ws=/(\d+)$/,Gs=/^(.*\D+)/,qs=/^(.*\D+)(\d+)$/;function Zs(e,t,o){let i=[],s=!1;for(let r of t){r===e&&(s=!0);const t=Ds(r?.content);if(o(t))i.push(t);else{if(s)return i;i=[]}}return i}function js(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}$s.add("simple_value_copy",{condition:(e,t)=>!(1!==t.length||e.isFormula||e.format&&Eo(e.format)),generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&Ds(e.content).type===ws.text&&qs.test(e.content),generateRule:(e,t)=>{const o=parseInt(e.content.match(Ws)[0]),i=e.content.match(Gs)[0],s=e.content.length-i.length,r=Zs(e,t,(e=>e.type===ws.text&&qs.test(e.value))).filter((e=>i===e.value.toString().match(Gs)[0])).map((e=>parseInt(e.value.toString().match(Ws)[0]))),n=js(r);return{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:i,current:o,increment:n,numberPostfixLength:s}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&Ds(e.content).type===ws.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&&Ds(e.content).type===ws.number,generateRule:(e,t)=>{const o=js(Zs(e,t,(e=>e.type===ws.number)).map((e=>Number(e.value)))),i=Ds(e.content);return{type:"INCREMENT_MODIFIER",increment:o,current:i.type===ws.number?i.value:0}},sequence:40});Oi`
53
+ `;class Li 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 Dt(this.backgroundColor)>.3?"#525252":"#C8C8C8"}get figure(){return this.props.figure}get chartStyle(){return Fi({padding:`${this.chartPadding}px`,background:this.backgroundColor})}get chartContentStyle(){return Fi({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 Pi).getElementMaxFontSize(this.getDrawableHeight(),this)*i,n=(new ki).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=_i(e.cellStyle);return t["font-size"]=`${e.fontSize}px`,t.display="inline-block",!t.color&&e.color&&(t.color=e.color),Fi(t)}getDrawableHeight(){const e=2*this.chartPadding;let t=this.props.figure.height-e;return t-=this.title?18*Di:0,t}getWidestElement(){const e=new ki,t=new Pi;return e.getElementWidth(.35,this.ctx,this)>t.getElementWidth(.65,this.ctx,this)?e:t}}class ki{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)/Di}}class Pi{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)/Di}}Li.props={figure:Object};class Ui{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 Vi(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const zi=new Ui;function Bi(e,t){return{url:e=Vi(e),label:t||e,isExternal:!0,isUrlEditable:!0}}zi.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 Hi={createLink:Bi,match:e=>st(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function $i(e){return zi.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((t=>t.match(e)))||Hi}function Wi(e,t){return $i(e.url).urlRepresentation(e.url,t)}function Gi(e,t){$i(e.url).open(e.url,t)}function qi(e){if("string"==typeof e){if(it(e)){const{label:t,url:o}=rt(e);return $i(o).createLink(o,t)}return st(e)?Bi(e):void 0}}const Zi=["number","string","boolean","undefined"];function ji(e,t){if(!e())throw new Error(t)}const Yi=e=>n("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function Xi(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(oo(e)||""===e)return so(e);const t=Te(e);if(t)return t.value;throw new Error(Yi(e));default:return 0}}function Ki(e){if(""===e)throw new Error(Yi(e));return Xi(e)}function Qi(e){return Math.trunc(Ki(e))}function Ji(e){ji((()=>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 es(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}const ts=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 os(e){return"string"==typeof e?ts(e):e}const is=e=>n("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function ss(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(is(e))}return!1;case"number":return!!e;default:return!1}}function ns(e){return Oe(Xi(e))}function rs(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 as(e,t){rs(e,t,t)}function ls(e,t){rs(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(Ki(e))}))}function cs(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 hs(e,t,o){return cs(e,t,t,o)}function ds(e,t,o){return cs(e,((e,o)=>"number"==typeof o?t(e,o):e),((e,o)=>t(e,Ki(o))),o)}function us(e,t,o){return cs(e,((e,o)=>null!=o?t(e,"number"==typeof o?o:"boolean"==typeof o?Xi(o):0):e),((e,o)=>t(e,Xi(o))),o)}function gs(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(is(e));return ss(e)}(e))))}function ps(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)),oo(i)?i=Xi(i):"TRUE"!==i&&"FALSE"!==i||(i=ss(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 ms(e,t){const{operator:o,operand:i}=t;if(void 0===e||void 0===i)return!1;if("number"==typeof i&&"="===o)return es(e)===es(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 fs(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=es(e[t+1]);a.push(ps(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=ms(e[t][o][s],a[t/2]),!n)break}n&&t(o,s)}}function bs(e,t){return os(e[0][t])}function vs(e,t){return os(e[t][0])}function Ss(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 Cs(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&&Es(t,c)>=0||Es(t,c)>=0&&Es(c,a)>0)&&(a=c,l=s):"nextGreater"===o&&(!a&&Es(t,c)<=0||Es(t,c)<=0&&Es(c,a)<0)&&(a=c,l=s)}return n?i-l-1:l}function Es(e,t){let o=Zi.indexOf(typeof e)-Zi.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 ws,xs;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(ws||(ws={})),function(e){e.PlainText="text/plain",e.Html="text/html"}(xs||(xs={}));const ys=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),Is=new Set([...ys,"DUPLICATE_SHEET","EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT"]),Rs=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"]),Ts=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 As(e){return Ts.has(e.type)}class Os{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new Os}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var Ms;e.CommandResult=void 0,(Ms=e.CommandResult||(e.CommandResult={}))[Ms.Success=0]="Success",Ms[Ms.CancelledForUnknownReason=1]="CancelledForUnknownReason",Ms[Ms.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",Ms[Ms.MergeIsDestructive=3]="MergeIsDestructive",Ms[Ms.CellIsMerged=4]="CellIsMerged",Ms[Ms.InvalidTarget=5]="InvalidTarget",Ms[Ms.EmptyUndoStack=6]="EmptyUndoStack",Ms[Ms.EmptyRedoStack=7]="EmptyRedoStack",Ms[Ms.NotEnoughElements=8]="NotEnoughElements",Ms[Ms.NotEnoughSheets=9]="NotEnoughSheets",Ms[Ms.MissingSheetName=10]="MissingSheetName",Ms[Ms.DuplicatedSheetName=11]="DuplicatedSheetName",Ms[Ms.DuplicatedSheetId=12]="DuplicatedSheetId",Ms[Ms.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",Ms[Ms.WrongSheetMove=14]="WrongSheetMove",Ms[Ms.WrongSheetPosition=15]="WrongSheetPosition",Ms[Ms.InvalidAnchorZone=16]="InvalidAnchorZone",Ms[Ms.SelectionOutOfBound=17]="SelectionOutOfBound",Ms[Ms.TargetOutOfSheet=18]="TargetOutOfSheet",Ms[Ms.WrongCutSelection=19]="WrongCutSelection",Ms[Ms.WrongPasteSelection=20]="WrongPasteSelection",Ms[Ms.WrongPasteOption=21]="WrongPasteOption",Ms[Ms.WrongFigurePasteOption=22]="WrongFigurePasteOption",Ms[Ms.EmptyClipboard=23]="EmptyClipboard",Ms[Ms.EmptyRange=24]="EmptyRange",Ms[Ms.InvalidRange=25]="InvalidRange",Ms[Ms.InvalidZones=26]="InvalidZones",Ms[Ms.InvalidSheetId=27]="InvalidSheetId",Ms[Ms.InvalidFigureId=28]="InvalidFigureId",Ms[Ms.InputAlreadyFocused=29]="InputAlreadyFocused",Ms[Ms.MaximumRangesReached=30]="MaximumRangesReached",Ms[Ms.InvalidInputId=31]="InvalidInputId",Ms[Ms.InvalidChartDefinition=32]="InvalidChartDefinition",Ms[Ms.InvalidDataSet=33]="InvalidDataSet",Ms[Ms.InvalidLabelRange=34]="InvalidLabelRange",Ms[Ms.InvalidScorecardKeyValue=35]="InvalidScorecardKeyValue",Ms[Ms.InvalidScorecardBaseline=36]="InvalidScorecardBaseline",Ms[Ms.InvalidGaugeDataRange=37]="InvalidGaugeDataRange",Ms[Ms.EmptyGaugeRangeMin=38]="EmptyGaugeRangeMin",Ms[Ms.GaugeRangeMinNaN=39]="GaugeRangeMinNaN",Ms[Ms.EmptyGaugeRangeMax=40]="EmptyGaugeRangeMax",Ms[Ms.GaugeRangeMaxNaN=41]="GaugeRangeMaxNaN",Ms[Ms.GaugeRangeMinBiggerThanRangeMax=42]="GaugeRangeMinBiggerThanRangeMax",Ms[Ms.GaugeLowerInflectionPointNaN=43]="GaugeLowerInflectionPointNaN",Ms[Ms.GaugeUpperInflectionPointNaN=44]="GaugeUpperInflectionPointNaN",Ms[Ms.GaugeLowerBiggerThanUpper=45]="GaugeLowerBiggerThanUpper",Ms[Ms.InvalidAutofillSelection=46]="InvalidAutofillSelection",Ms[Ms.WrongComposerSelection=47]="WrongComposerSelection",Ms[Ms.MinBiggerThanMax=48]="MinBiggerThanMax",Ms[Ms.LowerBiggerThanUpper=49]="LowerBiggerThanUpper",Ms[Ms.MidBiggerThanMax=50]="MidBiggerThanMax",Ms[Ms.MinBiggerThanMid=51]="MinBiggerThanMid",Ms[Ms.FirstArgMissing=52]="FirstArgMissing",Ms[Ms.SecondArgMissing=53]="SecondArgMissing",Ms[Ms.MinNaN=54]="MinNaN",Ms[Ms.MidNaN=55]="MidNaN",Ms[Ms.MaxNaN=56]="MaxNaN",Ms[Ms.ValueUpperInflectionNaN=57]="ValueUpperInflectionNaN",Ms[Ms.ValueLowerInflectionNaN=58]="ValueLowerInflectionNaN",Ms[Ms.MinInvalidFormula=59]="MinInvalidFormula",Ms[Ms.MidInvalidFormula=60]="MidInvalidFormula",Ms[Ms.MaxInvalidFormula=61]="MaxInvalidFormula",Ms[Ms.ValueUpperInvalidFormula=62]="ValueUpperInvalidFormula",Ms[Ms.ValueLowerInvalidFormula=63]="ValueLowerInvalidFormula",Ms[Ms.InvalidSortZone=64]="InvalidSortZone",Ms[Ms.WaitingSessionConfirmation=65]="WaitingSessionConfirmation",Ms[Ms.MergeOverlap=66]="MergeOverlap",Ms[Ms.TooManyHiddenElements=67]="TooManyHiddenElements",Ms[Ms.Readonly=68]="Readonly",Ms[Ms.InvalidViewportSize=69]="InvalidViewportSize",Ms[Ms.InvalidScrollingDirection=70]="InvalidScrollingDirection",Ms[Ms.FigureDoesNotExist=71]="FigureDoesNotExist",Ms[Ms.InvalidConditionalFormatId=72]="InvalidConditionalFormatId",Ms[Ms.InvalidCellPopover=73]="InvalidCellPopover",Ms[Ms.EmptyTarget=74]="EmptyTarget",Ms[Ms.InvalidFreezeQuantity=75]="InvalidFreezeQuantity",Ms[Ms.FrozenPaneOverlap=76]="FrozenPaneOverlap",Ms[Ms.ValuesNotChanged=77]="ValuesNotChanged",Ms[Ms.InvalidFilterZone=78]="InvalidFilterZone",Ms[Ms.FilterOverlap=79]="FilterOverlap",Ms[Ms.FilterNotFound=80]="FilterNotFound",Ms[Ms.MergeInFilter=81]="MergeInFilter",Ms[Ms.NonContinuousTargets=82]="NonContinuousTargets",Ms[Ms.DuplicatedFigureId=83]="DuplicatedFigureId",Ms[Ms.InvalidSelectionStep=84]="InvalidSelectionStep",Ms[Ms.DuplicatedChartId=85]="DuplicatedChartId",Ms[Ms.ChartDoesNotExist=86]="ChartDoesNotExist",Ms[Ms.InvalidHeaderIndex=87]="InvalidHeaderIndex",Ms[Ms.InvalidQuantity=88]="InvalidQuantity",Ms[Ms.MoreThanOneColumnSelected=89]="MoreThanOneColumnSelected",Ms[Ms.EmptySplitSeparator=90]="EmptySplitSeparator",Ms[Ms.SplitWillOverwriteContent=91]="SplitWillOverwriteContent",Ms[Ms.NoSplitSeparatorInSelection=92]="NoSplitSeparatorInSelection",Ms[Ms.NoActiveSheet=93]="NoActiveSheet",Ms[Ms.NoChanges=94]="NoChanges";const Ns=["thin","medium","thick","dashed","dotted"];var _s,Fs;function Ds(e,t){return ks(Ls(e||""),t)}function Ls(e){if(e.startsWith("="))throw new Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);return oo(e)||et(e)?Xi(e):function(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}(e)?"TRUE"===e.toUpperCase():e}function ks(e,t){const o=qi(e);return o?{...Ps(Ls(o.label),t||To(o.label)),link:o}:Ps(e,t)}function Ps(e,t){try{for(const o of Bs){const i=o(e,t);if(i)return i}return function(e,t){return{type:ws.text,value:e,format:t,isAutoSummable:!0,defaultAlign:"left",formattedValue:mo(e,t)}}((e||"").toString(),t)}catch(t){return zs((e||"").toString(),new c(a.GenericError,t.message||de))}}function Us(e,t){return{type:ws.number,value:e||0,format:t,isAutoSummable:!0,defaultAlign:"right",formattedValue:mo(e,t)}}!function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(_s||(_s={})),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"}(Fs||(Fs={}));const Vs={type:ws.empty,value:"",format:void 0,isAutoSummable:!0,defaultAlign:"left",formattedValue:""};function zs(e,t){return{type:ws.error,value:t.errorType,error:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:t.errorType}}const Bs=[function(e,t){if(""===e)return function(e){return void 0===e?Vs:{type:ws.empty,value:"",format:e,isAutoSummable:!0,defaultAlign:"left",formattedValue:""}}(t)},function(e,t){if(t&&"number"==typeof e&&Eo(t))return function(e,t){const o=mo(e,t);return{type:ws.number,value:e,format:t,isAutoSummable:!1,defaultAlign:"right",formattedValue:o}}(e,t)},function(e,t){return"number"==typeof e?Us(e,t):null===e?Us(0,t):void 0},function(e,t){if("boolean"==typeof e)return function(e,t){const o=e?"TRUE":"FALSE";return{type:ws.boolean,value:e,format:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:o}}(e,t)}],Hs=new Ui;Hs.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=mo(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:Ds(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 $s=new Ui,Ws=/(\d+)$/,Gs=/^(.*\D+)/,qs=/^(.*\D+)(\d+)$/;function Zs(e,t,o){let i=[],s=!1;for(let n of t){n===e&&(s=!0);const t=Ds(n?.content);if(o(t))i.push(t);else{if(s)return i;i=[]}}return i}function js(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}$s.add("simple_value_copy",{condition:(e,t)=>!(1!==t.length||e.isFormula||e.format&&Eo(e.format)),generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&Ds(e.content).type===ws.text&&qs.test(e.content),generateRule:(e,t)=>{const o=parseInt(e.content.match(Ws)[0]),i=e.content.match(Gs)[0],s=e.content.length-i.length,n=Zs(e,t,(e=>e.type===ws.text&&qs.test(e.value))).filter((e=>i===e.value.toString().match(Gs)[0])).map((e=>parseInt(e.value.toString().match(Ws)[0]))),r=js(n);return{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:i,current:o,increment:r,numberPostfixLength:s}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&Ds(e.content).type===ws.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&&Ds(e.content).type===ws.number,generateRule:(e,t)=>{const o=js(Zs(e,t,(e=>e.type===ws.number)).map((e=>Number(e.value)))),i=Ds(e.content);return{type:"INCREMENT_MODIFIER",increment:o,current:i.type===ws.number?i.value:0}},sequence:40});Oi`
54
54
  .o-error-tooltip {
55
55
  font-size: 13px;
56
56
  background-color: white;
@@ -163,7 +163,7 @@
163
163
  }
164
164
  }
165
165
  }
166
- `;class Js extends t.Component{static size={width:G,height:295};static template="o-spreadsheet-FilterMenu";static style=Qs;static components={FilterMenuValueItem:Ks};state=t.useState({values:[],textFilter:"",selectedValue:void 0});searchBar=t.useRef("filterMenuSearchBar");setup(){t.onWillUpdateProps((e=>{vt(e.filterPosition,this.props.filterPosition)||(this.state.values=this.getFilterValues(e.filterPosition))})),this.state.values=this.getFilterValues(this.props.filterPosition)}get isReadonly(){return this.env.model.getters.isReadonly()}getFilterValues(e){const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getFilter({sheetId:t,...e});if(!o)return[];const i=(o.filteredZone?vi(o.filteredZone):[]).filter((({row:e})=>!this.env.model.getters.isRowHidden(t,e))).map((({col:e,row:o})=>this.env.model.getters.getEvaluatedCell({sheetId:t,col:e,row:o}).formattedValue)),s=this.env.model.getters.getFilterValues({sheetId:t,...e}),r=[...i,...s],n=s.map(Et);return[...new Set(r.map(Et))].sort(((e,t)=>e.localeCompare(t,void 0,{numeric:!0,sensitivity:"base"}))).map((e=>({checked:-1===n.findIndex((t=>t===e)),string:r.find((t=>Et(t)===e))||""})))}checkValue(e){this.state.selectedValue=e.string,e.checked=!e.checked,this.searchBar.el?.focus()}onMouseMove(e){this.state.selectedValue=e.string}selectAll(){this.state.values.forEach((e=>e.checked=!0))}clearAll(){this.state.values.forEach((e=>e.checked=!1))}get filterTable(){const e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition;return this.env.model.getters.getFilterTable({sheetId:e,...t})}get displayedValues(){return this.state.textFilter?Ko(this.state.textFilter,this.state.values,(e=>e.string)):this.state.values}confirm(){const e=this.props.filterPosition;this.env.model.dispatch("UPDATE_FILTER",{...e,sheetId:this.env.model.getters.getActiveSheetId(),values:this.state.values.filter((e=>!e.checked)).map((e=>e.string))}),this.props.onClosed?.()}cancel(){this.props.onClosed?.()}onKeyDown(e){const t=this.displayedValues;if(0===t.length)return;let o;if(void 0!==this.state.selectedValue){const e=t.findIndex((e=>e.string===this.state.selectedValue));o=-1===e?void 0:e}switch(e.key){case"ArrowDown":o=void 0===o?0:Math.min(o+1,t.length-1),e.preventDefault(),e.stopPropagation();break;case"ArrowUp":o=void 0===o?t.length-1:Math.max(o-1,0),e.preventDefault(),e.stopPropagation();break;case"Enter":void 0!==o&&this.checkValue(t[o]),e.stopPropagation(),e.preventDefault()}this.state.selectedValue=void 0!==o?t[o].string:void 0,"ArrowUp"!==e.key&&"ArrowDown"!==e.key||this.scrollListToSelectedValue(e.key)}clearScrolledToValue(){this.state.values.forEach((e=>e.scrolledTo=void 0))}scrollListToSelectedValue(e){this.clearScrolledToValue();const t=this.state.values.find((e=>e.string===this.state.selectedValue));t&&(t.scrolledTo="ArrowUp"===e?"top":"bottom")}sortFilterZone(e){const t=this.props.filterPosition,o=this.filterTable;if(!t||!o||!o.contentZone)return;const i=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("SORT_CELLS",{sheetId:i,col:t.col,row:o.contentZone.top,zone:o.contentZone,sortDirection:e,sortOptions:{emptyCellAsZero:!0,sortHeaders:!0}}),this.props.onClosed?.()}}Js.props={filterPosition:Object,onClosed:{type:Function,optional:!0}};const er={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:Js,cellCorner:"BottomLeft"})},tr=/Mac/i;function or(e,t){return!!t.target&&e.contains(t.target)}function ir(){const e=document.querySelector(".o-grid-overlay");if(e){const{top:t,left:o}=e?.getBoundingClientRect();return{top:t,left:o}}throw new Error("Can't find spreadsheet position")}function sr(e){const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function*rr(e){if(yield e,e.hasChildNodes())for(let t of e.childNodes)yield*rr(t)}function nr(){return Boolean(tr.test(navigator.userAgent))}function ar(e){return nr()?e.metaKey:e.ctrlKey}function lr(){const e=t.useState({x:0,y:0,width:0,height:0});let o=document.querySelector(".o-spreadsheet");function i(){if(o||(o=document.querySelector(".o-spreadsheet")),o){const{top:t,left:i,width:s,height:r}=o.getBoundingClientRect();e.x=i,e.y=t,e.width=s,e.height=r}}return i(),t.onMounted(i),t.onPatched(i),e}function cr(e){const o=t.useState({x:0,y:0,width:0,height:0});function i(){const t=e.el;if(null===t)return;const{top:i,left:s,width:r,height:n}=t.getBoundingClientRect();o.x=s,o.y=i,o.width=r,o.height=n}return t.onMounted(i),t.onPatched(i),o}function hr(e,t){return ur(ci(dr(e),dr(t)))}function dr(e){return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}function ur(e){if(e)return{x:e.left,y:e.top,width:e.right-e.left,height:e.bottom-e.top}}Oi`
166
+ `;class Js extends t.Component{static size={width:G,height:295};static template="o-spreadsheet-FilterMenu";static style=Qs;static components={FilterMenuValueItem:Ks};state=t.useState({values:[],textFilter:"",selectedValue:void 0});searchBar=t.useRef("filterMenuSearchBar");setup(){t.onWillUpdateProps((e=>{vt(e.filterPosition,this.props.filterPosition)||(this.state.values=this.getFilterValues(e.filterPosition))})),this.state.values=this.getFilterValues(this.props.filterPosition)}get isReadonly(){return this.env.model.getters.isReadonly()}getFilterValues(e){const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getFilter({sheetId:t,...e});if(!o)return[];const i=(o.filteredZone?vi(o.filteredZone):[]).filter((({row:e})=>!this.env.model.getters.isRowHidden(t,e))).map((({col:e,row:o})=>this.env.model.getters.getEvaluatedCell({sheetId:t,col:e,row:o}).formattedValue)),s=this.env.model.getters.getFilterValues({sheetId:t,...e}),n=[...i,...s],r=s.map(Et);return[...new Set(n.map(Et))].sort(((e,t)=>e.localeCompare(t,void 0,{numeric:!0,sensitivity:"base"}))).map((e=>({checked:-1===r.findIndex((t=>t===e)),string:n.find((t=>Et(t)===e))||""})))}checkValue(e){this.state.selectedValue=e.string,e.checked=!e.checked,this.searchBar.el?.focus()}onMouseMove(e){this.state.selectedValue=e.string}selectAll(){this.state.values.forEach((e=>e.checked=!0))}clearAll(){this.state.values.forEach((e=>e.checked=!1))}get filterTable(){const e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition;return this.env.model.getters.getFilterTable({sheetId:e,...t})}get displayedValues(){return this.state.textFilter?Ko(this.state.textFilter,this.state.values,(e=>e.string)):this.state.values}confirm(){const e=this.props.filterPosition;this.env.model.dispatch("UPDATE_FILTER",{...e,sheetId:this.env.model.getters.getActiveSheetId(),values:this.state.values.filter((e=>!e.checked)).map((e=>e.string))}),this.props.onClosed?.()}cancel(){this.props.onClosed?.()}onKeyDown(e){const t=this.displayedValues;if(0===t.length)return;let o;if(void 0!==this.state.selectedValue){const e=t.findIndex((e=>e.string===this.state.selectedValue));o=-1===e?void 0:e}switch(e.key){case"ArrowDown":o=void 0===o?0:Math.min(o+1,t.length-1),e.preventDefault(),e.stopPropagation();break;case"ArrowUp":o=void 0===o?t.length-1:Math.max(o-1,0),e.preventDefault(),e.stopPropagation();break;case"Enter":void 0!==o&&this.checkValue(t[o]),e.stopPropagation(),e.preventDefault()}this.state.selectedValue=void 0!==o?t[o].string:void 0,"ArrowUp"!==e.key&&"ArrowDown"!==e.key||this.scrollListToSelectedValue(e.key)}clearScrolledToValue(){this.state.values.forEach((e=>e.scrolledTo=void 0))}scrollListToSelectedValue(e){this.clearScrolledToValue();const t=this.state.values.find((e=>e.string===this.state.selectedValue));t&&(t.scrolledTo="ArrowUp"===e?"top":"bottom")}sortFilterZone(e){const t=this.props.filterPosition,o=this.filterTable;if(!t||!o||!o.contentZone)return;const i=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("SORT_CELLS",{sheetId:i,col:t.col,row:o.contentZone.top,zone:o.contentZone,sortDirection:e,sortOptions:{emptyCellAsZero:!0,sortHeaders:!0}}),this.props.onClosed?.()}}Js.props={filterPosition:Object,onClosed:{type:Function,optional:!0}};const en={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:Js,cellCorner:"BottomLeft"})},tn=/Mac/i;function on(e,t){return!!t.target&&e.contains(t.target)}function sn(){const e=document.querySelector(".o-grid-overlay");if(e){const{top:t,left:o}=e?.getBoundingClientRect();return{top:t,left:o}}throw new Error("Can't find spreadsheet position")}function nn(e){const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function*rn(e){if(yield e,e.hasChildNodes())for(let t of e.childNodes)yield*rn(t)}function an(){return Boolean(tn.test(navigator.userAgent))}function ln(e){return an()?e.metaKey:e.ctrlKey}function cn(){const e=t.useState({x:0,y:0,width:0,height:0});let o=document.querySelector(".o-spreadsheet");function i(){if(o||(o=document.querySelector(".o-spreadsheet")),o){const{top:t,left:i,width:s,height:n}=o.getBoundingClientRect();e.x=i,e.y=t,e.width=s,e.height=n}}return i(),t.onMounted(i),t.onPatched(i),e}function hn(e){const o=t.useState({x:0,y:0,width:0,height:0});function i(){const t=e.el;if(null===t)return;const{top:i,left:s,width:n,height:r}=t.getBoundingClientRect();o.x=s,o.y=i,o.width=n,o.height=r}return t.onMounted(i),t.onPatched(i),o}function dn(e,t){return gn(ci(un(e),un(t)))}function un(e){return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}function gn(e){if(e)return{x:e.left,y:e.top,width:e.right-e.left,height:e.bottom-e.top}}Oi`
167
167
  .o-popover {
168
168
  position: absolute;
169
169
  z-index: ${ue.Popover};
@@ -172,7 +172,7 @@
172
172
  width: fit-content;
173
173
  height: fit-content;
174
174
  }
175
- `;class gr 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=lr();containerRect;setup(){this.containerRect=function(){const e=t.useState({x:0,y:0,width:0,height:0}),o=t.useComponent(),i=lr();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=hr(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},s={width:e.getBoundingClientRect().width,height:e.getBoundingClientRect().height},r=this.spreadsheetRect,n="BottomLeft"===this.props.positioning?new mr(t,this.containerRect,i,r):new fr(t,this.containerRect,i,r),a=n.getCss(s,this.props.verticalOffset);for(const t of Object.keys(a))e.style[t]=a[t];const l=n.getCurrentPosition(s);this.currentPosition&&l!==this.currentPosition&&this.props.onPopoverMoved?.(),this.currentPosition=l}))}get popoverStyle(){return Fi({"z-index":`${this.props.zIndex}`})}}gr.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 pr{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),r=Math.min(i,e.width),n=this.shouldRenderAtBottom(e.height),a=this.shouldRenderAtRight(e.width);t=n?t:-t;return{"max-height":o+"px","max-width":i+"px",top:this.getTopCoordinate(s,n)-this.spreadsheetOffset.y-t+"px",left:this.getLeftCoordinate(r,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 mr extends pr{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 fr extends pr{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}}Oi`
175
+ `;class pn 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=cn();containerRect;setup(){this.containerRect=function(){const e=t.useState({x:0,y:0,width:0,height:0}),o=t.useComponent(),i=cn();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=dn(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},s={width:e.getBoundingClientRect().width,height:e.getBoundingClientRect().height},n=this.spreadsheetRect,r="BottomLeft"===this.props.positioning?new fn(t,this.containerRect,i,n):new bn(t,this.containerRect,i,n),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 Fi({"z-index":`${this.props.zIndex}`})}}pn.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 mn{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{"max-height":o+"px","max-width":i+"px",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 fn extends mn{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 bn extends mn{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}}Oi`
176
176
  .o-menu {
177
177
  background-color: white;
178
178
  padding: ${6}px 0px;
@@ -224,7 +224,7 @@
224
224
  }
225
225
  }
226
226
  }
227
- `;class br extends t.Component{static template="o-spreadsheet-Menu";static components={Menu:br,Popover:gr};static defaultProps={depth:1};subMenu=t.useState({isOpen:!1,position:null,scrollOffset:0,menuItems:[]});menuRef=t.useRef("menu");position=cr(this.menuRef);setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0}),t.useExternalListener(window,"contextmenu",this.onExternalClick,{capture:!0}),t.onWillUpdateProps((e=>{e.menuItems!==this.props.menuItems&&this.closeSubMenu()}))}get menuItemsAndSeparators(){const e=[];for(let t=0;t<this.props.menuItems.length;t++){const o=this.props.menuItems[t];o.isVisible(this.env)&&e.push(o),o.separator&&t!==this.props.menuItems.length-1&&"separator"!==e[e.length-1]&&e.push("separator")}return"separator"===e[e.length-1]&&e.pop(),1===e.length&&"separator"===e[0]?[]:e}get subMenuPosition(){const e=Object.assign({},this.subMenu.position);return e.y-=this.subMenu.scrollOffset||0,e}get popoverProps(){const e=1===this.props.depth;return{anchorRect:{x:this.props.position.x-G*(this.props.depth-1),y:this.props.position.y,width:e?0:G,height:e?0:26},positioning:"TopRight",verticalOffset:e?0:6,onPopoverHidden:()=>this.closeSubMenu(),onPopoverMoved:()=>this.closeSubMenu()}}get childrenHaveIcon(){return this.props.menuItems.some((e=>!!e.icon||!!e.isActive))}getIconName(e){return e.icon?e.icon:e.isActive?.(this.env)?"o-spreadsheet-Icon.CHECK":""}getColor(e){return e.textColor?`color: ${e.textColor}`:void 0}async activateMenu(e){const t=await(e.execute?.(this.env));this.close(),this.props.onMenuClicked?.({detail:t})}close(){this.closeSubMenu(),this.props.onClose()}onExternalClick(e){this.menuRef.el&&Array.from(document.querySelectorAll(".o-spreadsheet .o-menu")).some((t=>or(t,e)))||(e.closedMenuId=this.props.menuId,this.close())}getName(e){return e.name(this.env)}isRoot(e){return!e.execute}isEnabled(e){return!!e.isEnabled(this.env)&&(!this.env.model.getters.isReadonly()||e.isReadonlyAllowed)}onScroll(e){this.subMenu.scrollOffset=e.target.scrollTop}openSubMenu(e,t,o){const i=o.currentTarget;if(!i)return;const s=i.getBoundingClientRect().top;this.subMenu.position={x:this.position.x+this.props.depth*G,y:s-(this.subMenu.scrollOffset||0)},this.subMenu.menuItems=e.children(this.env),this.subMenu.isOpen=!0,this.subMenu.parentMenu=e}isParentMenu(e,t){return e.parentMenu?.id===t.id}closeSubMenu(){this.subMenu.isOpen=!1,this.subMenu.parentMenu=void 0}onClickMenu(e,t,o){this.isEnabled(e)&&(this.isRoot(e)?this.openSubMenu(e,t,o):this.activateMenu(e))}onMouseOver(e,t,o){this.isEnabled(e)&&(this.isRoot(e)?this.openSubMenu(e,t,o):this.closeSubMenu())}}br.props={position:Object,menuItems:Array,depth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},onClose:Function,onMenuClicked:{type:Function,optional:!0},menuId:{type:String,optional:!0}};Oi`
227
+ `;class vn extends t.Component{static template="o-spreadsheet-Menu";static components={Menu:vn,Popover:pn};static defaultProps={depth:1};subMenu=t.useState({isOpen:!1,position:null,scrollOffset:0,menuItems:[]});menuRef=t.useRef("menu");position=hn(this.menuRef);setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0}),t.useExternalListener(window,"contextmenu",this.onExternalClick,{capture:!0}),t.onWillUpdateProps((e=>{e.menuItems!==this.props.menuItems&&this.closeSubMenu()}))}get menuItemsAndSeparators(){const e=[];for(let t=0;t<this.props.menuItems.length;t++){const o=this.props.menuItems[t];o.isVisible(this.env)&&e.push(o),o.separator&&t!==this.props.menuItems.length-1&&"separator"!==e[e.length-1]&&e.push("separator")}return"separator"===e[e.length-1]&&e.pop(),1===e.length&&"separator"===e[0]?[]:e}get subMenuPosition(){const e=Object.assign({},this.subMenu.position);return e.y-=this.subMenu.scrollOffset||0,e}get popoverProps(){const e=1===this.props.depth;return{anchorRect:{x:this.props.position.x-G*(this.props.depth-1),y:this.props.position.y,width:e?0:G,height:e?0:26},positioning:"TopRight",verticalOffset:e?0:6,onPopoverHidden:()=>this.closeSubMenu(),onPopoverMoved:()=>this.closeSubMenu()}}get childrenHaveIcon(){return this.props.menuItems.some((e=>!!e.icon||!!e.isActive))}getIconName(e){return e.icon?e.icon:e.isActive?.(this.env)?"o-spreadsheet-Icon.CHECK":""}getColor(e){return e.textColor?`color: ${e.textColor}`:void 0}async activateMenu(e){const t=await(e.execute?.(this.env));this.close(),this.props.onMenuClicked?.({detail:t})}close(){this.closeSubMenu(),this.props.onClose()}onExternalClick(e){this.menuRef.el&&Array.from(document.querySelectorAll(".o-spreadsheet .o-menu")).some((t=>on(t,e)))||(e.closedMenuId=this.props.menuId,this.close())}getName(e){return e.name(this.env)}isRoot(e){return!e.execute}isEnabled(e){return!!e.isEnabled(this.env)&&(!this.env.model.getters.isReadonly()||e.isReadonlyAllowed)}onScroll(e){this.subMenu.scrollOffset=e.target.scrollTop}openSubMenu(e,t,o){const i=o.currentTarget;if(!i)return;const s=i.getBoundingClientRect().top;this.subMenu.position={x:this.position.x+this.props.depth*G,y:s-(this.subMenu.scrollOffset||0)},this.subMenu.menuItems=e.children(this.env),this.subMenu.isOpen=!0,this.subMenu.parentMenu=e}isParentMenu(e,t){return e.parentMenu?.id===t.id}closeSubMenu(){this.subMenu.isOpen=!1,this.subMenu.parentMenu=void 0}onClickMenu(e,t,o){this.isEnabled(e)&&(this.isRoot(e)?this.openSubMenu(e,t,o):this.activateMenu(e))}onMouseOver(e,t,o){this.isEnabled(e)&&(this.isRoot(e)?this.openSubMenu(e,t,o):this.closeSubMenu())}}vn.props={position:Object,menuItems:Array,depth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},onClose:Function,onMenuClicked:{type:Function,optional:!0},menuId:{type:String,optional:!0}};Oi`
228
228
  .o-link-tool {
229
229
  font-size: 13px;
230
230
  background-color: white;
@@ -271,7 +271,7 @@
271
271
  cursor: pointer;
272
272
  color: #000;
273
273
  }
274
- `;class vr extends t.Component{static components={Menu:br};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. ${Gt(e,t)} is not a link.`)}getUrlRepresentation(e){return Wi(e,this.env.model.getters)}openLink(){Gi(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 Sr={onHover:(e,t)=>{const o=t.getEvaluatedCell(e);return!t.isDashboard()&&o.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:vr,props:{cellPosition:e},cellCorner:"BottomLeft"}:{isOpen:!1}}};vr.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const Cr={name:r("Link sheet"),children:[e=>e.model.getters.getSheetIds().map((t=>e.model.getters.getSheet(t))).map((e=>({id:e.id,name:e.name,execute:()=>rt(e.name,ct(e.id))})))]},Er={name:r("Delete"),isVisible:e=>e.model.getters.getSheetIds().length>1,execute:e=>e.askConfirmation(r("Are you sure you want to delete this sheet ?"),(()=>{e.model.dispatch("DELETE_SHEET",{sheetId:e.model.getters.getActiveSheetId()})}))},wr={name:r("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})}},xr=e=>({name:r("Rename"),execute:e.renameSheetCallback}),yr={name:r("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})},Ir={name:r("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})},Rr={name:r("Hide sheet"),isVisible:e=>1!==e.model.getters.getVisibleSheetIds().length,execute:e=>e.model.dispatch("HIDE_SHEET",{sheetId:e.model.getters.getActiveSheetId()})};function Tr(e){return e.map(Or).sort(((e,t)=>e.sequence-t.sequence))}const Ar=new Jo;function Or(e){const t=e.name,o=e.children;return{id:e.id||Ar.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(Or):()=>[],isReadonlyAllowed:e.isReadonlyAllowed||!1,separator:e.separator||!1,icon:e.icon||"",description:e.description||"",textColor:e.textColor,sequence:e.sequence||0}}class Mr extends Ui{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 Tr(this.getAll())}}const Nr=new Mr;Nr.add("sheet",{...Cr,sequence:10});Oi`
274
+ `;class Sn extends t.Component{static components={Menu:vn};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. ${Gt(e,t)} is not a link.`)}getUrlRepresentation(e){return Wi(e,this.env.model.getters)}openLink(){Gi(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 Cn={onHover:(e,t)=>{const o=t.getEvaluatedCell(e);return!t.isDashboard()&&o.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:Sn,props:{cellPosition:e},cellCorner:"BottomLeft"}:{isOpen:!1}}};Sn.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const En={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))})))]},wn={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()})}))},xn={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})}},yn=e=>({name:n("Rename"),execute:e.renameSheetCallback}),In={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})},Rn={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})},Tn={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 An(e){return e.map(Mn).sort(((e,t)=>e.sequence-t.sequence))}const On=new Jo;function Mn(e){const t=e.name,o=e.children;return{id:e.id||On.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(Mn):()=>[],isReadonlyAllowed:e.isReadonlyAllowed||!1,separator:e.separator||!1,icon:e.icon||"",description:e.description||"",textColor:e.textColor,sequence:e.sequence||0}}class Nn extends Ui{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 An(this.getAll())}}const _n=new Nn;_n.add("sheet",{...En,sequence:10});Oi`
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 _r extends t.Component{static template="o-spreadsheet-LinkEditor";static components={Menu:br};menuItems=Nr.getMenuItems();link=t.useState(this.defaultState);menu=t.useState({isOpen:!1});linkEditorRef=t.useRef("linkEditor");position=cr(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=qi(t);o&&(this.link.url=o.url,this.link.label=o.label,this.link.isUrlEditable=o.isUrlEditable)}getUrlRepresentation(e){return Wi(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:rt(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();break;case"Escape":this.cancel(),e.stopPropagation()}}}const Fr={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:_r,cellCorner:"BottomLeft"})};_r.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const Dr=new Ui;function Lr(e){return 8===(e=Mt(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}Dr.add("ErrorToolTip",Xs).add("LinkCell",Sr).add("LinkEditor",Fr).add("FilterMenu",er);class kr{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 Pr(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?ai(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?si(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):{...e}}function Ur(e,t,o,i){let s=!1;const r=[];for(let i in o){let n=o[i];if(n.labelCell){const e=Br(n.labelCell,t);n.labelCell!==e&&(s=!0,n={...n,labelCell:e})}const a=Br(n.dataRange,t);void 0===a||e.getRangeString(a,a.sheetId)===J?(s=!0,n=void 0):a!==n.dataRange&&(s=!0,n={...n,dataRange:a}),r[i]=n}let n=i;const a=Br(n,t);a!==n&&(s=!0,n=a);return{isStale:s,dataSets:r.filter(dt),labelRange:n}}function Vr(e,t,o){return o.map((o=>({dataRange:Yo(e,t,o.dataRange),labelCell:o.labelCell?Yo(e,t,o.labelCell):void 0})))}function zr(e,t,o){return o?Yo(e,t,o):void 0}function Br(e,t){if(!e)return;const o=t(e);switch(o.changeType){case"NONE":return e;case"REMOVE":return;default:return o.range}}function Hr(e,t,o,i){const s=[];for(const r of t){const t=e.getRangeFromSheetXC(o,r),{unboundedZone:n,sheetId:a,invalidSheetName:l,invalidXc:c}=t;if(!l&&!c)if(n.left!==n.right&&n.top!==n.bottom){if(void 0===n.right)continue;for(let t=n.left;t<=n.right;t++){const o={...n,left:t,right:t};s.push($r(e,a,o,i?{top:o.top,bottom:o.top,left:o.left,right:o.left}:void 0))}}else n.left===n.right&&n.top===n.bottom?i||s.push($r(e,a,n,void 0)):s.push($r(e,a,n,i?{top:n.top,bottom:n.top,left:n.left,right:n.left}:void 0))}return s}function $r(e,t,o,i){if(o.left!==o.right&&o.top!==o.bottom)throw new Error(`Zone should be a single column or row: ${ii(o)}`);if(i){const s=ii(o),r=ii(i);return{labelCell:e.getRangeFromSheetXC(t,r),dataRange:e.getRangeFromSheetXC(t,s)}}return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,ii(o))}}function Wr(e,t){const o=t.labelCell?.zone;let i=t.dataRange.zone;if(o){const{numberOfRows:e,numberOfCols:t}=fi(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"):void 0,range:e.getRangeString(s,"forceSheetReference")}}function Gr(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")}function qr(e,t){let o;if(e.labelRange){const i=Pr(ei(e.labelRange),t);o=i?ii(i):void 0}const i=e.dataSets.map(ei).map((e=>Pr(e,t))).filter(dt).map(ii);return{...e,labelRange:o,dataSets:i}}const Zr=["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 jr{graphColorIndex=0;next(){return Zr[this.graphColorIndex++%Zr.length]}}function Yr(e){return e&&Dt(e)<.3?"#FFFFFF":"#000000"}function Xr(e){if(e.dataSets){const t=void 0!==e.dataSets.find((e=>!Bo.test(e)));if(t)return 32;if(e.dataSets.map(ei).some((e=>e.top!==e.bottom&&xi(e))))return 32}return 0}function Kr(e){if(e.labelRange){if(!Bo.test(e.labelRange||""))return 33}return 0}function Qr(e,t,o){if(!o)return!1;if(!e)return!1;if(!t)return!0;const i=yi(t.dataRange.zone);return!(yi(e.zone)<i)}function Jr(e,t,o){if(e){if("text"===o||t?.type!==ws.number||e.type!==ws.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 mo(i,e.format);const s=Math.abs(parseFloat(i.toFixed(2))).toLocaleString();return"percentage"===o?s+"%":s}}return""}function en(e,t,o,i,s){if("text"===t||e?.type!==ws.number||o?.type!==ws.number)return;const r=o.value-e.value;return r>0?i:r<0?s:void 0}function tn(e,t,o){if("text"===o||e?.type!==ws.number||t?.type!==ws.number)return"neutral";const i=t.value-e.value;return i>0?"up":i<0?"down":"neutral"}const on={Errors:{25:r("The range is invalid"),51:r("The argument is missing. Please provide a value"),52:r("The second argument is missing. Please provide a value"),53:r("The minpoint must be a number"),54:r("The midpoint must be a number"),55:r("The maxpoint must be a number"),56:r("The first value must be a number"),57:r("The second value must be a number"),47:r("Minimum must be smaller then Maximum"),50:r("Minimum must be smaller then Midpoint"),49:r("Midpoint must be smaller then Maximum"),48:r("Lower inflection point must be smaller than upper inflection point"),58:r("Invalid Minpoint formula"),60:r("Invalid Maxpoint formula"),59:r("Invalid Midpoint formula"),61:r("Invalid upper inflection point formula"),62:r("Invalid lower inflection point formula"),24:r("A range needs to be defined"),Unexpected:r("The rule is invalid for an unknown reason")},ColorScale:r("Color scale"),IconSet:r("Icon set")},sn={IsEmpty:r("Is empty"),IsNotEmpty:r("Is not empty"),ContainsText:r("Contains"),NotContains:r("Does not contain"),BeginsWith:r("Starts with"),EndsWith:r("Ends with"),Equal:r("Is equal to"),NotEqual:r("Is not equal to"),GreaterThan:r("Is greater than"),GreaterThanOrEqual:r("Is greater than or equal to"),LessThan:r("Is less than"),LessThanOrEqual:r("Is less than or equal to"),Between:r("Is between"),NotBetween:r("Is not between")},rn={Series:r("Series"),Errors:{Unexpected:r("The chart definition is invalid for an unknown reason"),32:r("The dataset is invalid"),33:r("Labels are invalid"),34:r("The key value is invalid"),35:r("The baseline value is invalid"),36:r("The data range is invalid"),37:r("A minimum range limit value is needed"),38:r("The minimum range limit value must be a number"),39:r("A maximum range limit value is needed"),40:r("The maximum range limit value must be a number"),41:r("Minimum range limit must be smaller than maximum range limit"),42:r("The lower inflection point value must be a number"),43:r("The upper inflection point value must be a number")}},nn={Custom:r("Custom")},an=r("Merged cells are preventing this operation. Unmerge those cells and try again."),ln={Errors:{Unexpected:r("Cannot split the selection for an unknown reason"),91:r("There is no match for the selected separator in the selection"),88:r("Only a selection from a single column can be split"),90:r("Splitting will overwrite existing content")}};function cn(e,t){if(t.dataRange){const o=t.labelCell?[ii(t.labelCell.zone)]:[],i=pi([ii(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 hn(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 dn(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 r=e[o];for(const e of Ke(0,t.length))i[r][e]+="number"==typeof(s=t[e].data[o])?s:0}var s;return{labels:Object.keys(i),dataSetsValues:t.map(((e,t)=>({...e,data:Object.values(i).map((e=>e[t]))})))}}function un(e){return e?e.length>oe?e.substring(0,oe)+"…":e:""}function gn(e,t,o,i){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],r=i&&"number"==typeof s?mo(s,i):s?.toLocaleString()||"";return o?`${o}: ${r}`:r}}}},data:{labels:t.map(un),datasets:[]}}}function pn(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<cn(e,t[0]).length;o++)i.formattedValues.push(""),i.values.push("");else if(t[0]){i={formattedValues:Ke(0,cn(e,t[0]).length).map((e=>e.toString())),values:i.formattedValues}}return i}function mn(e,t){for(const o of t){const t=e.getRangeFormats(o.dataRange).find((e=>void 0!==e&&!Eo(e)));if(t)return t}}function fn(e,t){const o=[];for(const[i,s]of Object.entries(t)){let t;if(s.labelCell){const o=s.labelCell,r=o?e.getEvaluatedCell({sheetId:o.sheetId,col:o.zone.left,row:o.zone.top}):void 0;t=r&&o?un(r.formattedValue):t=`${rn.Series} ${parseInt(i)+1}`}else t=t=`${rn.Series} ${parseInt(i)+1}`;let r=s.dataRange?cn(e,s):[];o.push({data:r,label:t})}return o}function bn(e){return 0===e?"origin":e-1}class vn extends kr{dataSets;labelRange;background;verticalAxisPosition;legendPosition;stacked;aggregated;type="bar";dataSetsHaveTitle;constructor(e,t,o){super(e,t,o),this.dataSets=Hr(o,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Xo(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 qr(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,Xr,Kr)}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=Vr(this.sheetId,e,this.dataSets),o=zr(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new vn(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new vn(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=>Wr(this.getters,e))).filter((e=>""!==e.range)),t=Gr(this.getters,this.labelRange,Qr(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:Lr(this.background||w),fontColor:Lr(Yr(this.background)),dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:o,isStale:i}=Ur(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const s=this.getDefinitionWithSpecificDataSets(t,o);return new vn(s,this.sheetId,this.getters)}}function Sn(e){return e.dataRange&&!Bo.test(e.dataRange)?36:0}function Cn(e,t){return t((t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):0),(t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):0))}function En(e){return e.sectionRule&&Number(e.sectionRule.rangeMin)>=Number(e.sectionRule.rangeMax)?41:0}function wn(e,t){if(""===e)switch(t){case"rangeMin":return 37;case"rangeMax":return 39}return 0}function xn(e,t){if(isNaN(e))switch(t){case"rangeMin":return 38;case"rangeMax":return 40;case"lowerInflectionPointValue":return 42;case"upperInflectionPointValue":return 43}return 0}class yn extends kr{dataRange;sectionRule;background;type="gauge";constructor(e,t,o){super(e,t,o),this.dataRange=Xo(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,Sn,e.chainValidations(Cn(wn,e.batchValidations),Cn(xn,e.batchValidations),En),e.chainValidations((o=xn,(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=Pr(ei(e.dataRange),t)),{...e,dataRange:o?ii(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=zr(this.sheetId,e,this.dataRange),o=this.getDefinitionWithSpecificRanges(t,e);return new yn(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.dataRange,e);return new yn(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=Br(this.dataRange,e);if(this.dataRange===t)return this;const o=this.getDefinitionWithSpecificRanges(t);return new yn(o,this.sheetId,this.getters)}}const In={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},Rn={inSeconds:function(e){return Math.floor(e/In.second)},inMinutes:function(e){return Math.floor(e/In.minute)},inHours:function(e){return Math.floor(e/In.hour)},inDays:function(e){return Math.floor(e/In.day)},inMonths:function(e){return Math.floor(e/In.month)},inYears:function(e){return Math.floor(e/In.year)}},Tn=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function An(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=Math.max(...i)-Math.min(...i),r=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(In.second>=In[r]&&Rn.inSeconds(s)<180)return"second";if(In.minute>=In[r]&&Rn.inMinutes(s)<180)return"minute";if(In.hour>=In[r]&&Rn.inHours(s)<96)return"hour";if(In.day>=In[r]&&Rn.inDays(s)<90)return"day";if(In.month>=In[r]&&Rn.inMonths(s)<36)return"month";return"year"}(e,o),s={};return i&&(s[i]=o),{parser:o,displayFormats:s,unit:i}}class On extends kr{dataSets;labelRange;background;verticalAxisPosition;legendPosition;labelsAsText;stacked;aggregated;type="line";dataSetsHaveTitle;cumulative;constructor(e,t,o){super(e,t,o),this.dataSets=Hr(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Xo(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,Xr,Kr)}static transformDefinition(e,t){return qr(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}=Ur(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const s=this.getDefinitionWithSpecificDataSets(t,o);return new On(s,this.sheetId,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>Wr(this.getters,e))).filter((e=>""!==e.range)),t=Gr(this.getters,this.labelRange,Qr(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:Lr(this.background||w),fontColor:Lr(Yr(this.background)),dataSets:e,labelRange:t}}copyForSheetId(e){const t=Vr(this.sheetId,e,this.dataSets),o=zr(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new On(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new On(t,e,this.getters)}}function Mn(e,t){return _n(e,t)||Fn(e,t)}function Nn(e,t){return function(e,t){return!e.labelsAsText&&_n(e.labelRange,t)}(e,t)?"time":function(e,t){return!e.labelsAsText&&Fn(e.labelRange,t)}(e,t)?"linear":"category"}function _n(e,t){if(!e||!Fn(e,t))return!1;const o=t.getEvaluatedCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}).format;return Boolean(o&&Tn.test(o))}function Fn(e,t){if(!e)return!1;const o=t.getRangeValues(e);return!o.some((e=>isNaN(Number(e))&&e))&&!o.every((e=>!e))}class Dn extends kr{dataSets;labelRange;background;legendPosition;type="pie";aggregated;dataSetsHaveTitle;constructor(e,t,o){super(e,t,o),this.dataSets=Hr(o,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Xo(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 qr(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,Xr,Kr)}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=Vr(this.sheetId,e,this.dataSets),o=zr(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new Dn(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Dn(t,e,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>Wr(this.getters,e))).filter((e=>""!==e.range)),t=Gr(this.getters,this.labelRange,Qr(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:Lr(this.background||w),fontColor:Lr(Yr(this.background)),verticalAxisPosition:"left",dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:o,isStale:i}=Ur(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const s=this.getDefinitionWithSpecificDataSets(t,o);return new Dn(s,this.sheetId,this.getters)}}function Ln(e,t){const o=[],i=Math.max(...t.map((e=>e.data.length)));for(let t=0;t<=i;t++)o.push(e.next());return o}function kn(e){return e.keyValue&&!Bo.test(e.keyValue)?34:0}function Pn(e){return e.baseline&&!Bo.test(e.baseline)?35:0}class Un extends kr{keyValue;baseline;baselineMode;baselineDescr;background;baselineColorUp;baselineColorDown;fontColor;type="scorecard";constructor(e,t,o){super(e,t,o),this.keyValue=Xo(o,t,e.keyValue),this.baseline=Xo(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,kn,Pn)}static getDefinitionFromContextCreation(e){return{background:e.background,type:"scorecard",keyValue:e.range?e.range[0]:void 0,title:e.title||"",baselineMode:se,baselineColorUp:re,baselineColorDown:ne,baseline:e.auxiliaryRange||""}}static transformDefinition(e,t){let o,i;return e.baseline&&(o=Pr(ei(e.baseline),t)),e.keyValue&&(i=Pr(ei(e.keyValue),t)),{...e,baseline:o?ii(o):void 0,keyValue:i?ii(i):void 0}}copyForSheetId(e){const t=zr(this.sheetId,e,this.baseline),o=zr(this.sheetId,e,this.keyValue),i=this.getDefinitionWithSpecificRanges(t,o,e);return new Un(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,e);return new Un(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=Br(this.baseline,e),o=Br(this.keyValue,e);if(this.baseline===t&&this.keyValue===o)return this;const i=this.getDefinitionWithSpecificRanges(t,o);return new Un(i,this.sheetId,this.getters)}}const Vn=new Ui;Vn.add("bar",{match:e=>"bar"===e,createChart:(e,t,o)=>new vn(e,t,o),getChartRuntime:function(e,t){let o=pn(t,e.dataSets,e.labelRange).formattedValues,i=fn(t,e.dataSets);e.dataSetsHaveTitle&&i[0]&&o.length>i[0].data.length&&o.shift(),({labels:o,dataSetsValues:i}=hn(o,i)),e.aggregated&&({labels:o,dataSetsValues:i}=dn(o,i));const s=function(e,t,o){const i=Yr(e.background),s=gn(e,t,i,o),r={labels:{fontColor:i}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,s.options.legend={...s.options?.legend,...r},s.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},s.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:i}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:i,beginAtZero:!0,callback:e=>o?mo(e,o):e?.toLocaleString()||e}}]},e.stacked&&(s.options.scales.xAxes[0].stacked=!0,s.options.scales.yAxes[0].stacked=!0),s}(e,o,mn(t,e.dataSets)),r=new jr;for(let{label:e,data:t}of i){const o=r.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)=>vn.validateChartDefinition(e,t),transformDefinition:(e,t)=>vn.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>vn.getDefinitionFromContextCreation(e),name:r("Bar"),sequence:10}),Vn.add("line",{match:e=>"line"===e,createChart:(e,t,o)=>new On(e,t,o),getChartRuntime:function(e,t){const o=Nn(e,t),i=pn(t,e.dataSets,e.labelRange);let s="linear"===o?i.values:i.formattedValues,r=fn(t,e.dataSets);e.dataSetsHaveTitle&&r[0]&&s.length>r[0].data.length&&s.shift(),({labels:s,dataSetsValues:r}=hn(s,r)),"time"===o&&({labels:s,dataSetsValues:r}=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,r)),e.aggregated&&({labels:s,dataSetsValues:r}=dn(s,r));const n=mn(t,e.dataSets),a=function(e,t,o){const i=Yr(e.background),s=gn(e,t,i,o),r={labels:{fontColor:i,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,s.options.legend={...s.options?.legend,...r},s.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},s.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:i}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:i,beginAtZero:!0,callback:e=>o?mo(e,o):e?.toLocaleString()||e}}]},e.stacked&&(s.options.scales.yAxes[0].stacked=!0),s}(e,s,n),l=function(e,t){if(t)return e.getEvaluatedCell({sheetId:t.sheetId,col:t.zone.left,row:t.zone.top}).format}(t,e.labelRange);"time"===o?(a.options.scales.xAxes[0].type="time",a.options.scales.xAxes[0].time=An(s,l),a.options.scales.xAxes[0].ticks.maxTicksLimit=15):"linear"===o&&(a.options.scales.xAxes[0].type="linear",a.options.scales.xAxes[0].ticks.callback=e=>mo(e,l),a.options.tooltips.callbacks.title=e=>mo(e[0]?.xLabel||"",l));const c=new jr;for(let[t,{label:i,data:n}]of r.entries()){["linear","time"].includes(o)&&(n=n.map(((e,t)=>({x:s[t]||void 0,y:e}))));const r=c.next();let l=kt(r);if(e.stacked&&(l.a=ae),e.cumulative){let e=0;n=n.map((t=>isNaN(t)?t:(e+=parseFloat(t),e)))}const h={label:i,data:n,lineTension:0,borderColor:r,backgroundColor:Lt(l),pointBackgroundColor:r,fill:!!e.stacked&&bn(t)};a.data.datasets.push(h)}return{chartJsConfig:a,background:e.background||w}},validateChartDefinition:(e,t)=>On.validateChartDefinition(e,t),transformDefinition:(e,t)=>On.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>On.getDefinitionFromContextCreation(e),name:r("Line"),sequence:20}),Vn.add("pie",{match:e=>"pie"===e,createChart:(e,t,o)=>new Dn(e,t,o),getChartRuntime:function(e,t){let o=pn(t,e.dataSets,e.labelRange).formattedValues,i=fn(t,e.dataSets);e.dataSetsHaveTitle&&i[0]&&o.length>i[0].data.length&&o.shift(),({labels:o,dataSetsValues:i}=hn(o,i)),e.aggregated&&({labels:o,dataSetsValues:i}=dn(o,i));const s=function(e,t,o){const i=Yr(e.background),s=gn(e,t,i,o),r={labels:{fontColor:i}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,s.options.legend={...s.options?.legend,...r},s.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},s.options.tooltips.callbacks.title=function(e,t){return t.datasets[e[0].datasetIndex].label},s}(e,o,mn(t,e.dataSets)),r=new jr;for(let{label:e,data:t}of i){const o={label:e,data:t,borderColor:"#FFFFFF",backgroundColor:Ln(r,i)};s.data.datasets.push(o)}return{chartJsConfig:s,background:e.background||w}},validateChartDefinition:(e,t)=>Dn.validateChartDefinition(e,t),transformDefinition:(e,t)=>Dn.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Dn.getDefinitionFromContextCreation(e),name:r("Pie"),sequence:30}),Vn.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,o)=>new Un(e,t,o),getChartRuntime:function(e,t){let o,i,r="",n="";if(e.keyValue){const i={sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top};o=t.getEvaluatedCell(i),r=String(o.value),n=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:n||r,baselineDisplay:Jr(i,o,e.baselineMode),baselineArrow:tn(i,o,e.baselineMode),baselineColor:en(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)=>Un.validateChartDefinition(e,t),transformDefinition:(e,t)=>Un.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Un.getDefinitionFromContextCreation(e),name:r("Scorecard"),sequence:40}),Vn.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,o)=>new yn(e,t,o),getChartRuntime:function(e,t){const o=function(e){const t=gn(e,[],Yr(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,r=e.sectionRule.upperInflectionPoint,n=Number(s.value),a=Number(r.value),l=Number(e.sectionRule.rangeMin),c=Number(e.sectionRule.rangeMax),h=c-l,d=[];if(""!==s.value){const e="number"===s.type?n:l+h*n/100;d.push({value:We(e,l,c),color:i.lowerColor})}if(""!==r.value){const e="number"===r.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===ws.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)=>yn.validateChartDefinition(e,t),transformDefinition:(e,t)=>yn.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>yn.getDefinitionFromContextCreation(e),name:r("Gauge"),sequence:50});const zn=new Ui;zn.add("line",Ri),zn.add("bar",Ri),zn.add("pie",Ri),zn.add("gauge",Ri),zn.add("scorecard",Li);const Bn=new Ui;Oi`
347
+ `;class Fn extends t.Component{static template="o-spreadsheet-LinkEditor";static components={Menu:vn};menuItems=_n.getMenuItems();link=t.useState(this.defaultState);menu=t.useState({isOpen:!1});linkEditorRef=t.useRef("linkEditor");position=hn(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=qi(t);o&&(this.link.url=o.url,this.link.label=o.label,this.link.isUrlEditable=o.isUrlEditable)}getUrlRepresentation(e){return Wi(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();break;case"Escape":this.cancel(),e.stopPropagation()}}}const Dn={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:Fn,cellCorner:"BottomLeft"})};Fn.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const Ln=new Ui;function kn(e){return 8===(e=Mt(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}Ln.add("ErrorToolTip",Xs).add("LinkCell",Cn).add("LinkEditor",Dn).add("FilterMenu",en);class Pn{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 Un(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?ai(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?si(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):{...e}}function Vn(e,t,o,i){let s=!1;const n=[];for(let i in o){let r=o[i];if(r.labelCell){const e=Hn(r.labelCell,t);r.labelCell!==e&&(s=!0,r={...r,labelCell:e})}const a=Hn(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=Hn(r,t);a!==r&&(s=!0,r=a);return{isStale:s,dataSets:n.filter(dt),labelRange:r}}function zn(e,t,o){return o.map((o=>({dataRange:Yo(e,t,o.dataRange),labelCell:o.labelCell?Yo(e,t,o.labelCell):void 0})))}function Bn(e,t,o){return o?Yo(e,t,o):void 0}function Hn(e,t){if(!e)return;const o=t(e);switch(o.changeType){case"NONE":return e;case"REMOVE":return;default:return o.range}}function $n(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(Wn(e,a,o,i?{top:o.top,bottom:o.top,left:o.left,right:o.left}:void 0))}}else s.push(Wn(e,a,r,i?{top:r.top,bottom:r.top,left:r.left,right:r.left}:void 0))}return s}function Wn(e,t,o,i){if(o.left!==o.right&&o.top!==o.bottom)throw new Error(`Zone should be a single column or row: ${ii(o)}`);if(i){const s=ii(o),n=ii(i);return{labelCell:e.getRangeFromSheetXC(t,n),dataRange:e.getRangeFromSheetXC(t,s)}}return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,ii(o))}}function Gn(e,t){const o=t.labelCell?.zone;let i=t.dataRange.zone;if(o){const{numberOfRows:e,numberOfCols:t}=fi(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 qn(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 Zn(e,t){let o;if(e.labelRange){const i=Un(ei(e.labelRange),t);o=i?ii(i):void 0}const i=e.dataSets.map(ei).map((e=>Un(e,t))).filter(dt).map(ii);return{...e,labelRange:o,dataSets:i}}const jn=["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 Yn{graphColorIndex=0;next(){return jn[this.graphColorIndex++%jn.length]}}function Xn(e){return e&&Dt(e)<.3?"#FFFFFF":"#000000"}function Kn(e){if(e.dataSets){const t=void 0!==e.dataSets.find((e=>!Bo.test(e)));if(t)return 33;if(e.dataSets.map(ei).some((e=>e.top!==e.bottom&&xi(e))))return 33}return 0}function Qn(e){if(e.labelRange){if(!Bo.test(e.labelRange||""))return 34}return 0}function Jn(e,t,o){if(!o)return!1;if(!e)return!1;if(!t)return!0;const i=yi(t.dataRange.zone);return!(yi(e.zone)<i)}function er(e,t,o){if(e){if("text"===o||t?.type!==ws.number||e.type!==ws.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 mo(i,e.format);const s=Math.abs(parseFloat(i.toFixed(2))).toLocaleString();return"percentage"===o?s+"%":s}}return""}function tr(e,t,o,i,s){if("text"===t||e?.type!==ws.number||o?.type!==ws.number)return;const n=o.value-e.value;return n>0?i:n<0?s:void 0}function or(e,t,o){if("text"===o||e?.type!==ws.number||t?.type!==ws.number)return"neutral";const i=t.value-e.value;return i>0?"up":i<0?"down":"neutral"}const ir={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")},sr={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")},nr={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")}},rr={Custom:n("Custom")},ar=n("Merged cells are preventing this operation. Unmerge those cells and try again."),lr={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 cr(e,t){if(t.dataRange){const o=t.labelCell?[ii(t.labelCell.zone)]:[],i=pi([ii(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 hr(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 dr(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:Object.keys(i),dataSetsValues:t.map(((e,t)=>({...e,data:Object.values(i).map((e=>e[t]))})))}}function ur(e){return e?e.length>oe?e.substring(0,oe)+"…":e:""}function gr(e,t,o,i){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?mo(s,i):s?.toLocaleString()||"";return o?`${o}: ${n}`:n}}}},data:{labels:t.map(ur),datasets:[]}}}function pr(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<cr(e,t[0]).length;o++)i.formattedValues.push(""),i.values.push("");else if(t[0]){i={formattedValues:Ke(0,cr(e,t[0]).length).map((e=>e.toString())),values:i.formattedValues}}return i}function mr(e,t){for(const o of t){const t=e.getRangeFormats(o.dataRange).find((e=>void 0!==e&&!Eo(e)));if(t)return t}}function fr(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?ur(n.formattedValue):t=`${nr.Series} ${parseInt(i)+1}`}else t=t=`${nr.Series} ${parseInt(i)+1}`;let n=s.dataRange?cr(e,s):[];o.push({data:n,label:t})}return o}function br(e){return 0===e?"origin":e-1}class vr extends Pn{dataSets;labelRange;background;verticalAxisPosition;legendPosition;stacked;aggregated;type="bar";dataSetsHaveTitle;constructor(e,t,o){super(e,t,o),this.dataSets=$n(o,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Xo(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 Zn(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,Kn,Qn)}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=zn(this.sheetId,e,this.dataSets),o=Bn(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new vr(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new vr(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=>Gn(this.getters,e))).filter((e=>""!==e.range&&e.range!==J)),t=qn(this.getters,this.labelRange,Jn(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:kn(this.background||w),fontColor:kn(Xn(this.background)),dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:o,isStale:i}=Vn(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const s=this.getDefinitionWithSpecificDataSets(t,o);return new vr(s,this.sheetId,this.getters)}}function Sr(e){return e.dataRange&&!Bo.test(e.dataRange)?37:0}function Cr(e,t){return t((t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):0),(t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):0))}function Er(e){return e.sectionRule&&Number(e.sectionRule.rangeMin)>=Number(e.sectionRule.rangeMax)?42:0}function wr(e,t){if(""===e)switch(t){case"rangeMin":return 38;case"rangeMax":return 40}return 0}function xr(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 yr extends Pn{dataRange;sectionRule;background;type="gauge";constructor(e,t,o){super(e,t,o),this.dataRange=Xo(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,Sr,e.chainValidations(Cr(wr,e.batchValidations),Cr(xr,e.batchValidations),Er),e.chainValidations((o=xr,(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=Un(ei(e.dataRange),t)),{...e,dataRange:o?ii(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=Bn(this.sheetId,e,this.dataRange),o=this.getDefinitionWithSpecificRanges(t,e);return new yr(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.dataRange,e);return new yr(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=Hn(this.dataRange,e);if(this.dataRange===t)return this;const o=this.getDefinitionWithSpecificRanges(t);return new yr(o,this.sheetId,this.getters)}}const Ir={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},Rr={inSeconds:function(e){return Math.floor(e/Ir.second)},inMinutes:function(e){return Math.floor(e/Ir.minute)},inHours:function(e){return Math.floor(e/Ir.hour)},inDays:function(e){return Math.floor(e/Ir.day)},inMonths:function(e){return Math.floor(e/Ir.month)},inYears:function(e){return Math.floor(e/Ir.year)}},Tr=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function Ar(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=Math.max(...i)-Math.min(...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(Ir.second>=Ir[n]&&Rr.inSeconds(s)<180)return"second";if(Ir.minute>=Ir[n]&&Rr.inMinutes(s)<180)return"minute";if(Ir.hour>=Ir[n]&&Rr.inHours(s)<96)return"hour";if(Ir.day>=Ir[n]&&Rr.inDays(s)<90)return"day";if(Ir.month>=Ir[n]&&Rr.inMonths(s)<36)return"month";return"year"}(e,o),s={};return i&&(s[i]=o),{parser:o,displayFormats:s,unit:i}}class Or extends Pn{dataSets;labelRange;background;verticalAxisPosition;legendPosition;labelsAsText;stacked;aggregated;type="line";dataSetsHaveTitle;cumulative;constructor(e,t,o){super(e,t,o),this.dataSets=$n(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Xo(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,Kn,Qn)}static transformDefinition(e,t){return Zn(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}=Vn(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const s=this.getDefinitionWithSpecificDataSets(t,o);return new Or(s,this.sheetId,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>Gn(this.getters,e))).filter((e=>""!==e.range&&e.range!==J)),t=qn(this.getters,this.labelRange,Jn(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:kn(this.background||w),fontColor:kn(Xn(this.background)),dataSets:e,labelRange:t}}copyForSheetId(e){const t=zn(this.sheetId,e,this.dataSets),o=Bn(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new Or(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Or(t,e,this.getters)}}function Mr(e,t){return _r(e,t)||Fr(e,t)}function Nr(e,t){return function(e,t){return!e.labelsAsText&&_r(e.labelRange,t)}(e,t)?"time":function(e,t){return!e.labelsAsText&&Fr(e.labelRange,t)}(e,t)?"linear":"category"}function _r(e,t){if(!e||!Fr(e,t))return!1;const o=t.getEvaluatedCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}).format;return Boolean(o&&Tr.test(o))}function Fr(e,t){if(!e)return!1;const o=t.getRangeValues(e);return!o.some((e=>isNaN(Number(e))&&e))&&!o.every((e=>!e))}class Dr extends Pn{dataSets;labelRange;background;legendPosition;type="pie";aggregated;dataSetsHaveTitle;constructor(e,t,o){super(e,t,o),this.dataSets=$n(o,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Xo(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 Zn(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,Kn,Qn)}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=zn(this.sheetId,e,this.dataSets),o=Bn(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new Dr(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Dr(t,e,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>Gn(this.getters,e))).filter((e=>""!==e.range&&e.range!==J)),t=qn(this.getters,this.labelRange,Jn(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:kn(this.background||w),fontColor:kn(Xn(this.background)),verticalAxisPosition:"left",dataSets:e,labelRange:t}}updateRanges(e){const{dataSets:t,labelRange:o,isStale:i}=Vn(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const s=this.getDefinitionWithSpecificDataSets(t,o);return new Dr(s,this.sheetId,this.getters)}}function Lr(e,t){const o=[],i=Math.max(...t.map((e=>e.data.length)));for(let t=0;t<=i;t++)o.push(e.next());return o}function kr(e){return e.keyValue&&!Bo.test(e.keyValue)?35:0}function Pr(e){return e.baseline&&!Bo.test(e.baseline)?36:0}class Ur extends Pn{keyValue;baseline;baselineMode;baselineDescr;background;baselineColorUp;baselineColorDown;fontColor;type="scorecard";constructor(e,t,o){super(e,t,o),this.keyValue=Xo(o,t,e.keyValue),this.baseline=Xo(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,kr,Pr)}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=Un(ei(e.baseline),t)),e.keyValue&&(i=Un(ei(e.keyValue),t)),{...e,baseline:o?ii(o):void 0,keyValue:i?ii(i):void 0}}copyForSheetId(e){const t=Bn(this.sheetId,e,this.baseline),o=Bn(this.sheetId,e,this.keyValue),i=this.getDefinitionWithSpecificRanges(t,o,e);return new Ur(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,e);return new Ur(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=Hn(this.baseline,e),o=Hn(this.keyValue,e);if(this.baseline===t&&this.keyValue===o)return this;const i=this.getDefinitionWithSpecificRanges(t,o);return new Ur(i,this.sheetId,this.getters)}}const Vr=new Ui;Vr.add("bar",{match:e=>"bar"===e,createChart:(e,t,o)=>new vr(e,t,o),getChartRuntime:function(e,t){let o=pr(t,e.dataSets,e.labelRange).formattedValues,i=fr(t,e.dataSets);e.dataSetsHaveTitle&&i[0]&&o.length>i[0].data.length&&o.shift(),({labels:o,dataSetsValues:i}=hr(o,i)),e.aggregated&&({labels:o,dataSetsValues:i}=dr(o,i));const s=function(e,t,o){const i=Xn(e.background),s=gr(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?mo(e,o):e?.toLocaleString()||e}}]},e.stacked&&(s.options.scales.xAxes[0].stacked=!0,s.options.scales.yAxes[0].stacked=!0),s}(e,o,mr(t,e.dataSets)),n=new Yn;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)=>vr.validateChartDefinition(e,t),transformDefinition:(e,t)=>vr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>vr.getDefinitionFromContextCreation(e),name:n("Bar"),sequence:10}),Vr.add("line",{match:e=>"line"===e,createChart:(e,t,o)=>new Or(e,t,o),getChartRuntime:function(e,t){const o=Nr(e,t),i=pr(t,e.dataSets,e.labelRange);let s="linear"===o?i.values:i.formattedValues,n=fr(t,e.dataSets);e.dataSetsHaveTitle&&n[0]&&s.length>n[0].data.length&&s.shift(),({labels:s,dataSetsValues:n}=hr(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}=dr(s,n));const r=mr(t,e.dataSets),a=function(e,t,o){const i=Xn(e.background),s=gr(e,t,i,o),n={labels:{fontColor:i,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?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?mo(e,o):e?.toLocaleString()||e}}]},e.stacked&&(s.options.scales.yAxes[0].stacked=!0),s}(e,s,r),l=function(e,t){if(t)return e.getEvaluatedCell({sheetId:t.sheetId,col:t.zone.left,row:t.zone.top}).format}(t,e.labelRange);"time"===o?(a.options.scales.xAxes[0].type="time",a.options.scales.xAxes[0].time=Ar(s,l),a.options.scales.xAxes[0].ticks.maxTicksLimit=15):"linear"===o&&(a.options.scales.xAxes[0].type="linear",a.options.scales.xAxes[0].ticks.callback=e=>mo(e,l),a.options.tooltips.callbacks.title=e=>mo(e[0]?.xLabel||"",l));const c=new Yn;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=c.next();let l=kt(n);if(e.stacked&&(l.a=ae),e.cumulative){let e=0;r=r.map((t=>isNaN(t)?t:(e+=parseFloat(t),e)))}const h={label:i,data:r,lineTension:0,borderColor:n,backgroundColor:Lt(l),pointBackgroundColor:n,fill:!!e.stacked&&br(t)};a.data.datasets.push(h)}return{chartJsConfig:a,background:e.background||w}},validateChartDefinition:(e,t)=>Or.validateChartDefinition(e,t),transformDefinition:(e,t)=>Or.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Or.getDefinitionFromContextCreation(e),name:n("Line"),sequence:20}),Vr.add("pie",{match:e=>"pie"===e,createChart:(e,t,o)=>new Dr(e,t,o),getChartRuntime:function(e,t){let o=pr(t,e.dataSets,e.labelRange).formattedValues,i=fr(t,e.dataSets);e.dataSetsHaveTitle&&i[0]&&o.length>i[0].data.length&&o.shift(),({labels:o,dataSetsValues:i}=hr(o,i)),e.aggregated&&({labels:o,dataSetsValues:i}=dr(o,i));const s=function(e,t,o){const i=Xn(e.background),s=gr(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,mr(t,e.dataSets)),n=new Yn;for(let{label:e,data:t}of i){const o={label:e,data:t,borderColor:"#FFFFFF",backgroundColor:Lr(n,i)};s.data.datasets.push(o)}return{chartJsConfig:s,background:e.background||w}},validateChartDefinition:(e,t)=>Dr.validateChartDefinition(e,t),transformDefinition:(e,t)=>Dr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Dr.getDefinitionFromContextCreation(e),name:n("Pie"),sequence:30}),Vr.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,o)=>new Ur(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:er(i,o,e.baselineMode),baselineArrow:or(i,o,e.baselineMode),baselineColor:tr(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)=>Ur.validateChartDefinition(e,t),transformDefinition:(e,t)=>Ur.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Ur.getDefinitionFromContextCreation(e),name:n("Scorecard"),sequence:40}),Vr.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,o)=>new yr(e,t,o),getChartRuntime:function(e,t){const o=function(e){const t=gr(e,[],Xn(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===ws.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)=>yr.validateChartDefinition(e,t),transformDefinition:(e,t)=>yr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>yr.getDefinitionFromContextCreation(e),name:n("Gauge"),sequence:50});const zr=new Ui;zr.add("line",Ri),zr.add("bar",Ri),zr.add("pie",Ri),zr.add("gauge",Ri),zr.add("scorecard",Li);const Br=new Ui;Oi`
348
348
  .o-chart-container {
349
349
  width: 100%;
350
350
  height: 100%;
351
351
  position: relative;
352
352
  }
353
- `;class Hn 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=zn.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}Hn.props={figure:Object,onFigureDeleted:Function};class $n 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 Wn(e,t){const o=Be(t),i=e.getSheetViewDimension(),s=i.width,r=i.height;if(o.width>s){const e=s/o.width;o.width=s,o.height=o.height*e}if(o.height>r){const e=r/o.height;o.height=r,o.width=o.width*e}return o}$n.props={figure:Object,onFigureDeleted:Function};const Gn=new Ui;function qn(e,t){return{id:"copy",name:r("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 Zn(e,t){return{id:"cut",name:r("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 jn(e,t,o){return{id:"delete",name:r("Delete"),sequence:10,execute:()=>{o.model.dispatch("DELETE_FIGURE",{sheetId:o.model.getters.getActiveSheetId(),id:e}),t()}}}Gn.add("chart",{Component:Hn,SidePanelComponent:"ChartPanel",menuBuilder:function(e,t,o){return Tr([{id:"edit",name:r("Edit"),sequence:1,execute:()=>{o.model.dispatch("SELECT_FIGURE",{id:e}),o.openSidePanel("ChartPanel")}},qn(e,o),Zn(e,o),jn(e,t,o)])}}),Gn.add("image",{Component:$n,keepRatio:!0,minFigSize:20,borderWidth:0,menuBuilder:function(e,t,o){return Tr([qn(e,o),Zn(e,o),{id:"reset_size",name:r("Reset size"),sequence:4,execute:()=>{const t=o.model.getters.getImageSize(e),{height:i,width:s}=Wn(o.model.getters,t);o.model.dispatch("UPDATE_FIGURE",{sheetId:o.model.getters.getActiveSheetId(),id:e,height:i,width:s})}},jn(e,t,o)])}});const Yn=(new Ui).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 Ts.values())Yn.contains(e)||Yn.add(e,Xn);function Xn(e){return[e]}const Kn={MergeIsDestructive:r("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),MergeInFilter:r("You can't merge cells inside of an existing filter.")};function Qn(e,t){const o=Vn.getAll().find((t=>t.match(e.type)));if(!o)throw new Error("Unknown chart type.");return o.transformDefinition(e,t)}function Jn(e,t){let o=e;e.left!==e.right&&(o={...e,left:e.left+1});const i=[ii(o)],r=t.getActiveSheetId(),n=t.getCell({sheetId:r,col:e.left,row:e.top});if(1===yi(e)&&n?.content)return{type:"scorecard",title:"",background:n.style?.fillColor||void 0,keyValue:ii(e),baselineMode:se,baselineColorUp:re,baselineColorDown:ne};let a="";const l=t.getEvaluatedCellsInZone(r,{...o,bottom:o.top}),c=!!l.find((e=>e.type!==ws.empty&&e.type!==ws.number));if(c){const e=l.filter((e=>e.type!==ws.error&&e.type!==ws.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=ii({...e,right:e.left}));const d=o.right===o.left?"none":"top";return Mn(h?t.getRangeFromSheetXC(r,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 ea=[ws.number,ws.error,ws.text,ws.boolean];function ta(e,t,o,i,s){let n=Os.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 r=i.left;r<=i.right;r++){let i=e.model.getters.getMerge({sheetId:t,col:r,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)n=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s});else{const o=e.model.getters.getContiguousZone(t,i);hi(o,i)?n=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s}):e.askConfirmation(r("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,n=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s})}),(()=>{n=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:s})}))}if(n.isCancelledBecause(63)){const{col:t,row:s}=o;e.model.selection.selectZone({cell:{col:t,row:s},zone:i}),e.raiseError(r("Cannot sort. To sort, select only cells or only merges that have the same size."))}}function oa(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause(19)&&e.raiseError(r("This operation is not allowed with multiple selections."))}const ia={filterOverlap:r("You cannot create overlapping filters."),nonContinuousTargets:r("A filter can only be created on a continuous selection."),mergeInFilter:r("You can't create a filter over a range that contains a merge.")};function sa(e,t,o){const i=e.model.dispatch("CREATE_FILTER_TABLE",{target:o,sheetId:t});i.isCancelledBecause(78)?e.raiseError(ia.filterOverlap):i.isCancelledBecause(80)?e.raiseError(ia.mergeInFilter):i.isCancelledBecause(81)&&e.raiseError(ia.nonContinuousTargets)}const ra={wrongPasteSelection:r("This operation is not allowed with multiple selections."),willRemoveExistingMerge:r("This operation is not possible due to a merge. Please remove the merges first than try again."),wrongFigurePasteOption:r("Cannot do a special paste of a figure."),frozenPaneOverlap:r("Cannot paste merged cells over a frozen pane.")};function na(e,t){t.isSuccessful||(t.reasons.includes(20)?e.raiseError(ra.wrongPasteSelection):t.reasons.includes(2)?e.raiseError(ra.willRemoveExistingMerge):t.reasons.includes(22)?e.raiseError(ra.wrongFigurePasteOption):t.reasons.includes(75)&&e.raiseError(ra.frozenPaneOverlap))}function aa(e,t,o){const i=e.model.dispatch("PASTE",{target:t,pasteOption:o});na(e,i)}function la(e,t,o){const i=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,text:o});na(e,i)}function ca(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 ha(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 da(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function ua(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const ga=async e=>pa(e,"onlyValue");async function pa(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?la(e,s,i.content):aa(e,s,t);break;case"notImplemented":e.raiseError(r("Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead."));break;case"permissionDenied":e.raiseError(r("Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings."))}}const ma=(e,t)=>{const o=t.model.getters.getActiveSheetId(),i=t.model.getters.getElementsFromSelection(e),s=t.model.getters.checkElementsIncludeAllVisibleHeaders(o,e,i),r=t.model.getters.checkElementsIncludeAllNonFrozenHeaders(o,e,i);return!s&&!r},fa=e=>{const t=e.model.getters.getActiveRows();let o,i;if(t.size)o=Math.min(...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"})},ba=e=>{const t=e.model.getters.getActiveCols();let o,i;if(t.size)o=Math.min(...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})},va=e=>{const t=e.model.getters.getActiveCols();let o,i;if(t.size)o=Math.max(...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 Sa=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(r("An unexpected error occurred during the image transfer"))}}(e);if(!i)throw new Error("No image provider was given to the environment");const s=Wn(e.model.getters,i.size),n=function(e,t){const{x:o,y:i}=e.getMainViewportCoordinates(),{scrollX:s,scrollY:r}=e.getActiveSheetScrollInfo(),n=e.getSheetViewDimension(),a=e.getVisibleRect(e.getActiveMainViewport()),l=Math.min(a.width,n.width-o),c=Math.min(a.height,n.height-i);return{x:o+s+Math.max(0,(l-t.width)/2),y:i+r+Math.max(0,(c-t.height)/2)}}(e.model.getters,s);e.model.dispatch("CREATE_IMAGE",{sheetId:t,figureId:o,position:n,size:s,definition:i})}},Ca=e=>da(e,"0.00%"),Ea=e=>{let{col:t,row:o}=e.model.getters.getActivePosition();e.model.dispatch("OPEN_CELL_POPOVER",{col:t,row:o,popoverType:"LinkEditor"})},wa=e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,o)},xa=e=>1===e.model.getters.getSelectedZones().length,ya=(e,t)=>{if(!xa(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(),r=hi(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||r)},Ia={name:r("Undo"),description:"Ctrl+Z",execute:e=>e.model.dispatch("REQUEST_UNDO"),isEnabled:e=>e.model.getters.canUndo(),icon:"o-spreadsheet-Icon.UNDO"},Ra={name:r("Redo"),description:"Ctrl+Y",execute:e=>e.model.dispatch("REQUEST_REDO"),isEnabled:e=>e.model.getters.canRedo(),icon:"o-spreadsheet-Icon.REDO"},Ta={name:r("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"},Aa={name:r("Cut"),description:"Ctrl+X",execute:async e=>{oa(e),await e.clipboard.write(e.model.getters.getClipboardContent())},icon:"o-spreadsheet-Icon.CUT"},Oa={name:r("Paste"),description:"Ctrl+V",execute:async e=>pa(e),icon:"o-spreadsheet-Icon.PASTE"},Ma={name:r("Paste special"),isVisible:e=>!e.model.getters.isCutOperation(),icon:"o-spreadsheet-Icon.PASTE"},Na={name:r("Paste value only"),description:"Ctrl+Shift+V",execute:ga},_a={name:r("Paste format only"),execute:e=>aa(e,e.model.getters.getSelectedZones(),"onlyFormat")},Fa={name:r("Find and replace"),description:"Ctrl+H",isReadonlyAllowed:!0,execute:e=>{e.openSidePanel("FindAndReplace",{})},icon:"o-spreadsheet-Icon.FIND_AND_REPLACE"},Da={name:r("Delete values"),execute:e=>e.model.dispatch("DELETE_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},La={name:e=>{if(e.model.getters.getSelectedZones().length>1)return r("Delete rows");let t,o;const i=e.model.getters.getActiveRows();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.top,o=i.bottom}return t===o?r("Delete row %s",(t+1).toString()):r("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=>ma("ROW",e)},ka={...La,isVisible:xa},Pa={name:e=>{if(e.model.getters.getSelectedZones().length>1)return r("Clear rows");let t,o;const i=e.model.getters.getActiveRows();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.top,o=i.bottom}return t===o?r("Clear row %s",(t+1).toString()):r("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()})}},Ua={name:e=>{if(e.model.getters.getSelectedZones().length>1)return r("Delete columns");let t,o;const i=e.model.getters.getActiveCols();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.left,o=i.right}return t===o?r("Delete column %s",Vt(t)):r("Delete columns %s - %s",Vt(t),Vt(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=>ma("COL",e)},Va={...Ua,isVisible:xa},za={name:e=>{if(e.model.getters.getSelectedZones().length>1)return r("Clear columns");let t,o;const i=e.model.getters.getActiveCols();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.left,o=i.right}return t===o?r("Clear column %s",Vt(t)):r("Clear columns %s - %s",Vt(t),Vt(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()})}},Ba={name:r("Delete cells"),isVisible:xa},Ha={name:r("Delete cell and shift up"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});na(e,o)}},$a={name:r("Delete cell and shift left"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});na(e,o)}},Wa={name:r("Merge cells"),isEnabled:e=>!Ga(e),isActive:e=>qa(e),execute:e=>function(e){if(Ga(e))return;const t=e.model.getters.getSelectedZones(),o=[t[t.length-1]],i=e.model.getters.getActiveSheetId();qa(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(80)?e.raiseError(Kn.MergeInFilter):i.isCancelledBecause(3)&&e.askConfirmation(Kn.MergeIsDestructive,(()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:o,force:!0})}))}(e,i,o)}(e),icon:"o-spreadsheet-Icon.MERGE_CELL"};function Ga(e){const t=e.model.getters.getSelectedZones(),{top:o,left:i,right:s,bottom:r}=e.model.getters.getSelectedZone(),{sheetId:n}=e.model.getters.getActivePosition(),{xSplit:a,ySplit:l}=e.model.getters.getPaneDivisions(n);return t.length>1||o===r&&i===s||i<a&&a<=s||o<l&&l<=r}function qa(e){if(!Ga(e)){const t=e.model.getters.getSelectedZones(),{col:o,row:i,sheetId:s}=e.model.getters.getActivePosition(),r=e.model.getters.expandZone(s,wi({col:o,row:i}));return hi(t[0],r)}return!1}var Za=Object.freeze({__proto__:null,undo:Ia,redo:Ra,copy:Ta,cut:Aa,paste:Oa,pasteSpecial:Ma,pasteSpecialValue:Na,pasteSpecialFormat:_a,findAndReplace:Fa,deleteValues:Da,deleteRows:La,deleteRow:ka,clearRows:Pa,deleteCols:Ua,deleteCol:Va,clearCols:za,deleteCells:Ba,deleteCellShiftUp:Ha,deleteCellShiftLeft:$a,mergeCells:Wa});const ja=/(.*?)\((.*?)\)(.*)/,Ya=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function Xa(e,t=""){return function(e,t){let o=e.match(ja),i=o[1].trim();if(!i)throw new Error(`Function argument definition is missing a name: '${e}'.`);let s,r=[],n=!1,a=!1,l=!1;for(let e of o[2].split(",")){const t=e.trim().toUpperCase();let o=Ya.find((e=>t===e));o?r.push(o):"RANGE<ANY>"===t?r.push("RANGE"):"OPTIONAL"===t?n=!0:"REPEATING"===t?a=!0:"LAZY"===t?l=!0:t.startsWith("DEFAULT=")&&(s=e.trim().slice(8))}const c={name:i,description:t,type:r};n&&(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 Ka(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 Qa={description:r("Apply a large number format"),args:[Xa("value (number)",r("The number.")),Xa("unit (string, optional)",r("The formatting unit. Use 'k', 'm', or 'b' to force the unit"))],returns:["NUMBER"],computeFormat:(e,t)=>{const o=Math.abs(Xi(e.value)),i=e.format;if(void 0!==t){const e=t?.value;switch(e){case"k":return Ao(i,1e3,"k");case"m":return Ao(i,1e6,"m");case"b":return Ao(i,1e9,"b");default:throw new Error(r("The formatting unit should be 'k', 'm' or 'b'."))}}return o<1e5?Ao(i,0,""):o<1e8?Ao(i,1e3,"k"):o<1e11?Ao(i,1e6,"m"):Ao(i,1e9,"b")},compute:function(e){return Xi(e)}};var Ja=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:Qa});const el=/^-?[a-z0-9]+$/i,tl={description:r("Absolute value of a number."),args:[Xa("value (number)",r("The number of which to return the absolute value."))],returns:["NUMBER"],compute:function(e){return Math.abs(Xi(e))},isExported:!0},ol={description:r("Inverse cosine of a value, in radians."),args:[Xa("value (number)",r("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Xi(e);return ji((()=>Math.abs(t)<=1),r("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},il={description:r("Inverse hyperbolic cosine of a number."),args:[Xa("value (number)",r("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=Xi(e);return ji((()=>t>=1),r("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},sl={description:r("Inverse cotangent of a value."),args:[Xa("value (number)",r("The value for which to calculate the inverse cotangent."))],returns:["NUMBER"],compute:function(e){const t=Xi(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},rl={description:r("Inverse hyperbolic cotangent of a value."),args:[Xa("value (number)",r("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=Xi(e);return ji((()=>Math.abs(t)>1),r("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},nl={description:r("Inverse sine of a value, in radians."),args:[Xa("value (number)",r("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Xi(e);return ji((()=>Math.abs(t)<=1),r("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},al={description:r("Inverse hyperbolic sine of a number."),args:[Xa("value (number)",r("The value for which to calculate the inverse hyperbolic sine."))],returns:["NUMBER"],compute:function(e){return Math.asinh(Xi(e))},isExported:!0},ll={description:r("Inverse tangent of a value, in radians."),args:[Xa("value (number)",r("The value for which to calculate the inverse tangent."))],returns:["NUMBER"],compute:function(e){return Math.atan(Xi(e))},isExported:!0},cl={description:r("Angle from the X axis to a point (x,y), in radians."),args:[Xa("x (number)",r("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")),Xa("y (number)",r("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=Xi(e),i=Xi(t);return ji((()=>0!==o||0!==i),r("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(i,o)},isExported:!0},hl={description:r("Inverse hyperbolic tangent of a number."),args:[Xa("value (number)",r("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive."))],returns:["NUMBER"],compute:function(e){const t=Xi(e);return ji((()=>Math.abs(t)<1),r("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},dl={description:r("Rounds number up to nearest multiple of factor."),args:[Xa("value (number)",r("The value to round up to the nearest integer multiple of factor.")),Xa("factor (number, default=1)",r("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){const o=Xi(e),i=Xi(t);return ji((()=>i>=0||o<=0),r("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},ul={description:r("Rounds number up to nearest multiple of factor."),args:[Xa("number (number)",r("The value to round up to the nearest integer multiple of significance.")),Xa("significance (number, default=1)",r("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),Xa("mode (number, default=0)",r("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=Xi(t);if(0===i)return 0;const s=Xi(e);if(i=Math.abs(i),s>=0)return Math.ceil(s/i)*i;return 0===Xi(o)?-Math.floor(Math.abs(s)/i)*i:-Math.ceil(Math.abs(s)/i)*i},isExported:!0},gl={description:r("Rounds number up to nearest multiple of factor."),args:[Xa("number (number)",r("The value to round up to the nearest integer multiple of significance.")),Xa("significance (number, default=1)",r("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){return ul.compute(e,t,0)},isExported:!0},pl={description:r("Cosine of an angle provided in radians."),args:[Xa("angle (number)",r("The angle to find the cosine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.cos(Xi(e))},isExported:!0},ml={description:r("Hyperbolic cosine of any real number."),args:[Xa("value (number)",r("Any real value to calculate the hyperbolic cosine of."))],returns:["NUMBER"],compute:function(e){return Math.cosh(Xi(e))},isExported:!0},fl={description:r("Cotangent of an angle provided in radians."),args:[Xa("angle (number)",r("The angle to find the cotangent of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Xi(e);return ji((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},bl={description:r("Hyperbolic cotangent of any real number."),args:[Xa("value (number)",r("Any real value to calculate the hyperbolic cotangent of."))],returns:["NUMBER"],compute:function(e){const t=Xi(e);return ji((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},vl={description:r("Number of empty values."),args:[Xa("value1 (any, range)",r("The first value or range in which to count the number of blanks.")),Xa("value2 (any, range, repeating)",r("Additional values or ranges in which to count the number of blanks."))],returns:["NUMBER"],compute:function(...e){return hs(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},Sl={description:r("A conditional count across a range."),args:[Xa("range (range)",r("The range that is tested against criterion.")),Xa("criterion (string)",r("The pattern or test to apply to range."))],returns:["NUMBER"],compute:function(...e){let t=0;return fs(e,((e,o)=>{t+=1})),t},isExported:!0},Cl={description:r("Count values depending on multiple criteria."),args:[Xa("criteria_range1 (range)",r("The range to check against criterion1.")),Xa("criterion1 (string)",r("The pattern or test to apply to criteria_range1.")),Xa("criteria_range2 (any, range, repeating)",r("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.")),Xa("criterion2 (string, repeating)",r("Additional criteria to check."))],returns:["NUMBER"],compute:function(...e){let t=0;return fs(e,((e,o)=>{t+=1})),t},isExported:!0};function El(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const wl={description:r("Counts number of unique values in a range."),args:[Xa("value1 (any, range)",r("The first value or range to consider for uniqueness.")),Xa("value2 (any, range, repeating)",r("Additional values or ranges to consider for uniqueness."))],returns:["NUMBER"],compute:function(...e){return hs(e,((e,t)=>El(t)?e.add(t):e),new Set).size}},xl={description:r("Counts number of unique values in a range, filtered by a set of criteria."),args:[Xa("range (range)",r("The range of cells from which the number of unique values will be counted.")),Xa("criteria_range1 (range)",r("The range of cells over which to evaluate criterion1.")),Xa("criterion1 (string)",r("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),Xa("criteria_range2 (any, range, repeating)",r("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.")),Xa("criterion2 (string, repeating)",r("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=new Set;return fs(t,((t,i)=>{const s=e[t][i];El(s)&&o.add(s)})),o.size}},yl={description:r("Cosecant of an angle provided in radians."),args:[Xa("angle (number)",r("The angle to find the cosecant of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Xi(e);return ji((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},Il={description:r("Hyperbolic cosecant of any real number."),args:[Xa("value (number)",r("Any real value to calculate the hyperbolic cosecant of."))],returns:["NUMBER"],compute:function(e){const t=Xi(e);return ji((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},Rl={description:r("Converts from another base to decimal."),args:[Xa("value (string)",r("The number to convert.")),Xa(",base (number)",r("The base to convert the value from."))],returns:["NUMBER"],compute:function(e,t){let o=Xi(t);o=Math.floor(o),ji((()=>2<=o&&o<=36),r("The base (%s) must be between 2 and 36 inclusive.",o.toString()));const i=es(e);if(""===i)return 0;ji((()=>!!el.test(i)),r("The value (%s) must be a valid base %s representation.",i,o.toString()));const s=parseInt(i,o);return ji((()=>!isNaN(s)),r("The value (%s) must be a valid base %s representation.",i,o.toString())),s},isExported:!0},Tl={description:r("Converts an angle value in radians to degrees."),args:[Xa("angle (number)",r("The angle to convert from radians to degrees."))],returns:["NUMBER"],compute:function(e){return 180*Xi(e)/Math.PI},isExported:!0},Al={description:r("Euler's number, e (~2.718) raised to a power."),args:[Xa("value (number)",r("The exponent to raise e."))],returns:["NUMBER"],compute:function(e){return Math.exp(Xi(e))},isExported:!0},Ol={description:r("Rounds number down to nearest multiple of factor."),args:[Xa("value (number)",r("The value to round down to the nearest integer multiple of factor.")),Xa("factor (number, default=1)",r("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){const o=Xi(e),i=Xi(t);return ji((()=>i>=0||o<=0),r("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},Ml={description:r("Rounds number down to nearest multiple of factor."),args:[Xa("number (number)",r("The value to round down to the nearest integer multiple of significance.")),Xa("significance (number, default=1)",r("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),Xa("mode (number, default=0)",r("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=Xi(t);if(0===i)return 0;const s=Xi(e);if(i=Math.abs(i),s>=0)return Math.floor(s/i)*i;return 0===Xi(o)?-Math.ceil(Math.abs(s)/i)*i:-Math.floor(Math.abs(s)/i)*i},isExported:!0},Nl={description:r("Rounds number down to nearest multiple of factor."),args:[Xa("number (number)",r("The value to round down to the nearest integer multiple of significance.")),Xa("significance (number, default=1)",r("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){return Ml.compute(e,t,0)},isExported:!0},_l={description:r("Whether the provided value is even."),args:[Xa("value (number)",r("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Ki(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},Fl={description:r("Rounds number up to nearest multiple of factor."),args:[Xa("number (number)",r("The value to round up to the nearest integer multiple of significance.")),Xa("significance (number, default=1)",r("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=1){return ul.compute(e,t,0)},isExported:!0},Dl={description:r("Whether the provided value is even."),args:[Xa("value (number)",r("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Ki(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},Ll={description:r("The logarithm of a number, base e (euler's number)."),args:[Xa("value (number)",r("The value for which to calculate the logarithm, base e."))],returns:["NUMBER"],compute:function(e){const t=Xi(e);return ji((()=>t>0),r("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},kl={description:r("Modulo (remainder) operator."),args:[Xa("dividend (number)",r("The number to be divided to find the remainder.")),Xa("divisor (number)",r("The number to divide by."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){const o=Xi(t);ji((()=>0!==o),r("The divisor must be different from 0."));const i=Xi(e)%o;return i>0&&o<0||i<0&&o>0?i+o:i},isExported:!0},Pl={description:r("Rounds a number up to the nearest odd integer."),args:[Xa("value (number)",r("The value to round to the next greatest odd number."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e){const t=Xi(e);let o=Math.ceil(Math.abs(t));return o=1&o?o:o+1,t<0?-o:o},isExported:!0},Ul={description:r("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},Vl={description:r("A number raised to a power."),args:[Xa("base (number)",r("The number to raise to the exponent power.")),Xa("exponent (number)",r("The exponent to raise base to."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){const o=Xi(e),i=Xi(t);return ji((()=>o>=0||Number.isInteger(i)),r("The exponent (%s) must be an integer when the base is negative.",i.toString())),Math.pow(o,i)},isExported:!0},zl={description:r("Result of multiplying a series of numbers together."),args:[Xa("factor1 (number, range<number>)",r("The first number or range to calculate for the product.")),Xa("factor2 (number, range<number>, repeating)",r("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*=Ki(i),t+=1);return 0===t?0:o},isExported:!0},Bl={description:r("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},Hl={description:r("Random integer between two values, inclusive."),args:[Xa("low (number)",r("The low end of the random range.")),Xa("high (number)",r("The high end of the random range."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){let o=Xi(e);Number.isInteger(o)||(o=Math.ceil(o));let i=Xi(t);return Number.isInteger(i)||(i=Math.floor(i)),ji((()=>o<=i),r("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},$l={description:r("Rounds a number according to standard rules."),args:[Xa("value (number)",r("The value to round to places number of places.")),Xa("places (number, default=0)",r("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Xi(e);let i=Xi(t);const s=Math.abs(o);let r;return 0===i?r=Math.round(s):(Number.isInteger(i)||(i=Math.trunc(i)),r=Math.round(s*Math.pow(10,i))/Math.pow(10,i)),o>=0?r:-r},isExported:!0},Wl={description:r("Rounds down a number."),args:[Xa("value (number)",r("The value to round to places number of places, always rounding down.")),Xa("places (number, default=0)",r("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Xi(e);let i=Xi(t);const s=Math.abs(o);let r;return 0===i?r=Math.floor(s):(Number.isInteger(i)||(i=Math.trunc(i)),r=Math.floor(s*Math.pow(10,i))/Math.pow(10,i)),o>=0?r:-r},isExported:!0},Gl={description:r("Rounds up a number."),args:[Xa("value (number)",r("The value to round to places number of places, always rounding up.")),Xa("places (number, default=0)",r("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t=0){const o=Xi(e);let i=Xi(t);const s=Math.abs(o);let r;return 0===i?r=Math.ceil(s):(Number.isInteger(i)||(i=Math.trunc(i)),r=Math.ceil(s*Math.pow(10,i))/Math.pow(10,i)),o>=0?r:-r},isExported:!0},ql={description:r("Secant of an angle provided in radians."),args:[Xa("angle (number)",r("The angle to find the secant of, in radians."))],returns:["NUMBER"],compute:function(e){return 1/Math.cos(Xi(e))},isExported:!0},Zl={description:r("Hyperbolic secant of any real number."),args:[Xa("value (number)",r("Any real value to calculate the hyperbolic secant of."))],returns:["NUMBER"],compute:function(e){return 1/Math.cosh(Xi(e))},isExported:!0},jl={description:r("Sine of an angle provided in radians."),args:[Xa("angle (number)",r("The angle to find the sine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.sin(Xi(e))},isExported:!0},Yl={description:r("Hyperbolic sine of any real number."),args:[Xa("value (number)",r("Any real value to calculate the hyperbolic sine of."))],returns:["NUMBER"],compute:function(e){return Math.sinh(Xi(e))},isExported:!0},Xl={description:r("Positive square root of a positive number."),args:[Xa("value (number)",r("The number for which to calculate the positive square root."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e){const t=Xi(e);return ji((()=>t>=0),r("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},Kl={description:r("Sum of a series of numbers and/or cells."),args:[Xa("value1 (number, range<number>)",r("The first number or range to add together.")),Xa("value2 (number, range<number>, repeating)",r("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 ds(e,((e,t)=>e+t),0)},isExported:!0},Ql={description:r("A conditional sum across a range."),args:[Xa("criteria_range (range)",r("The range which is tested against criterion.")),Xa("criterion (string)",r("The pattern or test to apply to range.")),Xa("sum_range (range, default=criteria_range)",r("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 fs([e,t],((e,t)=>{const s=o[e][t];"number"==typeof s&&(i+=s)})),i},isExported:!0},Jl={description:r("Sums a range depending on multiple criteria."),args:[Xa("sum_range (range)",r("The range to sum.")),Xa("criteria_range1 (range)",r("The range to check against criterion1.")),Xa("criterion1 (string)",r("The pattern or test to apply to criteria_range1.")),Xa("criteria_range2 (any, range, repeating)",r("Additional ranges to check.")),Xa("criterion2 (string, repeating)",r("Additional criteria to check."))],returns:["NUMBER"],compute:function(e,...t){let o=0;return fs(t,((t,i)=>{const s=e[t][i];"number"==typeof s&&(o+=s)})),o},isExported:!0},ec={description:r("Tangent of an angle provided in radians."),args:[Xa("angle (number)",r("The angle to find the tangent of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.tan(Xi(e))},isExported:!0},tc={description:r("Hyperbolic tangent of any real number."),args:[Xa("value (number)",r("Any real value to calculate the hyperbolic tangent of."))],returns:["NUMBER"],compute:function(e){return Math.tanh(Xi(e))},isExported:!0},oc={description:r("Truncates a number."),args:[Xa("value (number)",r("The value to be truncated.")),Xa("places (number, default=0)",r("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=Xi(e);let i=Xi(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 ic=Object.freeze({__proto__:null,ABS:tl,ACOS:ol,ACOSH:il,ACOT:sl,ACOTH:rl,ASIN:nl,ASINH:al,ATAN:ll,ATAN2:cl,ATANH:hl,CEILING:dl,CEILING_MATH:ul,CEILING_PRECISE:gl,COS:pl,COSH:ml,COT:fl,COTH:bl,COUNTBLANK:vl,COUNTIF:Sl,COUNTIFS:Cl,COUNTUNIQUE:wl,COUNTUNIQUEIFS:xl,CSC:yl,CSCH:Il,DECIMAL:Rl,DEGREES:Tl,EXP:Al,FLOOR:Ol,FLOOR_MATH:Ml,FLOOR_PRECISE:Nl,ISEVEN:_l,ISO_CEILING:Fl,ISODD:Dl,LN:Ll,MOD:kl,ODD:Pl,PI:Ul,POWER:Vl,PRODUCT:zl,RAND:Bl,RANDBETWEEN:Hl,ROUND:$l,ROUNDDOWN:Wl,ROUNDUP:Gl,SEC:ql,SECH:Zl,SIN:jl,SINH:Yl,SQRT:Xl,SUM:Kl,SUMIF:Ql,SUMIFS:Jl,TAN:ec,TANH:tc,TRUNC:oc});function sc(e,t,o){let i=[],s=[],n=0,a=0;as([e],(e=>{i.push(e),n+=1})),as([t],(e=>{s.push(e),a+=1})),ji((()=>n===a),r("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",n.toString(),a.toString()));let l=0,c=0,h=0;for(let e=0;e<n;e++){const t=i[e],o=s[e];"number"==typeof t&&"number"==typeof o&&(l+=1,c+=t,h+=o)}ji((()=>0!==l&&(!o||1!==l)),r("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<n;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 rc(e,t,o){let i=0,s=0;const n=o?us:ds;s=n(e,((e,t)=>(i+=1,e+t)),0),ji((()=>0!==i&&(!t||1!==i)),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const a=s/i;return n(e,((e,t)=>e+Math.pow(t-a,2)),0)/(i-(t?1:0))}function nc(e,t,o){const i=Xi(t);ji((()=>o?0<=i&&i<=1:0<i&&i<1),r("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let s,n=[],a=0;return as(e,(e=>{"number"==typeof e&&(s=Ss(n,e,"nextSmaller","asc",n.length,((e,t)=>e[t])),n.splice(s+1,0,e),a++)})),ji((()=>0!==a),r("[[FUNCTION_NAME]] has no valid input data.")),o||ji((()=>1/(a+1)<=i&&i<=a/(a+1)),r("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),ro(n,i,o)}const ac={description:r("Average magnitude of deviations from mean."),args:[Xa("value1 (number, range<number>)",r("The first value or range of the sample.")),Xa("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){let t=0;const o=ds(e,((e,o)=>(t+=1,e+o)),0);ji((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const i=o/t;return ds(e,((e,t)=>e+Math.abs(i-t)),0)/t},isExported:!0},lc={description:r("Numerical average value in a dataset, ignoring text."),args:[Xa("value1 (number, range<number>)",r("The first value or range to consider when calculating the average value.")),Xa("value2 (number, range<number>, repeating)",r("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=ds(e,((e,o)=>(t+=1,e+o)),0);return ji((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/t},isExported:!0},cc=r("[[FUNCTION_NAME]] has mismatched range sizes."),hc=r("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),dc={description:r("Weighted average."),args:[Xa("values (number, range<number>)",r("Values to average.")),Xa("weights (number, range<number>)",r("Weights for each corresponding value.")),Xa("additional_values (number, range<number>, repeating)",r("Additional values to average.")),Xa("additional_weights (number, range<number>, repeating)",r("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;ji((()=>e.length%2==0),r("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let n=0;n<e.length-1;n+=2)if(t=e[n],o=e[n+1],Array.isArray(t)){ji((()=>Array.isArray(o)),cc);let e=t.length,n=t[0].length;ji((()=>e===o.length&&n===o[0].length),cc);for(let a=0;a<e;a++)for(let e=0;e<n;e++){let n=t[a][e],l=o[a][e],c="number"==typeof n,h="number"==typeof l;ji((()=>c===h),r("[[FUNCTION_NAME]] expects number values.")),h&&(ji((()=>l>=0),hc),i+=n*l,s+=l)}}else o=Xi(o),t=Xi(t),ji((()=>o>=0),hc),i+=t*o,s+=o;return ji((()=>0!==s),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/s}},uc={description:r("Numerical average value in a dataset."),args:[Xa("value1 (number, range<number>)",r("The first value or range to consider when calculating the average value.")),Xa("value2 (number, range<number>, repeating)",r("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=us(e,((e,o)=>(t+=1,e+o)),0);return ji((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/t},isExported:!0},gc={description:r("Average of values depending on criteria."),args:[Xa("criteria_range (range)",r("The range to check against criterion.")),Xa("criterion (string)",r("The pattern or test to apply to criteria_range.")),Xa("average_range (range, default=criteria_range)",r("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 fs([e,t],((t,r)=>{const n=(o||e)[t][r];"number"==typeof n&&(i+=1,s+=n)})),ji((()=>0!==i),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/i},isExported:!0},pc={description:r("Average of values depending on multiple criteria."),args:[Xa("average_range (range)",r("The range to average.")),Xa("criteria_range1 (range)",r("The range to check against criterion1.")),Xa("criterion1 (string)",r("The pattern or test to apply to criteria_range1.")),Xa("criteria_range2 (any, range, repeating)",r("Additional criteria_range and criterion to check.")),Xa("criterion2 (string, repeating)",r("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=0,i=0;return fs(t,((t,s)=>{const r=e[t][s];"number"==typeof r&&(o+=1,i+=r)})),ji((()=>0!==o),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/o},isExported:!0},mc={description:r("The number of numeric values in dataset."),args:[Xa("value1 (number, range<number>)",r("The first value or range to consider when counting.")),Xa("value2 (number, range<number>, repeating)",r("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||oo(o)||Te(o))&&(t+=1);return t},isExported:!0},fc={description:r("The number of values in a dataset."),args:[Xa("value1 (any, range)",r("The first value or range to consider when counting.")),Xa("value2 (any, range, repeating)",r("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){return hs(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},bc={description:r("The covariance of a dataset."),args:[Xa("data_y (any, range)",r("The range representing the array or matrix of dependent data.")),Xa("data_x (any, range)",r("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return sc(e,t,!1)},isExported:!0},vc={description:r("The covariance of a dataset."),args:[Xa("data_y (any, range)",r("The range representing the array or matrix of dependent data.")),Xa("data_x (any, range)",r("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return sc(e,t,!1)},isExported:!0},Sc={description:r("The sample covariance of a dataset."),args:[Xa("data_y (any, range)",r("The range representing the array or matrix of dependent data.")),Xa("data_x (any, range)",r("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return sc(e,t,!0)},isExported:!0},Cc={description:r("Nth largest element from a data set."),args:[Xa("data (any, range)",r("Array or range containing the dataset to consider.")),Xa("n (number)",r("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(Xi(t));let i,s=[],n=0;as([e],(e=>{"number"==typeof e&&(i=Ss(s,e,"nextSmaller","asc",s.length,((e,t)=>e[t])),s.splice(i+1,0,e),n++,n>o&&(s.shift(),n--))}));const a=s.shift();return ji((()=>void 0!==a),r("[[FUNCTION_NAME]] has no valid input data.")),ji((()=>n>=o),r("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",o.toString())),a},isExported:!0},Ec={description:r("Maximum value in a numeric dataset."),args:[Xa("value1 (number, range<number>)",r("The first value or range to consider when calculating the maximum value.")),Xa("value2 (number, range<number>, repeating)",r("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=ds(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},wc={description:r("Maximum numeric value in a dataset."),args:[Xa("value1 (any, range)",r("The first value or range to consider when calculating the maximum value.")),Xa("value2 (any, range, repeating)",r("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=us(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},xc={description:r("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:[Xa("range (range)",r("The range of cells from which the maximum will be determined.")),Xa("criteria_range1 (range)",r("The range of cells over which to evaluate criterion1.")),Xa("criterion1 (string)",r("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),Xa("criteria_range2 (any, range, repeating)",r("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.")),Xa("criterion2 (string, repeating)",r("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=-1/0;return fs(t,((t,i)=>{const s=e[t][i];"number"==typeof s&&(o=o<s?s:o)})),o===-1/0?0:o},isExported:!0},yc={description:r("Median value in a numeric dataset."),args:[Xa("value1 (any, range)",r("The first value or range to consider when calculating the median value.")),Xa("value2 (any, range, repeating)",r("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 ls(e,(e=>{t.push(e)})),nc(t,.5,!0)},isExported:!0},Ic={description:r("Minimum value in a numeric dataset."),args:[Xa("value1 (number, range<number>)",r("The first value or range to consider when calculating the minimum value.")),Xa("value2 (number, range<number>, repeating)",r("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=ds(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},Rc={description:r("Minimum numeric value in a dataset."),args:[Xa("value1 (number, range<number>)",r("The first value or range to consider when calculating the minimum value.")),Xa("value2 (number, range<number>, repeating)",r("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=us(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},Tc={description:r("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:[Xa("range (range)",r("The range of cells from which the minimum will be determined.")),Xa("criteria_range1 (range)",r("The range of cells over which to evaluate criterion1.")),Xa("criterion1 (string)",r("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),Xa("criteria_range2 (any, range, repeating)",r("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.")),Xa("criterion2 (string, repeating)",r("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=1/0;return fs(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:r("Value at a given percentile of a dataset."),args:[Xa("data (any, range)",r("The array or range containing the dataset to consider.")),Xa("percentile (number)",r("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 Mc.compute(e,t)},isExported:!0},Oc={description:r("Value at a given percentile of a dataset exclusive of 0 and 1."),args:[Xa("data (any, range)",r("The array or range containing the dataset to consider.")),Xa("percentile (number)",r("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 nc([e],t,!1)},isExported:!0},Mc={description:r("Value at a given percentile of a dataset."),args:[Xa("data (any, range)",r("The array or range containing the dataset to consider.")),Xa("percentile (number)",r("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 nc([e],t,!0)},isExported:!0},Nc={description:r("Value nearest to a specific quartile of a dataset."),args:[Xa("data (any, range)",r("The array or range containing the dataset to consider.")),Xa("quartile_number (number)",r("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return Fc.compute(e,t)},isExported:!0},_c={description:r("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:[Xa("data (any, range)",r("The array or range containing the dataset to consider.")),Xa("quartile_number (number)",r("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 nc([e],.25*Math.trunc(Xi(t)),!1)},isExported:!0},Fc={description:r("Value nearest to a specific quartile of a dataset."),args:[Xa("data (any, range)",r("The array or range containing the dataset to consider.")),Xa("quartile_number (number)",r("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>Array.isArray(e)?e[0][0]?.format:e?.format,compute:function(e,t){return nc([e],.25*Math.trunc(Xi(t)),!0)},isExported:!0},Dc={description:r("Nth smallest element in a data set."),args:[Xa("data (any, range)",r("The array or range containing the dataset to consider.")),Xa("n (number)",r("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(Xi(t));let i,s=[],n=0;as([e],(e=>{"number"==typeof e&&(i=Ss(s,e,"nextSmaller","asc",s.length,((e,t)=>e[t])),s.splice(i+1,0,e),n++,n>o&&(s.pop(),n--))}));const a=s.pop();return ji((()=>void 0!==a),r("[[FUNCTION_NAME]] has no valid input data.")),ji((()=>n>=o),r("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",o.toString())),a},isExported:!0},Lc={description:r("Standard deviation."),args:[Xa("value1 (number, range<number>)",r("The first value or range of the sample.")),Xa("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Bc.compute(...e))},isExported:!0},kc={description:r("Standard deviation of entire population."),args:[Xa("value1 (number, range<number>)",r("The first value or range of the population.")),Xa("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Hc.compute(...e))},isExported:!0},Pc={description:r("Standard deviation."),args:[Xa("value1 (number, range<number>)",r("The first value or range of the sample.")),Xa("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt($c.compute(...e))},isExported:!0},Uc={description:r("Standard deviation of sample (text as 0)."),args:[Xa("value1 (number, range<number>)",r("The first value or range of the sample.")),Xa("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Wc.compute(...e))},isExported:!0},Vc={description:r("Standard deviation of entire population."),args:[Xa("value1 (number, range<number>)",r("The first value or range of the population.")),Xa("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Gc.compute(...e))},isExported:!0},zc={description:r("Standard deviation of entire population (text as 0)."),args:[Xa("value1 (number, range<number>)",r("The first value or range of the population.")),Xa("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(qc.compute(...e))},isExported:!0},Bc={description:r("Variance."),args:[Xa("value1 (number, range<number>)",r("The first value or range of the sample.")),Xa("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return rc(e,!0,!1)},isExported:!0},Hc={description:r("Variance of entire population."),args:[Xa("value1 (number, range<number>)",r("The first value or range of the population.")),Xa("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return rc(e,!1,!1)},isExported:!0},$c={description:r("Variance."),args:[Xa("value1 (number, range<number>)",r("The first value or range of the sample.")),Xa("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return rc(e,!0,!1)},isExported:!0},Wc={description:r("Variance of sample (text as 0)."),args:[Xa("value1 (number, range<number>)",r("The first value or range of the sample.")),Xa("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return rc(e,!0,!0)},isExported:!0},Gc={description:r("Variance of entire population."),args:[Xa("value1 (number, range<number>)",r("The first value or range of the population.")),Xa("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return rc(e,!1,!1)},isExported:!0},qc={description:r("Variance of entire population (text as 0)."),args:[Xa("value1 (number, range<number>)",r("The first value or range of the population.")),Xa("value2 (number, range<number>, repeating)",r("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return rc(e,!1,!0)},isExported:!0};var Zc=Object.freeze({__proto__:null,AVEDEV:ac,AVERAGE:lc,AVERAGE_WEIGHTED:dc,AVERAGEA:uc,AVERAGEIF:gc,AVERAGEIFS:pc,COUNT:mc,COUNTA:fc,COVAR:bc,COVARIANCE_P:vc,COVARIANCE_S:Sc,LARGE:Cc,MAX:Ec,MAXA:wc,MAXIFS:xc,MEDIAN:yc,MIN:Ic,MINA:Rc,MINIFS:Tc,PERCENTILE:Ac,PERCENTILE_EXC:Oc,PERCENTILE_INC:Mc,QUARTILE:Nc,QUARTILE_EXC:_c,QUARTILE_INC:Fc,SMALL:Dc,STDEV:Lc,STDEV_P:kc,STDEV_S:Pc,STDEVA:Uc,STDEVP:Vc,STDEVPA:zc,VAR:Bc,VAR_P:Hc,VAR_S:$c,VARA:Wc,VARP:Gc,VARPA:qc});function jc(e,t,o){const i=new Map,s=e.length;for(let t=s-1;t>=0;t--)i.set(es(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(r("The field must be a number or a string"));let n;if("number"==typeof t){if(n=Math.trunc(t)-1,n<0||s-1<n)throw new Error(r("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=es(t).toUpperCase();if(n=i.get(e)??-1,-1===n)throw new Error(r("The field (%s) must be one of %s.",es(t),[...i.keys()].toString()))}const a=o[0].length;if(a<2)throw new Error(r("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=[],r=!0;for(let n=0;n<o.length;n++){const a=es(o[n][0]).toUpperCase(),l=i.get(a),h=o[n][t];if(void 0!==h){if(void 0===l){r=!1;break}s.push([e[l].slice(1,c)]),s.push(h)}}if(r){if(!(s.length>0)){l=new Set(Array(c-1).keys());break}fs(s,((e,t)=>{l.add(t)}),!0)}}const h=e[n];return[...l].map((e=>h[e+1]))}const Yc=[Xa("database (range)",r("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.")),Xa("field (any)",r("Indicates which column in database contains the values to be extracted and operated on.")),Xa("criteria (range)",r("An array or range containing zero or more criteria to filter the database values by before operating."))],Xc={description:r("Average of a set of values from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return lc.compute([i])},isExported:!0},Kc={description:r("Counts values from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return mc.compute([i])},isExported:!0},Qc={description:r("Counts values and text from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return fc.compute([i])},isExported:!0},Jc={description:r("Single value from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return ji((()=>1===i.length),r("More than one match found in DGET evaluation.")),i[0]},isExported:!0},eh={description:r("Maximum of values from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return Ec.compute([i])},isExported:!0},th={description:r("Minimum of values from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return Ic.compute([i])},isExported:!0},oh={description:r("Product of values from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return zl.compute([i])},isExported:!0},ih={description:r("Standard deviation of population sample from table."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return Lc.compute([i])},isExported:!0},sh={description:r("Standard deviation of entire population from table."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return Vc.compute([i])},isExported:!0},rh={description:r("Sum of values from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return Kl.compute([i])},isExported:!0},nh={description:r("Variance of population sample from table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return Bc.compute([i])},isExported:!0},ah={description:r("Variance of a population from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return Gc.compute([i])},isExported:!0};var lh=Object.freeze({__proto__:null,DAVERAGE:Xc,DCOUNT:Kc,DCOUNTA:Qc,DGET:Jc,DMAX:eh,DMIN:th,DPRODUCT:oh,DSTDEV:ih,DSTDEVP:sh,DSUM:rh,DVAR:nh,DVARP:ah});var ch;!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"}(ch||(ch={}));const hh={description:r("Converts year/month/day into a date."),args:[Xa("year (number)",r("The year component of the date.")),Xa("month (number)",r("The month component of the date.")),Xa("day (number)",r("The day component of the date."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o){let i=Math.trunc(Xi(e));const s=Math.trunc(Xi(t)),n=Math.trunc(Xi(o));ji((()=>0<=i&&i<=9999),r("The year (%s) must be between 0 and 9999 inclusive.",i.toString())),i<1900&&(i+=1900);const a=Me(new be(i,s-1,n));return ji((()=>a>=0),r("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),a},isExported:!0},dh={description:r("Calculates the number of days, months, or years between two dates."),args:[Xa("start_date (date)",r("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.")),Xa("end_date (date)",r("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.")),Xa("unit (string)",r('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=es(o).toUpperCase();ji((()=>Object.values(ch).includes(i)),((e,t)=>{const o=e.map((e=>`'${e}'`)).join(", ");return r("The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.",t,o)})(Object.values(ch),es(o)));const s=Math.trunc(Xi(e)),n=Math.trunc(Xi(t)),a=Oe(s),l=Oe(n);switch(ji((()=>n>=s),r("start_date (%s) should be on or before end_date (%s).",a.toLocaleDateString(),l.toLocaleDateString())),i){case ch.WHOLE_YEARS:return Ue(a,l);case ch.WHOLE_MONTHS:return ke(a,l);case ch.WHOLE_DAYS:return Pe(a,l);case ch.MONTH_WITHOUT_WHOLE_YEARS:return ke(a,l)-12*Ue(a,l);case ch.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 ch.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR:{if(function(e,t){return Le(e,t,1)<1}(s,n))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},uh={description:r("Converts a date string to a date value."),args:[Xa("date_string (string)",r("The string representing the date."))],returns:["NUMBER"],compute:function(e){const t=es(e),o=Te(t);return ji((()=>null!==o),r("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(o.value)},isExported:!0},gh={description:r("Day of the month that a specific date falls on."),args:[Xa("date (string)",r("The date from which to extract the day."))],returns:["NUMBER"],compute:function(e){return rs(e).getDate()},isExported:!0},ph={description:r("Number of days between two dates."),args:[Xa("end_date (date)",r("The end of the date range.")),Xa("start_date (date)",r("The start of the date range."))],returns:["NUMBER"],compute:function(e,t){const o=rs(e),i=rs(t),s=o.getTime()-i.getTime();return Math.round(s/Se)},isExported:!0},mh={description:r("Number of days between two dates on a 360-day year (months of 30 days)."),args:[Xa("start_date (date)",r("The start date to consider in the calculation.")),Xa("end_date (date)",r("The end date to consider in the calculation.")),Xa("method (number, default=0)",r("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=Xi(e),s=Xi(t),r=ss(o)?4:0,n=Lh.compute(e,t,r);return Math.sign(s-i)*Math.round(360*n)},isExported:!0},fh={description:r("Date a number of months before/after another date."),args:[Xa("start_date (date)",r("The date from which to calculate the result.")),Xa("months (number)",r("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(rs(e),Math.trunc(Xi(t)),!1))},isExported:!0},bh={description:r("Last day of a month before or after a date."),args:[Xa("start_date (date)",r("The date from which to calculate the result.")),Xa("months (number)",r("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=rs(e),i=Math.trunc(Xi(t)),s=o.getFullYear(),r=o.getMonth();return Me(new be(s,r+i+1,0))},isExported:!0},vh={description:r("Hour component of a specific time."),args:[Xa("time (date)",r("The time from which to calculate the hour component."))],returns:["NUMBER"],compute:function(e){return rs(e).getHours()},isExported:!0},Sh={description:r("ISO week number of the year."),args:[Xa("date (date)",r("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=rs(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 r=31;for(;4!==new be(o,11,r).getDay();)r-=1;const n=new be(o,11,r+3);let a,l;switch(a=s.getTime()<=t.getTime()?t.getTime()<=n.getTime()?0:1:-1,a){case 0:l=s;break;case 1:l=new be(o,11,r+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},Ch={description:r("Minute component of a specific time."),args:[Xa("time (date)",r("The time from which to calculate the minute component."))],returns:["NUMBER"],compute:function(e){return rs(e).getMinutes()},isExported:!0},Eh={description:r("Month of the year a specific date falls in"),args:[Xa("date (date)",r("The date from which to extract the month."))],returns:["NUMBER"],compute:function(e){return rs(e).getMonth()+1},isExported:!0},wh={description:r("Net working days between two provided days."),args:[Xa("start_date (date)",r("The start date of the period from which to calculate the number of net working days.")),Xa("end_date (date)",r("The end date of the period from which to calculate the number of net working days.")),Xa("holidays (date, range<date>, optional)",r("A range or array constant containing the date serial numbers to consider holidays."))],returns:["NUMBER"],compute:function(e,t,o){return yh.compute(e,t,1,o)},isExported:!0};function xh(e){if("string"==typeof e){ji((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),r('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 ji((()=>1<=e&&e<=7||11<=e&&e<=17),r("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(r("The weekend must be a number or a string."))}const yh={description:r("Net working days between two dates (specifying weekends)."),args:[Xa("start_date (date)",r("The start date of the period from which to calculate the number of net working days.")),Xa("end_date (date)",r("The end date of the period from which to calculate the number of net working days.")),Xa("weekend (any, default=1)",r("A number or string representing which days of the week are considered weekends.")),Xa("holidays (date, range<date>, optional)",r("A range or array constant containing the dates to consider as holidays."))],returns:["NUMBER"],compute:function(e,t,o=1,i){const s=rs(e),r=rs(t),n=xh(o);let a=new Set;void 0!==i&&as([i],(e=>{const t=rs(e);a.add(t.getTime())}));const l=s.getTime()>r.getTime(),c=be.fromTimestamp((l?s:r).getTime());let h=be.fromTimestamp((l?r:s).getTime());const d=c.getTime();let u=h.getTime(),g=0;for(;u<=d;)n.includes(h.getDay())||a.has(u)||(g+=1),h.setDate(h.getDate()+1),u=h.getTime();return l?-g:g},isExported:!0},Ih={description:r("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},Rh={description:r("Minute component of a specific time."),args:[Xa("time (date)",r("The time from which to calculate the second component."))],returns:["NUMBER"],compute:function(e){return rs(e).getSeconds()},isExported:!0},Th={description:r("Converts hour/minute/second into a time."),args:[Xa("hour (number)",r("The hour component of the time.")),Xa("minute (number)",r("The minute component of the time.")),Xa("second (number)",r("The second component of the time."))],returns:["DATE"],computeFormat:()=>"hh:mm:ss a",compute:function(e,t,o){let i=Math.trunc(Xi(e)),s=Math.trunc(Xi(t)),n=Math.trunc(Xi(o));return s+=Math.floor(n/60),n=n%60+(n<0?60:0),i+=Math.floor(s/60),s=s%60+(s<0?60:0),i%=24,ji((()=>i>=0),r("The function [[FUNCTION_NAME]] result cannot be negative")),i/24+s/1440+n/86400},isExported:!0},Ah={description:r("Converts a time string into its serial number representation."),args:[Xa("time_string (string)",r("The string that holds the time representation."))],returns:["NUMBER"],compute:function(e){const t=es(e),o=Te(t);ji((()=>null!==o),r("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},Oh={description:r("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},Mh={description:r("Day of the week of the date provided (as number)."),args:[Xa("date (date)",r("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.")),Xa("type (number, default=1)",r("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=rs(e),i=Math.round(Xi(t)),s=o.getDay();return ji((()=>[1,2,3].includes(i)),r("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},Nh={description:r("Week number of the year."),args:[Xa("date (date)",r("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.")),Xa("type (number, default=1)",r("A number representing the day that a week starts on. Sunday = 1."))],returns:["NUMBER"],compute:function(e,t=1){const o=rs(e),i=Math.round(Xi(t));if(ji((()=>1===i||2===i||11<=i&&i<=17||21===i),r("The type (%s) is out of range.",i.toString())),21===i)return Sh.compute(e);let s;s=1===i||2===i?i-1:i-10==7?0:i-10;const n=o.getFullYear();let a=1,l=new be(n,0,a);for(;l.getDay()!==s;)a+=1,l=new be(n,0,a);const c=(o.getTime()-l.getTime())/Se;return c<0?1:Math.floor(c/7)+(1===a?1:2)},isExported:!0},_h={description:r("Date after a number of workdays."),args:[Xa("start_date (date)",r("The date from which to begin counting.")),Xa("num_days (number)",r("The number of working days to advance from start_date. If negative, counts backwards.")),Xa("holidays (date, range<date>, optional)",r("A range or array constant containing the dates to consider holidays."))],returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o){return Fh.compute(e,t,1,o)},isExported:!0},Fh={description:r("Date after a number of workdays (specifying weekends)."),args:[Xa("start_date (date)",r("The date from which to begin counting.")),Xa("num_days (number)",r("The number of working days to advance from start_date. If negative, counts backwards.")),Xa("weekend (any, default=1)",r("A number or string representing which days of the week are considered weekends.")),Xa("holidays (date, range<date>, optional)",r("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=rs(e),n=Math.trunc(Xi(t));"string"==typeof o&&ji((()=>"1111111"!==o),r("The weekend (%s) must be different from '1111111'.",o));const a=xh(o);let l=new Set;void 0!==i&&as([i],(e=>{const t=rs(e);l.add(t.getTime())}));let c=be.fromTimestamp(s.getTime()),h=c.getTime();const d=Math.sign(n);let u=Math.abs(n);for(;u>0;)c.setDate(c.getDate()+d),h=c.getTime(),a.includes(c.getDay())||l.has(h)||(u-=1);const g=h-ve.getTime();return Math.round(g/Se)},isExported:!0},Dh={description:r("Year specified by a given date."),args:[Xa("date (date)",r("The date from which to extract the year."))],returns:["NUMBER"],compute:function(e){return rs(e).getFullYear()},isExported:!0},Lh={description:r("Exact number of years between two dates."),args:[Xa("start_date (date)",r("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.")),Xa("end_date (date)",r("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.")),Xa("day_count_convention (number, default=0)",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o=0){let i=Math.trunc(Xi(e)),s=Math.trunc(Xi(t));const n=Math.trunc(Xi(o));return ji((()=>i>=0),r("The start_date (%s) must be positive or null.",i.toString())),ji((()=>s>=0),r("The end_date (%s) must be positive or null.",s.toString())),ji((()=>0<=n&&n<=4),r("The day_count_convention (%s) must be between 0 and 4 inclusive.",n.toString())),Le(i,s,n)}},kh={description:r("First day of the month preceding a date."),args:[Xa("date (date)",r("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=rs(e),o=t.getFullYear(),i=t.getMonth();return Me(new be(o,i,1))}},Ph={description:r("Last day of the month following a date."),args:[Xa("date (date)",r("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){return bh.compute(e,0)}},Uh={description:r("Quarter of the year a specific date falls in"),args:[Xa("date (date)",r("The date from which to extract the quarter."))],returns:["NUMBER"],compute:function(e){return Math.ceil((rs(e).getMonth()+1)/3)}},Vh={description:r("First day of the quarter of the year a specific date falls in."),args:[Xa("date (date)",r("The date from which to calculate the start of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Uh.compute(e),o=Dh.compute(e);return Me(new be(o,3*(t-1),1))}},zh={description:r("Last day of the quarter of the year a specific date falls in."),args:[Xa("date (date)",r("The date from which to calculate the end of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Uh.compute(e),o=Dh.compute(e);return Me(new be(o,3*t,0))}},Bh={description:r("First day of the year a specific date falls in."),args:[Xa("date (date)",r("The date from which to calculate the start of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Dh.compute(e);return Me(new be(t,0,1))}},Hh={description:r("Last day of the year a specific date falls in."),args:[Xa("date (date)",r("The date from which to calculate the end of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Dh.compute(e);return Me(new be(t+1,0,0))}};var $h=Object.freeze({__proto__:null,DATE:hh,DATEDIF:dh,DATEVALUE:uh,DAY:gh,DAYS:ph,DAYS360:mh,EDATE:fh,EOMONTH:bh,HOUR:vh,ISOWEEKNUM:Sh,MINUTE:Ch,MONTH:Eh,NETWORKDAYS:wh,NETWORKDAYS_INTL:yh,NOW:Ih,SECOND:Rh,TIME:Th,TIMEVALUE:Ah,TODAY:Oh,WEEKDAY:Mh,WEEKNUM:Nh,WORKDAY:_h,WORKDAY_INTL:Fh,YEAR:Dh,YEARFRAC:Lh,MONTH_START:kh,MONTH_END:Ph,QUARTER:Uh,QUARTER_START:Vh,QUARTER_END:zh,YEAR_START:Bh,YEAR_END:Hh});const Wh={description:r("Compare two numeric values, returning 1 if they're equal."),args:[Xa("number1 (number)",r("The first number to compare.")),Xa("number2 (number, default=0)",r("The second number to compare."))],returns:["NUMBER"],compute:function(e,t=0){return Xi(e)===Xi(t)?1:0},isExported:!0};var Gh=Object.freeze({__proto__:null,DELTA:Wh});function qh(e,t){ji((()=>e<t),r("The maturity (%s) must be strictly greater than the settlement (%s).",t.toString(),e.toString()))}function Zh(e,t){ji((()=>t<e),r("The settlement date (%s) must be strictly greater than the issue date (%s).",e.toString(),t.toString()))}function jh(e){ji((()=>[1,2,4].includes(e)),r("The frequency (%s) must be one of %s",e.toString(),[1,2,4].toString()))}function Yh(e){ji((()=>0<=e&&e<=4),r("The day_count_convention (%s) must be between 0 and 4 inclusive.",e.toString()))}function Xh(e){ji((()=>e>0),r("The redemption (%s) must be strictly positive.",e.toString()))}function Kh(e){ji((()=>e>0),r("The price (%s) must be strictly positive.",e.toString()))}function Qh(e){ji((()=>e>0),r("The number_of_periods (%s) must be greater than 0.",e.toString()))}function Jh(e){ji((()=>e>0),r("The rate (%s) must be strictly positive.",e.toString()))}function ed(e){ji((()=>e>0),r("The life (%s) must be strictly positive.",e.toString()))}function td(e){ji((()=>e>=0),r("The cost (%s) must be positive or null.",e.toString()))}function od(e){ji((()=>e>0),r("The period (%s) must be strictly positive.",e.toString()))}function id(e){ji((()=>e>=0),r("The salvage (%s) must be positive or null.",e.toString()))}function sd(e){ji((()=>e>0),r("The present value (%s) must be strictly positive.",e.toString()))}function rd(e,t){ji((()=>e<=t),r("The period (%s) must be less than or equal life (%s).",e.toString(),t.toString()))}function nd(e){ji((()=>e>0),r("The investment (%s) must be strictly positive.",e.toString()))}function ad(e){ji((()=>e>0),r("The discount (%s) must be strictly positive.",e.toString()))}function ld(e){ji((()=>e<1),r("The discount (%s) must be smaller than 1.",e.toString()))}function cd(e){ji((()=>e>0),r("The depreciation factor (%s) must be strictly positive.",e.toString()))}function hd(e,t){const o=rs(e),i=rs(t),s=rs(e);s.setFullYear(o.getFullYear()+1),ji((()=>i.getTime()<=s.getTime()),r("The settlement date (%s) must at most one year after the maturity date (%s).",e.toString(),t.toString()))}function dd(e,t,o){Qh(o),ji((()=>e>0),r("The first_period (%s) must be strictly positive.",e.toString())),ji((()=>t>0),r("The last_period (%s) must be strictly positive.",t.toString())),ji((()=>e<=t),r("The first_period (%s) must be smaller or equal to the last_period (%s).",e.toString(),t.toString())),ji((()=>t<=o),r("The last_period (%s) must be smaller or equal to the number_of_periods (%s).",e.toString(),o.toString()))}function ud(e){ji((()=>e>-1),r("The rate_guess (%s) must be strictly greater than -1.",e.toString()))}function gd(e,t){ji((()=>e.length===t.length&&e[0].length===t[0].length),r("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."))}function pd(e){ji((()=>e.every((t=>t>=e[0]))),r("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e[0].toString()))}const md=[Xa("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("frequency (number)",r("The number of interest or coupon payments per year (1, 2, or 4).")),Xa("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))];function fd(e,t,o,i,s=1e-10,n){let a,l,c,h,d=o,u=!1,g=0;do{c=e(d),isNaN(c)?(ji((()=>g<i&&void 0!==n),r("Function [[FUNCTION_NAME]] didn't find any result.")),g++,d=n(h),h=d):(a=d-c/t(d),l=Math.abs(a-d),d=a,u=l<s||Math.abs(c)<s,ji((()=>g<i),r("Function [[FUNCTION_NAME]] didn't find any result.")),g++)}while(!u);return d}const bd={description:r("Accrued interest of security paying at maturity."),args:[Xa("issue (date)",r("The date the security was initially issued.")),Xa("maturity (date)",r("The maturity date of the security.")),Xa("rate (number)",r("The annualized rate of interest.")),Xa("redemption (number)",r("The redemption amount per 100 face value, or par.")),Xa("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const r=Math.trunc(Xi(e)),n=Math.trunc(Xi(t)),a=Xi(i),l=Xi(o),c=Math.trunc(Xi(s));Zh(n,r),Yh(c),Xh(a),Jh(l);return a*l*Lh.compute(r,n,s)},isExported:!0},vd={description:r("Depreciation for an accounting period."),args:[Xa("cost (number)",r("The initial cost of the asset.")),Xa("purchase_date (date)",r("The date the asset was purchased.")),Xa("first_period_end (date)",r("The date the first period ended.")),Xa("salvage (number)",r("The value of the asset at the end of depreciation.")),Xa("period (number)",r("The single period within life for which to calculate depreciation.")),Xa("rate (number)",r("The deprecation rate.")),Xa("day_count_convention (number, optional)",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n,a=0){a=a||0;const l=Xi(e),c=Math.trunc(Xi(t)),h=Math.trunc(Xi(o)),d=Xi(i),u=Xi(s),g=Xi(n),p=Math.trunc(Xi(a));!function(e){ji((()=>e>0),r("The cost (%s) must be strictly positive.",e.toString()))}(l),id(d),function(e,t){ji((()=>e<=t),r("The salvage (%s) must be smaller or equal than the cost (%s).",e.toString(),t.toString()))}(d,l),function(e){ji((()=>e>=0),r("The period (%s) must be positive or null.",e.toString()))}(u),Jh(g),Yh(p),ji((()=>c<=h),r("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=Lh.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},Sd={description:r("Days in coupon period containing settlement date."),args:md,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Xi(e)),r=Math.trunc(Xi(t)),n=Math.trunc(Xi(o)),a=Math.trunc(Xi(i));if(qh(s,r),jh(n),Yh(a),1===a){const s=yd.compute(e,t,o,i);return wd.compute(e,t,o,i)-s}return(3===a?365:360)/n},isExported:!0},Cd={description:r("Days from settlement until next coupon."),args:md,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Xi(e)),r=Math.trunc(Xi(t)),n=Math.trunc(Xi(o)),a=Math.trunc(Xi(i));qh(s,r),jh(n),Yh(a);const l=yd.compute(s,r,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=rs(s),h=rs(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},Ed={description:r("Days from settlement until next coupon."),args:md,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Xi(e)),r=Math.trunc(Xi(t)),n=Math.trunc(Xi(o)),a=Math.trunc(Xi(i));qh(s,r),jh(n),Yh(a);const l=wd.compute(s,r,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=Cd.compute(e,t,o,a);return Sd.compute(e,t,o,a)-c},isExported:!0},wd={description:r("Next coupon date after the settlement date."),args:md,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Xi(e)),r=Math.trunc(Xi(t)),n=Math.trunc(Xi(o)),a=Math.trunc(Xi(i));qh(s,r),jh(n),Yh(a);const l=12/n,c=xd.compute(e,t,o,i);return Me(Fe(rs(r),-(c-1)*l,!0))},isExported:!0},xd={description:r("Number of coupons between settlement and maturity."),args:md,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Xi(e)),r=Math.trunc(Xi(t)),n=Math.trunc(Xi(o)),a=Math.trunc(Xi(i));qh(s,r),jh(n),Yh(a);let l=1,c=r;const h=12/n;for(;c>s;)c=Me(Fe(rs(c),-h,!1)),l++;return l-1},isExported:!0},yd={description:r("Last coupon date prior to or on the settlement date."),args:md,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Xi(e)),r=Math.trunc(Xi(t)),n=Math.trunc(Xi(o)),a=Math.trunc(Xi(i));qh(s,r),jh(n),Yh(a);const l=12/n,c=xd.compute(e,t,o,i);return Me(Fe(rs(r),-c*l,!0))},isExported:!0},Id={description:r("Cumulative interest paid over a set of periods."),args:[Xa("rate (number)",r("The interest rate.")),Xa("number_of_periods (number)",r("The number of payments to be made.")),Xa("present_value (number)",r("The current value of the annuity.")),Xa("first_period (number)",r("The number of the payment period to begin the cumulative calculation.")),Xa("last_period (number)",r("The number of the payment period to end the cumulative calculation.")),Xa("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=0){const n=Xi(i),a=Xi(s),l=Xi(e),c=Xi(o),h=Xi(t);dd(n,a,h),Jh(l),sd(c);let d=0;for(let t=n;t<=a;t++){d+=Pd.compute(e,t,h,o,0,r)}return d},isExported:!0},Rd={description:r("Cumulative principal paid over a set of periods."),args:[Xa("rate (number)",r("The interest rate.")),Xa("number_of_periods (number)",r("The number of payments to be made.")),Xa("present_value (number)",r("The current value of the annuity.")),Xa("first_period (number)",r("The number of the payment period to begin the cumulative calculation.")),Xa("last_period (number)",r("The number of the payment period to end the cumulative calculation.")),Xa("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=0){const n=Xi(i),a=Xi(s),l=Xi(e),c=Xi(o),h=Xi(t);dd(n,a,h),Jh(l),sd(c);let d=0;for(let t=n;t<=a;t++){d+=Zd.compute(e,t,h,o,0,r)}return d},isExported:!0},Td={description:r("Depreciation via declining balance method."),args:[Xa("cost (number)",r("The initial cost of the asset.")),Xa("salvage (number)",r("The value of the asset at the end of depreciation.")),Xa("life (number)",r("The number of periods over which the asset is depreciated.")),Xa("period (number)",r("The single period within life for which to calculate depreciation.")),Xa("month (number, optional)",r("The number of months in the first year of depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,...s){const n=Xi(e),a=Xi(t),l=Xi(o),c=Math.trunc(Xi(i)),h=s.length?Math.trunc(Xi(s[0])):12,d=l+(12===h?0:1);td(n),id(a),od(c),ed(l),ji((()=>1<=h&&h<=12),r("The month (%s) must be between 1 and 12 inclusive.",h.toString())),ji((()=>c<=d),r("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/n,1/l);g=Math.round(1e3*g)/1e3;let p=n,m=n*(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},Ad={description:r("Depreciation via double-declining balance method."),args:[Xa("cost (number)",r("The initial cost of the asset.")),Xa("salvage (number)",r("The value of the asset at the end of depreciation.")),Xa("life (number)",r("The number of periods over which the asset is depreciated.")),Xa("period (number)",r("The single period within life for which to calculate depreciation.")),Xa("factor (number, default=2)",r("The factor by which depreciation decreases."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,s=2){s=s||0;const r=Xi(e),n=Xi(t),a=Xi(o),l=Xi(i),c=Xi(s);if(td(r),id(n),od(l),ed(a),rd(l,a),cd(c),0===r||n>=r)return 0;const h=c/a;if(h>1)return 1===i?r-n:0;if(l<=1)return r*h;const d=r*Math.pow(1-h,l-1),u=r*Math.pow(1-h,l),g=u<n?d-n:d-u;return Math.max(g,0)},isExported:!0},Od={description:r("Discount rate of a security based on price."),args:[Xa("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("price (number)",r("The price at which the security is bought per 100 face value.")),Xa("redemption (number)",r("The redemption amount per 100 face value, or par.")),Xa("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const r=Math.trunc(Xi(e)),n=Math.trunc(Xi(t)),a=Xi(o),l=Xi(i),c=Math.trunc(Xi(s));qh(r,n),Yh(c),Kh(a),Xh(l);return(l-a)/l/Lh.compute(r,n,c)},isExported:!0},Md={description:r("Convert a decimal fraction to decimal value."),args:[Xa("fractional_price (number)",r("The price quotation given using fractional decimal conventions.")),Xa("unit (number)",r("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const o=Xi(e),i=Math.trunc(Xi(t));ji((()=>i>0),r("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},Nd={description:r("Convert a decimal value to decimal fraction."),args:[Xa("decimal_price (number)",r("The price quotation given as a decimal value.")),Xa("unit (number)",r("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=Xi(e),i=Math.trunc(Xi(t));ji((()=>i>0),r("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},_d={description:r("Number of periods for an investment to reach a value."),args:[Xa("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("rate (number)",r("The annualized rate of interest.")),Xa("yield (number)",r("The expected annual yield of the security.")),Xa("frequency (number)",r("The number of interest or coupon payments per year (1, 2, or 4).")),Xa("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=0){n=n||0;const a=Math.trunc(Xi(e)),l=Math.trunc(Xi(t)),c=Xi(o),h=Xi(i),d=Math.trunc(Xi(s)),u=Math.trunc(Xi(n));qh(a,l),jh(d),Yh(u),ji((()=>c>=0),r("The rate (%s) must be positive or null.",c.toString())),ji((()=>h>=0),r("The yield (%s) must be positive or null.",h.toString()));const g=Lh.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},Fd={description:r("Annual effective interest rate."),args:[Xa("nominal_rate (number)",r("The nominal interest rate per year.")),Xa("periods_per_year (number)",r("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const o=Xi(e),i=Math.trunc(Xi(t));return ji((()=>o>0),r("The nominal rate (%s) must be strictly greater than 0.",o.toString())),ji((()=>i>0),r("The number of periods by year (%s) must strictly greater than 0.",i.toString())),Math.pow(1+o/i,i)-1},isExported:!0},Dd={description:r("Future value of an annuity investment."),args:[Xa("rate (number)",r("The interest rate.")),Xa("number_of_periods (number)",r("The number of payments to be made.")),Xa("payment_amount (number)",r("The amount per period to be paid.")),Xa("present_value (number, default=0)",r("The current value of the annuity.")),Xa("end_or_beginning (number, default=0)",r("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 r=Xi(e),n=Xi(t),a=Xi(o),l=Xi(i),c=ss(s)?1:0;return r?-l*(1+r)**n-a*(1+r*c)*((1+r)**n-1)/r:-(l+a*n)},isExported:!0},Ld={description:r("Future value of principal from series of rates."),args:[Xa("principal (number)",r("The amount of initial capital or value to compound against.")),Xa("rate_schedule (number, range<number>)",r("A series of interest rates to compound against the principal."))],returns:["NUMBER"],compute:function(e,t){return hs([t],((e,t)=>e*(1+Xi(t))),Xi(e))},isExported:!0},kd={description:r("Calculates effective interest rate."),args:[Xa("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("investment (number)",r("The amount invested in the security.")),Xa("redemption (number)",r("The amount to be received at maturity.")),Xa("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){const r=Math.trunc(Xi(e)),n=Math.trunc(Xi(t)),a=Xi(i),l=Xi(o);qh(r,n),nd(l),Xh(a);return(a-l)/l/Lh.compute(r,n,s)},isExported:!0},Pd={description:r("Payment on the principal of an investment."),args:[Xa("rate (number)",r("The annualized rate of interest.")),Xa("period (number)",r("The amortization period, in terms of number of periods.")),Xa("number_of_periods (number)",r("The number of payments to be made.")),Xa("present_value (number)",r("The current value of the annuity.")),Xa("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),Xa("end_or_beginning (number, default=0)",r("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){return qd.compute(e,o,i,s,r)-Zd.compute(e,t,o,i,s,r)},isExported:!0},Ud={description:r("Internal rate of return given periodic cashflows."),args:[Xa("cashflow_amounts (number, range<number>)",r("An array or range containing the income or payments associated with the investment.")),Xa("rate_guess (number, default=0.1)",r("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t=.1){const o=Xi(t);ud(o);let i=!1,s=!1,n=[];ls([e],(e=>{e>0&&(i=!0),e<0&&(s=!0),n.push(e)})),ji((()=>i&&s),r("The cashflow_amounts must include negative and positive values."));const a=n.shift();return fd((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,n)}),(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,n)}),o+1,20,1e-5)-1},isExported:!0},Vd={description:r("Returns the interest paid at a particular period of an investment."),args:[Xa("rate (number)",r("The interest rate.")),Xa("period (number)",r("The period for which you want to view the interest payment.")),Xa("number_of_periods (number)",r("The number of payments to be made.")),Xa("present_value (number)",r("The current value of the annuity."))],returns:["NUMBER"],compute:function(e,t,o,i){const s=Xi(e),n=Xi(t),a=Xi(o),l=Xi(i);ji((()=>0!==a),r("The number of periods must be different than 0.",a.toString()));return-1*(l-l*(n/a))*s},isExported:!0},zd={description:r("Modified Macaulay duration."),args:[Xa("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("rate (number)",r("The annualized rate of interest.")),Xa("yield (number)",r("The expected annual yield of the security.")),Xa("frequency (number)",r("The number of interest or coupon payments per year (1, 2, or 4).")),Xa("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,r=0){return _d.compute(e,t,o,i,s,r)/(1+Xi(i)/Math.trunc(Xi(s)))},isExported:!0},Bd={description:r("Modified internal rate of return."),args:[Xa("cashflow_amounts (range<number>)",r("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")),Xa("financing_rate (number)",r("The interest rate paid on funds invested.")),Xa("reinvestment_return_rate (number)",r("The return (as a percentage) earned on reinvestment of income received from the investment."))],returns:["NUMBER"],compute:function(e,t,o){const i=Xi(t),s=Xi(o),n=(a=e,a.length?a[0].map(((e,t)=>a.map((e=>e[t])))):a).flat().filter(dt).map(Xi);var a;const l=n.length;let c=0,h=0;for(const e of Ke(0,l)){const t=n[e];t>=0?c+=t*(s+1)**(l-e-1):h+=t/(i+1)**e}ji((()=>0!==h&&0!==c),r("There must be both positive and negative values in cashflow_amounts."));return(-c/h)**(1/(l-1))-1},isExported:!0},Hd={description:r("Annual nominal interest rate."),args:[Xa("effective_rate (number)",r("The effective interest rate per year.")),Xa("periods_per_year (number)",r("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const o=Xi(e),i=Math.trunc(Xi(t));return ji((()=>o>0),r("The effective rate (%s) must must strictly greater than 0.",o.toString())),ji((()=>i>0),r("The number of periods by year (%s) must strictly greater than 0.",i.toString())),(Math.pow(o+1,1/i)-1)*i},isExported:!0},$d={description:r("Number of payment periods for an investment."),args:[Xa("rate (number)",r("The interest rate.")),Xa("payment_amount (number)",r("The amount of each payment made.")),Xa("present_value (number)",r("The current value of the annuity.")),Xa("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),Xa("end_or_beginning (number, default=0)",r("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 r=Xi(e),n=Xi(t),a=Xi(o),l=Xi(i),c=ss(s)?1:0;if(0===r)return-(l+a)/n;const h=n*(1+r*c)/r;return Math.log((h-l)/(a+h))/Math.log(1+r)},isExported:!0};const Wd={description:r("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:[Xa("discount (number)",r("The discount rate of the investment over one period.")),Xa("cashflow1 (number, range<number>)",r("The first future cash flow.")),Xa("cashflow2 (number, range<number>, repeating)",r("Additional future cash flows."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,...t){const o=Xi(e);return ji((()=>-1!==o),r("The discount (%s) must be different from -1.",o.toString())),function(e,t,o){let i=0;return ds(o,((t,o)=>(i++,t+o/(1+e)**i)),t)}(o,0,t)},isExported:!0},Gd={description:r("Computes the number of periods needed for an investment to reach a value."),args:[Xa("rate (number)",r("The rate at which the investment grows each period.")),Xa("present_value (number)",r("The investment's current value.")),Xa("future_value (number)",r("The investment's desired future value."))],returns:["NUMBER"],compute:function(e,t,o){const i=Xi(e),s=Xi(t),n=Xi(o);return Jh(i),ji((()=>s>0),r("The present_value (%s) must be strictly positive.",s.toString())),ji((()=>n>0),r("The future_value (%s) must be strictly positive.",n.toString())),(Math.log(n)-Math.log(s))/Math.log(1+i)},isExported:!0},qd={description:r("Periodic payment for an annuity investment."),args:[Xa("rate (number)",r("The annualized rate of interest.")),Xa("number_of_periods (number)",r("The number of payments to be made.")),Xa("present_value (number)",r("The current value of the annuity.")),Xa("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),Xa("end_or_beginning (number, default=0)",r("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 r=Xi(t),n=Xi(e),a=ss(s)?1:0;let l=Xi(i),c=Xi(o);if(Qh(r),0===n)return-(l+c)/r;let h=-(c*(1+n)**r+l);return h=h*n/((1+n*a)*((1+n)**r-1)),h},isExported:!0},Zd={description:r("Payment on the principal of an investment."),args:[Xa("rate (number)",r("The annualized rate of interest.")),Xa("period (number)",r("The amortization period, in terms of number of periods.")),Xa("number_of_periods (number)",r("The number of payments to be made.")),Xa("present_value (number)",r("The current value of the annuity.")),Xa("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),Xa("end_or_beginning (number, default=0)",r("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){s=s||0,n=n||0;const a=Xi(o),l=Xi(e),c=Xi(t),h=ss(n)?1:0,d=Xi(s),u=Xi(i);Qh(a),ji((()=>c>0&&c<=a),r("The period must be between 1 and number_of_periods",a.toString()));const g=qd.compute(l,a,u,d,n);if(1===h&&1===c)return g;return g+-Dd.compute(l,0===h?c-1:c-2,g,u+g*h,0)*l},isExported:!0},jd={description:r("Present value of an annuity investment."),args:[Xa("rate (number)",r("The interest rate.")),Xa("number_of_periods (number)",r("The number of payments to be made.")),Xa("payment_amount (number)",r("The amount per period to be paid.")),Xa("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),Xa("end_or_beginning (number, default=0)",r("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 r=Xi(e),n=Xi(t),a=Xi(o),l=Xi(i),c=ss(s)?1:0;return r?-(a*(1+r*c)*((1+r)**n-1)/r+l)/(1+r)**n:-(l+a*n)},isExported:!0},Yd={description:r("Price of a security paying periodic interest."),args:[Xa("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("rate (number)",r("The annualized rate of interest.")),Xa("yield (number)",r("The expected annual yield of the security.")),Xa("redemption (number)",r("The redemption amount per 100 face value, or par.")),Xa("frequency (number)",r("The number of interest or coupon payments per year (1, 2, or 4).")),Xa("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n,a=0){a=a||0;const l=Math.trunc(Xi(e)),c=Math.trunc(Xi(t)),h=Xi(o),d=Xi(i),u=Xi(s),g=Math.trunc(Xi(n)),p=Math.trunc(Xi(a));qh(l,c),jh(g),Yh(p),ji((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),ji((()=>d>=0),r("The yield (%s) must be positive or null.",d.toString())),Xh(u);const m=Lh.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},Xd={description:r("Price of a discount security."),args:[Xa("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("discount (number)",r("The discount rate of the security at time of purchase.")),Xa("redemption (number)",r("The redemption amount per 100 face value, or par.")),Xa("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const r=Math.trunc(Xi(e)),n=Math.trunc(Xi(t)),a=Xi(o),l=Xi(i),c=Math.trunc(Xi(s));qh(r,n),Yh(c),ad(a),Xh(l);return l-a*l*Lh.compute(r,n,c)},isExported:!0},Kd={description:r("Calculates the price of a security paying interest at maturity, based on expected yield."),args:[Xa("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("issue (date)",r("The date the security was initially issued.")),Xa("rate (number)",r("The annualized rate of interest.")),Xa("yield (number)",r("The expected annual yield of the security.")),Xa("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=0){n=n||0;const a=Math.trunc(Xi(e)),l=Math.trunc(Xi(t)),c=Math.trunc(Xi(o)),h=Xi(i),d=Xi(s),u=Math.trunc(Xi(n));Zh(a,c),qh(a,l),Yh(u),ji((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),ji((()=>d>=0),r("The yield (%s) must be positive or null.",d.toString()));const g=Lh.compute(a,l,u),p=Lh.compute(a,c,u);return(100+Lh.compute(c,l,u)*h*100)/(1+g*d)-p*h*100},isExported:!0},Qd=.1,Jd={description:r("Interest rate of an annuity investment."),args:[Xa("number_of_periods (number)",r("The number of payments to be made.")),Xa("payment_per_period (number)",r("The amount per period to be paid.")),Xa("present_value (number)",r("The current value of the annuity.")),Xa("future_value (number, default=0)",r("The future value remaining after the final payment has been made.")),Xa("end_or_beginning (number, default=0)",r("Whether payments are due at the end (0) or beginning (1) of each period.")),Xa("rate_guess (number, default=0.1)",r("An estimate for what the interest rate will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t,o,i=0,s=0,n=.1){i=i||0,s=s||0,n=n||Qd;const a=Xi(e),l=Xi(t),c=ss(s)?1:0,h=Xi(n);let d=Xi(i),u=Xi(o);Qh(a),ji((()=>[l,u,d].some((e=>e>0))&&[l,u,d].some((e=>e<0))),r("There must be both positive and negative values in [payment_amount, present_value, future_value].",a.toString())),ud(h),d-=l*c,u+=l*c;return fd((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},eu={description:r("Amount received at maturity for a security."),args:[Xa("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("investment (number)",r("The amount invested (irrespective of face value of each security).")),Xa("discount (number)",r("The discount rate of the security invested in.")),Xa("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const r=Math.trunc(Xi(e)),n=Math.trunc(Xi(t)),a=Xi(o),l=Xi(i),c=Math.trunc(Xi(s));qh(r,n),Yh(c),nd(a),ad(l);return a/(1-l*Lh.compute(r,n,c))},isExported:!0},tu={description:r("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:[Xa("number_of_periods (number)",r("The number of periods.")),Xa("present_value (number)",r("The present value of the investment.")),Xa("future_value (number)",r("The future value of the investment."))],returns:["NUMBER"],compute:function(e,t,o){const i=Xi(e),s=Xi(t),r=Xi(o);return Qh(i),(r/s)**(1/i)-1},isExported:!0},ou={description:r("Depreciation of an asset using the straight-line method."),args:[Xa("cost (number)",r("The initial cost of the asset.")),Xa("salvage (number)",r("The value of the asset at the end of depreciation.")),Xa("life (number)",r("The number of periods over which the asset is depreciated."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o){return(Xi(e)-Xi(t))/Xi(o)},isExported:!0},iu={description:r("Depreciation via sum of years digit method."),args:[Xa("cost (number)",r("The initial cost of the asset.")),Xa("salvage (number)",r("The value of the asset at the end of depreciation.")),Xa("life (number)",r("The number of periods over which the asset is depreciated.")),Xa("period (number)",r("The single period within life for which to calculate depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i){const s=Xi(e),r=Xi(t),n=Xi(o),a=Xi(i);od(a),ed(n),rd(a,n);return(n-a+1)/(n*(n+1)/2)*(s-r)},isExported:!0},su={description:r("Price of a US Treasury bill."),args:[Xa("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("discount (number)",r("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Xi(e)),s=Math.trunc(Xi(t)),r=Xi(o);qh(i,s),hd(i,s),ad(r),ld(r);return 100*(1-r*Lh.compute(i,s,2))},isExported:!0},ru={description:r("Equivalent rate of return for a US Treasury bill."),args:[Xa("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("discount (number)",r("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Xi(e)),s=Math.trunc(Xi(t)),r=Xi(o);qh(i,s),hd(i,s),ad(r),ld(r);const n=ph.compute(s,i);if(n<=182)return 365*r/(360-r*n);const a=su.compute(i,s,r)/100,l=n/(366===n?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},nu={description:r("The yield of a US Treasury bill based on price."),args:[Xa("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("price (number)",r("The price at which the security is bought per 100 face value."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Xi(e)),s=Math.trunc(Xi(t)),r=Xi(o);qh(i,s),hd(i,s),Kh(r);return(100-r)/r*(1/Lh.compute(i,s,2))},isExported:!0},au={description:r("Variable declining balance. WARNING : does not handle decimal periods."),args:[Xa("cost (number)",r("The initial cost of the asset.")),Xa("salvage (number)",r("The value of the asset at the end of depreciation.")),Xa("life (number)",r("The number of periods over which the asset is depreciated.")),Xa("start (number)",r("Starting period to calculate depreciation.")),Xa("end (number)",r("Ending period to calculate depreciation.")),Xa("factor (number, default=2)",r("The number of months in the first year of depreciation.")),Xa("no_switch (number, default=false)",r("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,n=2,a=false){n=n||0;const l=Xi(e),c=Xi(t),h=Xi(o),d=Math.trunc(Xi(i)),u=Math.trunc(Xi(s)),g=Xi(n),p=ss(a);if(td(l),id(c),function(e,t,o){ed(o),ji((()=>e>=0),r("The start_period (%s) must be greater or equal than 0.",e.toString())),ji((()=>t>=0),r("The end_period (%s) must be greater or equal than 0.",t.toString())),ji((()=>e<=t),r("The start_period (%s) must be smaller or equal to the end_period (%s).",e.toString(),t.toString())),ji((()=>t<=o),r("The end_period (%s) must be smaller or equal to the life (%s).",e.toString(),o.toString()))}(d,u,h),cd(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},lu={description:r("Internal rate of return given non-periodic cash flows."),args:[Xa("cashflow_amounts (range<number>)",r("An range containing the income or payments associated with the investment.")),Xa("cashflow_dates (range<number>)",r("An range with dates corresponding to the cash flows in cashflow_amounts.")),Xa("rate_guess (number, default=0.1)",r("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],compute:function(e,t,o=.1){const i=Xi(o=o||0),s=e.flat().map(Xi),n=t.flat().map(Xi);var a;gd(e,t),a=s,ji((()=>a.some((e=>e>0))&&a.some((e=>e<0))),r("There must be both positive and negative values in cashflow_amounts.")),pd(n),ud(i);const l=new Map;for(const e of Ke(0,n.length)){const t=n[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 fd((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},cu={description:r("Net present value given to non-periodic cash flows.."),args:[Xa("discount (number)",r("The discount rate of the investment over one period.")),Xa("cashflow_amounts (number, range<number>)",r("An range containing the income or payments associated with the investment.")),Xa("cashflow_dates (number, range<number>)",r("An range with dates corresponding to the cash flows in cashflow_amounts."))],returns:["NUMBER"],compute:function(e,t,o){const i=Xi(e),s=Array.isArray(t)?t.flat().map(Ki):[Ki(t)],n=Array.isArray(o)?o.flat().map(Ki):[Ki(o)];if(Array.isArray(o)&&Array.isArray(t)?gd(t,o):ji((()=>s.length===n.length),r("There must be the same number of values in cashflow_amounts and cashflow_dates.")),pd(n),Jh(i),1===s.length)return s[0];const a=new Map;for(const e of Ke(0,n.length)){const t=n[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},hu={description:r("Annual yield of a security paying periodic interest."),args:[Xa("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("rate (number)",r("The annualized rate of interest.")),Xa("price (number)",r("The price at which the security is bought per 100 face value.")),Xa("redemption (number)",r("The redemption amount per 100 face value, or par.")),Xa("frequency (number)",r("The number of interest or coupon payments per year (1, 2, or 4).")),Xa("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n,a=0){a=a||0;const l=Math.trunc(Xi(e)),c=Math.trunc(Xi(t)),h=Xi(o),d=Xi(i),u=Xi(s),g=Math.trunc(Xi(n)),p=Math.trunc(Xi(a));qh(l,c),jh(g),Yh(p),ji((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),Kh(d),Xh(u);const m=Lh.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=fd((function(e){return function(e,t,o,i,s,r){let n=r-(e+s*(1-t))*i**(o-1+t);for(let e=1;e<=o;e++)n+=s*i**(e-1);return n}(d,b,f,e,v,u)}),(function(e){return function(e,t,o,i,s){let r=-(e+s*(1-t))*(o-1+t)*i**(o-2+t);for(let e=1;e<=o;e++)r+=s*(e-1)*i**(e-2);return r}(d,b,f,e,v)}),1+(h+1)/g,100,1e-5);return(S-1)*g},isExported:!0},du={description:r("Annual yield of a discount security."),args:[Xa("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("price (number)",r("The price at which the security is bought per 100 face value.")),Xa("redemption (number)",r("The redemption amount per 100 face value, or par.")),Xa("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s=0){s=s||0;const r=Math.trunc(Xi(e)),n=Math.trunc(Xi(t)),a=Xi(o),l=Xi(i),c=Math.trunc(Xi(s));qh(r,n),Yh(c),Kh(a),Xh(l);return(l/a-1)/Lh.compute(e,t,s)},isExported:!0},uu={description:r("Annual yield of a security paying interest at maturity."),args:[Xa("settlement (date)",r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",r("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("issue (date)",r("The date the security was initially issued.")),Xa("rate (number)",r("The annualized rate of interest.")),Xa("price (number)",r("The price at which the security is bought.")),Xa("day_count_convention (number, default=0 )",r("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,o,i,s,n=0){n=n||0;const a=Math.trunc(Xi(e)),l=Math.trunc(Xi(t)),c=Math.trunc(Xi(o)),h=Xi(i),d=Xi(s),u=Math.trunc(Xi(n));qh(a,l),Yh(u),ji((()=>a>=c),r("The settlement (%s) must be greater than or equal to the issue (%s).",a.toString(),c.toString())),ji((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),Kh(d);const g=Lh.compute(c,l,u),p=Lh.compute(c,a,u),m=Lh.compute(a,l,u);return(100*(1+h*g)/(d+100*h*p)-1)/m},isExported:!0};var gu=Object.freeze({__proto__:null,ACCRINTM:bd,AMORLINC:vd,COUPDAYS:Sd,COUPDAYBS:Cd,COUPDAYSNC:Ed,COUPNCD:wd,COUPNUM:xd,COUPPCD:yd,CUMIPMT:Id,CUMPRINC:Rd,DB:Td,DDB:Ad,DISC:Od,DOLLARDE:Md,DOLLARFR:Nd,DURATION:_d,EFFECT:Fd,FV:Dd,FVSCHEDULE:Ld,INTRATE:kd,IPMT:Pd,IRR:Ud,ISPMT:Vd,MDURATION:zd,MIRR:Bd,NOMINAL:Hd,NPER:$d,NPV:Wd,PDURATION:Gd,PMT:qd,PPMT:Zd,PV:jd,PRICE:Yd,PRICEDISC:Xd,PRICEMAT:Kd,RATE:Jd,RECEIVED:eu,RRI:tu,SLN:ou,SYD:iu,TBILLPRICE:su,TBILLEQ:ru,TBILLYIELD:nu,VDB:au,XIRR:lu,XNPV:cu,YIELD:hu,YIELDDISC:du,YIELDMAT:uu});const pu={description:r("Whether a value is an error other than #N/A."),args:[Xa("value (any, lazy)",r("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},mu={description:r("Whether a value is an error."),args:[Xa("value (any, lazy)",r("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},fu={description:r("Whether a value is `true` or `false`."),args:[Xa("value (any, lazy)",r("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},bu={description:r("Whether a value is the error #N/A."),args:[Xa("value (any, lazy)",r("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},vu={description:r("Whether a value is non-textual."),args:[Xa("value (any, lazy)",r("The value to be checked."))],returns:["BOOLEAN"],compute:function(e){try{return"string"!=typeof e()}catch(e){return!0}},isExported:!0},Su={description:r("Whether a value is a number."),args:[Xa("value (any, lazy)",r("The value to be verified as a number."))],returns:["BOOLEAN"],compute:function(e){try{return"number"==typeof e()}catch(e){return!1}},isExported:!0},Cu={description:r("Whether a value is text."),args:[Xa("value (any, lazy)",r("The value to be verified as text."))],returns:["BOOLEAN"],compute:function(e){try{return"string"==typeof e()}catch(e){return!1}},isExported:!0},Eu={description:r("Whether the referenced cell is empty"),args:[Xa("value (any, lazy)",r("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},wu={description:r("Returns the error value #N/A."),args:[],returns:["BOOLEAN"],compute:function(e){throw new g},isExported:!0};var xu=Object.freeze({__proto__:null,ISERR:pu,ISERROR:mu,ISLOGICAL:fu,ISNA:bu,ISNONTEXT:vu,ISNUMBER:Su,ISTEXT:Cu,ISBLANK:Eu,NA:wu});const yu={description:r("Logical `and` operator."),args:[Xa("logical_expression1 (boolean, range<boolean>)",r("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.")),Xa("logical_expression2 (boolean, range<boolean>, repeating)",r("More expressions that represent logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!0;return gs(e,(e=>(t=!0,o=o&&e,o))),ji((()=>t),r("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0},Iu={description:r("Returns value depending on logical expression."),args:[Xa("logical_expression (boolean)",r("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")),Xa("value_if_true (any, lazy)",r("The value the function returns if logical_expression is TRUE.")),Xa("value_if_false (any, lazy, default=FALSE)",r("The value the function returns if logical_expression is FALSE."))],returns:["ANY"],compute:function(e,t,o=(()=>!1)){const i=ss(e)?t():o();return null==i?"":i},isExported:!0},Ru={description:r("Value if it is not an error, otherwise 2nd argument."),args:[Xa("value (any, lazy)",r("The value to return if value itself is not an error.")),Xa('value_if_error (any, lazy, default="empty")',r("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},Tu={description:r("Value if it is not an #N/A error, otherwise 2nd argument."),args:[Xa("value (any, lazy)",r("The value to return if value itself is not #N/A an error.")),Xa('value_if_error (any, lazy, default="empty")',r("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},Au={description:r("Returns a value depending on multiple logical expressions."),args:[Xa("condition1 (boolean, lazy)",r("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")),Xa("value1 (any, lazy)",r("The returned value if condition1 is TRUE.")),Xa("condition2 (boolean, lazy, repeating)",r("Additional conditions to be evaluated if the previous ones are FALSE.")),Xa("value2 (any, lazy, repeating)",r("Additional values to be returned if their corresponding conditions are TRUE."))],returns:["ANY"],compute:function(...e){ji((()=>e.length%2==0),r("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(ss(e[t]())){const o=e[t+1]();return null!==o?o:""}throw new Error(r("No match."))},isExported:!0},Ou={description:r("Returns opposite of provided logical value."),args:[Xa("logical_expression (boolean)",r("An expression or reference to a cell holding an expression that represents some logical value."))],returns:["BOOLEAN"],compute:function(e){return!ss(e)},isExported:!0},Mu={description:r("Logical `or` operator."),args:[Xa("logical_expression1 (boolean, range<boolean>)",r("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.")),Xa("logical_expression2 (boolean, range<boolean>, repeating)",r("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!1;return gs(e,(e=>(t=!0,o=o||e,!o))),ji((()=>t),r("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0},Nu={description:r("Logical `xor` operator."),args:[Xa("logical_expression1 (boolean, range<boolean>)",r("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.")),Xa("logical_expression2 (boolean, range<boolean>, repeating)",r("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!1;return gs(e,(e=>(t=!0,o=o?!e:e,!0))),ji((()=>t),r("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0};var _u=Object.freeze({__proto__:null,AND:yu,IF:Iu,IFERROR:Ru,IFNA:Tu,IFS:Au,NOT:Ou,OR:Mu,XOR:Nu});function Fu(e,t){if(void 0===e)throw new g(r("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",es(t)))}const Du={description:r("Returns a cell reference as a string. "),args:[Xa("row (number)",r("The row number of the cell reference. ")),Xa("column (number)",r("The column number (not name) of the cell reference. A is column number 1. ")),Xa("absolute_relative_mode (number, default=1)",r("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).")),Xa("use_a1_notation (boolean, default=TRUE)",r("A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).")),Xa("sheet (string, optional)",r("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 n=Qi(e),a=Qi(t);Ji(n),Ji(a);const l=Qi(o);var c,h;ji((()=>[1,2,3,4].includes(l)),(c=4,h=l,r("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(ss(i)){d=Gt(a-1,n-1,{rowFixed:!![1,2].includes(l),colFixed:!![1,3].includes(l)})}else{d=([1,2].includes(l)?`R${n}`:`R[${n}]`)+([1,3].includes(l)?`C${a}`:`C[${a}]`)}return void 0!==s?`${$e(es(s))}!${d}`:d},isExported:!0},Lu={description:r("Column number of a specified cell."),args:[Xa("cell_reference (meta, default='this cell')",r("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?.();ji((()=>!!t),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return ti(t).left+1},isExported:!0},ku={description:r("Number of columns in a specified array or range."),args:[Xa("range (meta)",r("The range whose column count will be returned."))],returns:["NUMBER"],compute:function(e){const t=ti(e);return t.right-t.left+1},isExported:!0},Pu={description:r("Horizontal lookup"),args:[Xa("search_key (any)",r("The value to search for. For example, 42, 'Cats', or I24.")),Xa("range (range)",r("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")),Xa("index (number)",r("The row index of the value to be returned, where the first row in range is numbered 1.")),Xa("is_sorted (boolean, default=true)",r("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(Xi(o)),n=os(e);ji((()=>1<=s&&s<=t[0].length),r("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=ss(i)?Ss(t,n,"nextSmaller","asc",t.length,vs):Cs(t,n,"strict",t.length,vs);const l=t[a];return Fu(l,e),l[s-1]},isExported:!0},Uu={description:r("Returns the content of a cell, specified by row and column offset."),args:[Xa("reference (any, range)",r("The range of cells from which the values are returned.")),Xa("row (number)",r("The index of the row to be returned from within the reference range of cells.")),Xa("column (number)",r("The index of the column to be returned from within the reference range of cells."))],returns:["ANY"],computeFormat:(e,t,o)=>{const i=Xi(t.value);return e[Xi(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 n=Xi(t),a=Xi(o);return ji((()=>a>=0&&a-1<i.length&&n>=0&&n-1<i[0].length),r("Index out of range.")),ji((()=>0!==t&&0!==o),r("This function can only return a single cell value, not an array. Provide valid row and column indices.")),i[a-1][n-1]},isExported:!0},Vu={description:r("Look up a value."),args:[Xa("search_key (any)",r("The value to search for. For example, 42, 'Cats', or I24.")),Xa("search_array (range)",r("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.")),Xa("result_range (range, optional)",r("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 n=os(e),a=s>=i,l=Ss(t,n,"nextSmaller","asc",a?s:i,a?bs:vs);return-1===l&&Fu(void 0,e),Fu(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,ji((()=>1===i||1===s),r("The result_range must be a single row or a single column.")),i>1?(ji((()=>l<=i-1),r("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(l+1).toString())),o[l][0]):(ji((()=>l<=s-1),r("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(l+1).toString())),o[0][l]))},isExported:!0},zu={description:r("Position of item in range that matches value."),args:[Xa("search_key (any)",r("The value to search for. For example, 42, 'Cats', or I24.")),Xa("range (any, range)",r("The one-dimensional array to be searched.")),Xa("search_type (number, default=1)",r("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=Xi(o);const s=os(e),n=t.length,a=t[0].length;ji((()=>1===n||1===a),r("The range must be a single row or a single column."));let l=-1;const c=1===n?bs:vs,h=1===n?t[0].length:t.length;switch(i=Math.sign(i),i){case 1:l=Ss(t,s,"nextSmaller","asc",h,c);break;case 0:l=Cs(t,s,"strict",h,c);break;case-1:l=Ss(t,s,"nextGreater","desc",h,c)}return Fu(1===n?t[0][l]:t[l],e),l+1},isExported:!0},Bu={description:r("Row number of a specified cell."),args:[Xa("cell_reference (meta, default='this cell')",r("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?.(),ji((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return ti(e).top+1},isExported:!0},Hu={description:r("Number of rows in a specified array or range."),args:[Xa("range (meta)",r("The range whose row count will be returned."))],returns:["NUMBER"],compute:function(e){const t=ti(e);return t.bottom-t.top+1},isExported:!0},$u={description:r("Vertical lookup."),args:[Xa("search_key (any)",r("The value to search for. For example, 42, 'Cats', or I24.")),Xa("range (any, range)",r("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")),Xa("index (number)",r("The column index of the value to be returned, where the first column in range is numbered 1.")),Xa("is_sorted (boolean, default=true)",r("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(Xi(o)),n=os(e);ji((()=>1<=s&&s<=t.length),r("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=ss(i)?Ss(t,n,"nextSmaller","asc",t[0].length,bs):Cs(t,n,"strict",t[0].length,bs);const l=t[s-1][a];return Fu(l,e),l},isExported:!0},Wu={description:r("Search a range for a match and return the corresponding item from a second range."),args:[Xa("search_key (any)",r("The value to search for.")),Xa("lookup_range (any, range)",r("The range to consider for the search. Should be a single column or a single row.")),Xa("return_range (any, range)",r("The range containing the return value. Should have the same dimensions as lookup_range.")),Xa("if_not_found (any, lazy, optional)",r("If a valid match is not found, return this value.")),Xa("match_mode (any, default=0)",r("(0) Exact match. (-1) Return next smaller item if no match. (1) Return next greater item if no match.")),Xa("search_mode (any, default=1)",r("(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,n=1){const a=Math.trunc(Xi(s)),l=Math.trunc(Xi(n)),c=os(e);ji((()=>1===t.length||1===t[0].length),r("lookup_range should be either a single row or single column.")),ji((()=>1===o.length||1===o[0].length),r("return_range should be either a single row or single column.")),ji((()=>o.length===t.length&&o[0].length===t[0].length),r("return_range should have the same dimensions as lookup_range.")),ji((()=>[-1,1,-2,2].includes(l)),r("searchMode should be a value in [-1, 1, -2, 2].")),ji((()=>[-1,0,1].includes(a)),r("matchMode should be a value in [-1, 0, 1]."));const h=1===t.length?bs:vs,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=Ss(t,c,u,2===l?"asc":"desc",d,h)}else p=Cs(t,c,u,d,h,g);if(-1!==p)return 1===t.length?o[0][p]:o[p][0];const m=i?.();return Fu(m,e),m},isExported:!0};var Gu=Object.freeze({__proto__:null,ADDRESS:Du,COLUMN:Lu,COLUMNS:ku,HLOOKUP:Pu,INDEX:Uu,LOOKUP:Vu,MATCH:zu,ROW:Bu,ROWS:Hu,VLOOKUP:$u,XLOOKUP:Wu});const qu={description:r("Sum of two numbers."),args:[Xa("value1 (number)",r("The first addend.")),Xa("value2 (number)",r("The second addend."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Xi(e)+Xi(t)}},Zu={description:r("Concatenation of two values."),args:[Xa("value1 (string)",r("The value to which value2 will be appended.")),Xa("value2 (string)",r("The value to append to value1."))],returns:["STRING"],compute:function(e,t){return es(e)+es(t)},isExported:!0},ju={description:r("One number divided by another."),args:[Xa("dividend (number)",r("The number to be divided.")),Xa("divisor (number)",r("The number to divide by."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){const o=Xi(t);return ji((()=>0!==o),r("The divisor must be different from zero.")),Xi(e)/o}};function Yu(e){return null==e}const Xu={number:0,string:"",boolean:!1},Ku={description:r("Equal."),args:[Xa("value1 (any)",r("The first value.")),Xa("value2 (any)",r("The value to test against value1 for equality."))],returns:["BOOLEAN"],compute:function(e,t){return e=Yu(e)?Xu[typeof t]:e,t=Yu(t)?Xu[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function Qu(e,t,o){e=Yu(e)?Xu[typeof t]:e,t=Yu(t)?Xu[typeof e]:t,"number"!=typeof e&&(e=es(e).toUpperCase()),"number"!=typeof t&&(t=es(t).toUpperCase());const i=typeof e,s=typeof t;return"string"===i&&"number"===s||("string"!==s||"number"!==i)&&o(e,t)}const Ju={description:r("Strictly greater than."),args:[Xa("value1 (any)",r("The value to test as being greater than value2.")),Xa("value2 (any)",r("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return Qu(e,t,((e,t)=>e>t))}},eg={description:r("Greater than or equal to."),args:[Xa("value1 (any)",r("The value to test as being greater than or equal to value2.")),Xa("value2 (any)",r("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return Qu(e,t,((e,t)=>e>=t))}},tg={description:r("Less than."),args:[Xa("value1 (any)",r("The value to test as being less than value2.")),Xa("value2 (any)",r("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!eg.compute(e,t)}},og={description:r("Less than or equal to."),args:[Xa("value1 (any)",r("The value to test as being less than or equal to value2.")),Xa("value2 (any)",r("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!Ju.compute(e,t)}},ig={description:r("Difference of two numbers."),args:[Xa("value1 (number)",r("The minuend, or number to be subtracted from.")),Xa("value2 (number)",r("The subtrahend, or number to subtract from value1."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Xi(e)-Xi(t)}},sg={description:r("Product of two numbers"),args:[Xa("factor1 (number)",r("The first multiplicand.")),Xa("factor2 (number)",r("The second multiplicand."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Xi(e)*Xi(t)}},rg={description:r("Not equal."),args:[Xa("value1 (any)",r("The first value.")),Xa("value2 (any)",r("The value to test against value1 for inequality."))],returns:["BOOLEAN"],compute:function(e,t){return!Ku.compute(e,t)}},ng={description:r("A number raised to a power."),args:[Xa("base (number)",r("The number to raise to the exponent power.")),Xa("exponent (number)",r("The exponent to raise base to."))],returns:["NUMBER"],compute:function(e,t){return Vl.compute(e,t)}},ag={description:r("A number with the sign reversed."),args:[Xa("value (number)",r("The number to have its sign reversed. Equivalently, the number to multiply by -1."))],computeFormat:e=>e?.format,returns:["NUMBER"],compute:function(e){return-Xi(e)}},lg={description:r("Value interpreted as a percentage."),args:[Xa("percentage (number)",r("The value to interpret as a percentage."))],returns:["NUMBER"],compute:function(e){return Xi(e)/100}},cg={description:r("A specified number, unchanged."),args:[Xa("value (any)",r("The number to return."))],returns:["ANY"],computeFormat:e=>e?.format,compute:function(e){return null===e?"":e}};var hg=Object.freeze({__proto__:null,ADD:qu,CONCAT:Zu,DIVIDE:ju,EQ:Ku,GT:Ju,GTE:eg,LT:tg,LTE:og,MINUS:ig,MULTIPLY:sg,NE:rg,POW:ng,UMINUS:ag,UNARY_PERCENT:lg,UPLUS:cg});const dg=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,ug={description:r("Gets character associated with number."),args:[Xa("table_number (number)",r("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(Xi(e));return ji((()=>t>=1),r("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},gg={description:r("Remove non-printable characters from a piece of text."),args:[Xa("text (string)",r("The text whose non-printable characters are to be removed."))],returns:["STRING"],compute:function(e){const t=es(e);let o="";for(const e of t)e&&e.charCodeAt(0)>31&&(o+=e);return o},isExported:!0},pg={description:r("Appends strings to one another."),args:[Xa("string1 (string, range<string>)",r("The initial string.")),Xa("string2 (string, range<string>, repeating)",r("More strings to append in sequence."))],returns:["STRING"],compute:function(...e){return hs(e,((e,t)=>e+es(t)),"")},isExported:!0},mg={description:r("Tests whether two strings are identical."),args:[Xa("string1 (string)",r("The first string to compare.")),Xa("string2 (string)",r("The second string to compare."))],returns:["BOOLEAN"],compute:function(e,t){return es(e)===es(t)},isExported:!0},fg={description:r("First position of string found in text, case-sensitive."),args:[Xa("search_for (string)",r("The string to look for within text_to_search.")),Xa("text_to_search (string)",r("The text to search for the first occurrence of search_for.")),Xa("starting_at (number, default=1)",r("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,o=1){const i=es(e),s=es(t),n=Xi(o);ji((()=>""!==s),r("The text_to_search must be non-empty.")),ji((()=>n>=1),r("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const a=s.indexOf(i,n-1);return ji((()=>a>=0),r("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i.toString(),s)),a+1},isExported:!0},bg={description:r("Concatenates elements of arrays with delimiter."),args:[Xa("delimiter (string)",r("The character or string to place between each concatenated value.")),Xa("value_or_array1 (string, range<string>)",r("The value or values to be appended using delimiter.")),Xa("value_or_array2 (string, range<string>, repeating)",r("More values to be appended using delimiter."))],returns:["STRING"],compute:function(e,...t){const o=es(e);return hs(t,((e,t)=>(e?e+o:"")+es(t)),"")}},vg={description:r("Substring from beginning of specified string."),args:[Xa("text (string)",r("The string from which the left portion will be returned.")),Xa("number_of_characters (number, optional)",r("The number of characters to return from the left side of string."))],returns:["STRING"],compute:function(e,...t){const o=t.length?Xi(t[0]):1;return ji((()=>o>=0),r("The number_of_characters (%s) must be positive or null.",o.toString())),es(e).substring(0,o)},isExported:!0},Sg={description:r("Length of a string."),args:[Xa("text (string)",r("The string whose length will be returned."))],returns:["NUMBER"],compute:function(e){return es(e).length},isExported:!0},Cg={description:r("Converts a specified string to lowercase."),args:[Xa("text (string)",r("The string to convert to lowercase."))],returns:["STRING"],compute:function(e){return es(e).toLowerCase()},isExported:!0},Eg={description:r("A segment of a string."),args:[Xa("text (string)",r("The string to extract a segment from.")),Xa("starting_at (number)",r("The index from the left of string from which to begin extracting. The first character in string has the index 1.")),Xa("extract_length (number)",r("The length of the segment to extract."))],returns:["STRING"],compute:function(e,t,o){const i=es(e),s=Xi(t),n=Xi(o);return ji((()=>s>=1),r("The starting_at argument (%s) must be positive greater than one.",s.toString())),ji((()=>n>=0),r("The extract_length argument (%s) must be positive or null.",n.toString())),i.slice(s-1,s+n-1)},isExported:!0},wg={description:r("Capitalizes each word in a specified string."),args:[Xa("text_to_capitalize (string)",r("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 es(e).replace(dg,(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()))},isExported:!0},xg={description:r("Replaces part of a text string with different text."),args:[Xa("text (string)",r("The text, a part of which will be replaced.")),Xa("position (number)",r("The position where the replacement will begin (starting from 1).")),Xa("length (number)",r("The number of characters in the text to be replaced.")),Xa("new_text (string)",r("The text which will be inserted into the original text."))],returns:["STRING"],compute:function(e,t,o,i){const s=Xi(t);ji((()=>s>=1),r("The position (%s) must be greater than or equal to 1.",s.toString()));const n=es(e),a=Xi(o),l=es(i);return n.substring(0,s-1)+l+n.substring(s-1+a)},isExported:!0},yg={description:r("A substring from the end of a specified string."),args:[Xa("text (string)",r("The string from which the right portion will be returned.")),Xa("number_of_characters (number, optional)",r("The number of characters to return from the right side of string."))],returns:["STRING"],compute:function(e,...t){const o=t.length?Xi(t[0]):1;ji((()=>o>=0),r("The number_of_characters (%s) must be positive or null.",o.toString()));const i=es(e),s=i.length;return i.substring(s-o,s)},isExported:!0},Ig={description:r("First position of string found in text, ignoring case."),args:[Xa("search_for (string)",r("The string to look for within text_to_search.")),Xa("text_to_search (string)",r("The text to search for the first occurrence of search_for.")),Xa("starting_at (number, default=1)",r("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,o=1){const i=es(e).toLowerCase(),s=es(t).toLowerCase(),n=Xi(o);ji((()=>""!==s),r("The text_to_search must be non-empty.")),ji((()=>n>=1),r("The starting_at (%s) must be greater than or equal to 1.",n.toString()));const a=s.indexOf(i,n-1);return ji((()=>a>=0),r("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i,s)),a+1},isExported:!0},Rg={description:r("Replaces existing text with new text in a string."),args:[Xa("text_to_search (string)",r("The text within which to search and replace.")),Xa("search_for (string)",r("The string to search for within text_to_search.")),Xa("replace_with (string)",r("The string that will replace search_for.")),Xa("occurrence_number (number, optional)",r("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=Xi(i);ji((()=>s>=0),r("The occurrenceNumber (%s) must be positive or null.",s.toString()));const n=es(e),a=es(t);if(""===a)return n;const l=es(o),c=new RegExp(ze(a),"g");if(0===s)return n.replace(c,l);let h=0;return n.replace(c,(e=>++h===s?l:e))},isExported:!0},Tg={description:r("Combines text from multiple strings and/or arrays."),args:[Xa("delimiter (string)",r(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")),Xa("ignore_empty (boolean)",r("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")),Xa("text1 (string, range<string>)",r("Any text item. This could be a string, or an array of strings in a range.")),Xa("text2 (string, range<string>, repeating)",r("Additional text item(s)."))],returns:["STRING"],compute:function(e,t,...o){const i=es(e),s=ss(t);let r=0;return hs(o,((e,t)=>s&&""===es(t)?e:(r++?e+i:"")+es(t)),"")},isExported:!0},Ag={description:r("Removes space characters."),args:[Xa("text (string)",r("The text or reference to a cell containing text to be trimmed."))],returns:["STRING"],compute:function(e){return es(e).trim()},isExported:!0},Og={description:r("Converts a specified string to uppercase."),args:[Xa("text (string)",r("The string to convert to uppercase."))],returns:["STRING"],compute:function(e){return es(e).toUpperCase()},isExported:!0},Mg={description:r("Converts a number to text according to a specified format."),args:[Xa("number (number)",r("The number, date or time to format.")),Xa("format (string)",r("The pattern by which to format the number, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){return mo(Xi(e),es(t))},isExported:!0};var Ng=Object.freeze({__proto__:null,CHAR:ug,CLEAN:gg,CONCATENATE:pg,EXACT:mg,FIND:fg,JOIN:bg,LEFT:vg,LEN:Sg,LOWER:Cg,MID:Eg,PROPER:wg,REPLACE:xg,RIGHT:yg,SEARCH:Ig,SUBSTITUTE:Rg,TEXTJOIN:Tg,TRIM:Ag,UPPER:Og,TEXT:Mg});const _g={description:r("Creates a hyperlink in a cell."),args:[Xa("url (string)",r("The full URL of the link enclosed in quotation marks.")),Xa("link_label (string, optional)",r("The text to display in the cell, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){const o=es(e).trim(),i=es(t)||o;return""===o?i:rt(i,o)},isExported:!0};var Fg=Object.freeze({__proto__:null,HYPERLINK:_g});const Dg=[{name:r("Database"),functions:lh},{name:r("Date"),functions:$h},{name:r("Financial"),functions:gu},{name:r("Info"),functions:xu},{name:r("Lookup"),functions:Gu},{name:r("Logical"),functions:_u},{name:r("Math"),functions:ic},{name:r("Misc"),functions:Ja},{name:r("Operator"),functions:hg},{name:r("Statistical"),functions:Zc},{name:r("Text"),functions:Ng},{name:r("Engineering"),functions:Gh},{name:r("Web"),functions:Fg}],Lg=/^[A-Z0-9\_\.]+$/;function kg(e){return e.map((e=>{if(void 0!==e)return"function"==typeof e?()=>Pg(e()):Pg(e)}))}function Pg(e){return Array.isArray(e)?e.map((e=>e.map((e=>e?.value)))):e?.value}const Ug=new class extends Ui{mapping={};add(e,t){if(e=e.toUpperCase(),!Lg.test(e))throw new Error(r("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const o=Ka(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(r("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(r("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=o||t||i,n=!(s.optional||s.repeating||s.default);if(e&&n)throw new Error(r("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(...kg(e)),format:i(...e)}},super.add(e,o),this}};for(let e of Dg){const t=e.functions;for(let o in t){const i=t[o];i.category=i.category||e.name,o=o.replace(/_/g,"."),Ug.add(o,{isExported:!1,...i})}}const Vg={name:e=>{const t=ha(e);return 1===t?r("Insert row"):r("Insert %s rows",t.toString())},isVisible:e=>ya(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW"},zg={name:e=>{const t=ha(e);return 1===t?r("Insert row above"):r("Insert %s rows above",t.toString())},execute:fa,isVisible:e=>ya(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},Bg={...zg,name:e=>{const t=ha(e);return 1===t?r("Row above"):r("%s Rows above",t.toString())}},Hg={...zg,name:e=>{const t=ha(e);return 1===t?r("Insert row"):r("Insert %s rows",t.toString())},isVisible:xa,icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},$g={execute:e=>{const t=e.model.getters.getActiveRows();let o,i;if(t.size)o=Math.max(...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=ha(e);return 1===t?r("Insert row below"):r("Insert %s rows below",t.toString())},isVisible:e=>ya(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_AFTER"},Wg={...$g,name:e=>{const t=ha(e);return 1===t?r("Row below"):r("%s Rows below",t.toString())}},Gg={name:e=>{const t=ca(e);return 1===t?r("Insert column"):r("Insert %s columns",t.toString())},isVisible:e=>ya(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL"},qg={name:e=>{const t=ca(e);return 1===t?r("Insert column left"):r("Insert %s columns left",t.toString())},execute:ba,isVisible:e=>ya(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},Zg={...qg,name:e=>{const t=ca(e);return 1===t?r("Column left"):r("%s Columns left",t.toString())}},jg={...qg,name:e=>{const t=ca(e);return 1===t?r("Insert column"):r("Insert %s columns",t.toString())},isVisible:xa,icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},Yg={name:e=>{const t=ca(e);return 1===t?r("Insert column right"):r("Insert %s columns right",t.toString())},execute:va,isVisible:e=>ya(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_AFTER"},Xg={...Yg,name:e=>{const t=ca(e);return 1===t?r("Column right"):r("%s Columns right",t.toString())},execute:va},Kg={name:r("Insert cells"),isVisible:e=>xa(e)&&0===e.model.getters.getActiveCols().size&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_CELL"},Qg={name:r("Insert cells and shift down"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});na(e,o)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_DOWN"},Jg={name:r("Insert cells and shift right"),execute:e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});na(e,o)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_RIGHT"},ep={name:r("Chart"),execute:e=>{const t=e.model.getters,o=e.model.uuidGenerator.uuidv4(),i=t.getActiveSheetId();1===yi(e.model.getters.getSelectedZone())&&e.model.selection.selectTableAroundSelection();const s={width:536,height:335},r=function(e,t){const{x:o,y:i}=e.getMainViewportCoordinates(),{scrollX:s,scrollY:r}=e.getActiveSheetScrollInfo(),{width:n,height:a}=e.getVisibleRect(e.getActiveMainViewport());return{x:o+s+Math.max(0,(n-t.width)/2),y:i+r+Math.max(0,(a-t.height)/2)}}(t,s);e.model.dispatch("CREATE_CHART",{sheetId:i,id:o,position:r,size:s,definition:Jn(e.model.getters.getSelectedZone(),e.model.getters)}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{id:o}),e.openSidePanel("ChartPanel"))},icon:"o-spreadsheet-Icon.INSERT_CHART"},tp={name:r("Image"),description:"Ctrl+O",execute:Sa,isVisible:e=>void 0!==e.imageProvider,icon:"o-spreadsheet-Icon.INSERT_IMAGE"},op={name:r("Function"),icon:"o-spreadsheet-Icon.SHOW_HIDE_FORMULA"},ip={name:r("SUM"),execute:e=>e.startCellEdition("=SUM(")},sp={name:r("AVERAGE"),execute:e=>e.startCellEdition("=AVERAGE(")},rp={name:r("COUNT"),execute:e=>e.startCellEdition("=COUNT(")},np={name:r("MAX"),execute:e=>e.startCellEdition("=MAX(")},ap={name:r("MIN"),execute:e=>e.startCellEdition("=MIN(")},lp={name:r("All"),children:[function(){return dp(Ug.getKeys())}]};const cp={name:r("Link"),execute:Ea,icon:"o-spreadsheet-Icon.INSERT_LINK"},hp={name:r("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 dp(e){return e.sort().map(((e,t)=>({name:e,sequence:10*t,execute:t=>t.startCellEdition(`=${e}(`)})))}const up=new Mr;up.add("cut",{...Aa,sequence:10}).add("copy",{...Ta,sequence:20}).add("paste",{...Oa,sequence:30}).add("paste_special",{...Ma,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...Na,sequence:10}).addChild("paste_format_only",["paste_special"],{..._a,sequence:20}).add("add_row_before",{...Hg,sequence:70}).add("add_column_before",{...jg,sequence:90}).add("insert_cell",{...Kg,sequence:100,separator:!0}).addChild("insert_cell_down",["insert_cell"],{...Qg,name:r("Shift down"),sequence:10}).addChild("insert_cell_right",["insert_cell"],{...Jg,name:r("Shift right"),sequence:20}).add("delete_row",{...ka,sequence:110,icon:"o-spreadsheet-Icon.DELETE"}).add("delete_column",{...Va,sequence:120,icon:"o-spreadsheet-Icon.DELETE"}).add("delete_cell",{...Ba,sequence:130,separator:!0,icon:"o-spreadsheet-Icon.DELETE"}).addChild("delete_cell_up",["delete_cell"],{...Ha,name:r("Shift up"),sequence:10,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_UP"}).addChild("delete_cell_left",["delete_cell"],{...$a,name:r("Shift left"),sequence:20,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_LEFT"}).add("insert_link",{...cp,name:r("Insert link"),sequence:150,separator:!0});const gp={name:r("Sort range"),isVisible:xa,icon:"o-spreadsheet-Icon.SORT_RANGE"},pp={name:r("Ascending (A ⟶ Z)"),execute:e=>{const{anchor:t,zones:o}=e.model.getters.getSelection(),i=e.model.getters.getActiveSheetId();ta(e,i,t.cell,o[0],"ascending")},icon:"o-spreadsheet-Icon.SORT_ASCENDING"},mp={name:r("Descending (Z ⟶ A)"),execute:e=>{const{anchor:t,zones:o}=e.model.getters.getSelection(),i=e.model.getters.getActiveSheetId();ta(e,i,t.cell,o[0],"descending")},icon:"o-spreadsheet-Icon.SORT_DESCENDING"},fp={name:r("Create filter"),execute:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelection().zones;sa(e,t,o)},isVisible:e=>!wa(e),isEnabled:e=>(e=>Ii(...e.model.getters.getSelectedZones()))(e),icon:"o-spreadsheet-Icon.MENU_FILTER_ICON"},bp={name:r("Remove filter"),execute:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:t,target:e.model.getters.getSelectedZones()})},isVisible:wa,icon:"o-spreadsheet-Icon.MENU_FILTER_ICON"},vp={name:r("Split text to columns"),sequence:1,execute:e=>e.openSidePanel("SplitToColumns",{}),isEnabled:e=>e.model.getters.isSingleColSelected(),icon:"o-spreadsheet-Icon.SPLIT_TEXT"},Sp={name:r("Automatic"),execute:e=>da(e,""),isActive:e=>function(e){const t=e.model.getters.getCell(e.model.getters.getActivePosition());return!t||!t.format}(e)},Cp={name:r("Number"),description:"1,000.12",execute:e=>da(e,"#,##0.00"),isActive:e=>tm(e,"#,##0.00")},Ep={name:r("Format as percent"),execute:Ca,icon:"o-spreadsheet-Icon.PERCENT"},wp={name:r("Percent"),description:"10.12%",execute:Ca,isActive:e=>tm(e,"0.00%")},xp={name:r("Currency"),description:"$1,000.12",execute:e=>da(e,"[$$]#,##0.00"),isActive:e=>tm(e,"[$$]#,##0.00")},yp={name:r("Currency rounded"),description:"$1,000",execute:e=>da(e,"[$$]#,##0"),isActive:e=>tm(e,"[$$]#,##0")},Ip={name:r("Custom currency"),isVisible:e=>void 0!==e.loadCurrencies,execute:e=>{e.openSidePanel("CustomCurrency",{})}},Rp={name:r("Date"),description:"9/26/2008",execute:e=>da(e,"m/d/yyyy"),isActive:e=>tm(e,"m/d/yyyy")},Tp={name:r("Time"),description:"10:43:00 PM",execute:e=>da(e,"hh:mm:ss a"),isActive:e=>tm(e,"hh:mm:ss a")},Ap={name:r("Date time"),description:"9/26/2008 22:43:00",execute:e=>da(e,"m/d/yyyy hh:mm:ss"),isActive:e=>tm(e,"m/d/yyyy hh:mm:ss")},Op={name:r("Duration"),description:"27:51:38",execute:e=>da(e,"hhhh:mm:ss"),isActive:e=>tm(e,"hhhh:mm:ss")},Mp={name:r("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})},Np={name:r("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})},_p={name:r("Bold"),description:"Ctrl+B",execute:e=>ua(e,{bold:!e.model.getters.getCurrentStyle().bold}),icon:"o-spreadsheet-Icon.BOLD",isActive:e=>!!e.model.getters.getCurrentStyle().bold},Fp={name:r("Italic"),description:"Ctrl+I",execute:e=>ua(e,{italic:!e.model.getters.getCurrentStyle().italic}),icon:"o-spreadsheet-Icon.ITALIC",isActive:e=>!!e.model.getters.getCurrentStyle().italic},Dp={name:r("Underline"),description:"Ctrl+U",execute:e=>ua(e,{underline:!e.model.getters.getCurrentStyle().underline}),icon:"o-spreadsheet-Icon.UNDERLINE",isActive:e=>!!e.model.getters.getCurrentStyle().underline},Lp={name:r("Strikethrough"),execute:e=>ua(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),icon:"o-spreadsheet-Icon.STRIKE",isActive:e=>!!e.model.getters.getCurrentStyle().strikethrough},kp={name:r("Font size"),children:fe.map((e=>({name:e.toString(),sequence:e,id:`font_size_${e}`,execute:t=>ua(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"},Pp={name:r("Alignment"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},Up={name:r("Horizontal align"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},Vp={name:r("Left"),description:"Ctrl+Shift+L",execute:e=>ua(e,{align:"left"}),isActive:e=>"left"===om(e),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},zp={name:r("Center"),description:"Ctrl+Shift+E",execute:e=>ua(e,{align:"center"}),isActive:e=>"center"===om(e),icon:"o-spreadsheet-Icon.ALIGN_CENTER"},Bp={name:r("Right"),description:"Ctrl+Shift+R",execute:e=>ua(e,{align:"right"}),isActive:e=>"right"===om(e),icon:"o-spreadsheet-Icon.ALIGN_RIGHT"},Hp={name:r("Vertical align"),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},$p={name:r("Top"),execute:e=>ua(e,{verticalAlign:"top"}),isActive:e=>"top"===(e.model.getters.getCurrentStyle().verticalAlign||Y),icon:"o-spreadsheet-Icon.ALIGN_TOP"},Wp={name:r("Middle"),execute:e=>ua(e,{verticalAlign:"middle"}),isActive:e=>"middle"===(e.model.getters.getCurrentStyle().verticalAlign||Y),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},Gp={name:r("Bottom"),execute:e=>ua(e,{verticalAlign:"bottom"}),isActive:e=>"bottom"===(e.model.getters.getCurrentStyle().verticalAlign||Y),icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"},qp={name:r("Wrapping"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},Zp={name:r("Overflow"),execute:e=>ua(e,{wrapping:"overflow"}),isActive:e=>"overflow"===(e.model.getters.getCurrentStyle().wrapping||"overflow"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},jp={name:r("Wrap"),execute:e=>ua(e,{wrapping:"wrap"}),isActive:e=>"wrap"===e.model.getters.getCurrentStyle().wrapping,icon:"o-spreadsheet-Icon.WRAPPING_WRAP"},Yp={name:r("Clip"),execute:e=>ua(e,{wrapping:"clip"}),isActive:e=>"clip"===e.model.getters.getCurrentStyle().wrapping,icon:"o-spreadsheet-Icon.WRAPPING_CLIP"},Xp={name:r("Text Color"),icon:"o-spreadsheet-Icon.TEXT_COLOR"},Kp={name:r("Fill Color"),icon:"o-spreadsheet-Icon.FILL_COLOR"},Qp={name:r("Conditional formatting"),execute:e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},icon:"o-spreadsheet-Icon.CONDITIONAL_FORMAT"},Jp={name:r("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()},em={name:r("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 tm(e,t){return e.model.getters.getCell(e.model.getters.getActivePosition())?.format===t}function om(e){const t=e.model.getters.getCurrentStyle();if(t.align)return t.align;return e.model.getters.getActiveCell().defaultAlign}var im=Object.freeze({__proto__:null,formatNumberAutomatic:Sp,formatNumberNumber:Cp,formatPercent:Ep,formatNumberPercent:wp,formatNumberCurrency:xp,formatNumberCurrencyRounded:yp,formatCustomCurrency:Ip,formatNumberDate:Rp,formatNumberTime:Tp,formatNumberDateTime:Ap,formatNumberDuration:Op,incraseDecimalPlaces:Mp,decraseDecimalPlaces:Np,formatBold:_p,formatItalic:Fp,formatUnderline:Dp,formatStrikethrough:Lp,formatFontSize:kp,formatAlignment:Pp,formatAlignmentHorizontal:Up,formatAlignmentLeft:Vp,formatAlignmentCenter:zp,formatAlignmentRight:Bp,formatAlignmentVertical:Hp,formatAlignmentTop:$p,formatAlignmentMiddle:Wp,formatAlignmentBottom:Gp,formatWrapping:qp,formatWrappingOverflow:Zp,formatWrappingWrap:jp,formatWrappingClip:Yp,textColor:Xp,fillColor:Kp,formatCF:Qp,paintFormat:Jp,clearFormat:em});function sm(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(65)&&e.raiseError(an)}const rm={name:e=>{const t=e.model.getters.getElementsFromSelection("COL");let o=t[0],i=t[t.length-1];return 1===t.length?r("Hide column %s",Vt(o).toString()):i-o+1===t.length?r("Hide columns %s - %s",Vt(o).toString(),Vt(i).toString()):r("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"},nm={name:r("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)))}},am={name:r("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},lm={name:e=>{const t=e.model.getters.getElementsFromSelection("ROW");let o=t[0],i=t[t.length-1];return 1===t.length?r("Hide row %s",(o+1).toString()):i-o+1===t.length?r("Hide rows %s - %s",(o+1).toString(),(i+1).toString()):r("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"},cm={name:r("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)))}},hm={name:r("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},dm={name:r("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"},um={name:r("Freeze"),icon:"o-spreadsheet-Icon.FREEZE"},gm={name:r("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},pm={name:r("1 row"),execute:e=>sm(e,"ROW",1),isReadonlyAllowed:!0},mm={name:r("2 rows"),execute:e=>sm(e,"ROW",2),isReadonlyAllowed:!0},fm={name:r("Up to current row"),execute:e=>{const{bottom:t}=e.model.getters.getSelectedZone();sm(e,"ROW",t+1)},isReadonlyAllowed:!0},bm={name:r("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},vm={name:r("1 column"),execute:e=>sm(e,"COL",1),isReadonlyAllowed:!0},Sm={name:r("2 columns"),execute:e=>sm(e,"COL",2),isReadonlyAllowed:!0},Cm={name:r("Up to current column"),execute:e=>{const{right:t}=e.model.getters.getSelectedZone();sm(e,"COL",t+1)},isReadonlyAllowed:!0},Em={name:e=>e.model.getters.getGridLinesVisibility(e.model.getters.getActiveSheetId())?r("Hide gridlines"):r("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"},wm={name:e=>e.model.getters.shouldShowFormulas()?r("Hide formulas"):r("Show formulas"),execute:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,icon:"o-spreadsheet-Icon.SHOW_HIDE_FORMULA"},xm={name:e=>ym(e)?r("Remove selected filters"):r("Create filter"),isActive:e=>ym(e),isEnabled:e=>!Im(e),execute:e=>function(e){if(ym(e))return void e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()});if(Im(e))return;e.model.selection.selectTableAroundSelection();const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();sa(e,t,o)}(e),icon:"o-spreadsheet-Icon.FILTER_ICON_INACTIVE"};function ym(e){const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,o)}function Im(e){return!Ii(...e.model.getters.getSelectedZones())}var Rm=Object.freeze({__proto__:null,hideCols:rm,unhideCols:nm,unhideAllCols:am,hideRows:lm,unhideRows:cm,unhideAllRows:hm,unFreezePane:dm,freezePane:um,unFreezeRows:gm,freezeFirstRow:pm,freezeSecondRow:mm,freezeCurrentRow:fm,unFreezeCols:bm,freezeFirstCol:vm,freezeSecondCol:Sm,freezeCurrentCol:Cm,viewGridlines:Em,viewFormulas:wm,createRemoveFilter:xm});const Tm=new Mr;Tm.add("cut",{...Aa,sequence:10}).add("copy",{...Ta,sequence:20}).add("paste",{...Oa,sequence:30}).add("paste_special",{...Ma,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...Na,sequence:10}).addChild("paste_format_only",["paste_special"],{..._a,sequence:20}).add("sort_columns",{...gp,name:e=>e.model.getters.getActiveCols().size>1?r("Sort columns"):r("Sort column"),sequence:50,separator:!0}).addChild("sort_ascending",["sort_columns"],{...pp,sequence:10}).addChild("sort_descending",["sort_columns"],{...mp,sequence:20}).add("add_column_before",{...qg,sequence:70}).add("add_column_after",{...Yg,sequence:80}).add("delete_column",{...Ua,sequence:90,icon:"o-spreadsheet-Icon.DELETE"}).add("clear_column",{...za,sequence:100,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_columns",{...rm,sequence:105,separator:!0}).add("unhide_columns",{...nm,sequence:106,separator:!0}).add("conditional_formatting",{...Qp,sequence:110});const Am=new Mr;Am.add("format_number_automatic",{...Sp,sequence:10,separator:!0}).add("format_number_number",{...Cp,sequence:20}).add("format_number_percent",{...wp,sequence:30,separator:!0}).add("format_number_currency",{...xp,sequence:40}).add("format_number_currency_rounded",{...yp,sequence:50}).add("format_custom_currency",{...Ip,sequence:60,separator:!0}).add("format_number_date",{...Rp,sequence:70}).add("format_number_time",{...Tp,sequence:80}).add("format_number_date_time",{...Ap,sequence:90}).add("format_number_duration",{...Op,sequence:100,separator:!0});const Om={name:r("More formats"),icon:"o-spreadsheet-Icon.NUMBER_FORMATS",children:[()=>Am.getAll()]},Mm=new Mr;Mm.add("cut",{...Aa,sequence:10}).add("copy",{...Ta,sequence:20}).add("paste",{...Oa,sequence:30}).add("paste_special",{...Ma,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...Na,sequence:10}).addChild("paste_format_only",["paste_special"],{..._a,sequence:20}).add("add_row_before",{...zg,sequence:50}).add("add_row_after",{...$g,sequence:60}).add("delete_row",{...La,sequence:70,icon:"o-spreadsheet-Icon.DELETE"}).add("clear_row",{...Pa,sequence:80,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_rows",{...lm,sequence:85,separator:!0}).add("unhide_rows",{...cm,sequence:86,separator:!0}).add("conditional_formatting",{...Qp,sequence:90});const Nm=new Mr;Nm.add("file",{name:r("File"),sequence:10}).add("edit",{name:r("Edit"),sequence:20}).addChild("undo",["edit"],{...Ia,sequence:10}).addChild("redo",["edit"],{...Ra,sequence:20,separator:!0}).addChild("copy",["edit"],{...Ta,sequence:30}).addChild("cut",["edit"],{...Aa,sequence:40}).addChild("paste",["edit"],{...Oa,sequence:50}).addChild("paste_special",["edit"],{...Ma,sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{...Na,sequence:10}).addChild("paste_special_format",["edit","paste_special"],{..._a,sequence:20}).addChild("find_and_replace",["edit"],{...Fa,sequence:65,separator:!0}).addChild("delete",["edit"],{name:r("Delete"),icon:"o-spreadsheet-Icon.DELETE",sequence:70}).addChild("edit_delete_cell_values",["edit","delete"],{...Da,sequence:10}).addChild("edit_delete_row",["edit","delete"],{...La,sequence:20}).addChild("edit_delete_column",["edit","delete"],{...Ua,sequence:30}).addChild("edit_delete_cell_shift_up",["edit","delete"],{...Ha,sequence:40}).addChild("edit_delete_cell_shift_left",["edit","delete"],{...$a,sequence:50}).addChild("edit_unhide_columns",["edit"],{...am,sequence:80}).addChild("edit_unhide_rows",["edit"],{...hm,sequence:80}).add("view",{name:r("View"),sequence:30}).addChild("unfreeze_panes",["view"],{...dm,sequence:4}).addChild("freeze_panes",["view"],{...um,sequence:5,separator:!0}).addChild("unfreeze_rows",["view","freeze_panes"],{...gm,sequence:5}).addChild("freeze_first_row",["view","freeze_panes"],{...pm,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{...mm,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{...fm,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{...bm,sequence:25}).addChild("freeze_first_col",["view","freeze_panes"],{...vm,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{...Sm,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{...Cm,sequence:40}).addChild("view_gridlines",["view"],{...Em,sequence:10}).addChild("view_formulas",["view"],{...wm,sequence:15}).add("insert",{name:r("Insert"),sequence:40}).addChild("insert_row",["insert"],{...Vg,sequence:10}).addChild("insert_row_before",["insert","insert_row"],{...Bg,sequence:10}).addChild("insert_row_after",["insert","insert_row"],{...Wg,sequence:20}).addChild("insert_column",["insert"],{...Gg,sequence:20}).addChild("insert_column_before",["insert","insert_column"],{...Zg,sequence:10}).addChild("insert_column_after",["insert","insert_column"],{...Xg,sequence:20}).addChild("insert_cell",["insert"],{...Kg,sequence:43}).addChild("insert_cell_down",["insert","insert_cell"],{...Qg,name:r("Shift down"),sequence:10}).addChild("insert_cell_right",["insert","insert_cell"],{...Jg,name:r("Shift right"),sequence:20}).addChild("insert_sheet",["insert"],{...hp,sequence:80,separator:!0}).addChild("insert_chart",["insert"],{...ep,sequence:50}).addChild("insert_image",["insert"],{...tp,sequence:55}).addChild("insert_function",["insert"],{...op,sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{...ip,sequence:0}).addChild("insert_function_average",["insert","insert_function"],{...sp,sequence:10}).addChild("insert_function_count",["insert","insert_function"],{...rp,sequence:20}).addChild("insert_function_max",["insert","insert_function"],{...np,sequence:30}).addChild("insert_function_min",["insert","insert_function"],{...ap,sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{...lp,sequence:50}).addChild("categories_function_list",["insert","insert_function"],(()=>{const e=Ug.content;return[...new Set(Ug.getAll().map((e=>e.category)))].filter(dt).sort().map(((t,o)=>{const i=Object.keys(e).filter((o=>e[o].category===t));return{name:t,children:dp(i)}}))})).addChild("insert_link",["insert"],{...cp,separator:!0,sequence:70}).add("format",{name:r("Format"),sequence:50}).addChild("format_number",["format"],{...Om,name:r("Number"),sequence:10,separator:!0}).addChild("format_bold",["format"],{..._p,sequence:20}).addChild("format_italic",["format"],{...Fp,sequence:30}).addChild("format_underline",["format"],{...Dp,sequence:40}).addChild("format_strikethrough",["format"],{...Lp,sequence:50,separator:!0}).addChild("format_font_size",["format"],{...kp,sequence:60,separator:!0}).addChild("format_alignment",["format"],{...Pp,sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{...Vp,sequence:10}).addChild("format_alignment_center",["format","format_alignment"],{...zp,sequence:20}).addChild("format_alignment_right",["format","format_alignment"],{...Bp,sequence:30,separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{...$p,sequence:40}).addChild("format_alignment_middle",["format","format_alignment"],{...Wp,sequence:50}).addChild("format_alignment_bottom",["format","format_alignment"],{...Gp,sequence:60,separator:!0}).addChild("format_wrapping",["format"],{...qp,sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{...Zp,sequence:10}).addChild("format_wrapping_wrap",["format","format_wrapping"],{...jp,sequence:20}).addChild("format_wrapping_clip",["format","format_wrapping"],{...Yp,sequence:30}).addChild("format_cf",["format"],{...Qp,sequence:90,separator:!0}).addChild("format_clearFormat",["format"],{...em,sequence:100,separator:!0}).add("data",{name:r("Data"),sequence:60}).addChild("sort_range",["data"],{...gp,sequence:10,separator:!0}).addChild("sort_ascending",["data","sort_range"],{...pp,sequence:10}).addChild("sort_descending",["data","sort_range"],{...mp,sequence:20}).addChild("split_to_columns",["data"],{...vp,sequence:20,separator:!0}).addChild("add_data_filter",["data"],{...fp,sequence:30}).addChild("remove_data_filter",["data"],{...bp,sequence:30});const _m=new class extends Ui{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)}},Fm={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function Dm(e,t){const o=Fm[e.key];e.shiftKey?t.resizeAnchorZone(o,ar(e)?"end":1):t.moveAnchorCell(o,ar(e)?"end":1)}const Lm=new Jo;Oi`
353
+ `;class Hr 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=zr.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}Hr.props={figure:Object,onFigureDeleted:Function};class $r 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 Wr(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}$r.props={figure:Object,onFigureDeleted:Function};const Gr=new Ui;function qr(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 Zr(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 jr(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()}}}Gr.add("chart",{Component:Hr,SidePanelComponent:"ChartPanel",menuBuilder:function(e,t,o){return An([{id:"edit",name:n("Edit"),sequence:1,execute:()=>{o.model.dispatch("SELECT_FIGURE",{id:e}),o.openSidePanel("ChartPanel")}},qr(e,o),Zr(e,o),jr(e,t,o)])}}),Gr.add("image",{Component:$r,keepRatio:!0,minFigSize:20,borderWidth:0,menuBuilder:function(e,t,o){return An([qr(e,o),Zr(e,o),{id:"reset_size",name:n("Reset size"),sequence:4,execute:()=>{const t=o.model.getters.getImageSize(e),{height:i,width:s}=Wr(o.model.getters,t);o.model.dispatch("UPDATE_FIGURE",{sheetId:o.model.getters.getActiveSheetId(),id:e,height:i,width:s})}},jr(e,t,o)])}});const Yr=(new Ui).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 Ts.values())Yr.contains(e)||Yr.add(e,Xr);function Xr(e){return[e]}const Kr={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 Qr(e,t){const o=Vr.getAll().find((t=>t.match(e.type)));if(!o)throw new Error("Unknown chart type.");return o.transformDefinition(e,t)}function Jr(e,t){let o=e;e.left!==e.right&&(o={...e,left:e.left+1});const i=[ii(o)],n=t.getActiveSheetId(),r=t.getCell({sheetId:n,col:e.left,row:e.top});if(1===yi(e)&&r?.content)return{type:"scorecard",title:"",background:r.style?.fillColor||void 0,keyValue:ii(e),baselineMode:se,baselineColorUp:ne,baselineColorDown:re};let a="";const l=t.getEvaluatedCellsInZone(n,{...o,bottom:o.top}),c=!!l.find((e=>e.type!==ws.empty&&e.type!==ws.number));if(c){const e=l.filter((e=>e.type!==ws.error&&e.type!==ws.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=ii({...e,right:e.left}));const d=o.right===o.left?"none":"top";return Mr(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 ea=[ws.number,ws.error,ws.text,ws.boolean];function ta(e,t,o,i,s){let r=Os.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);hi(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 oa(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause(19)&&e.raiseError(n("This operation is not allowed with multiple selections."))}const ia={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 sa(e,t,o){const i=e.model.dispatch("CREATE_FILTER_TABLE",{target:o,sheetId:t});i.isCancelledBecause(79)?e.raiseError(ia.filterOverlap):i.isCancelledBecause(81)?e.raiseError(ia.mergeInFilter):i.isCancelledBecause(82)&&e.raiseError(ia.nonContinuousTargets)}const na={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 ra(e,t){t.isSuccessful||(t.reasons.includes(20)?e.raiseError(na.wrongPasteSelection):t.reasons.includes(2)?e.raiseError(na.willRemoveExistingMerge):t.reasons.includes(22)?e.raiseError(na.wrongFigurePasteOption):t.reasons.includes(76)&&e.raiseError(na.frozenPaneOverlap))}function aa(e,t,o){const i=e.model.dispatch("PASTE",{target:t,pasteOption:o});ra(e,i)}function la(e,t,o){const i=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,text:o});ra(e,i)}function ca(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 ha(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 da(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function ua(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const ga=async e=>pa(e,"onlyValue");async function pa(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?la(e,s,i.content):aa(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 ma=(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},fa=e=>{const t=e.model.getters.getActiveRows();let o,i;if(t.size)o=Math.min(...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"})},ba=e=>{const t=e.model.getters.getActiveCols();let o,i;if(t.size)o=Math.min(...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})},va=e=>{const t=e.model.getters.getActiveCols();let o,i;if(t.size)o=Math.max(...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 Sa=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=Wr(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})}},Ca=e=>da(e,"0.00%"),Ea=e=>{let{col:t,row:o}=e.model.getters.getActivePosition();e.model.dispatch("OPEN_CELL_POPOVER",{col:t,row:o,popoverType:"LinkEditor"})},wa=e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,o)},xa=e=>1===e.model.getters.getSelectedZones().length,ya=(e,t)=>{if(!xa(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=hi(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)},Ia={name:n("Undo"),description:"Ctrl+Z",execute:e=>e.model.dispatch("REQUEST_UNDO"),isEnabled:e=>e.model.getters.canUndo(),icon:"o-spreadsheet-Icon.UNDO"},Ra={name:n("Redo"),description:"Ctrl+Y",execute:e=>e.model.dispatch("REQUEST_REDO"),isEnabled:e=>e.model.getters.canRedo(),icon:"o-spreadsheet-Icon.REDO"},Ta={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"},Aa={name:n("Cut"),description:"Ctrl+X",execute:async e=>{oa(e),await e.clipboard.write(e.model.getters.getClipboardContent())},icon:"o-spreadsheet-Icon.CUT"},Oa={name:n("Paste"),description:"Ctrl+V",execute:async e=>pa(e),icon:"o-spreadsheet-Icon.PASTE"},Ma={name:n("Paste special"),isVisible:e=>!e.model.getters.isCutOperation(),icon:"o-spreadsheet-Icon.PASTE"},Na={name:n("Paste value only"),description:"Ctrl+Shift+V",execute:ga},_a={name:n("Paste format only"),execute:e=>aa(e,e.model.getters.getSelectedZones(),"onlyFormat")},Fa={name:n("Find and replace"),description:"Ctrl+H",isReadonlyAllowed:!0,execute:e=>{e.openSidePanel("FindAndReplace",{})},icon:"o-spreadsheet-Icon.FIND_AND_REPLACE"},Da={name:n("Delete values"),execute:e=>e.model.dispatch("DELETE_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},La={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=Math.min(...i),o=Math.max(...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=>ma("ROW",e)},ka={...La,isVisible:xa},Pa={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=Math.min(...i),o=Math.max(...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()})}},Ua={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=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.left,o=i.right}return t===o?n("Delete column %s",Vt(t)):n("Delete columns %s - %s",Vt(t),Vt(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=>ma("COL",e)},Va={...Ua,isVisible:xa},za={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=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.left,o=i.right}return t===o?n("Clear column %s",Vt(t)):n("Clear columns %s - %s",Vt(t),Vt(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()})}},Ba={name:n("Delete cells"),isVisible:xa},Ha={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"});ra(e,o)}},$a={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"});ra(e,o)}},Wa={name:n("Merge cells"),isEnabled:e=>!Ga(e),isActive:e=>qa(e),execute:e=>function(e){if(Ga(e))return;const t=e.model.getters.getSelectedZones(),o=[t[t.length-1]],i=e.model.getters.getActiveSheetId();qa(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(Kr.MergeInFilter):i.isCancelledBecause(3)&&e.askConfirmation(Kr.MergeIsDestructive,(()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:o,force:!0})}))}(e,i,o)}(e),icon:"o-spreadsheet-Icon.MERGE_CELL"};function Ga(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 qa(e){if(!Ga(e)){const t=e.model.getters.getSelectedZones(),{col:o,row:i,sheetId:s}=e.model.getters.getActivePosition(),n=e.model.getters.expandZone(s,wi({col:o,row:i}));return hi(t[0],n)}return!1}var Za=Object.freeze({__proto__:null,undo:Ia,redo:Ra,copy:Ta,cut:Aa,paste:Oa,pasteSpecial:Ma,pasteSpecialValue:Na,pasteSpecialFormat:_a,findAndReplace:Fa,deleteValues:Da,deleteRows:La,deleteRow:ka,clearRows:Pa,deleteCols:Ua,deleteCol:Va,clearCols:za,deleteCells:Ba,deleteCellShiftUp:Ha,deleteCellShiftLeft:$a,mergeCells:Wa});const ja=/(.*?)\((.*?)\)(.*)/,Ya=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function Xa(e,t=""){return function(e,t){let o=e.match(ja),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=Ya.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 Ka(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 Qa={description:n("Apply a large number format"),args:[Xa("value (number)",n("The number.")),Xa("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(Xi(e.value)),i=e.format;if(void 0!==t){const e=t?.value;switch(e){case"k":return Ao(i,1e3,"k");case"m":return Ao(i,1e6,"m");case"b":return Ao(i,1e9,"b");default:throw new Error(n("The formatting unit should be 'k', 'm' or 'b'."))}}return o<1e5?Ao(i,0,""):o<1e8?Ao(i,1e3,"k"):o<1e11?Ao(i,1e6,"m"):Ao(i,1e9,"b")},compute:function(e){return Xi(e)}};var Ja=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:Qa});const el=/^-?[a-z0-9]+$/i,tl={description:n("Absolute value of a number."),args:[Xa("value (number)",n("The number of which to return the absolute value."))],returns:["NUMBER"],compute:function(e){return Math.abs(Xi(e))},isExported:!0},ol={description:n("Inverse cosine of a value, in radians."),args:[Xa("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=Xi(e);return ji((()=>Math.abs(t)<=1),n("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},il={description:n("Inverse hyperbolic cosine of a number."),args:[Xa("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=Xi(e);return ji((()=>t>=1),n("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},sl={description:n("Inverse cotangent of a value."),args:[Xa("value (number)",n("The value for which to calculate the inverse cotangent."))],returns:["NUMBER"],compute:function(e){const t=Xi(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},nl={description:n("Inverse hyperbolic cotangent of a value."),args:[Xa("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=Xi(e);return ji((()=>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},rl={description:n("Inverse sine of a value, in radians."),args:[Xa("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=Xi(e);return ji((()=>Math.abs(t)<=1),n("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},al={description:n("Inverse hyperbolic sine of a number."),args:[Xa("value (number)",n("The value for which to calculate the inverse hyperbolic sine."))],returns:["NUMBER"],compute:function(e){return Math.asinh(Xi(e))},isExported:!0},ll={description:n("Inverse tangent of a value, in radians."),args:[Xa("value (number)",n("The value for which to calculate the inverse tangent."))],returns:["NUMBER"],compute:function(e){return Math.atan(Xi(e))},isExported:!0},cl={description:n("Angle from the X axis to a point (x,y), in radians."),args:[Xa("x (number)",n("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")),Xa("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=Xi(e),i=Xi(t);return ji((()=>0!==o||0!==i),n("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(i,o)},isExported:!0},hl={description:n("Inverse hyperbolic tangent of a number."),args:[Xa("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=Xi(e);return ji((()=>Math.abs(t)<1),n("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},dl={description:n("Rounds number up to nearest multiple of factor."),args:[Xa("value (number)",n("The value to round up to the nearest integer multiple of factor.")),Xa("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=Xi(e),i=Xi(t);return ji((()=>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},ul={description:n("Rounds number up to nearest multiple of factor."),args:[Xa("number (number)",n("The value to round up to the nearest integer multiple of significance.")),Xa("significance (number, default=1)",n("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),Xa("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=Xi(t);if(0===i)return 0;const s=Xi(e);if(i=Math.abs(i),s>=0)return Math.ceil(s/i)*i;return 0===Xi(o)?-Math.floor(Math.abs(s)/i)*i:-Math.ceil(Math.abs(s)/i)*i},isExported:!0},gl={description:n("Rounds number up to nearest multiple of factor."),args:[Xa("number (number)",n("The value to round up to the nearest integer multiple of significance.")),Xa("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 ul.compute(e,t,0)},isExported:!0},pl={description:n("Cosine of an angle provided in radians."),args:[Xa("angle (number)",n("The angle to find the cosine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.cos(Xi(e))},isExported:!0},ml={description:n("Hyperbolic cosine of any real number."),args:[Xa("value (number)",n("Any real value to calculate the hyperbolic cosine of."))],returns:["NUMBER"],compute:function(e){return Math.cosh(Xi(e))},isExported:!0},fl={description:n("Cotangent of an angle provided in radians."),args:[Xa("angle (number)",n("The angle to find the cotangent of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Xi(e);return ji((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},bl={description:n("Hyperbolic cotangent of any real number."),args:[Xa("value (number)",n("Any real value to calculate the hyperbolic cotangent of."))],returns:["NUMBER"],compute:function(e){const t=Xi(e);return ji((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},vl={description:n("Number of empty values."),args:[Xa("value1 (any, range)",n("The first value or range in which to count the number of blanks.")),Xa("value2 (any, range, repeating)",n("Additional values or ranges in which to count the number of blanks."))],returns:["NUMBER"],compute:function(...e){return hs(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},Sl={description:n("A conditional count across a range."),args:[Xa("range (range)",n("The range that is tested against criterion.")),Xa("criterion (string)",n("The pattern or test to apply to range."))],returns:["NUMBER"],compute:function(...e){let t=0;return fs(e,((e,o)=>{t+=1})),t},isExported:!0},Cl={description:n("Count values depending on multiple criteria."),args:[Xa("criteria_range1 (range)",n("The range to check against criterion1.")),Xa("criterion1 (string)",n("The pattern or test to apply to criteria_range1.")),Xa("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.")),Xa("criterion2 (string, repeating)",n("Additional criteria to check."))],returns:["NUMBER"],compute:function(...e){let t=0;return fs(e,((e,o)=>{t+=1})),t},isExported:!0};function El(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const wl={description:n("Counts number of unique values in a range."),args:[Xa("value1 (any, range)",n("The first value or range to consider for uniqueness.")),Xa("value2 (any, range, repeating)",n("Additional values or ranges to consider for uniqueness."))],returns:["NUMBER"],compute:function(...e){return hs(e,((e,t)=>El(t)?e.add(t):e),new Set).size}},xl={description:n("Counts number of unique values in a range, filtered by a set of criteria."),args:[Xa("range (range)",n("The range of cells from which the number of unique values will be counted.")),Xa("criteria_range1 (range)",n("The range of cells over which to evaluate criterion1.")),Xa("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.")),Xa("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.")),Xa("criterion2 (string, repeating)",n("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=new Set;return fs(t,((t,i)=>{const s=e[t][i];El(s)&&o.add(s)})),o.size}},yl={description:n("Cosecant of an angle provided in radians."),args:[Xa("angle (number)",n("The angle to find the cosecant of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Xi(e);return ji((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},Il={description:n("Hyperbolic cosecant of any real number."),args:[Xa("value (number)",n("Any real value to calculate the hyperbolic cosecant of."))],returns:["NUMBER"],compute:function(e){const t=Xi(e);return ji((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},Rl={description:n("Converts from another base to decimal."),args:[Xa("value (string)",n("The number to convert.")),Xa(",base (number)",n("The base to convert the value from."))],returns:["NUMBER"],compute:function(e,t){let o=Xi(t);o=Math.floor(o),ji((()=>2<=o&&o<=36),n("The base (%s) must be between 2 and 36 inclusive.",o.toString()));const i=es(e);if(""===i)return 0;ji((()=>!!el.test(i)),n("The value (%s) must be a valid base %s representation.",i,o.toString()));const s=parseInt(i,o);return ji((()=>!isNaN(s)),n("The value (%s) must be a valid base %s representation.",i,o.toString())),s},isExported:!0},Tl={description:n("Converts an angle value in radians to degrees."),args:[Xa("angle (number)",n("The angle to convert from radians to degrees."))],returns:["NUMBER"],compute:function(e){return 180*Xi(e)/Math.PI},isExported:!0},Al={description:n("Euler's number, e (~2.718) raised to a power."),args:[Xa("value (number)",n("The exponent to raise e."))],returns:["NUMBER"],compute:function(e){return Math.exp(Xi(e))},isExported:!0},Ol={description:n("Rounds number down to nearest multiple of factor."),args:[Xa("value (number)",n("The value to round down to the nearest integer multiple of factor.")),Xa("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=Xi(e),i=Xi(t);return ji((()=>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},Ml={description:n("Rounds number down to nearest multiple of factor."),args:[Xa("number (number)",n("The value to round down to the nearest integer multiple of significance.")),Xa("significance (number, default=1)",n("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),Xa("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=Xi(t);if(0===i)return 0;const s=Xi(e);if(i=Math.abs(i),s>=0)return Math.floor(s/i)*i;return 0===Xi(o)?-Math.ceil(Math.abs(s)/i)*i:-Math.floor(Math.abs(s)/i)*i},isExported:!0},Nl={description:n("Rounds number down to nearest multiple of factor."),args:[Xa("number (number)",n("The value to round down to the nearest integer multiple of significance.")),Xa("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 Ml.compute(e,t,0)},isExported:!0},_l={description:n("Whether the provided value is even."),args:[Xa("value (number)",n("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Ki(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},Fl={description:n("Rounds number up to nearest multiple of factor."),args:[Xa("number (number)",n("The value to round up to the nearest integer multiple of significance.")),Xa("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 ul.compute(e,t,0)},isExported:!0},Dl={description:n("Whether the provided value is even."),args:[Xa("value (number)",n("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Ki(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},Ll={description:n("The logarithm of a number, base e (euler's number)."),args:[Xa("value (number)",n("The value for which to calculate the logarithm, base e."))],returns:["NUMBER"],compute:function(e){const t=Xi(e);return ji((()=>t>0),n("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},kl={description:n("Modulo (remainder) operator."),args:[Xa("dividend (number)",n("The number to be divided to find the remainder.")),Xa("divisor (number)",n("The number to divide by."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){const o=Xi(t);ji((()=>0!==o),n("The divisor must be different from 0."));const i=Xi(e)%o;return i>0&&o<0||i<0&&o>0?i+o:i},isExported:!0},Pl={description:n("Rounds a number up to the nearest odd integer."),args:[Xa("value (number)",n("The value to round to the next greatest odd number."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e){const t=Xi(e);let o=Math.ceil(Math.abs(t));return o=1&o?o:o+1,t<0?-o:o},isExported:!0},Ul={description:n("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},Vl={description:n("A number raised to a power."),args:[Xa("base (number)",n("The number to raise to the exponent power.")),Xa("exponent (number)",n("The exponent to raise base to."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){const o=Xi(e),i=Xi(t);return ji((()=>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},zl={description:n("Result of multiplying a series of numbers together."),args:[Xa("factor1 (number, range<number>)",n("The first number or range to calculate for the product.")),Xa("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*=Ki(i),t+=1);return 0===t?0:o},isExported:!0},Bl={description:n("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},Hl={description:n("Random integer between two values, inclusive."),args:[Xa("low (number)",n("The low end of the random range.")),Xa("high (number)",n("The high end of the random range."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e,t){let o=Xi(e);Number.isInteger(o)||(o=Math.ceil(o));let i=Xi(t);return Number.isInteger(i)||(i=Math.floor(i)),ji((()=>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},$l={description:n("Rounds a number according to standard rules."),args:[Xa("value (number)",n("The value to round to places number of places.")),Xa("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=Xi(e);let i=Xi(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},Wl={description:n("Rounds down a number."),args:[Xa("value (number)",n("The value to round to places number of places, always rounding down.")),Xa("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=Xi(e);let i=Xi(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},Gl={description:n("Rounds up a number."),args:[Xa("value (number)",n("The value to round to places number of places, always rounding up.")),Xa("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=Xi(e);let i=Xi(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},ql={description:n("Secant of an angle provided in radians."),args:[Xa("angle (number)",n("The angle to find the secant of, in radians."))],returns:["NUMBER"],compute:function(e){return 1/Math.cos(Xi(e))},isExported:!0},Zl={description:n("Hyperbolic secant of any real number."),args:[Xa("value (number)",n("Any real value to calculate the hyperbolic secant of."))],returns:["NUMBER"],compute:function(e){return 1/Math.cosh(Xi(e))},isExported:!0},jl={description:n("Sine of an angle provided in radians."),args:[Xa("angle (number)",n("The angle to find the sine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.sin(Xi(e))},isExported:!0},Yl={description:n("Hyperbolic sine of any real number."),args:[Xa("value (number)",n("Any real value to calculate the hyperbolic sine of."))],returns:["NUMBER"],compute:function(e){return Math.sinh(Xi(e))},isExported:!0},Xl={description:n("Positive square root of a positive number."),args:[Xa("value (number)",n("The number for which to calculate the positive square root."))],returns:["NUMBER"],computeFormat:e=>e?.format,compute:function(e){const t=Xi(e);return ji((()=>t>=0),n("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},Kl={description:n("Sum of a series of numbers and/or cells."),args:[Xa("value1 (number, range<number>)",n("The first number or range to add together.")),Xa("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 ds(e,((e,t)=>e+t),0)},isExported:!0},Ql={description:n("A conditional sum across a range."),args:[Xa("criteria_range (range)",n("The range which is tested against criterion.")),Xa("criterion (string)",n("The pattern or test to apply to range.")),Xa("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 fs([e,t],((e,t)=>{const s=o[e][t];"number"==typeof s&&(i+=s)})),i},isExported:!0},Jl={description:n("Sums a range depending on multiple criteria."),args:[Xa("sum_range (range)",n("The range to sum.")),Xa("criteria_range1 (range)",n("The range to check against criterion1.")),Xa("criterion1 (string)",n("The pattern or test to apply to criteria_range1.")),Xa("criteria_range2 (any, range, repeating)",n("Additional ranges to check.")),Xa("criterion2 (string, repeating)",n("Additional criteria to check."))],returns:["NUMBER"],compute:function(e,...t){let o=0;return fs(t,((t,i)=>{const s=e[t][i];"number"==typeof s&&(o+=s)})),o},isExported:!0},ec={description:n("Tangent of an angle provided in radians."),args:[Xa("angle (number)",n("The angle to find the tangent of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.tan(Xi(e))},isExported:!0},tc={description:n("Hyperbolic tangent of any real number."),args:[Xa("value (number)",n("Any real value to calculate the hyperbolic tangent of."))],returns:["NUMBER"],compute:function(e){return Math.tanh(Xi(e))},isExported:!0},oc={description:n("Truncates a number."),args:[Xa("value (number)",n("The value to be truncated.")),Xa("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=Xi(e);let i=Xi(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 ic=Object.freeze({__proto__:null,ABS:tl,ACOS:ol,ACOSH:il,ACOT:sl,ACOTH:nl,ASIN:rl,ASINH:al,ATAN:ll,ATAN2:cl,ATANH:hl,CEILING:dl,CEILING_MATH:ul,CEILING_PRECISE:gl,COS:pl,COSH:ml,COT:fl,COTH:bl,COUNTBLANK:vl,COUNTIF:Sl,COUNTIFS:Cl,COUNTUNIQUE:wl,COUNTUNIQUEIFS:xl,CSC:yl,CSCH:Il,DECIMAL:Rl,DEGREES:Tl,EXP:Al,FLOOR:Ol,FLOOR_MATH:Ml,FLOOR_PRECISE:Nl,ISEVEN:_l,ISO_CEILING:Fl,ISODD:Dl,LN:Ll,MOD:kl,ODD:Pl,PI:Ul,POWER:Vl,PRODUCT:zl,RAND:Bl,RANDBETWEEN:Hl,ROUND:$l,ROUNDDOWN:Wl,ROUNDUP:Gl,SEC:ql,SECH:Zl,SIN:jl,SINH:Yl,SQRT:Xl,SUM:Kl,SUMIF:Ql,SUMIFS:Jl,TAN:ec,TANH:tc,TRUNC:oc});function sc(e,t,o){let i=[],s=[],r=0,a=0;as([e],(e=>{i.push(e),r+=1})),as([t],(e=>{s.push(e),a+=1})),ji((()=>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)}ji((()=>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 nc(e,t,o){let i=0,s=0;const r=o?us:ds;s=r(e,((e,t)=>(i+=1,e+t)),0),ji((()=>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 rc(e,t,o){const i=Xi(t);ji((()=>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 as(e,(e=>{"number"==typeof e&&(s=Ss(r,e,"nextSmaller","asc",r.length,((e,t)=>e[t])),r.splice(s+1,0,e),a++)})),ji((()=>0!==a),n("[[FUNCTION_NAME]] has no valid input data.")),o||ji((()=>1/(a+1)<=i&&i<=a/(a+1)),n("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),no(r,i,o)}const ac={description:n("Average magnitude of deviations from mean."),args:[Xa("value1 (number, range<number>)",n("The first value or range of the sample.")),Xa("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=ds(e,((e,o)=>(t+=1,e+o)),0);ji((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const i=o/t;return ds(e,((e,t)=>e+Math.abs(i-t)),0)/t},isExported:!0},lc={description:n("Numerical average value in a dataset, ignoring text."),args:[Xa("value1 (number, range<number>)",n("The first value or range to consider when calculating the average value.")),Xa("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=ds(e,((e,o)=>(t+=1,e+o)),0);return ji((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/t},isExported:!0},cc=n("[[FUNCTION_NAME]] has mismatched range sizes."),hc=n("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),dc={description:n("Weighted average."),args:[Xa("values (number, range<number>)",n("Values to average.")),Xa("weights (number, range<number>)",n("Weights for each corresponding value.")),Xa("additional_values (number, range<number>, repeating)",n("Additional values to average.")),Xa("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;ji((()=>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)){ji((()=>Array.isArray(o)),cc);let e=t.length,r=t[0].length;ji((()=>e===o.length&&r===o[0].length),cc);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;ji((()=>c===h),n("[[FUNCTION_NAME]] expects number values.")),h&&(ji((()=>l>=0),hc),i+=r*l,s+=l)}}else o=Xi(o),t=Xi(t),ji((()=>o>=0),hc),i+=t*o,s+=o;return ji((()=>0!==s),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/s}},uc={description:n("Numerical average value in a dataset."),args:[Xa("value1 (number, range<number>)",n("The first value or range to consider when calculating the average value.")),Xa("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=us(e,((e,o)=>(t+=1,e+o)),0);return ji((()=>0!==t),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/t},isExported:!0},gc={description:n("Average of values depending on criteria."),args:[Xa("criteria_range (range)",n("The range to check against criterion.")),Xa("criterion (string)",n("The pattern or test to apply to criteria_range.")),Xa("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 fs([e,t],((t,n)=>{const r=(o||e)[t][n];"number"==typeof r&&(i+=1,s+=r)})),ji((()=>0!==i),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),s/i},isExported:!0},pc={description:n("Average of values depending on multiple criteria."),args:[Xa("average_range (range)",n("The range to average.")),Xa("criteria_range1 (range)",n("The range to check against criterion1.")),Xa("criterion1 (string)",n("The pattern or test to apply to criteria_range1.")),Xa("criteria_range2 (any, range, repeating)",n("Additional criteria_range and criterion to check.")),Xa("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 fs(t,((t,s)=>{const n=e[t][s];"number"==typeof n&&(o+=1,i+=n)})),ji((()=>0!==o),n("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/o},isExported:!0},mc={description:n("The number of numeric values in dataset."),args:[Xa("value1 (number, range<number>)",n("The first value or range to consider when counting.")),Xa("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||oo(o)||Te(o))&&(t+=1);return t},isExported:!0},fc={description:n("The number of values in a dataset."),args:[Xa("value1 (any, range)",n("The first value or range to consider when counting.")),Xa("value2 (any, range, repeating)",n("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){return hs(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},bc={description:n("The covariance of a dataset."),args:[Xa("data_y (any, range)",n("The range representing the array or matrix of dependent data.")),Xa("data_x (any, range)",n("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return sc(e,t,!1)},isExported:!0},vc={description:n("The covariance of a dataset."),args:[Xa("data_y (any, range)",n("The range representing the array or matrix of dependent data.")),Xa("data_x (any, range)",n("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return sc(e,t,!1)},isExported:!0},Sc={description:n("The sample covariance of a dataset."),args:[Xa("data_y (any, range)",n("The range representing the array or matrix of dependent data.")),Xa("data_x (any, range)",n("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return sc(e,t,!0)},isExported:!0},Cc={description:n("Nth largest element from a data set."),args:[Xa("data (any, range)",n("Array or range containing the dataset to consider.")),Xa("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(Xi(t));let i,s=[],r=0;as([e],(e=>{"number"==typeof e&&(i=Ss(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 ji((()=>void 0!==a),n("[[FUNCTION_NAME]] has no valid input data.")),ji((()=>r>=o),n("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",o.toString())),a},isExported:!0},Ec={description:n("Maximum value in a numeric dataset."),args:[Xa("value1 (number, range<number>)",n("The first value or range to consider when calculating the maximum value.")),Xa("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=ds(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},wc={description:n("Maximum numeric value in a dataset."),args:[Xa("value1 (any, range)",n("The first value or range to consider when calculating the maximum value.")),Xa("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=us(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},xc={description:n("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:[Xa("range (range)",n("The range of cells from which the maximum will be determined.")),Xa("criteria_range1 (range)",n("The range of cells over which to evaluate criterion1.")),Xa("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.")),Xa("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.")),Xa("criterion2 (string, repeating)",n("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=-1/0;return fs(t,((t,i)=>{const s=e[t][i];"number"==typeof s&&(o=o<s?s:o)})),o===-1/0?0:o},isExported:!0},yc={description:n("Median value in a numeric dataset."),args:[Xa("value1 (any, range)",n("The first value or range to consider when calculating the median value.")),Xa("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 ls(e,(e=>{t.push(e)})),rc(t,.5,!0)},isExported:!0},Ic={description:n("Minimum value in a numeric dataset."),args:[Xa("value1 (number, range<number>)",n("The first value or range to consider when calculating the minimum value.")),Xa("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=ds(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},Rc={description:n("Minimum numeric value in a dataset."),args:[Xa("value1 (number, range<number>)",n("The first value or range to consider when calculating the minimum value.")),Xa("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=us(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},Tc={description:n("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:[Xa("range (range)",n("The range of cells from which the minimum will be determined.")),Xa("criteria_range1 (range)",n("The range of cells over which to evaluate criterion1.")),Xa("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.")),Xa("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.")),Xa("criterion2 (string, repeating)",n("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let o=1/0;return fs(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("Value at a given percentile of a dataset."),args:[Xa("data (any, range)",n("The array or range containing the dataset to consider.")),Xa("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 Mc.compute(e,t)},isExported:!0},Oc={description:n("Value at a given percentile of a dataset exclusive of 0 and 1."),args:[Xa("data (any, range)",n("The array or range containing the dataset to consider.")),Xa("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 rc([e],t,!1)},isExported:!0},Mc={description:n("Value at a given percentile of a dataset."),args:[Xa("data (any, range)",n("The array or range containing the dataset to consider.")),Xa("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 rc([e],t,!0)},isExported:!0},Nc={description:n("Value nearest to a specific quartile of a dataset."),args:[Xa("data (any, range)",n("The array or range containing the dataset to consider.")),Xa("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 Fc.compute(e,t)},isExported:!0},_c={description:n("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:[Xa("data (any, range)",n("The array or range containing the dataset to consider.")),Xa("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 rc([e],.25*Math.trunc(Xi(t)),!1)},isExported:!0},Fc={description:n("Value nearest to a specific quartile of a dataset."),args:[Xa("data (any, range)",n("The array or range containing the dataset to consider.")),Xa("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 rc([e],.25*Math.trunc(Xi(t)),!0)},isExported:!0},Dc={description:n("Nth smallest element in a data set."),args:[Xa("data (any, range)",n("The array or range containing the dataset to consider.")),Xa("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(Xi(t));let i,s=[],r=0;as([e],(e=>{"number"==typeof e&&(i=Ss(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 ji((()=>void 0!==a),n("[[FUNCTION_NAME]] has no valid input data.")),ji((()=>r>=o),n("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",o.toString())),a},isExported:!0},Lc={description:n("Standard deviation."),args:[Xa("value1 (number, range<number>)",n("The first value or range of the sample.")),Xa("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Bc.compute(...e))},isExported:!0},kc={description:n("Standard deviation of entire population."),args:[Xa("value1 (number, range<number>)",n("The first value or range of the population.")),Xa("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Hc.compute(...e))},isExported:!0},Pc={description:n("Standard deviation."),args:[Xa("value1 (number, range<number>)",n("The first value or range of the sample.")),Xa("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt($c.compute(...e))},isExported:!0},Uc={description:n("Standard deviation of sample (text as 0)."),args:[Xa("value1 (number, range<number>)",n("The first value or range of the sample.")),Xa("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Wc.compute(...e))},isExported:!0},Vc={description:n("Standard deviation of entire population."),args:[Xa("value1 (number, range<number>)",n("The first value or range of the population.")),Xa("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Gc.compute(...e))},isExported:!0},zc={description:n("Standard deviation of entire population (text as 0)."),args:[Xa("value1 (number, range<number>)",n("The first value or range of the population.")),Xa("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("Variance."),args:[Xa("value1 (number, range<number>)",n("The first value or range of the sample.")),Xa("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return nc(e,!0,!1)},isExported:!0},Hc={description:n("Variance of entire population."),args:[Xa("value1 (number, range<number>)",n("The first value or range of the population.")),Xa("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return nc(e,!1,!1)},isExported:!0},$c={description:n("Variance."),args:[Xa("value1 (number, range<number>)",n("The first value or range of the sample.")),Xa("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return nc(e,!0,!1)},isExported:!0},Wc={description:n("Variance of sample (text as 0)."),args:[Xa("value1 (number, range<number>)",n("The first value or range of the sample.")),Xa("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return nc(e,!0,!0)},isExported:!0},Gc={description:n("Variance of entire population."),args:[Xa("value1 (number, range<number>)",n("The first value or range of the population.")),Xa("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return nc(e,!1,!1)},isExported:!0},qc={description:n("Variance of entire population (text as 0)."),args:[Xa("value1 (number, range<number>)",n("The first value or range of the population.")),Xa("value2 (number, range<number>, repeating)",n("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return nc(e,!1,!0)},isExported:!0};var Zc=Object.freeze({__proto__:null,AVEDEV:ac,AVERAGE:lc,AVERAGE_WEIGHTED:dc,AVERAGEA:uc,AVERAGEIF:gc,AVERAGEIFS:pc,COUNT:mc,COUNTA:fc,COVAR:bc,COVARIANCE_P:vc,COVARIANCE_S:Sc,LARGE:Cc,MAX:Ec,MAXA:wc,MAXIFS:xc,MEDIAN:yc,MIN:Ic,MINA:Rc,MINIFS:Tc,PERCENTILE:Ac,PERCENTILE_EXC:Oc,PERCENTILE_INC:Mc,QUARTILE:Nc,QUARTILE_EXC:_c,QUARTILE_INC:Fc,SMALL:Dc,STDEV:Lc,STDEV_P:kc,STDEV_S:Pc,STDEVA:Uc,STDEVP:Vc,STDEVPA:zc,VAR:Bc,VAR_P:Hc,VAR_S:$c,VARA:Wc,VARP:Gc,VARPA:qc});function jc(e,t,o){const i=new Map,s=e.length;for(let t=s-1;t>=0;t--)i.set(es(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=es(t).toUpperCase();if(r=i.get(e)??-1,-1===r)throw new Error(n("The field (%s) must be one of %s.",es(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=es(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}fs(s,((e,t)=>{l.add(t)}),!0)}}const h=e[r];return[...l].map((e=>h[e+1]))}const Yc=[Xa("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.")),Xa("field (any)",n("Indicates which column in database contains the values to be extracted and operated on.")),Xa("criteria (range)",n("An array or range containing zero or more criteria to filter the database values by before operating."))],Xc={description:n("Average of a set of values from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return lc.compute([i])},isExported:!0},Kc={description:n("Counts values from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return mc.compute([i])},isExported:!0},Qc={description:n("Counts values and text from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return fc.compute([i])},isExported:!0},Jc={description:n("Single value from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return ji((()=>1===i.length),n("More than one match found in DGET evaluation.")),i[0]},isExported:!0},eh={description:n("Maximum of values from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return Ec.compute([i])},isExported:!0},th={description:n("Minimum of values from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return Ic.compute([i])},isExported:!0},oh={description:n("Product of values from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return zl.compute([i])},isExported:!0},ih={description:n("Standard deviation of population sample from table."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return Lc.compute([i])},isExported:!0},sh={description:n("Standard deviation of entire population from table."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return Vc.compute([i])},isExported:!0},nh={description:n("Sum of values from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return Kl.compute([i])},isExported:!0},rh={description:n("Variance of population sample from table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return Bc.compute([i])},isExported:!0},ah={description:n("Variance of a population from a table-like range."),args:Yc,returns:["NUMBER"],compute:function(e,t,o){const i=jc(e,t,o);return Gc.compute([i])},isExported:!0};var lh=Object.freeze({__proto__:null,DAVERAGE:Xc,DCOUNT:Kc,DCOUNTA:Qc,DGET:Jc,DMAX:eh,DMIN:th,DPRODUCT:oh,DSTDEV:ih,DSTDEVP:sh,DSUM:nh,DVAR:rh,DVARP:ah});var ch;!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"}(ch||(ch={}));const hh={description:n("Converts year/month/day into a date."),args:[Xa("year (number)",n("The year component of the date.")),Xa("month (number)",n("The month component of the date.")),Xa("day (number)",n("The day component of the date."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o){let i=Math.trunc(Xi(e));const s=Math.trunc(Xi(t)),r=Math.trunc(Xi(o));ji((()=>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 ji((()=>a>=0),n("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),a},isExported:!0},dh={description:n("Calculates the number of days, months, or years between two dates."),args:[Xa("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.")),Xa("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.")),Xa("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=es(o).toUpperCase();ji((()=>Object.values(ch).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(ch),es(o)));const s=Math.trunc(Xi(e)),r=Math.trunc(Xi(t)),a=Oe(s),l=Oe(r);switch(ji((()=>r>=s),n("start_date (%s) should be on or before end_date (%s).",a.toLocaleDateString(),l.toLocaleDateString())),i){case ch.WHOLE_YEARS:return Ue(a,l);case ch.WHOLE_MONTHS:return ke(a,l);case ch.WHOLE_DAYS:return Pe(a,l);case ch.MONTH_WITHOUT_WHOLE_YEARS:return ke(a,l)-12*Ue(a,l);case ch.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 ch.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},uh={description:n("Converts a date string to a date value."),args:[Xa("date_string (string)",n("The string representing the date."))],returns:["NUMBER"],compute:function(e){const t=es(e),o=Te(t);return ji((()=>null!==o),n("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(o.value)},isExported:!0},gh={description:n("Day of the month that a specific date falls on."),args:[Xa("date (string)",n("The date from which to extract the day."))],returns:["NUMBER"],compute:function(e){return ns(e).getDate()},isExported:!0},ph={description:n("Number of days between two dates."),args:[Xa("end_date (date)",n("The end of the date range.")),Xa("start_date (date)",n("The start of the date range."))],returns:["NUMBER"],compute:function(e,t){const o=ns(e),i=ns(t),s=o.getTime()-i.getTime();return Math.round(s/Se)},isExported:!0},mh={description:n("Number of days between two dates on a 360-day year (months of 30 days)."),args:[Xa("start_date (date)",n("The start date to consider in the calculation.")),Xa("end_date (date)",n("The end date to consider in the calculation.")),Xa("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=Xi(e),s=Xi(t),n=ss(o)?4:0,r=Lh.compute(e,t,n);return Math.sign(s-i)*Math.round(360*r)},isExported:!0},fh={description:n("Date a number of months before/after another date."),args:[Xa("start_date (date)",n("The date from which to calculate the result.")),Xa("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(ns(e),Math.trunc(Xi(t)),!1))},isExported:!0},bh={description:n("Last day of a month before or after a date."),args:[Xa("start_date (date)",n("The date from which to calculate the result.")),Xa("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=ns(e),i=Math.trunc(Xi(t)),s=o.getFullYear(),n=o.getMonth();return Me(new be(s,n+i+1,0))},isExported:!0},vh={description:n("Hour component of a specific time."),args:[Xa("time (date)",n("The time from which to calculate the hour component."))],returns:["NUMBER"],compute:function(e){return ns(e).getHours()},isExported:!0},Sh={description:n("ISO week number of the year."),args:[Xa("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=ns(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},Ch={description:n("Minute component of a specific time."),args:[Xa("time (date)",n("The time from which to calculate the minute component."))],returns:["NUMBER"],compute:function(e){return ns(e).getMinutes()},isExported:!0},Eh={description:n("Month of the year a specific date falls in"),args:[Xa("date (date)",n("The date from which to extract the month."))],returns:["NUMBER"],compute:function(e){return ns(e).getMonth()+1},isExported:!0},wh={description:n("Net working days between two provided days."),args:[Xa("start_date (date)",n("The start date of the period from which to calculate the number of net working days.")),Xa("end_date (date)",n("The end date of the period from which to calculate the number of net working days.")),Xa("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 yh.compute(e,t,1,o)},isExported:!0};function xh(e){if("string"==typeof e){ji((()=>{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 ji((()=>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 yh={description:n("Net working days between two dates (specifying weekends)."),args:[Xa("start_date (date)",n("The start date of the period from which to calculate the number of net working days.")),Xa("end_date (date)",n("The end date of the period from which to calculate the number of net working days.")),Xa("weekend (any, default=1)",n("A number or string representing which days of the week are considered weekends.")),Xa("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=ns(e),n=ns(t),r=xh(o);let a=new Set;void 0!==i&&as([i],(e=>{const t=ns(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},Ih={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},Rh={description:n("Minute component of a specific time."),args:[Xa("time (date)",n("The time from which to calculate the second component."))],returns:["NUMBER"],compute:function(e){return ns(e).getSeconds()},isExported:!0},Th={description:n("Converts hour/minute/second into a time."),args:[Xa("hour (number)",n("The hour component of the time.")),Xa("minute (number)",n("The minute component of the time.")),Xa("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(Xi(e)),s=Math.trunc(Xi(t)),r=Math.trunc(Xi(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,ji((()=>i>=0),n("The function [[FUNCTION_NAME]] result cannot be negative")),i/24+s/1440+r/86400},isExported:!0},Ah={description:n("Converts a time string into its serial number representation."),args:[Xa("time_string (string)",n("The string that holds the time representation."))],returns:["NUMBER"],compute:function(e){const t=es(e),o=Te(t);ji((()=>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},Oh={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},Mh={description:n("Day of the week of the date provided (as number)."),args:[Xa("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.")),Xa("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=ns(e),i=Math.round(Xi(t)),s=o.getDay();return ji((()=>[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},Nh={description:n("Week number of the year."),args:[Xa("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.")),Xa("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=ns(e),i=Math.round(Xi(t));if(ji((()=>1===i||2===i||11<=i&&i<=17||21===i),n("The type (%s) is out of range.",i.toString())),21===i)return Sh.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},_h={description:n("Date after a number of workdays."),args:[Xa("start_date (date)",n("The date from which to begin counting.")),Xa("num_days (number)",n("The number of working days to advance from start_date. If negative, counts backwards.")),Xa("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 Fh.compute(e,t,1,o)},isExported:!0},Fh={description:n("Date after a number of workdays (specifying weekends)."),args:[Xa("start_date (date)",n("The date from which to begin counting.")),Xa("num_days (number)",n("The number of working days to advance from start_date. If negative, counts backwards.")),Xa("weekend (any, default=1)",n("A number or string representing which days of the week are considered weekends.")),Xa("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=ns(e),r=Math.trunc(Xi(t));"string"==typeof o&&ji((()=>"1111111"!==o),n("The weekend (%s) must be different from '1111111'.",o));const a=xh(o);let l=new Set;void 0!==i&&as([i],(e=>{const t=ns(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},Dh={description:n("Year specified by a given date."),args:[Xa("date (date)",n("The date from which to extract the year."))],returns:["NUMBER"],compute:function(e){return ns(e).getFullYear()},isExported:!0},Lh={description:n("Exact number of years between two dates."),args:[Xa("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.")),Xa("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.")),Xa("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(Xi(e)),s=Math.trunc(Xi(t));const r=Math.trunc(Xi(o));return ji((()=>i>=0),n("The start_date (%s) must be positive or null.",i.toString())),ji((()=>s>=0),n("The end_date (%s) must be positive or null.",s.toString())),ji((()=>0<=r&&r<=4),n("The day_count_convention (%s) must be between 0 and 4 inclusive.",r.toString())),Le(i,s,r)}},kh={description:n("First day of the month preceding a date."),args:[Xa("date (date)",n("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=ns(e),o=t.getFullYear(),i=t.getMonth();return Me(new be(o,i,1))}},Ph={description:n("Last day of the month following a date."),args:[Xa("date (date)",n("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){return bh.compute(e,0)}},Uh={description:n("Quarter of the year a specific date falls in"),args:[Xa("date (date)",n("The date from which to extract the quarter."))],returns:["NUMBER"],compute:function(e){return Math.ceil((ns(e).getMonth()+1)/3)}},Vh={description:n("First day of the quarter of the year a specific date falls in."),args:[Xa("date (date)",n("The date from which to calculate the start of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Uh.compute(e),o=Dh.compute(e);return Me(new be(o,3*(t-1),1))}},zh={description:n("Last day of the quarter of the year a specific date falls in."),args:[Xa("date (date)",n("The date from which to calculate the end of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Uh.compute(e),o=Dh.compute(e);return Me(new be(o,3*t,0))}},Bh={description:n("First day of the year a specific date falls in."),args:[Xa("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=Dh.compute(e);return Me(new be(t,0,1))}},Hh={description:n("Last day of the year a specific date falls in."),args:[Xa("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=Dh.compute(e);return Me(new be(t+1,0,0))}};var $h=Object.freeze({__proto__:null,DATE:hh,DATEDIF:dh,DATEVALUE:uh,DAY:gh,DAYS:ph,DAYS360:mh,EDATE:fh,EOMONTH:bh,HOUR:vh,ISOWEEKNUM:Sh,MINUTE:Ch,MONTH:Eh,NETWORKDAYS:wh,NETWORKDAYS_INTL:yh,NOW:Ih,SECOND:Rh,TIME:Th,TIMEVALUE:Ah,TODAY:Oh,WEEKDAY:Mh,WEEKNUM:Nh,WORKDAY:_h,WORKDAY_INTL:Fh,YEAR:Dh,YEARFRAC:Lh,MONTH_START:kh,MONTH_END:Ph,QUARTER:Uh,QUARTER_START:Vh,QUARTER_END:zh,YEAR_START:Bh,YEAR_END:Hh});const Wh={description:n("Compare two numeric values, returning 1 if they're equal."),args:[Xa("number1 (number)",n("The first number to compare.")),Xa("number2 (number, default=0)",n("The second number to compare."))],returns:["NUMBER"],compute:function(e,t=0){return Xi(e)===Xi(t)?1:0},isExported:!0};var Gh=Object.freeze({__proto__:null,DELTA:Wh});function qh(e,t){ji((()=>e<t),n("The maturity (%s) must be strictly greater than the settlement (%s).",t.toString(),e.toString()))}function Zh(e,t){ji((()=>t<e),n("The settlement date (%s) must be strictly greater than the issue date (%s).",e.toString(),t.toString()))}function jh(e){ji((()=>[1,2,4].includes(e)),n("The frequency (%s) must be one of %s",e.toString(),[1,2,4].toString()))}function Yh(e){ji((()=>0<=e&&e<=4),n("The day_count_convention (%s) must be between 0 and 4 inclusive.",e.toString()))}function Xh(e){ji((()=>e>0),n("The redemption (%s) must be strictly positive.",e.toString()))}function Kh(e){ji((()=>e>0),n("The price (%s) must be strictly positive.",e.toString()))}function Qh(e){ji((()=>e>0),n("The number_of_periods (%s) must be greater than 0.",e.toString()))}function Jh(e){ji((()=>e>0),n("The rate (%s) must be strictly positive.",e.toString()))}function ed(e){ji((()=>e>0),n("The life (%s) must be strictly positive.",e.toString()))}function td(e){ji((()=>e>=0),n("The cost (%s) must be positive or null.",e.toString()))}function od(e){ji((()=>e>0),n("The period (%s) must be strictly positive.",e.toString()))}function id(e){ji((()=>e>=0),n("The salvage (%s) must be positive or null.",e.toString()))}function sd(e){ji((()=>e>0),n("The present value (%s) must be strictly positive.",e.toString()))}function nd(e,t){ji((()=>e<=t),n("The period (%s) must be less than or equal life (%s).",e.toString(),t.toString()))}function rd(e){ji((()=>e>0),n("The investment (%s) must be strictly positive.",e.toString()))}function ad(e){ji((()=>e>0),n("The discount (%s) must be strictly positive.",e.toString()))}function ld(e){ji((()=>e<1),n("The discount (%s) must be smaller than 1.",e.toString()))}function cd(e){ji((()=>e>0),n("The depreciation factor (%s) must be strictly positive.",e.toString()))}function hd(e,t){const o=ns(e),i=ns(t),s=ns(e);s.setFullYear(o.getFullYear()+1),ji((()=>i.getTime()<=s.getTime()),n("The settlement date (%s) must at most one year after the maturity date (%s).",e.toString(),t.toString()))}function dd(e,t,o){Qh(o),ji((()=>e>0),n("The first_period (%s) must be strictly positive.",e.toString())),ji((()=>t>0),n("The last_period (%s) must be strictly positive.",t.toString())),ji((()=>e<=t),n("The first_period (%s) must be smaller or equal to the last_period (%s).",e.toString(),t.toString())),ji((()=>t<=o),n("The last_period (%s) must be smaller or equal to the number_of_periods (%s).",e.toString(),o.toString()))}function ud(e){ji((()=>e>-1),n("The rate_guess (%s) must be strictly greater than -1.",e.toString()))}function gd(e,t){ji((()=>e.length===t.length&&e[0].length===t[0].length),n("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."))}function pd(e){ji((()=>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 md=[Xa("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("frequency (number)",n("The number of interest or coupon payments per year (1, 2, or 4).")),Xa("day_count_convention (number, default=0 )",n("An indicator of what day count method to use."))];function fd(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)?(ji((()=>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,ji((()=>g<i),n("Function [[FUNCTION_NAME]] didn't find any result.")),g++)}while(!u);return d}const bd={description:n("Accrued interest of security paying at maturity."),args:[Xa("issue (date)",n("The date the security was initially issued.")),Xa("maturity (date)",n("The maturity date of the security.")),Xa("rate (number)",n("The annualized rate of interest.")),Xa("redemption (number)",n("The redemption amount per 100 face value, or par.")),Xa("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(Xi(e)),r=Math.trunc(Xi(t)),a=Xi(i),l=Xi(o),c=Math.trunc(Xi(s));Zh(r,n),Yh(c),Xh(a),Jh(l);return a*l*Lh.compute(n,r,s)},isExported:!0},vd={description:n("Depreciation for an accounting period."),args:[Xa("cost (number)",n("The initial cost of the asset.")),Xa("purchase_date (date)",n("The date the asset was purchased.")),Xa("first_period_end (date)",n("The date the first period ended.")),Xa("salvage (number)",n("The value of the asset at the end of depreciation.")),Xa("period (number)",n("The single period within life for which to calculate depreciation.")),Xa("rate (number)",n("The deprecation rate.")),Xa("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=Xi(e),c=Math.trunc(Xi(t)),h=Math.trunc(Xi(o)),d=Xi(i),u=Xi(s),g=Xi(r),p=Math.trunc(Xi(a));!function(e){ji((()=>e>0),n("The cost (%s) must be strictly positive.",e.toString()))}(l),id(d),function(e,t){ji((()=>e<=t),n("The salvage (%s) must be smaller or equal than the cost (%s).",e.toString(),t.toString()))}(d,l),function(e){ji((()=>e>=0),n("The period (%s) must be positive or null.",e.toString()))}(u),Jh(g),Yh(p),ji((()=>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=Lh.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},Sd={description:n("Days in coupon period containing settlement date."),args:md,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Xi(e)),n=Math.trunc(Xi(t)),r=Math.trunc(Xi(o)),a=Math.trunc(Xi(i));if(qh(s,n),jh(r),Yh(a),1===a){const s=yd.compute(e,t,o,i);return wd.compute(e,t,o,i)-s}return(3===a?365:360)/r},isExported:!0},Cd={description:n("Days from settlement until next coupon."),args:md,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Xi(e)),n=Math.trunc(Xi(t)),r=Math.trunc(Xi(o)),a=Math.trunc(Xi(i));qh(s,n),jh(r),Yh(a);const l=yd.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=ns(s),h=ns(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},Ed={description:n("Days from settlement until next coupon."),args:md,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Xi(e)),n=Math.trunc(Xi(t)),r=Math.trunc(Xi(o)),a=Math.trunc(Xi(i));qh(s,n),jh(r),Yh(a);const l=wd.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=Cd.compute(e,t,o,a);return Sd.compute(e,t,o,a)-c},isExported:!0},wd={description:n("Next coupon date after the settlement date."),args:md,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Xi(e)),n=Math.trunc(Xi(t)),r=Math.trunc(Xi(o)),a=Math.trunc(Xi(i));qh(s,n),jh(r),Yh(a);const l=12/r,c=xd.compute(e,t,o,i);return Me(Fe(ns(n),-(c-1)*l,!0))},isExported:!0},xd={description:n("Number of coupons between settlement and maturity."),args:md,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Xi(e)),n=Math.trunc(Xi(t)),r=Math.trunc(Xi(o)),a=Math.trunc(Xi(i));qh(s,n),jh(r),Yh(a);let l=1,c=n;const h=12/r;for(;c>s;)c=Me(Fe(ns(c),-h,!1)),l++;return l-1},isExported:!0},yd={description:n("Last coupon date prior to or on the settlement date."),args:md,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o,i=0){i=i||0;const s=Math.trunc(Xi(e)),n=Math.trunc(Xi(t)),r=Math.trunc(Xi(o)),a=Math.trunc(Xi(i));qh(s,n),jh(r),Yh(a);const l=12/r,c=xd.compute(e,t,o,i);return Me(Fe(ns(n),-c*l,!0))},isExported:!0},Id={description:n("Cumulative interest paid over a set of periods."),args:[Xa("rate (number)",n("The interest rate.")),Xa("number_of_periods (number)",n("The number of payments to be made.")),Xa("present_value (number)",n("The current value of the annuity.")),Xa("first_period (number)",n("The number of the payment period to begin the cumulative calculation.")),Xa("last_period (number)",n("The number of the payment period to end the cumulative calculation.")),Xa("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=Xi(i),a=Xi(s),l=Xi(e),c=Xi(o),h=Xi(t);dd(r,a,h),Jh(l),sd(c);let d=0;for(let t=r;t<=a;t++){d+=Pd.compute(e,t,h,o,0,n)}return d},isExported:!0},Rd={description:n("Cumulative principal paid over a set of periods."),args:[Xa("rate (number)",n("The interest rate.")),Xa("number_of_periods (number)",n("The number of payments to be made.")),Xa("present_value (number)",n("The current value of the annuity.")),Xa("first_period (number)",n("The number of the payment period to begin the cumulative calculation.")),Xa("last_period (number)",n("The number of the payment period to end the cumulative calculation.")),Xa("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=Xi(i),a=Xi(s),l=Xi(e),c=Xi(o),h=Xi(t);dd(r,a,h),Jh(l),sd(c);let d=0;for(let t=r;t<=a;t++){d+=Zd.compute(e,t,h,o,0,n)}return d},isExported:!0},Td={description:n("Depreciation via declining balance method."),args:[Xa("cost (number)",n("The initial cost of the asset.")),Xa("salvage (number)",n("The value of the asset at the end of depreciation.")),Xa("life (number)",n("The number of periods over which the asset is depreciated.")),Xa("period (number)",n("The single period within life for which to calculate depreciation.")),Xa("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=Xi(e),a=Xi(t),l=Xi(o),c=Math.trunc(Xi(i)),h=s.length?Math.trunc(Xi(s[0])):12,d=l+(12===h?0:1);td(r),id(a),od(c),ed(l),ji((()=>1<=h&&h<=12),n("The month (%s) must be between 1 and 12 inclusive.",h.toString())),ji((()=>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},Ad={description:n("Depreciation via double-declining balance method."),args:[Xa("cost (number)",n("The initial cost of the asset.")),Xa("salvage (number)",n("The value of the asset at the end of depreciation.")),Xa("life (number)",n("The number of periods over which the asset is depreciated.")),Xa("period (number)",n("The single period within life for which to calculate depreciation.")),Xa("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=Xi(e),r=Xi(t),a=Xi(o),l=Xi(i),c=Xi(s);if(td(n),id(r),od(l),ed(a),nd(l,a),cd(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},Od={description:n("Discount rate of a security based on price."),args:[Xa("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("price (number)",n("The price at which the security is bought per 100 face value.")),Xa("redemption (number)",n("The redemption amount per 100 face value, or par.")),Xa("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(Xi(e)),r=Math.trunc(Xi(t)),a=Xi(o),l=Xi(i),c=Math.trunc(Xi(s));qh(n,r),Yh(c),Kh(a),Xh(l);return(l-a)/l/Lh.compute(n,r,c)},isExported:!0},Md={description:n("Convert a decimal fraction to decimal value."),args:[Xa("fractional_price (number)",n("The price quotation given using fractional decimal conventions.")),Xa("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=Xi(e),i=Math.trunc(Xi(t));ji((()=>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},Nd={description:n("Convert a decimal value to decimal fraction."),args:[Xa("decimal_price (number)",n("The price quotation given as a decimal value.")),Xa("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=Xi(e),i=Math.trunc(Xi(t));ji((()=>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},_d={description:n("Number of periods for an investment to reach a value."),args:[Xa("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("rate (number)",n("The annualized rate of interest.")),Xa("yield (number)",n("The expected annual yield of the security.")),Xa("frequency (number)",n("The number of interest or coupon payments per year (1, 2, or 4).")),Xa("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(Xi(e)),l=Math.trunc(Xi(t)),c=Xi(o),h=Xi(i),d=Math.trunc(Xi(s)),u=Math.trunc(Xi(r));qh(a,l),jh(d),Yh(u),ji((()=>c>=0),n("The rate (%s) must be positive or null.",c.toString())),ji((()=>h>=0),n("The yield (%s) must be positive or null.",h.toString()));const g=Lh.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},Fd={description:n("Annual effective interest rate."),args:[Xa("nominal_rate (number)",n("The nominal interest rate per year.")),Xa("periods_per_year (number)",n("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const o=Xi(e),i=Math.trunc(Xi(t));return ji((()=>o>0),n("The nominal rate (%s) must be strictly greater than 0.",o.toString())),ji((()=>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},Dd={description:n("Future value of an annuity investment."),args:[Xa("rate (number)",n("The interest rate.")),Xa("number_of_periods (number)",n("The number of payments to be made.")),Xa("payment_amount (number)",n("The amount per period to be paid.")),Xa("present_value (number, default=0)",n("The current value of the annuity.")),Xa("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=Xi(e),r=Xi(t),a=Xi(o),l=Xi(i),c=ss(s)?1:0;return n?-l*(1+n)**r-a*(1+n*c)*((1+n)**r-1)/n:-(l+a*r)},isExported:!0},Ld={description:n("Future value of principal from series of rates."),args:[Xa("principal (number)",n("The amount of initial capital or value to compound against.")),Xa("rate_schedule (number, range<number>)",n("A series of interest rates to compound against the principal."))],returns:["NUMBER"],compute:function(e,t){return hs([t],((e,t)=>e*(1+Xi(t))),Xi(e))},isExported:!0},kd={description:n("Calculates effective interest rate."),args:[Xa("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("investment (number)",n("The amount invested in the security.")),Xa("redemption (number)",n("The amount to be received at maturity.")),Xa("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(Xi(e)),r=Math.trunc(Xi(t)),a=Xi(i),l=Xi(o);qh(n,r),rd(l),Xh(a);return(a-l)/l/Lh.compute(n,r,s)},isExported:!0},Pd={description:n("Payment on the principal of an investment."),args:[Xa("rate (number)",n("The annualized rate of interest.")),Xa("period (number)",n("The amortization period, in terms of number of periods.")),Xa("number_of_periods (number)",n("The number of payments to be made.")),Xa("present_value (number)",n("The current value of the annuity.")),Xa("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),Xa("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 qd.compute(e,o,i,s,n)-Zd.compute(e,t,o,i,s,n)},isExported:!0},Ud={description:n("Internal rate of return given periodic cashflows."),args:[Xa("cashflow_amounts (number, range<number>)",n("An array or range containing the income or payments associated with the investment.")),Xa("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=Xi(t);ud(o);let i=!1,s=!1,r=[];ls([e],(e=>{e>0&&(i=!0),e<0&&(s=!0),r.push(e)})),ji((()=>i&&s),n("The cashflow_amounts must include negative and positive values."));const a=r.shift();return fd((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},Vd={description:n("Returns the interest paid at a particular period of an investment."),args:[Xa("rate (number)",n("The interest rate.")),Xa("period (number)",n("The period for which you want to view the interest payment.")),Xa("number_of_periods (number)",n("The number of payments to be made.")),Xa("present_value (number)",n("The current value of the annuity."))],returns:["NUMBER"],compute:function(e,t,o,i){const s=Xi(e),r=Xi(t),a=Xi(o),l=Xi(i);ji((()=>0!==a),n("The number of periods must be different than 0.",a.toString()));return-1*(l-l*(r/a))*s},isExported:!0},zd={description:n("Modified Macaulay duration."),args:[Xa("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("rate (number)",n("The annualized rate of interest.")),Xa("yield (number)",n("The expected annual yield of the security.")),Xa("frequency (number)",n("The number of interest or coupon payments per year (1, 2, or 4).")),Xa("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 _d.compute(e,t,o,i,s,n)/(1+Xi(i)/Math.trunc(Xi(s)))},isExported:!0},Bd={description:n("Modified internal rate of return."),args:[Xa("cashflow_amounts (range<number>)",n("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")),Xa("financing_rate (number)",n("The interest rate paid on funds invested.")),Xa("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=Xi(t),s=Xi(o),r=(a=e,a.length?a[0].map(((e,t)=>a.map((e=>e[t])))):a).flat().filter(dt).map(Xi);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}ji((()=>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},Hd={description:n("Annual nominal interest rate."),args:[Xa("effective_rate (number)",n("The effective interest rate per year.")),Xa("periods_per_year (number)",n("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const o=Xi(e),i=Math.trunc(Xi(t));return ji((()=>o>0),n("The effective rate (%s) must must strictly greater than 0.",o.toString())),ji((()=>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},$d={description:n("Number of payment periods for an investment."),args:[Xa("rate (number)",n("The interest rate.")),Xa("payment_amount (number)",n("The amount of each payment made.")),Xa("present_value (number)",n("The current value of the annuity.")),Xa("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),Xa("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=Xi(e),r=Xi(t),a=Xi(o),l=Xi(i),c=ss(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 Wd={description:n("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:[Xa("discount (number)",n("The discount rate of the investment over one period.")),Xa("cashflow1 (number, range<number>)",n("The first future cash flow.")),Xa("cashflow2 (number, range<number>, repeating)",n("Additional future cash flows."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,...t){const o=Xi(e);return ji((()=>-1!==o),n("The discount (%s) must be different from -1.",o.toString())),function(e,t,o){let i=0;return ds(o,((t,o)=>(i++,t+o/(1+e)**i)),t)}(o,0,t)},isExported:!0},Gd={description:n("Computes the number of periods needed for an investment to reach a value."),args:[Xa("rate (number)",n("The rate at which the investment grows each period.")),Xa("present_value (number)",n("The investment's current value.")),Xa("future_value (number)",n("The investment's desired future value."))],returns:["NUMBER"],compute:function(e,t,o){const i=Xi(e),s=Xi(t),r=Xi(o);return Jh(i),ji((()=>s>0),n("The present_value (%s) must be strictly positive.",s.toString())),ji((()=>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},qd={description:n("Periodic payment for an annuity investment."),args:[Xa("rate (number)",n("The annualized rate of interest.")),Xa("number_of_periods (number)",n("The number of payments to be made.")),Xa("present_value (number)",n("The current value of the annuity.")),Xa("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),Xa("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=Xi(t),r=Xi(e),a=ss(s)?1:0;let l=Xi(i),c=Xi(o);if(Qh(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},Zd={description:n("Payment on the principal of an investment."),args:[Xa("rate (number)",n("The annualized rate of interest.")),Xa("period (number)",n("The amortization period, in terms of number of periods.")),Xa("number_of_periods (number)",n("The number of payments to be made.")),Xa("present_value (number)",n("The current value of the annuity.")),Xa("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),Xa("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=Xi(o),l=Xi(e),c=Xi(t),h=ss(r)?1:0,d=Xi(s),u=Xi(i);Qh(a),ji((()=>c>0&&c<=a),n("The period must be between 1 and number_of_periods",a.toString()));const g=qd.compute(l,a,u,d,r);if(1===h&&1===c)return g;return g+-Dd.compute(l,0===h?c-1:c-2,g,u+g*h,0)*l},isExported:!0},jd={description:n("Present value of an annuity investment."),args:[Xa("rate (number)",n("The interest rate.")),Xa("number_of_periods (number)",n("The number of payments to be made.")),Xa("payment_amount (number)",n("The amount per period to be paid.")),Xa("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),Xa("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=Xi(e),r=Xi(t),a=Xi(o),l=Xi(i),c=ss(s)?1:0;return n?-(a*(1+n*c)*((1+n)**r-1)/n+l)/(1+n)**r:-(l+a*r)},isExported:!0},Yd={description:n("Price of a security paying periodic interest."),args:[Xa("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("rate (number)",n("The annualized rate of interest.")),Xa("yield (number)",n("The expected annual yield of the security.")),Xa("redemption (number)",n("The redemption amount per 100 face value, or par.")),Xa("frequency (number)",n("The number of interest or coupon payments per year (1, 2, or 4).")),Xa("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(Xi(e)),c=Math.trunc(Xi(t)),h=Xi(o),d=Xi(i),u=Xi(s),g=Math.trunc(Xi(r)),p=Math.trunc(Xi(a));qh(l,c),jh(g),Yh(p),ji((()=>h>=0),n("The rate (%s) must be positive or null.",h.toString())),ji((()=>d>=0),n("The yield (%s) must be positive or null.",d.toString())),Xh(u);const m=Lh.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},Xd={description:n("Price of a discount security."),args:[Xa("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("discount (number)",n("The discount rate of the security at time of purchase.")),Xa("redemption (number)",n("The redemption amount per 100 face value, or par.")),Xa("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(Xi(e)),r=Math.trunc(Xi(t)),a=Xi(o),l=Xi(i),c=Math.trunc(Xi(s));qh(n,r),Yh(c),ad(a),Xh(l);return l-a*l*Lh.compute(n,r,c)},isExported:!0},Kd={description:n("Calculates the price of a security paying interest at maturity, based on expected yield."),args:[Xa("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("issue (date)",n("The date the security was initially issued.")),Xa("rate (number)",n("The annualized rate of interest.")),Xa("yield (number)",n("The expected annual yield of the security.")),Xa("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(Xi(e)),l=Math.trunc(Xi(t)),c=Math.trunc(Xi(o)),h=Xi(i),d=Xi(s),u=Math.trunc(Xi(r));Zh(a,c),qh(a,l),Yh(u),ji((()=>h>=0),n("The rate (%s) must be positive or null.",h.toString())),ji((()=>d>=0),n("The yield (%s) must be positive or null.",d.toString()));const g=Lh.compute(a,l,u),p=Lh.compute(a,c,u);return(100+Lh.compute(c,l,u)*h*100)/(1+g*d)-p*h*100},isExported:!0},Qd=.1,Jd={description:n("Interest rate of an annuity investment."),args:[Xa("number_of_periods (number)",n("The number of payments to be made.")),Xa("payment_per_period (number)",n("The amount per period to be paid.")),Xa("present_value (number)",n("The current value of the annuity.")),Xa("future_value (number, default=0)",n("The future value remaining after the final payment has been made.")),Xa("end_or_beginning (number, default=0)",n("Whether payments are due at the end (0) or beginning (1) of each period.")),Xa("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||Qd;const a=Xi(e),l=Xi(t),c=ss(s)?1:0,h=Xi(r);let d=Xi(i),u=Xi(o);Qh(a),ji((()=>[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())),ud(h),d-=l*c,u+=l*c;return fd((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},eu={description:n("Amount received at maturity for a security."),args:[Xa("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("investment (number)",n("The amount invested (irrespective of face value of each security).")),Xa("discount (number)",n("The discount rate of the security invested in.")),Xa("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(Xi(e)),r=Math.trunc(Xi(t)),a=Xi(o),l=Xi(i),c=Math.trunc(Xi(s));qh(n,r),Yh(c),rd(a),ad(l);return a/(1-l*Lh.compute(n,r,c))},isExported:!0},tu={description:n("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:[Xa("number_of_periods (number)",n("The number of periods.")),Xa("present_value (number)",n("The present value of the investment.")),Xa("future_value (number)",n("The future value of the investment."))],returns:["NUMBER"],compute:function(e,t,o){const i=Xi(e),s=Xi(t),n=Xi(o);return Qh(i),(n/s)**(1/i)-1},isExported:!0},ou={description:n("Depreciation of an asset using the straight-line method."),args:[Xa("cost (number)",n("The initial cost of the asset.")),Xa("salvage (number)",n("The value of the asset at the end of depreciation.")),Xa("life (number)",n("The number of periods over which the asset is depreciated."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o){return(Xi(e)-Xi(t))/Xi(o)},isExported:!0},iu={description:n("Depreciation via sum of years digit method."),args:[Xa("cost (number)",n("The initial cost of the asset.")),Xa("salvage (number)",n("The value of the asset at the end of depreciation.")),Xa("life (number)",n("The number of periods over which the asset is depreciated.")),Xa("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=Xi(e),n=Xi(t),r=Xi(o),a=Xi(i);od(a),ed(r),nd(a,r);return(r-a+1)/(r*(r+1)/2)*(s-n)},isExported:!0},su={description:n("Price of a US Treasury bill."),args:[Xa("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("discount (number)",n("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Xi(e)),s=Math.trunc(Xi(t)),n=Xi(o);qh(i,s),hd(i,s),ad(n),ld(n);return 100*(1-n*Lh.compute(i,s,2))},isExported:!0},nu={description:n("Equivalent rate of return for a US Treasury bill."),args:[Xa("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("discount (number)",n("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Xi(e)),s=Math.trunc(Xi(t)),n=Xi(o);qh(i,s),hd(i,s),ad(n),ld(n);const r=ph.compute(s,i);if(r<=182)return 365*n/(360-n*r);const a=su.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},ru={description:n("The yield of a US Treasury bill based on price."),args:[Xa("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("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(Xi(e)),s=Math.trunc(Xi(t)),n=Xi(o);qh(i,s),hd(i,s),Kh(n);return(100-n)/n*(1/Lh.compute(i,s,2))},isExported:!0},au={description:n("Variable declining balance. WARNING : does not handle decimal periods."),args:[Xa("cost (number)",n("The initial cost of the asset.")),Xa("salvage (number)",n("The value of the asset at the end of depreciation.")),Xa("life (number)",n("The number of periods over which the asset is depreciated.")),Xa("start (number)",n("Starting period to calculate depreciation.")),Xa("end (number)",n("Ending period to calculate depreciation.")),Xa("factor (number, default=2)",n("The number of months in the first year of depreciation.")),Xa("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=Xi(e),c=Xi(t),h=Xi(o),d=Math.trunc(Xi(i)),u=Math.trunc(Xi(s)),g=Xi(r),p=ss(a);if(td(l),id(c),function(e,t,o){ed(o),ji((()=>e>=0),n("The start_period (%s) must be greater or equal than 0.",e.toString())),ji((()=>t>=0),n("The end_period (%s) must be greater or equal than 0.",t.toString())),ji((()=>e<=t),n("The start_period (%s) must be smaller or equal to the end_period (%s).",e.toString(),t.toString())),ji((()=>t<=o),n("The end_period (%s) must be smaller or equal to the life (%s).",e.toString(),o.toString()))}(d,u,h),cd(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},lu={description:n("Internal rate of return given non-periodic cash flows."),args:[Xa("cashflow_amounts (range<number>)",n("An range containing the income or payments associated with the investment.")),Xa("cashflow_dates (range<number>)",n("An range with dates corresponding to the cash flows in cashflow_amounts.")),Xa("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=Xi(o=o||0),s=e.flat().map(Xi),r=t.flat().map(Xi);var a;gd(e,t),a=s,ji((()=>a.some((e=>e>0))&&a.some((e=>e<0))),n("There must be both positive and negative values in cashflow_amounts.")),pd(r),ud(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 fd((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},cu={description:n("Net present value given to non-periodic cash flows.."),args:[Xa("discount (number)",n("The discount rate of the investment over one period.")),Xa("cashflow_amounts (number, range<number>)",n("An range containing the income or payments associated with the investment.")),Xa("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=Xi(e),s=Array.isArray(t)?t.flat().map(Ki):[Ki(t)],r=Array.isArray(o)?o.flat().map(Ki):[Ki(o)];if(Array.isArray(o)&&Array.isArray(t)?gd(t,o):ji((()=>s.length===r.length),n("There must be the same number of values in cashflow_amounts and cashflow_dates.")),pd(r),Jh(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},hu={description:n("Annual yield of a security paying periodic interest."),args:[Xa("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("rate (number)",n("The annualized rate of interest.")),Xa("price (number)",n("The price at which the security is bought per 100 face value.")),Xa("redemption (number)",n("The redemption amount per 100 face value, or par.")),Xa("frequency (number)",n("The number of interest or coupon payments per year (1, 2, or 4).")),Xa("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(Xi(e)),c=Math.trunc(Xi(t)),h=Xi(o),d=Xi(i),u=Xi(s),g=Math.trunc(Xi(r)),p=Math.trunc(Xi(a));qh(l,c),jh(g),Yh(p),ji((()=>h>=0),n("The rate (%s) must be positive or null.",h.toString())),Kh(d),Xh(u);const m=Lh.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=fd((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},du={description:n("Annual yield of a discount security."),args:[Xa("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("price (number)",n("The price at which the security is bought per 100 face value.")),Xa("redemption (number)",n("The redemption amount per 100 face value, or par.")),Xa("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(Xi(e)),r=Math.trunc(Xi(t)),a=Xi(o),l=Xi(i),c=Math.trunc(Xi(s));qh(n,r),Yh(c),Kh(a),Xh(l);return(l/a-1)/Lh.compute(e,t,s)},isExported:!0},uu={description:n("Annual yield of a security paying interest at maturity."),args:[Xa("settlement (date)",n("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),Xa("maturity (date)",n("The maturity or end date of the security, when it can be redeemed at face, or par value.")),Xa("issue (date)",n("The date the security was initially issued.")),Xa("rate (number)",n("The annualized rate of interest.")),Xa("price (number)",n("The price at which the security is bought.")),Xa("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(Xi(e)),l=Math.trunc(Xi(t)),c=Math.trunc(Xi(o)),h=Xi(i),d=Xi(s),u=Math.trunc(Xi(r));qh(a,l),Yh(u),ji((()=>a>=c),n("The settlement (%s) must be greater than or equal to the issue (%s).",a.toString(),c.toString())),ji((()=>h>=0),n("The rate (%s) must be positive or null.",h.toString())),Kh(d);const g=Lh.compute(c,l,u),p=Lh.compute(c,a,u),m=Lh.compute(a,l,u);return(100*(1+h*g)/(d+100*h*p)-1)/m},isExported:!0};var gu=Object.freeze({__proto__:null,ACCRINTM:bd,AMORLINC:vd,COUPDAYS:Sd,COUPDAYBS:Cd,COUPDAYSNC:Ed,COUPNCD:wd,COUPNUM:xd,COUPPCD:yd,CUMIPMT:Id,CUMPRINC:Rd,DB:Td,DDB:Ad,DISC:Od,DOLLARDE:Md,DOLLARFR:Nd,DURATION:_d,EFFECT:Fd,FV:Dd,FVSCHEDULE:Ld,INTRATE:kd,IPMT:Pd,IRR:Ud,ISPMT:Vd,MDURATION:zd,MIRR:Bd,NOMINAL:Hd,NPER:$d,NPV:Wd,PDURATION:Gd,PMT:qd,PPMT:Zd,PV:jd,PRICE:Yd,PRICEDISC:Xd,PRICEMAT:Kd,RATE:Jd,RECEIVED:eu,RRI:tu,SLN:ou,SYD:iu,TBILLPRICE:su,TBILLEQ:nu,TBILLYIELD:ru,VDB:au,XIRR:lu,XNPV:cu,YIELD:hu,YIELDDISC:du,YIELDMAT:uu});const pu={description:n("Whether a value is an error other than #N/A."),args:[Xa("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},mu={description:n("Whether a value is an error."),args:[Xa("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},fu={description:n("Whether a value is `true` or `false`."),args:[Xa("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},bu={description:n("Whether a value is the error #N/A."),args:[Xa("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},vu={description:n("Whether a value is non-textual."),args:[Xa("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},Su={description:n("Whether a value is a number."),args:[Xa("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},Cu={description:n("Whether a value is text."),args:[Xa("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},Eu={description:n("Whether the referenced cell is empty"),args:[Xa("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},wu={description:n("Returns the error value #N/A."),args:[],returns:["BOOLEAN"],compute:function(e){throw new g},isExported:!0};var xu=Object.freeze({__proto__:null,ISERR:pu,ISERROR:mu,ISLOGICAL:fu,ISNA:bu,ISNONTEXT:vu,ISNUMBER:Su,ISTEXT:Cu,ISBLANK:Eu,NA:wu});const yu={description:n("Logical `and` operator."),args:[Xa("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.")),Xa("logical_expression2 (boolean, range<boolean>, repeating)",n("More expressions that represent logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!0;return gs(e,(e=>(t=!0,o=o&&e,o))),ji((()=>t),n("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0},Iu={description:n("Returns value depending on logical expression."),args:[Xa("logical_expression (boolean)",n("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")),Xa("value_if_true (any, lazy)",n("The value the function returns if logical_expression is TRUE.")),Xa("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=ss(e)?t():o();return null==i?"":i},isExported:!0},Ru={description:n("Value if it is not an error, otherwise 2nd argument."),args:[Xa("value (any, lazy)",n("The value to return if value itself is not an error.")),Xa('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},Tu={description:n("Value if it is not an #N/A error, otherwise 2nd argument."),args:[Xa("value (any, lazy)",n("The value to return if value itself is not #N/A an error.")),Xa('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},Au={description:n("Returns a value depending on multiple logical expressions."),args:[Xa("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.")),Xa("value1 (any, lazy)",n("The returned value if condition1 is TRUE.")),Xa("condition2 (boolean, lazy, repeating)",n("Additional conditions to be evaluated if the previous ones are FALSE.")),Xa("value2 (any, lazy, repeating)",n("Additional values to be returned if their corresponding conditions are TRUE."))],returns:["ANY"],compute:function(...e){ji((()=>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(ss(e[t]())){const o=e[t+1]();return null!==o?o:""}throw new Error(n("No match."))},isExported:!0},Ou={description:n("Returns opposite of provided logical value."),args:[Xa("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!ss(e)},isExported:!0},Mu={description:n("Logical `or` operator."),args:[Xa("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.")),Xa("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 gs(e,(e=>(t=!0,o=o||e,!o))),ji((()=>t),n("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0},Nu={description:n("Logical `xor` operator."),args:[Xa("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.")),Xa("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 gs(e,(e=>(t=!0,o=o?!e:e,!0))),ji((()=>t),n("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0};var _u=Object.freeze({__proto__:null,AND:yu,IF:Iu,IFERROR:Ru,IFNA:Tu,IFS:Au,NOT:Ou,OR:Mu,XOR:Nu});function Fu(e,t){if(void 0===e)throw new g(n("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",es(t)))}const Du={description:n("Returns a cell reference as a string. "),args:[Xa("row (number)",n("The row number of the cell reference. ")),Xa("column (number)",n("The column number (not name) of the cell reference. A is column number 1. ")),Xa("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).")),Xa("use_a1_notation (boolean, default=TRUE)",n("A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).")),Xa("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=Qi(e),a=Qi(t);Ji(r),Ji(a);const l=Qi(o);var c,h;ji((()=>[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(ss(i)){d=Gt(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(es(s))}!${d}`:d},isExported:!0},Lu={description:n("Column number of a specified cell."),args:[Xa("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?.();ji((()=>!!t),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return ti(t).left+1},isExported:!0},ku={description:n("Number of columns in a specified array or range."),args:[Xa("range (meta)",n("The range whose column count will be returned."))],returns:["NUMBER"],compute:function(e){const t=ti(e);return t.right-t.left+1},isExported:!0},Pu={description:n("Horizontal lookup"),args:[Xa("search_key (any)",n("The value to search for. For example, 42, 'Cats', or I24.")),Xa("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.")),Xa("index (number)",n("The row index of the value to be returned, where the first row in range is numbered 1.")),Xa("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(Xi(o)),r=os(e);ji((()=>1<=s&&s<=t[0].length),n("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=ss(i)?Ss(t,r,"nextSmaller","asc",t.length,vs):Cs(t,r,"strict",t.length,vs);const l=t[a];return Fu(l,e),l[s-1]},isExported:!0},Uu={description:n("Returns the content of a cell, specified by row and column offset."),args:[Xa("reference (any, range)",n("The range of cells from which the values are returned.")),Xa("row (number)",n("The index of the row to be returned from within the reference range of cells.")),Xa("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=Xi(t.value);return e[Xi(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=Xi(t),a=Xi(o);return ji((()=>a>=0&&a-1<i.length&&r>=0&&r-1<i[0].length),n("Index out of range.")),ji((()=>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},Vu={description:n("Look up a value."),args:[Xa("search_key (any)",n("The value to search for. For example, 42, 'Cats', or I24.")),Xa("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.")),Xa("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=os(e),a=s>=i,l=Ss(t,r,"nextSmaller","asc",a?s:i,a?bs:vs);return-1===l&&Fu(void 0,e),Fu(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,ji((()=>1===i||1===s),n("The result_range must be a single row or a single column.")),i>1?(ji((()=>l<=i-1),n("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(l+1).toString())),o[l][0]):(ji((()=>l<=s-1),n("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(l+1).toString())),o[0][l]))},isExported:!0},zu={description:n("Position of item in range that matches value."),args:[Xa("search_key (any)",n("The value to search for. For example, 42, 'Cats', or I24.")),Xa("range (any, range)",n("The one-dimensional array to be searched.")),Xa("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=Xi(o);const s=os(e),r=t.length,a=t[0].length;ji((()=>1===r||1===a),n("The range must be a single row or a single column."));let l=-1;const c=1===r?bs:vs,h=1===r?t[0].length:t.length;switch(i=Math.sign(i),i){case 1:l=Ss(t,s,"nextSmaller","asc",h,c);break;case 0:l=Cs(t,s,"strict",h,c);break;case-1:l=Ss(t,s,"nextGreater","desc",h,c)}return Fu(1===r?t[0][l]:t[l],e),l+1},isExported:!0},Bu={description:n("Row number of a specified cell."),args:[Xa("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?.(),ji((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return ti(e).top+1},isExported:!0},Hu={description:n("Number of rows in a specified array or range."),args:[Xa("range (meta)",n("The range whose row count will be returned."))],returns:["NUMBER"],compute:function(e){const t=ti(e);return t.bottom-t.top+1},isExported:!0},$u={description:n("Vertical lookup."),args:[Xa("search_key (any)",n("The value to search for. For example, 42, 'Cats', or I24.")),Xa("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.")),Xa("index (number)",n("The column index of the value to be returned, where the first column in range is numbered 1.")),Xa("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(Xi(o)),r=os(e);ji((()=>1<=s&&s<=t.length),n("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=ss(i)?Ss(t,r,"nextSmaller","asc",t[0].length,bs):Cs(t,r,"strict",t[0].length,bs);const l=t[s-1][a];return Fu(l,e),l},isExported:!0},Wu={description:n("Search a range for a match and return the corresponding item from a second range."),args:[Xa("search_key (any)",n("The value to search for.")),Xa("lookup_range (any, range)",n("The range to consider for the search. Should be a single column or a single row.")),Xa("return_range (any, range)",n("The range containing the return value. Should have the same dimensions as lookup_range.")),Xa("if_not_found (any, lazy, optional)",n("If a valid match is not found, return this value.")),Xa("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.")),Xa("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(Xi(s)),l=Math.trunc(Xi(r)),c=os(e);ji((()=>1===t.length||1===t[0].length),n("lookup_range should be either a single row or single column.")),ji((()=>1===o.length||1===o[0].length),n("return_range should be either a single row or single column.")),ji((()=>o.length===t.length&&o[0].length===t[0].length),n("return_range should have the same dimensions as lookup_range.")),ji((()=>[-1,1,-2,2].includes(l)),n("searchMode should be a value in [-1, 1, -2, 2].")),ji((()=>[-1,0,1].includes(a)),n("matchMode should be a value in [-1, 0, 1]."));const h=1===t.length?bs:vs,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=Ss(t,c,u,2===l?"asc":"desc",d,h)}else p=Cs(t,c,u,d,h,g);if(-1!==p)return 1===t.length?o[0][p]:o[p][0];const m=i?.();return Fu(m,e),m},isExported:!0};var Gu=Object.freeze({__proto__:null,ADDRESS:Du,COLUMN:Lu,COLUMNS:ku,HLOOKUP:Pu,INDEX:Uu,LOOKUP:Vu,MATCH:zu,ROW:Bu,ROWS:Hu,VLOOKUP:$u,XLOOKUP:Wu});const qu={description:n("Sum of two numbers."),args:[Xa("value1 (number)",n("The first addend.")),Xa("value2 (number)",n("The second addend."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Xi(e)+Xi(t)}},Zu={description:n("Concatenation of two values."),args:[Xa("value1 (string)",n("The value to which value2 will be appended.")),Xa("value2 (string)",n("The value to append to value1."))],returns:["STRING"],compute:function(e,t){return es(e)+es(t)},isExported:!0},ju={description:n("One number divided by another."),args:[Xa("dividend (number)",n("The number to be divided.")),Xa("divisor (number)",n("The number to divide by."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){const o=Xi(t);return ji((()=>0!==o),n("The divisor must be different from zero.")),Xi(e)/o}};function Yu(e){return null==e}const Xu={number:0,string:"",boolean:!1},Ku={description:n("Equal."),args:[Xa("value1 (any)",n("The first value.")),Xa("value2 (any)",n("The value to test against value1 for equality."))],returns:["BOOLEAN"],compute:function(e,t){return e=Yu(e)?Xu[typeof t]:e,t=Yu(t)?Xu[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function Qu(e,t,o){e=Yu(e)?Xu[typeof t]:e,t=Yu(t)?Xu[typeof e]:t,"number"!=typeof e&&(e=es(e).toUpperCase()),"number"!=typeof t&&(t=es(t).toUpperCase());const i=typeof e,s=typeof t;return"string"===i&&"number"===s||("string"!==s||"number"!==i)&&o(e,t)}const Ju={description:n("Strictly greater than."),args:[Xa("value1 (any)",n("The value to test as being greater than value2.")),Xa("value2 (any)",n("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return Qu(e,t,((e,t)=>e>t))}},eg={description:n("Greater than or equal to."),args:[Xa("value1 (any)",n("The value to test as being greater than or equal to value2.")),Xa("value2 (any)",n("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return Qu(e,t,((e,t)=>e>=t))}},tg={description:n("Less than."),args:[Xa("value1 (any)",n("The value to test as being less than value2.")),Xa("value2 (any)",n("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!eg.compute(e,t)}},og={description:n("Less than or equal to."),args:[Xa("value1 (any)",n("The value to test as being less than or equal to value2.")),Xa("value2 (any)",n("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!Ju.compute(e,t)}},ig={description:n("Difference of two numbers."),args:[Xa("value1 (number)",n("The minuend, or number to be subtracted from.")),Xa("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 Xi(e)-Xi(t)}},sg={description:n("Product of two numbers"),args:[Xa("factor1 (number)",n("The first multiplicand.")),Xa("factor2 (number)",n("The second multiplicand."))],returns:["NUMBER"],computeFormat:(e,t)=>e?.format||t?.format,compute:function(e,t){return Xi(e)*Xi(t)}},ng={description:n("Not equal."),args:[Xa("value1 (any)",n("The first value.")),Xa("value2 (any)",n("The value to test against value1 for inequality."))],returns:["BOOLEAN"],compute:function(e,t){return!Ku.compute(e,t)}},rg={description:n("A number raised to a power."),args:[Xa("base (number)",n("The number to raise to the exponent power.")),Xa("exponent (number)",n("The exponent to raise base to."))],returns:["NUMBER"],compute:function(e,t){return Vl.compute(e,t)}},ag={description:n("A number with the sign reversed."),args:[Xa("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-Xi(e)}},lg={description:n("Value interpreted as a percentage."),args:[Xa("percentage (number)",n("The value to interpret as a percentage."))],returns:["NUMBER"],compute:function(e){return Xi(e)/100}},cg={description:n("A specified number, unchanged."),args:[Xa("value (any)",n("The number to return."))],returns:["ANY"],computeFormat:e=>e?.format,compute:function(e){return null===e?"":e}};var hg=Object.freeze({__proto__:null,ADD:qu,CONCAT:Zu,DIVIDE:ju,EQ:Ku,GT:Ju,GTE:eg,LT:tg,LTE:og,MINUS:ig,MULTIPLY:sg,NE:ng,POW:rg,UMINUS:ag,UNARY_PERCENT:lg,UPLUS:cg});const dg=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,ug={description:n("Gets character associated with number."),args:[Xa("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(Xi(e));return ji((()=>t>=1),n("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},gg={description:n("Remove non-printable characters from a piece of text."),args:[Xa("text (string)",n("The text whose non-printable characters are to be removed."))],returns:["STRING"],compute:function(e){const t=es(e);let o="";for(const e of t)e&&e.charCodeAt(0)>31&&(o+=e);return o},isExported:!0},pg={description:n("Appends strings to one another."),args:[Xa("string1 (string, range<string>)",n("The initial string.")),Xa("string2 (string, range<string>, repeating)",n("More strings to append in sequence."))],returns:["STRING"],compute:function(...e){return hs(e,((e,t)=>e+es(t)),"")},isExported:!0},mg={description:n("Tests whether two strings are identical."),args:[Xa("string1 (string)",n("The first string to compare.")),Xa("string2 (string)",n("The second string to compare."))],returns:["BOOLEAN"],compute:function(e,t){return es(e)===es(t)},isExported:!0},fg={description:n("First position of string found in text, case-sensitive."),args:[Xa("search_for (string)",n("The string to look for within text_to_search.")),Xa("text_to_search (string)",n("The text to search for the first occurrence of search_for.")),Xa("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=es(e),s=es(t),r=Xi(o);ji((()=>""!==s),n("The text_to_search must be non-empty.")),ji((()=>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 ji((()=>a>=0),n("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i.toString(),s)),a+1},isExported:!0},bg={description:n("Concatenates elements of arrays with delimiter."),args:[Xa("delimiter (string)",n("The character or string to place between each concatenated value.")),Xa("value_or_array1 (string, range<string>)",n("The value or values to be appended using delimiter.")),Xa("value_or_array2 (string, range<string>, repeating)",n("More values to be appended using delimiter."))],returns:["STRING"],compute:function(e,...t){const o=es(e);return hs(t,((e,t)=>(e?e+o:"")+es(t)),"")}},vg={description:n("Substring from beginning of specified string."),args:[Xa("text (string)",n("The string from which the left portion will be returned.")),Xa("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?Xi(t[0]):1;return ji((()=>o>=0),n("The number_of_characters (%s) must be positive or null.",o.toString())),es(e).substring(0,o)},isExported:!0},Sg={description:n("Length of a string."),args:[Xa("text (string)",n("The string whose length will be returned."))],returns:["NUMBER"],compute:function(e){return es(e).length},isExported:!0},Cg={description:n("Converts a specified string to lowercase."),args:[Xa("text (string)",n("The string to convert to lowercase."))],returns:["STRING"],compute:function(e){return es(e).toLowerCase()},isExported:!0},Eg={description:n("A segment of a string."),args:[Xa("text (string)",n("The string to extract a segment from.")),Xa("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.")),Xa("extract_length (number)",n("The length of the segment to extract."))],returns:["STRING"],compute:function(e,t,o){const i=es(e),s=Xi(t),r=Xi(o);return ji((()=>s>=1),n("The starting_at argument (%s) must be positive greater than one.",s.toString())),ji((()=>r>=0),n("The extract_length argument (%s) must be positive or null.",r.toString())),i.slice(s-1,s+r-1)},isExported:!0},wg={description:n("Capitalizes each word in a specified string."),args:[Xa("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 es(e).replace(dg,(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()))},isExported:!0},xg={description:n("Replaces part of a text string with different text."),args:[Xa("text (string)",n("The text, a part of which will be replaced.")),Xa("position (number)",n("The position where the replacement will begin (starting from 1).")),Xa("length (number)",n("The number of characters in the text to be replaced.")),Xa("new_text (string)",n("The text which will be inserted into the original text."))],returns:["STRING"],compute:function(e,t,o,i){const s=Xi(t);ji((()=>s>=1),n("The position (%s) must be greater than or equal to 1.",s.toString()));const r=es(e),a=Xi(o),l=es(i);return r.substring(0,s-1)+l+r.substring(s-1+a)},isExported:!0},yg={description:n("A substring from the end of a specified string."),args:[Xa("text (string)",n("The string from which the right portion will be returned.")),Xa("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?Xi(t[0]):1;ji((()=>o>=0),n("The number_of_characters (%s) must be positive or null.",o.toString()));const i=es(e),s=i.length;return i.substring(s-o,s)},isExported:!0},Ig={description:n("First position of string found in text, ignoring case."),args:[Xa("search_for (string)",n("The string to look for within text_to_search.")),Xa("text_to_search (string)",n("The text to search for the first occurrence of search_for.")),Xa("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=es(e).toLowerCase(),s=es(t).toLowerCase(),r=Xi(o);ji((()=>""!==s),n("The text_to_search must be non-empty.")),ji((()=>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 ji((()=>a>=0),n("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i,s)),a+1},isExported:!0},Rg={description:n("Replaces existing text with new text in a string."),args:[Xa("text_to_search (string)",n("The text within which to search and replace.")),Xa("search_for (string)",n("The string to search for within text_to_search.")),Xa("replace_with (string)",n("The string that will replace search_for.")),Xa("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=Xi(i);ji((()=>s>=0),n("The occurrenceNumber (%s) must be positive or null.",s.toString()));const r=es(e),a=es(t);if(""===a)return r;const l=es(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},Tg={description:n("Combines text from multiple strings and/or arrays."),args:[Xa("delimiter (string)",n(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")),Xa("ignore_empty (boolean)",n("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")),Xa("text1 (string, range<string>)",n("Any text item. This could be a string, or an array of strings in a range.")),Xa("text2 (string, range<string>, repeating)",n("Additional text item(s)."))],returns:["STRING"],compute:function(e,t,...o){const i=es(e),s=ss(t);let n=0;return hs(o,((e,t)=>s&&""===es(t)?e:(n++?e+i:"")+es(t)),"")},isExported:!0},Ag={description:n("Removes space characters."),args:[Xa("text (string)",n("The text or reference to a cell containing text to be trimmed."))],returns:["STRING"],compute:function(e){return es(e).trim()},isExported:!0},Og={description:n("Converts a specified string to uppercase."),args:[Xa("text (string)",n("The string to convert to uppercase."))],returns:["STRING"],compute:function(e){return es(e).toUpperCase()},isExported:!0},Mg={description:n("Converts a number to text according to a specified format."),args:[Xa("number (number)",n("The number, date or time to format.")),Xa("format (string)",n("The pattern by which to format the number, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){return mo(Xi(e),es(t))},isExported:!0};var Ng=Object.freeze({__proto__:null,CHAR:ug,CLEAN:gg,CONCATENATE:pg,EXACT:mg,FIND:fg,JOIN:bg,LEFT:vg,LEN:Sg,LOWER:Cg,MID:Eg,PROPER:wg,REPLACE:xg,RIGHT:yg,SEARCH:Ig,SUBSTITUTE:Rg,TEXTJOIN:Tg,TRIM:Ag,UPPER:Og,TEXT:Mg});const _g={description:n("Creates a hyperlink in a cell."),args:[Xa("url (string)",n("The full URL of the link enclosed in quotation marks.")),Xa("link_label (string, optional)",n("The text to display in the cell, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){const o=es(e).trim(),i=es(t)||o;return""===o?i:nt(i,o)},isExported:!0};var Fg=Object.freeze({__proto__:null,HYPERLINK:_g});const Dg=[{name:n("Database"),functions:lh},{name:n("Date"),functions:$h},{name:n("Financial"),functions:gu},{name:n("Info"),functions:xu},{name:n("Lookup"),functions:Gu},{name:n("Logical"),functions:_u},{name:n("Math"),functions:ic},{name:n("Misc"),functions:Ja},{name:n("Operator"),functions:hg},{name:n("Statistical"),functions:Zc},{name:n("Text"),functions:Ng},{name:n("Engineering"),functions:Gh},{name:n("Web"),functions:Fg}],Lg=/^[A-Z0-9\_\.]+$/;function kg(e){return e.map((e=>{if(void 0!==e)return"function"==typeof e?()=>Pg(e()):Pg(e)}))}function Pg(e){return Array.isArray(e)?e.map((e=>e.map((e=>e?.value)))):e?.value}const Ug=new class extends Ui{mapping={};add(e,t){if(e=e.toUpperCase(),!Lg.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=Ka(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(...kg(e)),format:i(...e)}},super.add(e,o),this}};for(let e of Dg){const t=e.functions;for(let o in t){const i=t[o];i.category=i.category||e.name,o=o.replace(/_/g,"."),Ug.add(o,{isExported:!1,...i})}}const Vg={name:e=>{const t=ha(e);return 1===t?n("Insert row"):n("Insert %s rows",t.toString())},isVisible:e=>ya(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW"},zg={name:e=>{const t=ha(e);return 1===t?n("Insert row above"):n("Insert %s rows above",t.toString())},execute:fa,isVisible:e=>ya(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},Bg={...zg,name:e=>{const t=ha(e);return 1===t?n("Row above"):n("%s Rows above",t.toString())}},Hg={...zg,name:e=>{const t=ha(e);return 1===t?n("Insert row"):n("Insert %s rows",t.toString())},isVisible:xa,icon:"o-spreadsheet-Icon.INSERT_ROW_BEFORE"},$g={execute:e=>{const t=e.model.getters.getActiveRows();let o,i;if(t.size)o=Math.max(...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=ha(e);return 1===t?n("Insert row below"):n("Insert %s rows below",t.toString())},isVisible:e=>ya(e,"ROW"),icon:"o-spreadsheet-Icon.INSERT_ROW_AFTER"},Wg={...$g,name:e=>{const t=ha(e);return 1===t?n("Row below"):n("%s Rows below",t.toString())}},Gg={name:e=>{const t=ca(e);return 1===t?n("Insert column"):n("Insert %s columns",t.toString())},isVisible:e=>ya(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL"},qg={name:e=>{const t=ca(e);return 1===t?n("Insert column left"):n("Insert %s columns left",t.toString())},execute:ba,isVisible:e=>ya(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},Zg={...qg,name:e=>{const t=ca(e);return 1===t?n("Column left"):n("%s Columns left",t.toString())}},jg={...qg,name:e=>{const t=ca(e);return 1===t?n("Insert column"):n("Insert %s columns",t.toString())},isVisible:xa,icon:"o-spreadsheet-Icon.INSERT_COL_BEFORE"},Yg={name:e=>{const t=ca(e);return 1===t?n("Insert column right"):n("Insert %s columns right",t.toString())},execute:va,isVisible:e=>ya(e,"COL"),icon:"o-spreadsheet-Icon.INSERT_COL_AFTER"},Xg={...Yg,name:e=>{const t=ca(e);return 1===t?n("Column right"):n("%s Columns right",t.toString())},execute:va},Kg={name:n("Insert cells"),isVisible:e=>xa(e)&&0===e.model.getters.getActiveCols().size&&0===e.model.getters.getActiveRows().size,icon:"o-spreadsheet-Icon.INSERT_CELL"},Qg={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"});ra(e,o)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_DOWN"},Jg={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"});ra(e,o)},isVisible:e=>0===e.model.getters.getActiveRows().size&&0===e.model.getters.getActiveCols().size,icon:"o-spreadsheet-Icon.INSERT_CELL_SHIFT_RIGHT"},ep={name:n("Chart"),execute:e=>{const t=e.model.getters,o=e.model.uuidGenerator.uuidv4(),i=t.getActiveSheetId();1===yi(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:Jr(e.model.getters.getSelectedZone(),e.model.getters)}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{id:o}),e.openSidePanel("ChartPanel"))},icon:"o-spreadsheet-Icon.INSERT_CHART"},tp={name:n("Image"),description:"Ctrl+O",execute:Sa,isVisible:e=>void 0!==e.imageProvider,icon:"o-spreadsheet-Icon.INSERT_IMAGE"},op={name:n("Function"),icon:"o-spreadsheet-Icon.SHOW_HIDE_FORMULA"},ip={name:n("SUM"),execute:e=>e.startCellEdition("=SUM(")},sp={name:n("AVERAGE"),execute:e=>e.startCellEdition("=AVERAGE(")},np={name:n("COUNT"),execute:e=>e.startCellEdition("=COUNT(")},rp={name:n("MAX"),execute:e=>e.startCellEdition("=MAX(")},ap={name:n("MIN"),execute:e=>e.startCellEdition("=MIN(")},lp={name:n("All"),children:[function(){return dp(Ug.getKeys())}]};const cp={name:n("Link"),execute:Ea,icon:"o-spreadsheet-Icon.INSERT_LINK"},hp={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 dp(e){return e.sort().map(((e,t)=>({name:e,sequence:10*t,execute:t=>t.startCellEdition(`=${e}(`)})))}const up=new Nn;up.add("cut",{...Aa,sequence:10}).add("copy",{...Ta,sequence:20}).add("paste",{...Oa,sequence:30}).add("paste_special",{...Ma,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...Na,sequence:10}).addChild("paste_format_only",["paste_special"],{..._a,sequence:20}).add("add_row_before",{...Hg,sequence:70}).add("add_column_before",{...jg,sequence:90}).add("insert_cell",{...Kg,sequence:100,separator:!0}).addChild("insert_cell_down",["insert_cell"],{...Qg,name:n("Shift down"),sequence:10}).addChild("insert_cell_right",["insert_cell"],{...Jg,name:n("Shift right"),sequence:20}).add("delete_row",{...ka,sequence:110,icon:"o-spreadsheet-Icon.DELETE"}).add("delete_column",{...Va,sequence:120,icon:"o-spreadsheet-Icon.DELETE"}).add("delete_cell",{...Ba,sequence:130,separator:!0,icon:"o-spreadsheet-Icon.DELETE"}).addChild("delete_cell_up",["delete_cell"],{...Ha,name:n("Shift up"),sequence:10,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_UP"}).addChild("delete_cell_left",["delete_cell"],{...$a,name:n("Shift left"),sequence:20,icon:"o-spreadsheet-Icon.DELETE_CELL_SHIFT_LEFT"}).add("insert_link",{...cp,name:n("Insert link"),sequence:150,separator:!0});const gp={name:n("Sort range"),isVisible:xa,icon:"o-spreadsheet-Icon.SORT_RANGE"},pp={name:n("Ascending (A ⟶ Z)"),execute:e=>{const{anchor:t,zones:o}=e.model.getters.getSelection(),i=e.model.getters.getActiveSheetId();ta(e,i,t.cell,o[0],"ascending")},icon:"o-spreadsheet-Icon.SORT_ASCENDING"},mp={name:n("Descending (Z ⟶ A)"),execute:e=>{const{anchor:t,zones:o}=e.model.getters.getSelection(),i=e.model.getters.getActiveSheetId();ta(e,i,t.cell,o[0],"descending")},icon:"o-spreadsheet-Icon.SORT_DESCENDING"},fp={name:n("Create filter"),execute:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelection().zones;sa(e,t,o)},isVisible:e=>!wa(e),isEnabled:e=>(e=>Ii(...e.model.getters.getSelectedZones()))(e),icon:"o-spreadsheet-Icon.MENU_FILTER_ICON"},bp={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:wa,icon:"o-spreadsheet-Icon.MENU_FILTER_ICON"},vp={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"},Sp={name:n("Automatic"),execute:e=>da(e,""),isActive:e=>function(e){const t=e.model.getters.getCell(e.model.getters.getActivePosition());return!t||!t.format}(e)},Cp={name:n("Number"),description:"1,000.12",execute:e=>da(e,"#,##0.00"),isActive:e=>tm(e,"#,##0.00")},Ep={name:n("Format as percent"),execute:Ca,icon:"o-spreadsheet-Icon.PERCENT"},wp={name:n("Percent"),description:"10.12%",execute:Ca,isActive:e=>tm(e,"0.00%")},xp={name:n("Currency"),description:"$1,000.12",execute:e=>da(e,"[$$]#,##0.00"),isActive:e=>tm(e,"[$$]#,##0.00")},yp={name:n("Currency rounded"),description:"$1,000",execute:e=>da(e,"[$$]#,##0"),isActive:e=>tm(e,"[$$]#,##0")},Ip={name:n("Custom currency"),isVisible:e=>void 0!==e.loadCurrencies,execute:e=>{e.openSidePanel("CustomCurrency",{})}},Rp={name:n("Date"),description:"9/26/2008",execute:e=>da(e,"m/d/yyyy"),isActive:e=>tm(e,"m/d/yyyy")},Tp={name:n("Time"),description:"10:43:00 PM",execute:e=>da(e,"hh:mm:ss a"),isActive:e=>tm(e,"hh:mm:ss a")},Ap={name:n("Date time"),description:"9/26/2008 22:43:00",execute:e=>da(e,"m/d/yyyy hh:mm:ss"),isActive:e=>tm(e,"m/d/yyyy hh:mm:ss")},Op={name:n("Duration"),description:"27:51:38",execute:e=>da(e,"hhhh:mm:ss"),isActive:e=>tm(e,"hhhh:mm:ss")},Mp={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})},Np={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})},_p={name:n("Bold"),description:"Ctrl+B",execute:e=>ua(e,{bold:!e.model.getters.getCurrentStyle().bold}),icon:"o-spreadsheet-Icon.BOLD",isActive:e=>!!e.model.getters.getCurrentStyle().bold},Fp={name:n("Italic"),description:"Ctrl+I",execute:e=>ua(e,{italic:!e.model.getters.getCurrentStyle().italic}),icon:"o-spreadsheet-Icon.ITALIC",isActive:e=>!!e.model.getters.getCurrentStyle().italic},Dp={name:n("Underline"),description:"Ctrl+U",execute:e=>ua(e,{underline:!e.model.getters.getCurrentStyle().underline}),icon:"o-spreadsheet-Icon.UNDERLINE",isActive:e=>!!e.model.getters.getCurrentStyle().underline},Lp={name:n("Strikethrough"),execute:e=>ua(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),icon:"o-spreadsheet-Icon.STRIKE",isActive:e=>!!e.model.getters.getCurrentStyle().strikethrough},kp={name:n("Font size"),children:fe.map((e=>({name:e.toString(),sequence:e,id:`font_size_${e}`,execute:t=>ua(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"},Pp={name:n("Alignment"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},Up={name:n("Horizontal align"),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},Vp={name:n("Left"),description:"Ctrl+Shift+L",execute:e=>ua(e,{align:"left"}),isActive:e=>"left"===om(e),icon:"o-spreadsheet-Icon.ALIGN_LEFT"},zp={name:n("Center"),description:"Ctrl+Shift+E",execute:e=>ua(e,{align:"center"}),isActive:e=>"center"===om(e),icon:"o-spreadsheet-Icon.ALIGN_CENTER"},Bp={name:n("Right"),description:"Ctrl+Shift+R",execute:e=>ua(e,{align:"right"}),isActive:e=>"right"===om(e),icon:"o-spreadsheet-Icon.ALIGN_RIGHT"},Hp={name:n("Vertical align"),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},$p={name:n("Top"),execute:e=>ua(e,{verticalAlign:"top"}),isActive:e=>"top"===(e.model.getters.getCurrentStyle().verticalAlign||Y),icon:"o-spreadsheet-Icon.ALIGN_TOP"},Wp={name:n("Middle"),execute:e=>ua(e,{verticalAlign:"middle"}),isActive:e=>"middle"===(e.model.getters.getCurrentStyle().verticalAlign||Y),icon:"o-spreadsheet-Icon.ALIGN_MIDDLE"},Gp={name:n("Bottom"),execute:e=>ua(e,{verticalAlign:"bottom"}),isActive:e=>"bottom"===(e.model.getters.getCurrentStyle().verticalAlign||Y),icon:"o-spreadsheet-Icon.ALIGN_BOTTOM"},qp={name:n("Wrapping"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},Zp={name:n("Overflow"),execute:e=>ua(e,{wrapping:"overflow"}),isActive:e=>"overflow"===(e.model.getters.getCurrentStyle().wrapping||"overflow"),icon:"o-spreadsheet-Icon.WRAPPING_OVERFLOW"},jp={name:n("Wrap"),execute:e=>ua(e,{wrapping:"wrap"}),isActive:e=>"wrap"===e.model.getters.getCurrentStyle().wrapping,icon:"o-spreadsheet-Icon.WRAPPING_WRAP"},Yp={name:n("Clip"),execute:e=>ua(e,{wrapping:"clip"}),isActive:e=>"clip"===e.model.getters.getCurrentStyle().wrapping,icon:"o-spreadsheet-Icon.WRAPPING_CLIP"},Xp={name:n("Text Color"),icon:"o-spreadsheet-Icon.TEXT_COLOR"},Kp={name:n("Fill Color"),icon:"o-spreadsheet-Icon.FILL_COLOR"},Qp={name:n("Conditional formatting"),execute:e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},icon:"o-spreadsheet-Icon.CONDITIONAL_FORMAT"},Jp={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()},em={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 tm(e,t){return e.model.getters.getCell(e.model.getters.getActivePosition())?.format===t}function om(e){const t=e.model.getters.getCurrentStyle();if(t.align)return t.align;return e.model.getters.getActiveCell().defaultAlign}var im=Object.freeze({__proto__:null,formatNumberAutomatic:Sp,formatNumberNumber:Cp,formatPercent:Ep,formatNumberPercent:wp,formatNumberCurrency:xp,formatNumberCurrencyRounded:yp,formatCustomCurrency:Ip,formatNumberDate:Rp,formatNumberTime:Tp,formatNumberDateTime:Ap,formatNumberDuration:Op,incraseDecimalPlaces:Mp,decraseDecimalPlaces:Np,formatBold:_p,formatItalic:Fp,formatUnderline:Dp,formatStrikethrough:Lp,formatFontSize:kp,formatAlignment:Pp,formatAlignmentHorizontal:Up,formatAlignmentLeft:Vp,formatAlignmentCenter:zp,formatAlignmentRight:Bp,formatAlignmentVertical:Hp,formatAlignmentTop:$p,formatAlignmentMiddle:Wp,formatAlignmentBottom:Gp,formatWrapping:qp,formatWrappingOverflow:Zp,formatWrappingWrap:jp,formatWrappingClip:Yp,textColor:Xp,fillColor:Kp,formatCF:Qp,paintFormat:Jp,clearFormat:em});function sm(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(ar)}const nm={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",Vt(o).toString()):i-o+1===t.length?n("Hide columns %s - %s",Vt(o).toString(),Vt(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"},rm={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)))}},am={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},lm={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"},cm={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)))}},hm={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},dm={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"},um={name:n("Freeze"),icon:"o-spreadsheet-Icon.FREEZE"},gm={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},pm={name:n("1 row"),execute:e=>sm(e,"ROW",1),isReadonlyAllowed:!0},mm={name:n("2 rows"),execute:e=>sm(e,"ROW",2),isReadonlyAllowed:!0},fm={name:n("Up to current row"),execute:e=>{const{bottom:t}=e.model.getters.getSelectedZone();sm(e,"ROW",t+1)},isReadonlyAllowed:!0},bm={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},vm={name:n("1 column"),execute:e=>sm(e,"COL",1),isReadonlyAllowed:!0},Sm={name:n("2 columns"),execute:e=>sm(e,"COL",2),isReadonlyAllowed:!0},Cm={name:n("Up to current column"),execute:e=>{const{right:t}=e.model.getters.getSelectedZone();sm(e,"COL",t+1)},isReadonlyAllowed:!0},Em={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"},wm={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"},xm={name:e=>ym(e)?n("Remove selected filters"):n("Create filter"),isActive:e=>ym(e),isEnabled:e=>!Im(e),execute:e=>function(e){if(ym(e))return void e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()});if(Im(e))return;e.model.selection.selectTableAroundSelection();const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();sa(e,t,o)}(e),icon:"o-spreadsheet-Icon.FILTER_ICON_INACTIVE"};function ym(e){const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,o)}function Im(e){return!Ii(...e.model.getters.getSelectedZones())}var Rm=Object.freeze({__proto__:null,hideCols:nm,unhideCols:rm,unhideAllCols:am,hideRows:lm,unhideRows:cm,unhideAllRows:hm,unFreezePane:dm,freezePane:um,unFreezeRows:gm,freezeFirstRow:pm,freezeSecondRow:mm,freezeCurrentRow:fm,unFreezeCols:bm,freezeFirstCol:vm,freezeSecondCol:Sm,freezeCurrentCol:Cm,viewGridlines:Em,viewFormulas:wm,createRemoveFilter:xm});const Tm=new Nn;Tm.add("cut",{...Aa,sequence:10}).add("copy",{...Ta,sequence:20}).add("paste",{...Oa,sequence:30}).add("paste_special",{...Ma,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...Na,sequence:10}).addChild("paste_format_only",["paste_special"],{..._a,sequence:20}).add("sort_columns",{...gp,name:e=>e.model.getters.getActiveCols().size>1?n("Sort columns"):n("Sort column"),sequence:50,separator:!0}).addChild("sort_ascending",["sort_columns"],{...pp,sequence:10}).addChild("sort_descending",["sort_columns"],{...mp,sequence:20}).add("add_column_before",{...qg,sequence:70}).add("add_column_after",{...Yg,sequence:80}).add("delete_column",{...Ua,sequence:90,icon:"o-spreadsheet-Icon.DELETE"}).add("clear_column",{...za,sequence:100,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_columns",{...nm,sequence:105,separator:!0}).add("unhide_columns",{...rm,sequence:106,separator:!0}).add("conditional_formatting",{...Qp,sequence:110});const Am=new Nn;Am.add("format_number_automatic",{...Sp,sequence:10,separator:!0}).add("format_number_number",{...Cp,sequence:20}).add("format_number_percent",{...wp,sequence:30,separator:!0}).add("format_number_currency",{...xp,sequence:40}).add("format_number_currency_rounded",{...yp,sequence:50}).add("format_custom_currency",{...Ip,sequence:60,separator:!0}).add("format_number_date",{...Rp,sequence:70}).add("format_number_time",{...Tp,sequence:80}).add("format_number_date_time",{...Ap,sequence:90}).add("format_number_duration",{...Op,sequence:100,separator:!0});const Om={name:n("More formats"),icon:"o-spreadsheet-Icon.NUMBER_FORMATS",children:[()=>Am.getAll()]},Mm=new Nn;Mm.add("cut",{...Aa,sequence:10}).add("copy",{...Ta,sequence:20}).add("paste",{...Oa,sequence:30}).add("paste_special",{...Ma,sequence:40,separator:!0}).addChild("paste_value_only",["paste_special"],{...Na,sequence:10}).addChild("paste_format_only",["paste_special"],{..._a,sequence:20}).add("add_row_before",{...zg,sequence:50}).add("add_row_after",{...$g,sequence:60}).add("delete_row",{...La,sequence:70,icon:"o-spreadsheet-Icon.DELETE"}).add("clear_row",{...Pa,sequence:80,icon:"o-spreadsheet-Icon.CLEAR"}).add("hide_rows",{...lm,sequence:85,separator:!0}).add("unhide_rows",{...cm,sequence:86,separator:!0}).add("conditional_formatting",{...Qp,sequence:90});const Nm=new Nn;Nm.add("file",{name:n("File"),sequence:10}).add("edit",{name:n("Edit"),sequence:20}).addChild("undo",["edit"],{...Ia,sequence:10}).addChild("redo",["edit"],{...Ra,sequence:20,separator:!0}).addChild("copy",["edit"],{...Ta,sequence:30}).addChild("cut",["edit"],{...Aa,sequence:40}).addChild("paste",["edit"],{...Oa,sequence:50}).addChild("paste_special",["edit"],{...Ma,sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{...Na,sequence:10}).addChild("paste_special_format",["edit","paste_special"],{..._a,sequence:20}).addChild("find_and_replace",["edit"],{...Fa,sequence:65,separator:!0}).addChild("delete",["edit"],{name:n("Delete"),icon:"o-spreadsheet-Icon.DELETE",sequence:70}).addChild("edit_delete_cell_values",["edit","delete"],{...Da,sequence:10}).addChild("edit_delete_row",["edit","delete"],{...La,sequence:20}).addChild("edit_delete_column",["edit","delete"],{...Ua,sequence:30}).addChild("edit_delete_cell_shift_up",["edit","delete"],{...Ha,sequence:40}).addChild("edit_delete_cell_shift_left",["edit","delete"],{...$a,sequence:50}).addChild("edit_unhide_columns",["edit"],{...am,sequence:80}).addChild("edit_unhide_rows",["edit"],{...hm,sequence:80}).add("view",{name:n("View"),sequence:30}).addChild("unfreeze_panes",["view"],{...dm,sequence:4}).addChild("freeze_panes",["view"],{...um,sequence:5,separator:!0}).addChild("unfreeze_rows",["view","freeze_panes"],{...gm,sequence:5}).addChild("freeze_first_row",["view","freeze_panes"],{...pm,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{...mm,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{...fm,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{...bm,sequence:25}).addChild("freeze_first_col",["view","freeze_panes"],{...vm,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{...Sm,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{...Cm,sequence:40}).addChild("view_gridlines",["view"],{...Em,sequence:10}).addChild("view_formulas",["view"],{...wm,sequence:15}).add("insert",{name:n("Insert"),sequence:40}).addChild("insert_row",["insert"],{...Vg,sequence:10}).addChild("insert_row_before",["insert","insert_row"],{...Bg,sequence:10}).addChild("insert_row_after",["insert","insert_row"],{...Wg,sequence:20}).addChild("insert_column",["insert"],{...Gg,sequence:20}).addChild("insert_column_before",["insert","insert_column"],{...Zg,sequence:10}).addChild("insert_column_after",["insert","insert_column"],{...Xg,sequence:20}).addChild("insert_cell",["insert"],{...Kg,sequence:43}).addChild("insert_cell_down",["insert","insert_cell"],{...Qg,name:n("Shift down"),sequence:10}).addChild("insert_cell_right",["insert","insert_cell"],{...Jg,name:n("Shift right"),sequence:20}).addChild("insert_sheet",["insert"],{...hp,sequence:80,separator:!0}).addChild("insert_chart",["insert"],{...ep,sequence:50}).addChild("insert_image",["insert"],{...tp,sequence:55}).addChild("insert_function",["insert"],{...op,sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{...ip,sequence:0}).addChild("insert_function_average",["insert","insert_function"],{...sp,sequence:10}).addChild("insert_function_count",["insert","insert_function"],{...np,sequence:20}).addChild("insert_function_max",["insert","insert_function"],{...rp,sequence:30}).addChild("insert_function_min",["insert","insert_function"],{...ap,sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{...lp,sequence:50}).addChild("categories_function_list",["insert","insert_function"],(()=>{const e=Ug.content;return[...new Set(Ug.getAll().map((e=>e.category)))].filter(dt).sort().map(((t,o)=>{const i=Object.keys(e).filter((o=>e[o].category===t));return{name:t,children:dp(i)}}))})).addChild("insert_link",["insert"],{...cp,separator:!0,sequence:70}).add("format",{name:n("Format"),sequence:50}).addChild("format_number",["format"],{...Om,name:n("Number"),sequence:10,separator:!0}).addChild("format_bold",["format"],{..._p,sequence:20}).addChild("format_italic",["format"],{...Fp,sequence:30}).addChild("format_underline",["format"],{...Dp,sequence:40}).addChild("format_strikethrough",["format"],{...Lp,sequence:50,separator:!0}).addChild("format_font_size",["format"],{...kp,sequence:60,separator:!0}).addChild("format_alignment",["format"],{...Pp,sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{...Vp,sequence:10}).addChild("format_alignment_center",["format","format_alignment"],{...zp,sequence:20}).addChild("format_alignment_right",["format","format_alignment"],{...Bp,sequence:30,separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{...$p,sequence:40}).addChild("format_alignment_middle",["format","format_alignment"],{...Wp,sequence:50}).addChild("format_alignment_bottom",["format","format_alignment"],{...Gp,sequence:60,separator:!0}).addChild("format_wrapping",["format"],{...qp,sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{...Zp,sequence:10}).addChild("format_wrapping_wrap",["format","format_wrapping"],{...jp,sequence:20}).addChild("format_wrapping_clip",["format","format_wrapping"],{...Yp,sequence:30}).addChild("format_cf",["format"],{...Qp,sequence:90,separator:!0}).addChild("format_clearFormat",["format"],{...em,sequence:100,separator:!0}).add("data",{name:n("Data"),sequence:60}).addChild("sort_range",["data"],{...gp,sequence:10,separator:!0}).addChild("sort_ascending",["data","sort_range"],{...pp,sequence:10}).addChild("sort_descending",["data","sort_range"],{...mp,sequence:20}).addChild("split_to_columns",["data"],{...vp,sequence:20,separator:!0}).addChild("add_data_filter",["data"],{...fp,sequence:30}).addChild("remove_data_filter",["data"],{...bp,sequence:30});const _m=new class extends Ui{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)}},Fm={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function Dm(e,t){const o=Fm[e.key];e.shiftKey?t.resizeAnchorZone(o,ln(e)?"end":1):t.moveAnchorCell(o,ln(e)?"end":1)}const Lm=new Jo;Oi`
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 km extends t.Component{static template="o-spreadsheet-SelectionInput";id=Lm.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,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(),Dm(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?.()}}km.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 Pm extends t.Component{static template="o-spreadsheet-LineBarPieConfigPanel";static components={SelectionInput:km};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=>rn.Errors[e]||rn.Errors.Unexpected))}get isDatasetInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause(32)}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.isCancelledBecause(33)}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.figureId,{dataSetsHaveTitle:e.target.checked})}onDataSeriesRangesChanged(e){this.dataSeriesRanges=e}onDataSeriesConfirmed(){this.state.datasetDispatchResult=this.props.updateChart(this.props.figureId,{dataSets:this.dataSeriesRanges})}onLabelRangeChanged(e){this.labelRange=e[0]}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.figureId,{labelRange:this.labelRange})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}calculateHeaderPosition(){if(this.isDatasetInvalid||this.isLabelInvalid)return;const e=this.env.model.getters,t=e.getActiveSheetId(),o=Xo(e,t,this.labelRange),i=Hr(e,this.dataSeriesRanges,t,this.props.definition.dataSetsHaveTitle);return i.length?i[0].dataRange.zone.top+1:o?o.zone.top+1:void 0}}Pm.props={figureId:String,definition:Object,updateChart:Function};class Um extends Pm{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 Vm=218,zm=182;function Bm(e){return Lt(Pt({h:360*e.offsetX/Vm,s:100,l:100*e.offsetY/zm,a:1}))}Oi`
403
+ `;class km extends t.Component{static template="o-spreadsheet-SelectionInput";id=Lm.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,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(),Dm(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?.()}}km.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 Pm extends t.Component{static template="o-spreadsheet-LineBarPieConfigPanel";static components={SelectionInput:km};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=>nr.Errors[e]||nr.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=Xo(e,t,this.labelRange),i=$n(e,this.dataSeriesRanges,t,this.props.definition.dataSetsHaveTitle);return i.length?i[0].dataRange.zone.top+1:o?o.zone.top+1:void 0}}Pm.props={figureId:String,definition:Object,updateChart:Function};class Um extends Pm{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 Vm=218,zm=182;function Bm(e){return Lt(Pt({h:360*e.offsetX/Vm,s:100,l:100*e.offsetY/zm,a:1}))}Oi`
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);
@@ -537,7 +537,7 @@
537
537
  width: 30px;
538
538
  height: 30px;
539
539
  }
540
- `;class Hm extends t.Component{static template="o-spreadsheet-ColorPicker";static defaultProps={currentColor:""};static components={Popover:gr};COLORS=_;state=t.useState({showGradient:!1,currentColor:Nt(this.props.currentColor)?this.props.currentColor:"",isCurrentColorInvalid:!1,style:{display:"none",background:"#ffffff",left:"0",top:"0"}});get colorPickerStyle(){return void 0!==this.props.maxHeight&&this.props.maxHeight<=0?Fi({display:"none"}):""}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"BottomLeft",verticalOffset:0}}onColorClick(e){e&&this.props.onColorPicked(Mt(e))}getCheckMarkColor(){return Yr(this.props.currentColor)}resetColor(){this.props.onColorPicked("")}setCustomColor(e){if(!Nt(this.state.currentColor))return e.stopPropagation(),void(this.state.isCurrentColorInvalid=!0);const t=Mt(this.state.currentColor);this.state.isCurrentColorInvalid=!1,this.props.onColorPicked(t),this.state.currentColor=t}toggleColorPicker(){this.state.showGradient=!this.state.showGradient}computeCustomColor(e){this.state.isCurrentColorInvalid=!1,this.state.currentColor=Bm(e)}hideMagnifier(e){this.state.style.display="none"}showMagnifier(e){this.state.style.display="block"}moveMagnifier(e){this.state.style.background=Bm(e);this.state.style.left=`${e.offsetX+10}px`,this.state.style.top=`${e.offsetY+10}px`}get magnifyingGlassStyle(){const{display:e,background:t,left:o,top:i}=this.state.style;return Fi({display:e,"background-color":"block"===e?t:void 0,left:o,top:i})}isSameColor(e,t){return function(e,t){return Nt(e)&&Nt(t)&&Mt(e)===Mt(t)}(e,t)}}Hm.props={onColorPicked:Function,currentColor:{type:String,optional:!0},maxHeight:{type:Number,optional:!0},anchorRect:Object},Oi`
540
+ `;class Hm extends t.Component{static template="o-spreadsheet-ColorPicker";static defaultProps={currentColor:""};static components={Popover:pn};COLORS=_;state=t.useState({showGradient:!1,currentColor:Nt(this.props.currentColor)?this.props.currentColor:"",isCurrentColorInvalid:!1,style:{display:"none",background:"#ffffff",left:"0",top:"0"}});get colorPickerStyle(){return void 0!==this.props.maxHeight&&this.props.maxHeight<=0?Fi({display:"none"}):""}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"BottomLeft",verticalOffset:0}}onColorClick(e){e&&this.props.onColorPicked(Mt(e))}getCheckMarkColor(){return Xn(this.props.currentColor)}resetColor(){this.props.onColorPicked("")}setCustomColor(e){if(!Nt(this.state.currentColor))return e.stopPropagation(),void(this.state.isCurrentColorInvalid=!0);const t=Mt(this.state.currentColor);this.state.isCurrentColorInvalid=!1,this.props.onColorPicked(t),this.state.currentColor=t}toggleColorPicker(){this.state.showGradient=!this.state.showGradient}computeCustomColor(e){this.state.isCurrentColorInvalid=!1,this.state.currentColor=Bm(e)}hideMagnifier(e){this.state.style.display="none"}showMagnifier(e){this.state.style.display="block"}moveMagnifier(e){this.state.style.background=Bm(e);this.state.style.left=`${e.offsetX+10}px`,this.state.style.top=`${e.offsetY+10}px`}get magnifyingGlassStyle(){const{display:e,background:t,left:o,top:i}=this.state.style;return Fi({display:e,"background-color":"block"===e?t:void 0,left:o,top:i})}isSameColor(e,t){return function(e,t){return Nt(e)&&Nt(t)&&Mt(e)===Mt(t)}(e,t)}}Hm.props={onColorPicked:Function,currentColor:{type:String,optional:!0},maxHeight:{type:Number,optional:!0},anchorRect:Object},Oi`
541
541
  .o-color-picker-widget {
542
542
  display: flex;
543
543
  position: relative;
@@ -570,7 +570,7 @@
570
570
  }
571
571
  }
572
572
  }
573
- `;class $m extends t.Component{static template="o-spreadsheet-ColorPickerWidget";static components={ColorPicker:Hm};colorPickerButtonRef=t.useRef("colorPickerButton");get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:"border-bottom-style: hidden"}get colorPickerAnchorRect(){const e=this.colorPickerButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}}$m.props={currentColor:{type:String,optional:!0},toggleColorPicker:Function,showColorPicker:Boolean,onColorPicked:Function,icon:String,title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};class Wm extends t.Component{static template="o-spreadsheet-LineBarPieDesignPanel";static components={ColorPickerWidget:$m};state=t.useState({fillColorTool:!1});onClick(e){this.state.fillColorTool=!1}setup(){t.useExternalListener(window,"click",this.onClick)}toggleColorPicker(){this.state.fillColorTool=!this.state.fillColorTool}updateBackgroundColor(e){this.props.updateChart(this.props.figureId,{background:e})}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}updateSelect(e,t){this.props.updateChart(this.props.figureId,{[e]:t.target.value})}}Wm.props={figureId:String,definition:Object,updateChart:Function};class Gm extends t.Component{static template="o-spreadsheet-GaugeChartConfigPanel";static components={SelectionInput:km};state=t.useState({dataRangeDispatchResult:void 0});dataRange=this.props.definition.dataRange;get configurationErrorMessages(){return[...this.state.dataRangeDispatchResult?.reasons||[]].map((e=>rn.Errors[e]||rn.Errors.Unexpected))}get isDataRangeInvalid(){return!!this.state.dataRangeDispatchResult?.isCancelledBecause(36)}onDataRangeChanged(e){this.dataRange=e[0]}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.figureId,{dataRange:this.dataRange})}}Gm.props={figureId:String,definition:Object,updateChart:Function},Oi`
573
+ `;class $m extends t.Component{static template="o-spreadsheet-ColorPickerWidget";static components={ColorPicker:Hm};colorPickerButtonRef=t.useRef("colorPickerButton");get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:"border-bottom-style: hidden"}get colorPickerAnchorRect(){const e=this.colorPickerButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}}$m.props={currentColor:{type:String,optional:!0},toggleColorPicker:Function,showColorPicker:Boolean,onColorPicked:Function,icon:String,title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};class Wm extends t.Component{static template="o-spreadsheet-LineBarPieDesignPanel";static components={ColorPickerWidget:$m};state=t.useState({fillColorTool:!1});onClick(e){this.state.fillColorTool=!1}setup(){t.useExternalListener(window,"click",this.onClick)}toggleColorPicker(){this.state.fillColorTool=!this.state.fillColorTool}updateBackgroundColor(e){this.props.updateChart(this.props.figureId,{background:e})}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}updateSelect(e,t){this.props.updateChart(this.props.figureId,{[e]:t.target.value})}}Wm.props={figureId:String,definition:Object,updateChart:Function};class Gm extends t.Component{static template="o-spreadsheet-GaugeChartConfigPanel";static components={SelectionInput:km};state=t.useState({dataRangeDispatchResult:void 0});dataRange=this.props.definition.dataRange;get configurationErrorMessages(){return[...this.state.dataRangeDispatchResult?.reasons||[]].map((e=>nr.Errors[e]||nr.Errors.Unexpected))}get isDataRangeInvalid(){return!!this.state.dataRangeDispatchResult?.isCancelledBecause(37)}onDataRangeChanged(e){this.dataRange=e[0]}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.figureId,{dataRange:this.dataRange})}}Gm.props={figureId:String,definition:Object,updateChart:Function},Oi`
574
574
  .o-gauge-color-set {
575
575
  table {
576
576
  table-layout: fixed;
@@ -600,7 +600,7 @@
600
600
  box-sizing: border-box;
601
601
  }
602
602
  }
603
- `;class qm extends t.Component{static template="o-spreadsheet-GaugeChartDesignPanel";static components={ColorPickerWidget:$m};state=t.useState({openedMenu:void 0,sectionRuleDispatchResult:void 0});setup(){t.useExternalListener(window,"click",this.closeMenus)}get designErrorMessages(){return[...this.state.sectionRuleDispatchResult?.reasons||[]].map((e=>rn.Errors[e]||rn.Errors.Unexpected))}updateBackgroundColor(e){this.state.openedMenu=void 0,this.props.updateChart(this.props.figureId,{background:e})}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}isRangeMinInvalid(){return!!(this.state.sectionRuleDispatchResult?.isCancelledBecause(37)||this.state.sectionRuleDispatchResult?.isCancelledBecause(38)||this.state.sectionRuleDispatchResult?.isCancelledBecause(41))}isRangeMaxInvalid(){return!!(this.state.sectionRuleDispatchResult?.isCancelledBecause(39)||this.state.sectionRuleDispatchResult?.isCancelledBecause(40)||this.state.sectionRuleDispatchResult?.isCancelledBecause(41))}get isLowerInflectionPointInvalid(){return!(!this.state.sectionRuleDispatchResult?.isCancelledBecause(42)&&!this.state.sectionRuleDispatchResult?.isCancelledBecause(44))}get isUpperInflectionPointInvalid(){return!(!this.state.sectionRuleDispatchResult?.isCancelledBecause(43)&&!this.state.sectionRuleDispatchResult?.isCancelledBecause(44))}updateInflectionPointValue(e,t){const o=Be(this.props.definition.sectionRule);o[e].value=t.target.value,this.updateSectionRule(o)}updateInflectionPointType(e,t){const o=Be(this.props.definition.sectionRule);o[e].type=t.target.value,this.updateSectionRule(o)}updateSectionColor(e,t){const o=Be(this.props.definition.sectionRule);o.colors[e]=t,this.updateSectionRule(o),this.closeMenus()}updateRangeMin(e){let t=Be(this.props.definition.sectionRule);t={...t,rangeMin:e.target.value},this.updateSectionRule(t)}updateRangeMax(e){let t=Be(this.props.definition.sectionRule);t={...t,rangeMax:e.target.value},this.updateSectionRule(t)}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}updateSectionRule(e){this.state.sectionRuleDispatchResult=this.props.updateChart(this.props.figureId,{sectionRule:e})}closeMenus(){this.state.openedMenu=void 0}}qm.props={figureId:String,definition:Object,updateChart:Function};class Zm extends Pm{static template="o-spreadsheet-LineConfigPanel";get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.figureId);return!!(e&&e instanceof On)&&Mn(e.labelRange,this.env.model.getters)}onUpdateLabelsAsText(e){this.props.updateChart(this.props.figureId,{labelsAsText:e.target.checked})}onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e.target.checked})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}onUpdateCumulative(e){this.props.updateChart(this.props.figureId,{cumulative:e.target.checked})}}class jm extends t.Component{static template="o-spreadsheet-ScorecardChartConfigPanel";static components={SelectionInput:km};state=t.useState({keyValueDispatchResult:void 0,baselineDispatchResult:void 0});keyValue=this.props.definition.keyValue;baseline=this.props.definition.baseline;get errorMessages(){return[...this.state.keyValueDispatchResult?.reasons||[],...this.state.baselineDispatchResult?.reasons||[]].map((e=>rn.Errors[e]||rn.Errors.Unexpected))}get isKeyValueInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause(34)}get isBaselineInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause(35)}onKeyValueRangeChanged(e){this.keyValue=e[0]}updateKeyValueRange(){this.state.keyValueDispatchResult=this.props.updateChart(this.props.figureId,{keyValue:this.keyValue})}onBaselineRangeChanged(e){this.baseline=e[0]}updateBaselineRange(){this.state.baselineDispatchResult=this.props.updateChart(this.props.figureId,{baseline:this.baseline})}updateBaselineMode(e){this.props.updateChart(this.props.figureId,{baselineMode:e.target.value})}}jm.props={figureId:String,definition:Object,updateChart:Function};class Ym extends t.Component{static template="o-spreadsheet-ScorecardChartDesignPanel";static components={ColorPickerWidget:$m};state=t.useState({openedColorPicker:void 0});setup(){t.useExternalListener(window,"click",this.closeMenus)}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}updateBaselineDescr(e){this.props.updateChart(this.props.figureId,{baselineDescr:e.target.value})}toggleColorPicker(e){this.state.openedColorPicker===e?this.state.openedColorPicker=void 0:this.state.openedColorPicker=e}setColor(e,t){switch(t){case"backgroundColor":this.props.updateChart(this.props.figureId,{background:e});break;case"baselineColorDown":this.props.updateChart(this.props.figureId,{baselineColorDown:e});break;case"baselineColorUp":this.props.updateChart(this.props.figureId,{baselineColorUp:e})}this.closeMenus()}closeMenus(){this.state.openedColorPicker=void 0}}Ym.props={figureId:String,definition:Object,updateChart:Function};const Xm=new Ui;Xm.add("line",{configuration:Zm,design:class extends Wm{static template="o-spreadsheet-LineChartDesignPanel"}}).add("bar",{configuration:Um,design:class extends Wm{static template="o-spreadsheet-BarChartDesignPanel"}}).add("pie",{configuration:Pm,design:Wm}).add("gauge",{configuration:Gm,design:qm}).add("scorecard",{configuration:jm,design:Ym}),Oi`
603
+ `;class qm extends t.Component{static template="o-spreadsheet-GaugeChartDesignPanel";static components={ColorPickerWidget:$m};state=t.useState({openedMenu:void 0,sectionRuleDispatchResult:void 0});setup(){t.useExternalListener(window,"click",this.closeMenus)}get designErrorMessages(){return[...this.state.sectionRuleDispatchResult?.reasons||[]].map((e=>nr.Errors[e]||nr.Errors.Unexpected))}updateBackgroundColor(e){this.state.openedMenu=void 0,this.props.updateChart(this.props.figureId,{background:e})}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}isRangeMinInvalid(){return!!(this.state.sectionRuleDispatchResult?.isCancelledBecause(38)||this.state.sectionRuleDispatchResult?.isCancelledBecause(39)||this.state.sectionRuleDispatchResult?.isCancelledBecause(42))}isRangeMaxInvalid(){return!!(this.state.sectionRuleDispatchResult?.isCancelledBecause(40)||this.state.sectionRuleDispatchResult?.isCancelledBecause(41)||this.state.sectionRuleDispatchResult?.isCancelledBecause(42))}get isLowerInflectionPointInvalid(){return!(!this.state.sectionRuleDispatchResult?.isCancelledBecause(43)&&!this.state.sectionRuleDispatchResult?.isCancelledBecause(45))}get isUpperInflectionPointInvalid(){return!(!this.state.sectionRuleDispatchResult?.isCancelledBecause(44)&&!this.state.sectionRuleDispatchResult?.isCancelledBecause(45))}updateInflectionPointValue(e,t){const o=Be(this.props.definition.sectionRule);o[e].value=t.target.value,this.updateSectionRule(o)}updateInflectionPointType(e,t){const o=Be(this.props.definition.sectionRule);o[e].type=t.target.value,this.updateSectionRule(o)}updateSectionColor(e,t){const o=Be(this.props.definition.sectionRule);o.colors[e]=t,this.updateSectionRule(o),this.closeMenus()}updateRangeMin(e){let t=Be(this.props.definition.sectionRule);t={...t,rangeMin:e.target.value},this.updateSectionRule(t)}updateRangeMax(e){let t=Be(this.props.definition.sectionRule);t={...t,rangeMax:e.target.value},this.updateSectionRule(t)}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}updateSectionRule(e){this.state.sectionRuleDispatchResult=this.props.updateChart(this.props.figureId,{sectionRule:e})}closeMenus(){this.state.openedMenu=void 0}}qm.props={figureId:String,definition:Object,updateChart:Function};class Zm extends Pm{static template="o-spreadsheet-LineConfigPanel";get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.figureId);return!!(e&&e instanceof Or)&&Mr(e.labelRange,this.env.model.getters)}onUpdateLabelsAsText(e){this.props.updateChart(this.props.figureId,{labelsAsText:e.target.checked})}onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e.target.checked})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}onUpdateCumulative(e){this.props.updateChart(this.props.figureId,{cumulative:e.target.checked})}}class jm extends t.Component{static template="o-spreadsheet-ScorecardChartConfigPanel";static components={SelectionInput:km};state=t.useState({keyValueDispatchResult:void 0,baselineDispatchResult:void 0});keyValue=this.props.definition.keyValue;baseline=this.props.definition.baseline;get errorMessages(){return[...this.state.keyValueDispatchResult?.reasons||[],...this.state.baselineDispatchResult?.reasons||[]].map((e=>nr.Errors[e]||nr.Errors.Unexpected))}get isKeyValueInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause(35)}get isBaselineInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause(36)}onKeyValueRangeChanged(e){this.keyValue=e[0]}updateKeyValueRange(){this.state.keyValueDispatchResult=this.props.updateChart(this.props.figureId,{keyValue:this.keyValue})}onBaselineRangeChanged(e){this.baseline=e[0]}updateBaselineRange(){this.state.baselineDispatchResult=this.props.updateChart(this.props.figureId,{baseline:this.baseline})}updateBaselineMode(e){this.props.updateChart(this.props.figureId,{baselineMode:e.target.value})}}jm.props={figureId:String,definition:Object,updateChart:Function};class Ym extends t.Component{static template="o-spreadsheet-ScorecardChartDesignPanel";static components={ColorPickerWidget:$m};state=t.useState({openedColorPicker:void 0});setup(){t.useExternalListener(window,"click",this.closeMenus)}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}updateBaselineDescr(e){this.props.updateChart(this.props.figureId,{baselineDescr:e.target.value})}toggleColorPicker(e){this.state.openedColorPicker===e?this.state.openedColorPicker=void 0:this.state.openedColorPicker=e}setColor(e,t){switch(t){case"backgroundColor":this.props.updateChart(this.props.figureId,{background:e});break;case"baselineColorDown":this.props.updateChart(this.props.figureId,{baselineColorDown:e});break;case"baselineColorUp":this.props.updateChart(this.props.figureId,{baselineColorUp:e})}this.closeMenus()}closeMenus(){this.state.openedColorPicker=void 0}}Ym.props={figureId:String,definition:Object,updateChart:Function};const Xm=new Ui;Xm.add("line",{configuration:Zm,design:class extends Wm{static template="o-spreadsheet-LineChartDesignPanel"}}).add("bar",{configuration:Um,design:class extends Wm{static template="o-spreadsheet-BarChartDesignPanel"}}).add("pie",{configuration:Pm,design:Wm}).add("gauge",{configuration:Gm,design:qm}).add("scorecard",{configuration:jm,design:Ym}),Oi`
604
604
  .o-chart {
605
605
  .o-panel {
606
606
  display: flex;
@@ -623,7 +623,7 @@
623
623
  }
624
624
  }
625
625
  }
626
- `;class Km extends t.Component{static template="o-spreadsheet-ChartPanel";state;get figureId(){return this.state.figureId}setup(){const e=this.env.model.getters.getSelectedFigureId();e?(this.state=t.useState({panel:"configuration",figureId:e}),t.onWillUpdateProps((()=>{const e=this.env.model.getters.getSelectedFigureId();e&&e!==this.state.figureId&&(this.state.figureId=e),this.env.model.getters.isChartDefined(this.figureId)||this.props.onCloseSidePanel()}))):this.props.onCloseSidePanel()}updateChart(e,t){if(e!==this.figureId)return;const o={...this.getChartDefinition(),...t};return this.env.model.dispatch("UPDATE_CHART",{definition:o,id:e,sheetId:this.env.model.getters.getFigureSheetId(e)})}onTypeChange(e){const t=this.env.model.getters.getContextCreationChart(this.figureId);if(!t)throw new Error("Chart not defined.");const o=function(e,t){return Vn.get(t).getChartDefinitionFromContextCreation(e)}(t,e);this.env.model.dispatch("UPDATE_CHART",{definition:o,id:this.figureId,sheetId:this.env.model.getters.getFigureSheetId(this.figureId)})}get chartPanel(){const e=this.env.model.getters.getChartType(this.figureId);if(!e)throw new Error("Chart not defined.");const t=Xm.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}getChartDefinition(e=this.figureId){return this.env.model.getters.getChartDefinition(e)}get chartTypes(){return function(){const e={};for(const t of Vn.getKeys())e[t]=Vn.get(t).name;return e}()}activatePanel(e){this.state.panel=e}}Km.props={onCloseSidePanel:Function},Oi`
626
+ `;class Km extends t.Component{static template="o-spreadsheet-ChartPanel";state;get figureId(){return this.state.figureId}setup(){const e=this.env.model.getters.getSelectedFigureId();e?(this.state=t.useState({panel:"configuration",figureId:e}),t.onWillUpdateProps((()=>{const e=this.env.model.getters.getSelectedFigureId();e&&e!==this.state.figureId&&(this.state.figureId=e),this.env.model.getters.isChartDefined(this.figureId)||this.props.onCloseSidePanel()}))):this.props.onCloseSidePanel()}updateChart(e,t){if(e!==this.figureId)return;const o={...this.getChartDefinition(),...t};return this.env.model.dispatch("UPDATE_CHART",{definition:o,id:e,sheetId:this.env.model.getters.getFigureSheetId(e)})}onTypeChange(e){const t=this.env.model.getters.getContextCreationChart(this.figureId);if(!t)throw new Error("Chart not defined.");const o=function(e,t){return Vr.get(t).getChartDefinitionFromContextCreation(e)}(t,e);this.env.model.dispatch("UPDATE_CHART",{definition:o,id:this.figureId,sheetId:this.env.model.getters.getFigureSheetId(this.figureId)})}get chartPanel(){const e=this.env.model.getters.getChartType(this.figureId);if(!e)throw new Error("Chart not defined.");const t=Xm.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}getChartDefinition(e=this.figureId){return this.env.model.getters.getChartDefinition(e)}get chartTypes(){return function(){const e={};for(const t of Vr.getKeys())e[t]=Vr.get(t).name;return e}()}activatePanel(e){this.state.panel=e}}Km.props={onCloseSidePanel:Function},Oi`
627
627
  .o-spreadsheet {
628
628
  .o-icon {
629
629
  .small-text {
@@ -923,13 +923,13 @@
923
923
  }
924
924
  }
925
925
  }
926
- `;class of extends t.Component{static template="o-spreadsheet-ConditionalFormattingPanel";static components={SelectionInput:km,IconPicker:tf,ColorPickerWidget:$m};icons=Jm;cellIsOperators=sn;iconSets=ef;getTextDecoration=Mi;colorNumberString=Ot;activeSheetId;state;setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId(),this.state=t.useState({mode:"list",errors:[],rules:this.getDefaultRules()});const e=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(1===o.length){const e=this.conditionalFormats.find((e=>e.id===o[0]));e&&this.editConditionalFormat(e)}t.onWillUpdateProps((e=>{const t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(1===o.length){const e=this.conditionalFormats.find((e=>e.id===o[0]));e&&this.editConditionalFormat(e)}else this.switchToList()}})),t.useExternalListener(window,"click",this.closeMenus)}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId())}get isRangeValid(){return this.state.errors.includes(24)}errorMessage(e){return on.Errors[e]||on.Errors.Unexpected}switchToList(){this.state.mode="list",this.state.currentCF=void 0,this.state.currentCFType=void 0,this.state.errors=[],this.state.rules=this.getDefaultRules()}getStyle(e){if("CellIsRule"===e.type)return Fi({"font-weight":e.style.bold?"bold":"normal","text-decoration":Mi(e.style),"font-style":e.style.italic?"italic":"normal",color:e.style.textColor||"none","background-color":e.style.fillColor||"none"});if("ColorScaleRule"===e.type){const t=Ot(e.minimum.color),o=e.midpoint?Ot(e.midpoint.color):null,i=Ot(e.maximum.color),s="background-image: linear-gradient(to right, ";return o?s+t+", "+o+", "+i+")":s+t+", "+i+")"}return""}getDescription(e){switch(e.rule.type){case"CellIsRule":const t=sn[e.rule.operator];return 1===e.rule.values.length?`${t} ${e.rule.values[0]}`:2===e.rule.values.length?s("%s %s and %s",t,e.rule.values[0],e.rule.values[1]):t;case"ColorScaleRule":return on.ColorScale;case"IconSetRule":return on.IconSet;default:return""}}saveConditionalFormat(){if(this.state.currentCF){if(this.state.currentCF.ranges.some((e=>!e.match(Bo))))return void(this.state.errors=[25]);const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{rule:this.getEditorRule(),id:"edit"===this.state.mode?this.state.currentCF.id:this.env.model.uuidGenerator.uuidv4()},ranges:this.state.currentCF.ranges.map((t=>this.env.model.getters.getRangeDataFromXc(e,t))),sheetId:e});t.isSuccessful?this.switchToList():this.state.errors=t.reasons}}getEditorRule(){switch(this.state.currentCFType){case"CellIsRule":return this.state.rules.cellIs;case"ColorScaleRule":return this.state.rules.colorScale;case"IconSetRule":return this.state.rules.iconSet}throw new Error(`Invalid cf type: ${this.state.currentCFType}`)}getDefaultRules(){return{cellIs:{type:"CellIsRule",operator:"IsNotEmpty",values:[],style:{fillColor:"#b6d7a8"}},colorScale:{type:"ColorScaleRule",minimum:{type:"value",color:16777215},midpoint:void 0,maximum:{type:"value",color:6989903}},iconSet:{type:"IconSetRule",icons:{upper:"arrowGood",middle:"arrowNeutral",lower:"arrowBad"},upperInflectionPoint:{type:"percentage",value:"66",operator:"gt"},lowerInflectionPoint:{type:"percentage",value:"33",operator:"gt"}}}}addConditionalFormat(){this.state.mode="add",this.state.currentCFType="CellIsRule",this.state.currentCF={id:this.env.model.uuidGenerator.uuidv4(),ranges:this.env.model.getters.getSelectedZones().map((e=>this.env.model.getters.zoneToXC(this.env.model.getters.getActiveSheetId(),e)))}}deleteConditionalFormat(e){this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:e.id,sheetId:this.env.model.getters.getActiveSheetId()})}editConditionalFormat(e){if("reorder"!==this.state.mode)switch(this.state.mode="edit",this.state.currentCF=e,this.state.currentCFType=e.rule.type,e.rule.type){case"CellIsRule":this.state.rules.cellIs=e.rule;break;case"ColorScaleRule":this.state.rules.colorScale=e.rule;break;case"IconSetRule":this.state.rules.iconSet=e.rule}}reorderConditionalFormats(){this.state.mode="reorder"}reorderRule(e,t){this.env.model.dispatch("MOVE_CONDITIONAL_FORMAT",{cfId:e.id,direction:t,sheetId:this.env.model.getters.getActiveSheetId()})}changeRuleType(e){this.state.currentCFType!==e&&this.state.rules&&(this.state.errors=[],this.state.currentCFType=e)}onRangesChanged(e){this.state.currentCF&&(this.state.currentCF.ranges=e)}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){return!!this.state.errors?.includes(51)}get isValue2Invalid(){return!!this.state.errors?.includes(52)}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.closeMenus()}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.closeMenus()}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes(58)||this.state.errors.includes(50)||this.state.errors.includes(47)||this.state.errors.includes(53);case"midpoint":return this.state.errors.includes(59)||this.state.errors.includes(54)||this.state.errors.includes(49);case"maximum":return this.state.errors.includes(60)||this.state.errors.includes(55);default:return!1}}setColorScaleColor(e,t){const o=this.state.rules.colorScale[e];o&&(o.color=Number.parseInt(t.substr(1),16)),this.closeMenus()}getPreviewGradient(){const e=this.state.rules.colorScale,t=Ot(e.minimum.color),o=Ot(e.midpoint?.color||I),i=Ot(e.maximum.color),s="background-image: linear-gradient(to right, ";return void 0===e.midpoint?s+t+", "+i+")":s+t+", "+o+", "+i+")"}getThresholdColor(e){return Ot(e?e.color:I)}onMidpointChange(e){const t=e.target.value,o=this.state.rules.colorScale;o.midpoint="none"===t?void 0:{color:I,value:"",...o.midpoint,type:t}}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes(57)||this.state.errors.includes(62)||this.state.errors.includes(48);case"upperInflectionPoint":return this.state.errors.includes(56)||this.state.errors.includes(61)||this.state.errors.includes(48);default:return!0}}reverseIcons(){const e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t}setIconSet(e){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad}setIcon(e,t){this.state.rules.iconSet.icons[e]=t}}of.props={selection:{type:Object,optional:!0},onCloseSidePanel:Function},Oi`
926
+ `;class of extends t.Component{static template="o-spreadsheet-ConditionalFormattingPanel";static components={SelectionInput:km,IconPicker:tf,ColorPickerWidget:$m};icons=Jm;cellIsOperators=sr;iconSets=ef;getTextDecoration=Mi;colorNumberString=Ot;activeSheetId;state;setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId(),this.state=t.useState({mode:"list",errors:[],rules:this.getDefaultRules()});const e=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(1===o.length){const e=this.conditionalFormats.find((e=>e.id===o[0]));e&&this.editConditionalFormat(e)}t.onWillUpdateProps((e=>{const t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(1===o.length){const e=this.conditionalFormats.find((e=>e.id===o[0]));e&&this.editConditionalFormat(e)}else this.switchToList()}})),t.useExternalListener(window,"click",this.closeMenus)}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId())}get isRangeValid(){return this.state.errors.includes(24)}errorMessage(e){return ir.Errors[e]||ir.Errors.Unexpected}switchToList(){this.state.mode="list",this.state.currentCF=void 0,this.state.currentCFType=void 0,this.state.errors=[],this.state.rules=this.getDefaultRules()}getStyle(e){if("CellIsRule"===e.type)return Fi({"font-weight":e.style.bold?"bold":"normal","text-decoration":Mi(e.style),"font-style":e.style.italic?"italic":"normal",color:e.style.textColor||"none","background-color":e.style.fillColor||"none"});if("ColorScaleRule"===e.type){const t=Ot(e.minimum.color),o=e.midpoint?Ot(e.midpoint.color):null,i=Ot(e.maximum.color),s="background-image: linear-gradient(to right, ";return o?s+t+", "+o+", "+i+")":s+t+", "+i+")"}return""}getDescription(e){switch(e.rule.type){case"CellIsRule":const t=sr[e.rule.operator];return 1===e.rule.values.length?`${t} ${e.rule.values[0]}`:2===e.rule.values.length?s("%s %s and %s",t,e.rule.values[0],e.rule.values[1]):t;case"ColorScaleRule":return ir.ColorScale;case"IconSetRule":return ir.IconSet;default:return""}}saveConditionalFormat(){if(this.state.currentCF){if(this.state.currentCF.ranges.some((e=>!e.match(Bo))))return void(this.state.errors=[25]);const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{rule:this.getEditorRule(),id:"edit"===this.state.mode?this.state.currentCF.id:this.env.model.uuidGenerator.uuidv4()},ranges:this.state.currentCF.ranges.map((t=>this.env.model.getters.getRangeDataFromXc(e,t))),sheetId:e});t.isSuccessful?this.switchToList():this.state.errors=t.reasons}}getEditorRule(){switch(this.state.currentCFType){case"CellIsRule":return this.state.rules.cellIs;case"ColorScaleRule":return this.state.rules.colorScale;case"IconSetRule":return this.state.rules.iconSet}throw new Error(`Invalid cf type: ${this.state.currentCFType}`)}getDefaultRules(){return{cellIs:{type:"CellIsRule",operator:"IsNotEmpty",values:[],style:{fillColor:"#b6d7a8"}},colorScale:{type:"ColorScaleRule",minimum:{type:"value",color:16777215},midpoint:void 0,maximum:{type:"value",color:6989903}},iconSet:{type:"IconSetRule",icons:{upper:"arrowGood",middle:"arrowNeutral",lower:"arrowBad"},upperInflectionPoint:{type:"percentage",value:"66",operator:"gt"},lowerInflectionPoint:{type:"percentage",value:"33",operator:"gt"}}}}addConditionalFormat(){this.state.mode="add",this.state.currentCFType="CellIsRule",this.state.currentCF={id:this.env.model.uuidGenerator.uuidv4(),ranges:this.env.model.getters.getSelectedZones().map((e=>this.env.model.getters.zoneToXC(this.env.model.getters.getActiveSheetId(),e)))}}deleteConditionalFormat(e){this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:e.id,sheetId:this.env.model.getters.getActiveSheetId()})}editConditionalFormat(e){if("reorder"!==this.state.mode)switch(this.state.mode="edit",this.state.currentCF=e,this.state.currentCFType=e.rule.type,e.rule.type){case"CellIsRule":this.state.rules.cellIs=e.rule;break;case"ColorScaleRule":this.state.rules.colorScale=e.rule;break;case"IconSetRule":this.state.rules.iconSet=e.rule}}reorderConditionalFormats(){this.state.mode="reorder"}reorderRule(e,t){this.env.model.dispatch("MOVE_CONDITIONAL_FORMAT",{cfId:e.id,direction:t,sheetId:this.env.model.getters.getActiveSheetId()})}changeRuleType(e){this.state.currentCFType!==e&&this.state.rules&&(this.state.errors=[],this.state.currentCFType=e)}onRangesChanged(e){this.state.currentCF&&(this.state.currentCF.ranges=e)}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){return!!this.state.errors?.includes(52)}get isValue2Invalid(){return!!this.state.errors?.includes(53)}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.closeMenus()}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.closeMenus()}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes(59)||this.state.errors.includes(51)||this.state.errors.includes(48)||this.state.errors.includes(54);case"midpoint":return this.state.errors.includes(60)||this.state.errors.includes(55)||this.state.errors.includes(50);case"maximum":return this.state.errors.includes(61)||this.state.errors.includes(56);default:return!1}}setColorScaleColor(e,t){const o=this.state.rules.colorScale[e];o&&(o.color=Number.parseInt(t.substr(1),16)),this.closeMenus()}getPreviewGradient(){const e=this.state.rules.colorScale,t=Ot(e.minimum.color),o=Ot(e.midpoint?.color||I),i=Ot(e.maximum.color),s="background-image: linear-gradient(to right, ";return void 0===e.midpoint?s+t+", "+i+")":s+t+", "+o+", "+i+")"}getThresholdColor(e){return Ot(e?e.color:I)}onMidpointChange(e){const t=e.target.value,o=this.state.rules.colorScale;o.midpoint="none"===t?void 0:{color:I,value:"",...o.midpoint,type:t}}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes(58)||this.state.errors.includes(63)||this.state.errors.includes(49);case"upperInflectionPoint":return this.state.errors.includes(57)||this.state.errors.includes(62)||this.state.errors.includes(49);default:return!0}}reverseIcons(){const e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t}setIconSet(e){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad}setIcon(e,t){this.state.rules.iconSet.icons[e]=t}}of.props={selection:{type:Object,optional:!0},onCloseSidePanel:Function},Oi`
927
927
  .o-custom-currency {
928
928
  .o-format-proposals {
929
929
  color: black;
930
930
  }
931
931
  }
932
- `;class sf extends t.Component{static template="o-spreadsheet-CustomCurrencyPanel";availableCurrencies;state;setup(){this.availableCurrencies=[],this.state=t.useState({selectedCurrencyIndex:0,currencyCode:"",currencySymbol:"",selectedFormatIndex:0}),t.onWillStart((()=>this.updateAvailableCurrencies()))}get formatProposals(){const e=this.availableCurrencies[this.state.selectedCurrencyIndex],t=this.initProposalBases(e.decimalPlaces),o=e.position,i="before"===e.position?"after":"before",s=this.state.currencySymbol.trim()?this.state.currencySymbol:"",r=this.state.currencyCode.trim()?this.state.currencyCode:"";return r||s?[...this.createFormatProposals(t,s,r,o),...this.createFormatProposals(t,s,r,i)]:[]}get isSameFormat(){const e=this.formatProposals[this.state.selectedFormatIndex];return!!e&&e.format===this.getCommonFormat()}async updateAvailableCurrencies(){if(0===Bn.getAll().length){(await(this.env.loadCurrencies?.())||[]).forEach(((e,t)=>{Bn.add(t.toString(),e)}))}const e={name:this.env._t(nn.Custom),code:"",symbol:"",decimalPlaces:2,position:"after"};this.availableCurrencies=[e,...Bn.getAll()]}updateSelectCurrency(e){const t=e.target;this.state.selectedCurrencyIndex=parseInt(t.value,10);const o=this.availableCurrencies[this.state.selectedCurrencyIndex];this.state.currencyCode=o.code,this.state.currencySymbol=o.symbol}updateCode(e){const t=e.target;this.state.currencyCode=t.value,this.initAvailableCurrencies()}updateSymbol(e){const t=e.target;this.state.currencySymbol=t.value,this.initAvailableCurrencies()}updateSelectFormat(e){const t=e.target;this.state.selectedFormatIndex=parseInt(t.value,10)}apply(){const e=this.formatProposals[this.state.selectedFormatIndex];this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),format:e.format})}initAvailableCurrencies(){this.state.selectedCurrencyIndex=0}initProposalBases(e){const t=[{format:"#,##0",example:"1,000"}],o=e?"."+"0".repeat(e):"";return o&&t.push({format:"#,##0"+o,example:"1,000"+o}),t}createFormatProposals(e,t,o,i){let s=[];if(t)for(let o of e)s.push(this.createFormatProposal(i,o.example,o.format,t));if(o)for(let r of e){const e=("after"===i?" ":"")+o+" "+t;s.push(this.createFormatProposal(i,r.example,r.format,e))}return s}createFormatProposal(e,t,o,i){const s="[$"+i+"]";return{example:"before"===e?i+t:t+i,format:"before"===e?s+o:o+s}}getCommonFormat(){const e=this.env.model.getters.getSelectedZones(),t=this.env.model.getters.getActiveSheetId(),o=e.map((e=>this.env.model.getters.getEvaluatedCellsInZone(t,e))).flat(),i=o[0].format;return o.every((e=>e.format===i))?i:void 0}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:"")}}sf.props={onCloseSidePanel:Function},Oi`
932
+ `;class sf extends t.Component{static template="o-spreadsheet-CustomCurrencyPanel";availableCurrencies;state;setup(){this.availableCurrencies=[],this.state=t.useState({selectedCurrencyIndex:0,currencyCode:"",currencySymbol:"",selectedFormatIndex:0}),t.onWillStart((()=>this.updateAvailableCurrencies()))}get formatProposals(){const e=this.availableCurrencies[this.state.selectedCurrencyIndex],t=this.initProposalBases(e.decimalPlaces),o=e.position,i="before"===e.position?"after":"before",s=this.state.currencySymbol.trim()?this.state.currencySymbol:"",n=this.state.currencyCode.trim()?this.state.currencyCode:"";return n||s?[...this.createFormatProposals(t,s,n,o),...this.createFormatProposals(t,s,n,i)]:[]}get isSameFormat(){const e=this.formatProposals[this.state.selectedFormatIndex];return!!e&&e.format===this.getCommonFormat()}async updateAvailableCurrencies(){if(0===Br.getAll().length){(await(this.env.loadCurrencies?.())||[]).forEach(((e,t)=>{Br.add(t.toString(),e)}))}const e={name:this.env._t(rr.Custom),code:"",symbol:"",decimalPlaces:2,position:"after"};this.availableCurrencies=[e,...Br.getAll()]}updateSelectCurrency(e){const t=e.target;this.state.selectedCurrencyIndex=parseInt(t.value,10);const o=this.availableCurrencies[this.state.selectedCurrencyIndex];this.state.currencyCode=o.code,this.state.currencySymbol=o.symbol}updateCode(e){const t=e.target;this.state.currencyCode=t.value,this.initAvailableCurrencies()}updateSymbol(e){const t=e.target;this.state.currencySymbol=t.value,this.initAvailableCurrencies()}updateSelectFormat(e){const t=e.target;this.state.selectedFormatIndex=parseInt(t.value,10)}apply(){const e=this.formatProposals[this.state.selectedFormatIndex];this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),format:e.format})}initAvailableCurrencies(){this.state.selectedCurrencyIndex=0}initProposalBases(e){const t=[{format:"#,##0",example:"1,000"}],o=e?"."+"0".repeat(e):"";return o&&t.push({format:"#,##0"+o,example:"1,000"+o}),t}createFormatProposals(e,t,o,i){let s=[];if(t)for(let o of e)s.push(this.createFormatProposal(i,o.example,o.format,t));if(o)for(let n of e){const e=("after"===i?" ":"")+o+" "+t;s.push(this.createFormatProposal(i,n.example,n.format,e))}return s}createFormatProposal(e,t,o,i){const s="[$"+i+"]";return{example:"before"===e?i+t:t+i,format:"before"===e?s+o:o+s}}getCommonFormat(){const e=this.env.model.getters.getSelectedZones(),t=this.env.model.getters.getActiveSheetId(),o=e.map((e=>this.env.model.getters.getEvaluatedCellsInZone(t,e))).flat(),i=o[0].format;return o.every((e=>e.format===i))?i:void 0}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:"")}}sf.props={onCloseSidePanel:Function},Oi`
933
933
  .o-find-and-replace {
934
934
  .o-far-item {
935
935
  display: block;
@@ -962,7 +962,7 @@
962
962
  }
963
963
  }
964
964
  }
965
- `;class rf extends t.Component{static template="o-spreadsheet-FindAndReplacePanel";state=t.useState(this.initialState());debounceTimeoutId;showFormulaState=!1;findAndReplaceRef=t.useRef("findAndReplace");get hasSearchResult(){return null!==this.env.model.getters.getCurrentSelectedMatchIndex()}get pendingSearch(){return void 0!==this.debounceTimeoutId}setup(){this.showFormulaState=this.env.model.getters.shouldShowFormulas(),t.onMounted((()=>this.focusInput())),t.onWillUnmount((()=>{clearTimeout(this.debounceTimeoutId),this.env.model.dispatch("CLEAR_SEARCH"),this.env.model.dispatch("SET_FORMULA_VISIBILITY",{show:this.showFormulaState})})),t.useEffect((()=>{this.state.searchOptions.searchFormulas=this.env.model.getters.shouldShowFormulas(),this.searchFormulas()}),(()=>[this.env.model.getters.shouldShowFormulas()]))}onInput(e){this.state.toSearch=e.target.value,this.debouncedUpdateSearch()}onKeydownSearch(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),this.onSelectNextCell())}onKeydownReplace(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),this.replace())}searchFormulas(){this.env.model.dispatch("SET_FORMULA_VISIBILITY",{show:this.state.searchOptions.searchFormulas}),this.updateSearch()}onSelectPreviousCell(){this.env.model.dispatch("SELECT_SEARCH_PREVIOUS_MATCH")}onSelectNextCell(){this.env.model.dispatch("SELECT_SEARCH_NEXT_MATCH")}updateSearch(){this.env.model.dispatch("UPDATE_SEARCH",{toSearch:this.state.toSearch,searchOptions:this.state.searchOptions})}debouncedUpdateSearch(){clearTimeout(this.debounceTimeoutId),this.debounceTimeoutId=setTimeout((()=>{this.updateSearch(),this.debounceTimeoutId=void 0}),200)}replace(){this.env.model.dispatch("REPLACE_SEARCH",{replaceWith:this.state.replaceWith})}replaceAll(){this.env.model.dispatch("REPLACE_ALL_SEARCH",{replaceWith:this.state.replaceWith})}focusInput(){const e=this.findAndReplaceRef.el.querySelector("input");e&&e.focus()}initialState(){return{toSearch:"",replaceWith:"",searchOptions:{matchCase:!1,exactMatch:!1,searchFormulas:!1}}}}rf.props={onCloseSidePanel:Function};const nf={SplitIsDestructive:r("This will overwrite data in the subsequent columns. Split anyway?")};const af=[{name:r("Detect automatically"),value:"auto"},{name:r("Custom separator"),value:"custom"},{name:r("Space"),value:" "},{name:r("Comma"),value:","},{name:r("Semicolon"),value:";"},{name:r("Line Break"),value:me}];class lf extends t.Component{static template="o-spreadsheet-SplitIntoColumnsPanel";state=t.useState({separatorValue:"auto",addNewColumns:!1,customSeparator:""});setup(){t.onWillUpdateProps((()=>{"inactive"!==this.env.model.getters.getEditionMode()&&this.props.onCloseSidePanel()})),t.onMounted((()=>{this.env.model.dispatch("STOP_EDITION")}))}onSeparatorChange(e){this.state.separatorValue=e}updateCustomSeparator(e){e.target&&(this.state.customSeparator=e.target.value)}updateAddNewColumnsCheckbox(e){e.target&&(this.state.addNewColumns=e.target.checked)}confirm(){(function(e,t,o){let i=e.model.dispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:t,addNewColumns:o});return i.isCancelledBecause(90)&&e.askConfirmation(nf.SplitIsDestructive,(()=>{i=e.model.dispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:t,addNewColumns:o,force:!0})})),i})(this.env,this.separatorValue,this.state.addNewColumns).isSuccessful&&this.props.onCloseSidePanel()}get errorMessages(){const e=this.env.model.canDispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!0}).reasons,t=new Set;for(const o of e)switch(o){case 90:case 89:break;default:t.add(ln.Errors[o]||ln.Errors.Unexpected)}return Array.from(t)}get warningMessages(){const e=[];return this.env.model.canDispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!1}).reasons.includes(90)&&e.push(ln.Errors[90]),e}get separatorValue(){return"custom"===this.state.separatorValue?this.state.customSeparator:"auto"===this.state.separatorValue?this.env.model.getters.getAutomaticSeparator():this.state.separatorValue}get separators(){return af}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}}lf.props={onCloseSidePanel:Function};const cf=new Ui;cf.add("ConditionalFormatting",{title:r("Conditional formatting"),Body:of}),cf.add("ChartPanel",{title:r("Chart"),Body:Km}),cf.add("FindAndReplace",{title:r("Find and Replace"),Body:rf}),cf.add("CustomCurrency",{title:r("Custom currency format"),Body:sf}),cf.add("SplitToColumns",{title:r("Split text into columns"),Body:lf});const hf=new class extends Ui{mapping={};uuidGenerator=new Jo;add(e,t){const o={...t,id:this.uuidGenerator.uuidv4()};return super.add(e,o)}};Oi`
965
+ `;class nf extends t.Component{static template="o-spreadsheet-FindAndReplacePanel";state=t.useState(this.initialState());debounceTimeoutId;showFormulaState=!1;findAndReplaceRef=t.useRef("findAndReplace");get hasSearchResult(){return null!==this.env.model.getters.getCurrentSelectedMatchIndex()}get pendingSearch(){return void 0!==this.debounceTimeoutId}setup(){this.showFormulaState=this.env.model.getters.shouldShowFormulas(),t.onMounted((()=>this.focusInput())),t.onWillUnmount((()=>{clearTimeout(this.debounceTimeoutId),this.env.model.dispatch("CLEAR_SEARCH"),this.env.model.dispatch("SET_FORMULA_VISIBILITY",{show:this.showFormulaState})})),t.useEffect((()=>{this.state.searchOptions.searchFormulas=this.env.model.getters.shouldShowFormulas(),this.searchFormulas()}),(()=>[this.env.model.getters.shouldShowFormulas()]))}onInput(e){this.state.toSearch=e.target.value,this.debouncedUpdateSearch()}onKeydownSearch(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),this.onSelectNextCell())}onKeydownReplace(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),this.replace())}searchFormulas(){this.env.model.dispatch("SET_FORMULA_VISIBILITY",{show:this.state.searchOptions.searchFormulas}),this.updateSearch()}onSelectPreviousCell(){this.env.model.dispatch("SELECT_SEARCH_PREVIOUS_MATCH")}onSelectNextCell(){this.env.model.dispatch("SELECT_SEARCH_NEXT_MATCH")}updateSearch(){this.env.model.dispatch("UPDATE_SEARCH",{toSearch:this.state.toSearch,searchOptions:this.state.searchOptions})}debouncedUpdateSearch(){clearTimeout(this.debounceTimeoutId),this.debounceTimeoutId=setTimeout((()=>{this.updateSearch(),this.debounceTimeoutId=void 0}),200)}replace(){this.env.model.dispatch("REPLACE_SEARCH",{replaceWith:this.state.replaceWith})}replaceAll(){this.env.model.dispatch("REPLACE_ALL_SEARCH",{replaceWith:this.state.replaceWith})}focusInput(){const e=this.findAndReplaceRef.el.querySelector("input");e&&e.focus()}initialState(){return{toSearch:"",replaceWith:"",searchOptions:{matchCase:!1,exactMatch:!1,searchFormulas:!1}}}}nf.props={onCloseSidePanel:Function};const rf={SplitIsDestructive:n("This will overwrite data in the subsequent columns. Split anyway?")};const af=[{name:n("Detect automatically"),value:"auto"},{name:n("Custom separator"),value:"custom"},{name:n("Space"),value:" "},{name:n("Comma"),value:","},{name:n("Semicolon"),value:";"},{name:n("Line Break"),value:me}];class lf extends t.Component{static template="o-spreadsheet-SplitIntoColumnsPanel";state=t.useState({separatorValue:"auto",addNewColumns:!1,customSeparator:""});setup(){t.onWillUpdateProps((()=>{"inactive"!==this.env.model.getters.getEditionMode()&&this.props.onCloseSidePanel()})),t.onMounted((()=>{this.env.model.dispatch("STOP_EDITION")}))}onSeparatorChange(e){this.state.separatorValue=e}updateCustomSeparator(e){e.target&&(this.state.customSeparator=e.target.value)}updateAddNewColumnsCheckbox(e){e.target&&(this.state.addNewColumns=e.target.checked)}confirm(){(function(e,t,o){let i=e.model.dispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:t,addNewColumns:o});return i.isCancelledBecause(91)&&e.askConfirmation(rf.SplitIsDestructive,(()=>{i=e.model.dispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:t,addNewColumns:o,force:!0})})),i})(this.env,this.separatorValue,this.state.addNewColumns).isSuccessful&&this.props.onCloseSidePanel()}get errorMessages(){const e=this.env.model.canDispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!0}).reasons,t=new Set;for(const o of e)switch(o){case 91:case 90:break;default:t.add(lr.Errors[o]||lr.Errors.Unexpected)}return Array.from(t)}get warningMessages(){const e=[];return this.env.model.canDispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!1}).reasons.includes(91)&&e.push(lr.Errors[91]),e}get separatorValue(){return"custom"===this.state.separatorValue?this.state.customSeparator:"auto"===this.state.separatorValue?this.env.model.getters.getAutomaticSeparator():this.state.separatorValue}get separators(){return af}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}}lf.props={onCloseSidePanel:Function};const cf=new Ui;cf.add("ConditionalFormatting",{title:n("Conditional formatting"),Body:of}),cf.add("ChartPanel",{title:n("Chart"),Body:Km}),cf.add("FindAndReplace",{title:n("Find and Replace"),Body:nf}),cf.add("CustomCurrency",{title:n("Custom currency format"),Body:sf}),cf.add("SplitToColumns",{title:n("Split text into columns"),Body:lf});const hf=new class extends Ui{mapping={};uuidGenerator=new Jo;add(e,t){const o={...t,id:this.uuidGenerator.uuidv4()};return super.add(e,o)}};Oi`
966
966
  div.o-figure {
967
967
  box-sizing: border-box;
968
968
  position: absolute;
@@ -1035,7 +1035,7 @@
1035
1035
  }
1036
1036
  }
1037
1037
  }
1038
- `;class df extends t.Component{static template="o-spreadsheet-FigureComponent";static components={Menu:br};static defaultProps={onFigureDeleted:()=>{},onMouseDown:()=>{},onClickAnchor:()=>{}};menuState=t.useState({isOpen:!1,position:null,menuItems:[]});figureRef=t.useRef("figure");menuButtonRef=t.useRef("menuButton");menuButtonRect=cr(this.menuButtonRef);borderWidth;get isSelected(){return this.env.model.getters.getSelectedFigureId()===this.props.figure.id}get figureRegistry(){return Gn}getBorderWidth(){return this.env.isDashboard()?0:this.isSelected?2:this.borderWidth}get borderStyle(){return`border: ${this.getBorderWidth()}px solid ${this.isSelected?E:"#c9ccd2"};`}get wrapperStyle(){const{x:e,y:t,width:o,height:i}=this.props.figure;return Fi({left:`${e}px`,top:`${t}px`,width:`${o}px`,height:`${i}px`,"z-index":String(ue.Figure+(this.isSelected?1:0))})}getResizerPosition(e){let t={};return e.includes("top")?t.top="-3px":e.includes("bottom")?t.bottom="-3px":t.bottom="calc(50% - 3px)",e.includes("left")?t.left="-3px":e.includes("right")?t.right="-3px":t.right="calc(50% - 3px)",Fi(t)}setup(){const e=Gn.get(this.props.figure.tag).borderWidth;this.borderWidth=void 0!==e?e:1,t.useEffect(((e,t,o)=>{e===t&&o?.focus({preventScroll:!0})}),(()=>[this.env.model.getters.getSelectedFigureId(),this.props.figure.id,this.figureRef.el]))}clickAnchor(e,t,o){this.props.onClickAnchor(e,t,o)}onMouseDown(e){this.props.onMouseDown(e)}onKeyDown(e){const t=this.props.figure;switch(e.key){case"Delete":this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:t.id}),this.props.onFigureDeleted(),e.stopPropagation(),e.preventDefault();break;case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":const o={ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1]}[e.key];this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:t.id,x:t.x+o[0],y:t.y+o[1]}),e.stopPropagation(),e.preventDefault()}}onContextMenu(e){if(this.env.isDashboard())return;const t={x:e.clientX,y:e.clientY};this.openContextMenu(t)}showMenu(){const{x:e,y:t,width:o}=this.menuButtonRect,i={x:e>=G?e-G:e+o,y:t};this.openContextMenu(i)}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.position=e,this.menuState.menuItems=Gn.get(this.props.figure.tag).menuBuilder(this.props.figure.id,this.props.onFigureDeleted,this.env)}}function uf(e,t,o=(()=>{})){const i=r=>{t(r),window.removeEventListener("mousedown",o),window.removeEventListener("mouseup",i),window.removeEventListener("dragstart",s),window.removeEventListener("mousemove",e),window.removeEventListener("wheel",e)};function s(e){e.preventDefault()}window.addEventListener("mousedown",o),window.addEventListener("mouseup",i),window.addEventListener("dragstart",s),window.addEventListener("mousemove",e),window.addEventListener("wheel",e,{passive:!1})}function gf(e,t,o,i=!1){let s,r,n,a,l,c=null;const h=e.model.getters,d=h.getActiveSheetId(),u=ir();let g,p;const m=o=>{if(s=o,c)return;const{x:n,y:f}=h.getMainViewportCoordinates();let{top:b,left:v,bottom:S,right:C}=h.getActiveMainViewport(),{scrollX:E,scrollY:w}=h.getActiveSheetDOMScrollInfo();const{xSplit:x,ySplit:y}=h.getPaneDivisions(d);let I=!1,R=qt;const T=s.clientX-u.left;if(g=h.getColIndex(T),"vertical"!==i){const t=r.clientX-u.left,o=h.getEdgeScrollCol(T,t,a);if(o.canEdgeScroll){let t;switch(I=!0,R=Math.min(R,o.delay),o.direction){case"reset":g=x,t=x;break;case 1:g=C,t=v+1;break;case-1:for(g=v-1;e.model.getters.isColHidden(d,g);)g--;t=g}E=h.getColDimensions(d,t).start-n}}const A=s.clientY-u.top;if(p=h.getRowIndex(A),"horizontal"!==i){const t=r.clientY-u.top,o=h.getEdgeScrollRow(A,t,l);if(o.canEdgeScroll){let t;switch(I=!0,R=Math.min(R,o.delay),o.direction){case"reset":p=y,t=y;break;case 1:p=S,t=b+o.direction;break;case-1:for(p=b-1;e.model.getters.isRowHidden(d,p);)p--;t=p}w=e.model.getters.getRowDimensions(d,t).start-f}}I||(-1===p&&(p=A<0?0:h.getNumberRows(d)-1),-1===g&&T<0&&(g=T<0?0:h.getNumberCols(d)-1)),t(g,p,s),I&&(e.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:E,offsetY:w}),c=setTimeout((()=>{c=null,m(s)}),Math.round(R))),r=s};uf(m,(()=>{clearTimeout(c),o()}),(e=>{r=e,n=e,a=n.clientX-u.left,l=n.clientY-u.top}))}df.props={figure:Object,style:{type:String,optional:!0},onFigureDeleted:{type:Function,optional:!0},onMouseDown:{type:Function,optional:!0},onClickAnchor:{type:Function,optional:!0}},Oi`
1038
+ `;class df extends t.Component{static template="o-spreadsheet-FigureComponent";static components={Menu:vn};static defaultProps={onFigureDeleted:()=>{},onMouseDown:()=>{},onClickAnchor:()=>{}};menuState=t.useState({isOpen:!1,position:null,menuItems:[]});figureRef=t.useRef("figure");menuButtonRef=t.useRef("menuButton");menuButtonRect=hn(this.menuButtonRef);borderWidth;get isSelected(){return this.env.model.getters.getSelectedFigureId()===this.props.figure.id}get figureRegistry(){return Gr}getBorderWidth(){return this.env.isDashboard()?0:this.isSelected?2:this.borderWidth}get borderStyle(){return`border: ${this.getBorderWidth()}px solid ${this.isSelected?E:"#c9ccd2"};`}get wrapperStyle(){const{x:e,y:t,width:o,height:i}=this.props.figure;return Fi({left:`${e}px`,top:`${t}px`,width:`${o}px`,height:`${i}px`,"z-index":String(ue.Figure+(this.isSelected?1:0))})}getResizerPosition(e){let t={};return e.includes("top")?t.top="-3px":e.includes("bottom")?t.bottom="-3px":t.bottom="calc(50% - 3px)",e.includes("left")?t.left="-3px":e.includes("right")?t.right="-3px":t.right="calc(50% - 3px)",Fi(t)}setup(){const e=Gr.get(this.props.figure.tag).borderWidth;this.borderWidth=void 0!==e?e:1,t.useEffect(((e,t,o)=>{e===t&&o?.focus({preventScroll:!0})}),(()=>[this.env.model.getters.getSelectedFigureId(),this.props.figure.id,this.figureRef.el]))}clickAnchor(e,t,o){this.props.onClickAnchor(e,t,o)}onMouseDown(e){this.props.onMouseDown(e)}onKeyDown(e){const t=this.props.figure;switch(e.key){case"Delete":this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:t.id}),this.props.onFigureDeleted(),e.stopPropagation(),e.preventDefault();break;case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":const o={ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1]}[e.key];this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:t.id,x:t.x+o[0],y:t.y+o[1]}),e.stopPropagation(),e.preventDefault()}}onContextMenu(e){if(this.env.isDashboard())return;const t={x:e.clientX,y:e.clientY};this.openContextMenu(t)}showMenu(){const{x:e,y:t,width:o}=this.menuButtonRect,i={x:e>=G?e-G:e+o,y:t};this.openContextMenu(i)}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.position=e,this.menuState.menuItems=Gr.get(this.props.figure.tag).menuBuilder(this.props.figure.id,this.props.onFigureDeleted,this.env)}}function uf(e,t,o=(()=>{})){const i=n=>{t(n),window.removeEventListener("mousedown",o),window.removeEventListener("mouseup",i),window.removeEventListener("dragstart",s),window.removeEventListener("mousemove",e),window.removeEventListener("wheel",e)};function s(e){e.preventDefault()}window.addEventListener("mousedown",o),window.addEventListener("mouseup",i),window.addEventListener("dragstart",s),window.addEventListener("mousemove",e),window.addEventListener("wheel",e,{passive:!1})}function gf(e,t,o,i=!1){let s,n,r,a,l,c=null;const h=e.model.getters,d=h.getActiveSheetId(),u=sn();let g,p;const m=o=>{if(s=o,c)return;const{x:r,y:f}=h.getMainViewportCoordinates();let{top:b,left:v,bottom:S,right:C}=h.getActiveMainViewport(),{scrollX:E,scrollY:w}=h.getActiveSheetDOMScrollInfo();const{xSplit:x,ySplit:y}=h.getPaneDivisions(d);let I=!1,R=qt;const T=s.clientX-u.left;if(g=h.getColIndex(T),"vertical"!==i){const t=n.clientX-u.left,o=h.getEdgeScrollCol(T,t,a);if(o.canEdgeScroll){let t;switch(I=!0,R=Math.min(R,o.delay),o.direction){case"reset":g=x,t=x;break;case 1:g=C,t=v+1;break;case-1:for(g=v-1;e.model.getters.isColHidden(d,g);)g--;t=g}E=h.getColDimensions(d,t).start-r}}const A=s.clientY-u.top;if(p=h.getRowIndex(A),"horizontal"!==i){const t=n.clientY-u.top,o=h.getEdgeScrollRow(A,t,l);if(o.canEdgeScroll){let t;switch(I=!0,R=Math.min(R,o.delay),o.direction){case"reset":p=y,t=y;break;case 1:p=S,t=b+o.direction;break;case-1:for(p=b-1;e.model.getters.isRowHidden(d,p);)p--;t=p}w=e.model.getters.getRowDimensions(d,t).start-f}}I||(-1===p&&(p=A<0?0:h.getNumberRows(d)-1),-1===g&&T<0&&(g=T<0?0:h.getNumberCols(d)-1)),t(g,p,s),I&&(e.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:E,offsetY:w}),c=setTimeout((()=>{c=null,m(s)}),Math.round(R))),n=s};uf(m,(()=>{clearTimeout(c),o()}),(e=>{n=e,r=e,a=r.clientX-u.left,l=r.clientY-u.top}))}df.props={figure:Object,style:{type:String,optional:!0},onFigureDeleted:{type:Function,optional:!0},onMouseDown:{type:Function,optional:!0},onClickAnchor:{type:Function,optional:!0}},Oi`
1039
1039
  .o-autofill {
1040
1040
  position: absolute;
1041
1041
  height: ${8}px;
@@ -1063,7 +1063,7 @@
1063
1063
  pointer-events: none;
1064
1064
  white-space: nowrap;
1065
1065
  }
1066
- `;class pf extends t.Component{static template="o-spreadsheet-Autofill";state=t.useState({position:{left:0,top:0},handler:!1});get style(){const{left:e,top:t}=this.props.position;return Fi({top:`${t}px`,left:`${e}px`,visibility:this.props.isVisible?"visible":"hidden"})}get handlerStyle(){const{left:e,top:t}=this.state.handler?this.state.position:this.props.position;return Fi({top:`${t}px`,left:`${e}px`})}get styleNextValue(){const{left:e,top:t}=this.state.position;return Fi({top:`${t+5}px`,left:`${e+15}px`})}getTooltip(){const e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=mf),e}onMouseDown(e){let t,o;this.state.handler=!0;const i=e.clientX-this.props.position.left,s=e.clientY-this.props.position.top;gf(this.env,((e,r,n)=>{if(this.state.position={left:n.clientX-i,top:n.clientY-s},t!==e||o!==r){const i=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getNumberCols(i),n=this.env.model.getters.getNumberRows(i);t=-1===e?t:We(e,0,s),o=-1===r?o:We(r,0,n),void 0!==t&&void 0!==o&&this.env.model.dispatch("AUTOFILL_SELECT",{col:t,row:o})}}),(()=>{this.state.handler=!1,this.state.position={...this.props.position},this.env.model.dispatch("AUTOFILL")}))}onDblClick(){this.env.model.dispatch("AUTOFILL_AUTO")}}pf.props={position:Object,isVisible:Boolean};class mf extends t.Component{static template=t.xml`
1066
+ `;class pf extends t.Component{static template="o-spreadsheet-Autofill";state=t.useState({position:{left:0,top:0},handler:!1});get style(){const{left:e,top:t}=this.props.position;return Fi({top:`${t}px`,left:`${e}px`,visibility:this.props.isVisible?"visible":"hidden"})}get handlerStyle(){const{left:e,top:t}=this.state.handler?this.state.position:this.props.position;return Fi({top:`${t}px`,left:`${e}px`})}get styleNextValue(){const{left:e,top:t}=this.state.position;return Fi({top:`${t+5}px`,left:`${e+15}px`})}getTooltip(){const e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=mf),e}onMouseDown(e){let t,o;this.state.handler=!0;const i=e.clientX-this.props.position.left,s=e.clientY-this.props.position.top;gf(this.env,((e,n,r)=>{if(this.state.position={left:r.clientX-i,top:r.clientY-s},t!==e||o!==n){const i=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getNumberCols(i),r=this.env.model.getters.getNumberRows(i);t=-1===e?t:We(e,0,s),o=-1===n?o:We(n,0,r),void 0!==t&&void 0!==o&&this.env.model.dispatch("AUTOFILL_SELECT",{col:t,row:o})}}),(()=>{this.state.handler=!1,this.state.position={...this.props.position},this.env.model.dispatch("AUTOFILL")}))}onDblClick(){this.env.model.dispatch("AUTOFILL_AUTO")}}pf.props={position:Object,isVisible:Boolean};class mf extends t.Component{static template=t.xml`
1067
1067
  <div t-esc="props.content"/>
1068
1068
  `}mf.props={content:String},Oi`
1069
1069
  .o-client-tag {
@@ -1075,7 +1075,7 @@
1075
1075
  opacity: 0;
1076
1076
  pointer-events: none;
1077
1077
  }
1078
- `;class ff extends t.Component{static template="o-spreadsheet-ClientTag";get tagStyle(){const{col:e,row:t,color:o}=this.props,{height:i}=this.env.model.getters.getSheetViewDimensionWithHeaders(),{x:s,y:r}=this.env.model.getters.getVisibleRect({left:e,top:t,right:e,bottom:t});return Fi({bottom:i-r+15+"px",left:s-1+"px",border:`1px solid ${o}`,"background-color":o,opacity:this.props.active?"1 !important":void 0})}}ff.props={active:Boolean,name:String,color:String,col:Number,row:Number},Oi`
1078
+ `;class ff extends t.Component{static template="o-spreadsheet-ClientTag";get tagStyle(){const{col:e,row:t,color:o}=this.props,{height:i}=this.env.model.getters.getSheetViewDimensionWithHeaders(),{x:s,y:n}=this.env.model.getters.getVisibleRect({left:e,top:t,right:e,bottom:t});return Fi({bottom:i-n+15+"px",left:s-1+"px",border:`1px solid ${o}`,"background-color":o,opacity:this.props.active?"1 !important":void 0})}}ff.props={active:Boolean,name:String,color:String,col:Number,row:Number},Oi`
1079
1079
  .o-autocomplete-dropdown {
1080
1080
  pointer-events: auto;
1081
1081
  background-color: #fff;
@@ -1094,7 +1094,7 @@
1094
1094
  }
1095
1095
  }
1096
1096
  }
1097
- `;class bf extends t.Component{static template="o-spreadsheet-TextValueProvider"}bf.props={values:Array,selectedIndex:Number,onValueSelected:Function};class vf{el;constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){let o=window.getSelection();this.removeSelection();let i=document.createRange();if(e==t&&0===e)i.setStart(this.el,0),i.setEnd(this.el,0),o.addRange(i);else{const s=this.getText().length;(e<0||t>s)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${s}`),e<0&&(e=0),t>s&&(t=s),e>s&&(e=s));let r=this.findChildAtCharacterIndex(e),n=this.findChildAtCharacterIndex(t);i.setStart(r.node,r.offset),o.addRange(i),o.extend(n.node,n.offset)}}findChildAtCharacterIndex(e){let t,o,i=rr(this.el),s=e,r=!0;do{t=i.next(),t.done||t.value.hasChildNodes()||(t.value.textContent&&t.value.textContent.length<s?s-=t.value.textContent.length:t.value.textContent&&t.value.textContent.length>=s&&i.return(t.value),o=t.value),t.done||"P"!==t.value.nodeName||(r?r=!1:s--)}while(!t.done&&s);return t.value?{node:t.value,offset:s}:{node:o,offset:s}}setText(e){if(this.el.innerHTML="",0!==e.length)for(const t of e){const e=document.createElement("p");if(0===t.length||t.every((e=>!e.value&&!e.class)))e.appendChild(document.createElement("br")),this.el.appendChild(e);else{for(const o of t){if(!o.value&&!o.class)continue;const t=document.createElement("span");t.innerText=o.value,t.style.color=o.color||"",o.class&&t.classList.add(o.class),e.appendChild(t)}this.el.appendChild(e)}}}scrollSelectionIntoView(){const e=document.getSelection()?.focusNode;if(!e||!this.el.contains(e))return;(e instanceof HTMLElement?e:e.parentElement)?.scrollIntoView({block:"nearest"})}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){let{startElement:e,endElement:t,startSelectionOffset:o,endSelectionOffset:i}=this.getStartAndEndSelection();return{start:this.findSelectionIndex(e,o),end:this.findSelectionIndex(t,i)}}findSelectionIndex(e,t){let o=0,i=rr(this.el),s=i.next(),r=!0;for(;!s.done&&s.value!==e;)s.value.hasChildNodes()||s.value.textContent&&(o+=s.value.textContent.length),("P"===s.value.nodeName||"DIV"===s.value.nodeName&&s.value!==this.el)&&(r?r=!1:o++),s=i.next();if(s.value!==e)return 0;if(s.value.hasChildNodes()){const e=[...s.value.childNodes].slice(0,t);o+=e.reduce(((t,o,i)=>{if(null!==o.textContent){let s=o.textContent.length;return"P"===o.nodeName&&i!==e.length-1&&s++,t+s}return t}),0)}else o+=t;return"P"!==e.nodeName||r||""!=e.textContent||o++,o}getStartAndEndSelection(){const e=document.getSelection();return{startElement:e.anchorNode||this.el,startSelectionOffset:e.anchorOffset,endElement:e.focusNode||this.el,endSelectionOffset:e.focusOffset}}getText(){let e="",t=rr(this.el),o=t.next(),i=!0;for(;!o.done;)o.value.hasChildNodes()||(e+=o.value.textContent),("P"===o.value.nodeName||"DIV"===o.value.nodeName&&o.value!==this.el)&&(i?i=!1:e+=me),o=t.next();return e}}Oi`
1097
+ `;class bf extends t.Component{static template="o-spreadsheet-TextValueProvider"}bf.props={values:Array,selectedIndex:Number,onValueSelected:Function};class vf{el;constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){let o=window.getSelection();this.removeSelection();let i=document.createRange();if(e==t&&0===e)i.setStart(this.el,0),i.setEnd(this.el,0),o.addRange(i);else{const s=this.getText().length;(e<0||t>s)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${s}`),e<0&&(e=0),t>s&&(t=s),e>s&&(e=s));let n=this.findChildAtCharacterIndex(e),r=this.findChildAtCharacterIndex(t);i.setStart(n.node,n.offset),o.addRange(i),o.extend(r.node,r.offset)}}findChildAtCharacterIndex(e){let t,o,i=rn(this.el),s=e,n=!0;do{t=i.next(),t.done||t.value.hasChildNodes()||(t.value.textContent&&t.value.textContent.length<s?s-=t.value.textContent.length:t.value.textContent&&t.value.textContent.length>=s&&i.return(t.value),o=t.value),t.done||"P"!==t.value.nodeName||(n?n=!1:s--)}while(!t.done&&s);return t.value?{node:t.value,offset:s}:{node:o,offset:s}}setText(e){if(this.el.innerHTML="",0!==e.length)for(const t of e){const e=document.createElement("p");if(0===t.length||t.every((e=>!e.value&&!e.class)))e.appendChild(document.createElement("br")),this.el.appendChild(e);else{for(const o of t){if(!o.value&&!o.class)continue;const t=document.createElement("span");t.innerText=o.value,t.style.color=o.color||"",o.class&&t.classList.add(o.class),e.appendChild(t)}this.el.appendChild(e)}}}scrollSelectionIntoView(){const e=document.getSelection()?.focusNode;if(!e||!this.el.contains(e))return;(e instanceof HTMLElement?e:e.parentElement)?.scrollIntoView({block:"nearest"})}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){let{startElement:e,endElement:t,startSelectionOffset:o,endSelectionOffset:i}=this.getStartAndEndSelection();return{start:this.findSelectionIndex(e,o),end:this.findSelectionIndex(t,i)}}findSelectionIndex(e,t){let o=0,i=rn(this.el),s=i.next(),n=!0;for(;!s.done&&s.value!==e;)s.value.hasChildNodes()||s.value.textContent&&(o+=s.value.textContent.length),("P"===s.value.nodeName||"DIV"===s.value.nodeName&&s.value!==this.el)&&(n?n=!1:o++),s=i.next();if(s.value!==e)return 0;if(s.value.hasChildNodes()){const e=[...s.value.childNodes].slice(0,t);o+=e.reduce(((t,o,i)=>{if(null!==o.textContent){let s=o.textContent.length;return"P"===o.nodeName&&i!==e.length-1&&s++,t+s}return t}),0)}else o+=t;return"P"!==e.nodeName||n||""!=e.textContent||o++,o}getStartAndEndSelection(){const e=document.getSelection();return{startElement:e.anchorNode||this.el,startSelectionOffset:e.anchorOffset,endElement:e.focusNode||this.el,endSelectionOffset:e.focusOffset}}getText(){let e="",t=rn(this.el),o=t.next(),i=!0;for(;!o.done;)o.value.hasChildNodes()||(e+=o.value.textContent),("P"===o.value.nodeName||"DIV"===o.value.nodeName&&o.value!==this.el)&&(i?i=!1:e+=me),o=t.next();return e}}Oi`
1098
1098
  .o-formula-assistant {
1099
1099
  .o-formula-assistant-head {
1100
1100
  background-color: #f2f2f2;
@@ -1159,7 +1159,7 @@
1159
1159
  pointer-events: none;
1160
1160
  }
1161
1161
  }
1162
- `;class If extends t.Component{static template="o-spreadsheet-Composer";static components={TextValueProvider:bf,FunctionDescriptionProvider:Sf};static defaultProps={inputStyle:""};composerRef=t.useRef("o_composer");contentHelper=new vf(this.composerRef.el);composerState=t.useState({positionStart:0,positionEnd:0});autoCompleteState=t.useState({showProvider:!1,values:[],selectedIndex:0});functionDescriptionState=t.useState({showDescription:!1,functionName:"",functionDescription:{},argToFocus:0});isKeyStillDown=!1;compositionActive=!1;get assistantStyle(){if(this.props.delimitation&&this.props.rect){const{x:e,y:t,height:o}=this.props.rect;let i={};return t>this.props.delimitation.height-(t+o)&&(i.top="-3px",i.transform="translate(0, -100%)"),e+300>this.props.delimitation.width&&(i.right="0px"),i.width="300px",Fi(i)}return Fi({width:"300px"})}shouldProcessInputEvents=!1;tokens=[];keyMapping={ArrowUp:this.processArrowKeys,ArrowDown:this.processArrowKeys,ArrowLeft:this.processArrowKeys,ArrowRight:this.processArrowKeys,Enter:this.processEnterKey,Escape:this.processEscapeKey,F2:()=>console.warn("Not implemented"),F4:this.processF4Key,Tab:e=>this.processTabKey(e)};setup(){t.onMounted((()=>{const e=this.composerRef.el;this.contentHelper.updateEl(e),this.processContent(),this.contentHelper.scrollSelectionIntoView()})),t.onWillUnmount((()=>{this.props.onComposerUnmounted?.()})),t.onPatched((()=>{this.isKeyStillDown||this.processContent()}))}processArrowKeys(e){if(this.env.model.getters.isSelectingForComposer())return this.functionDescriptionState.showDescription=!1,e.preventDefault(),e.stopPropagation(),void Dm(e,this.env.model.selection);const t=this.env.model.getters.getCurrentContent();"cellFocus"!==this.props.focus||this.autoCompleteState.showProvider||t.startsWith("=")?(e.stopPropagation(),this.handleArrowKeysForAutocomplete(e)):this.env.model.dispatch("STOP_EDITION")}handleArrowKeysForAutocomplete(e){["ArrowUp","ArrowDown"].includes(e.key)&&this.autoCompleteState.showProvider&&(e.preventDefault(),"ArrowUp"===e.key?(this.autoCompleteState.selectedIndex--,this.autoCompleteState.selectedIndex<0&&(this.autoCompleteState.selectedIndex=this.autoCompleteState.values.length-1)):this.autoCompleteState.selectedIndex=(this.autoCompleteState.selectedIndex+1)%this.autoCompleteState.values.length),this.updateCursorIfNeeded()}processTabKey(e){if(e.preventDefault(),e.stopPropagation(),this.autoCompleteState.showProvider){const e=this.autoCompleteState.values[this.autoCompleteState.selectedIndex]?.text;if(e)return void this.autoComplete(e)}else this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION");const t=e.shiftKey?"left":"right";this.env.model.dispatch("STOP_EDITION"),this.env.model.selection.moveAnchorCell(t,1)}processEnterKey(e){if(e.preventDefault(),e.stopPropagation(),e.altKey||e.ctrlKey){const e=this.contentHelper.getCurrentSelection(),t=this.env.model.getters.getCurrentContent(),o=t.slice(0,e.start)+me+t.slice(e.end);return this.env.model.dispatch("SET_CURRENT_CONTENT",{content:o,selection:{start:e.start+1,end:e.start+1}}),this.processContent(),void this.contentHelper.scrollSelectionIntoView()}if(this.isKeyStillDown=!1,this.autoCompleteState.showProvider){const e=this.autoCompleteState.values[this.autoCompleteState.selectedIndex]?.text;if(e)return void this.autoComplete(e)}this.env.model.dispatch("STOP_EDITION");const t=e.shiftKey?"up":"down";this.env.model.selection.moveAnchorCell(t,1)}processEscapeKey(){this.env.model.dispatch("STOP_EDITION",{cancel:!0})}processF4Key(){this.env.model.dispatch("CYCLE_EDITION_REFERENCES"),this.processContent()}onCompositionStart(){this.compositionActive=!0}onCompositionEnd(){this.compositionActive=!1}onKeydown(e){let t=this.keyMapping[e.key];t?t.call(this,e):(e.stopPropagation(),this.updateCursorIfNeeded())}updateCursorIfNeeded(){if(!this.env.model.getters.isSelectingForComposer()){const{start:e,end:t}=this.contentHelper.getCurrentSelection();this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:e,end:t}),this.isKeyStillDown=!0}}onInput(){"inactive"!==this.props.focus&&this.shouldProcessInputEvents&&(this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION"),this.env.model.dispatch("SET_CURRENT_CONTENT",{content:this.contentHelper.getText(),selection:this.contentHelper.getCurrentSelection()}))}onKeyup(e){if(this.isKeyStillDown=!1,"inactive"===this.props.focus||["Control","Alt","Shift","Tab","Enter","F4"].includes(e.key))return;if(this.autoCompleteState.showProvider&&["ArrowUp","ArrowDown"].includes(e.key))return;if(this.env.model.getters.isSelectingForComposer()&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return;if(e.preventDefault(),e.stopPropagation(),this.autoCompleteState.showProvider=!1,e.ctrlKey&&" "===e.key)return this.showAutocomplete(""),void this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION");const{start:t,end:o}=this.env.model.getters.getComposerSelection(),{start:i,end:s}=this.contentHelper.getCurrentSelection();i===t&&s===o||this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",this.contentHelper.getCurrentSelection()),this.processTokenAtCursor(),this.processContent()}showAutocomplete(e){this.autoCompleteState.showProvider=!0;let t=Object.entries(Ug.content).filter((([e,{hidden:t}])=>!t)).map((([e,{description:t}])=>({text:e,description:t})));t=e?"true"===e.toLowerCase()||"false"===e.toLowerCase()?[]:Ko(e,t,(e=>e.text)):t.sort(((e,t)=>e.text.localeCompare(t.text))),this.autoCompleteState.values=t.slice(0,10),this.autoCompleteState.selectedIndex=0}onMousedown(e){e.button>0||this.contentHelper.removeSelection()}onClick(){if(this.env.model.getters.isReadonly())return;const e=this.contentHelper.getCurrentSelection();this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION"),"inactive"===this.props.focus&&this.props.onComposerContentFocused(e),this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",e),this.processTokenAtCursor()}onBlur(){this.isKeyStillDown=!1}processContent(){if(this.compositionActive)return;const e=this.composerRef.el?.scrollTop||0;this.contentHelper.removeAll(),this.shouldProcessInputEvents=!1,"inactive"!==this.props.focus&&(this.contentHelper.el.focus(),this.contentHelper.selectRange(0,0));const t=this.getContentLines();if(0!==t.length&&0!==t.length[0]){this.contentHelper.setText(t);const{start:o,end:i}=this.env.model.getters.getComposerSelection();"inactive"!==this.props.focus&&this.contentHelper.selectRange(o,i),function(e,t){e&&(e.scrollTop=t)}(this.composerRef.el,e)}this.shouldProcessInputEvents=!0}getContentLines(){let e=this.env.model.getters.getCurrentContent();const t=e.startsWith("=")&&this.env.model.getters.getCurrentTokens().length>0;return""===e?[]:t&&"inactive"!==this.props.focus?this.splitHtmlContentIntoLines(this.getColoredTokens()):this.splitHtmlContentIntoLines([{value:e}])}getColoredTokens(){const e=this.env.model.getters.getCurrentTokens(),t=this.env.model.getters.getTokenAtCursor(),o=[],{end:i,start:s}=this.env.model.getters.getComposerSelection();for(const r of e){switch(r.type){case"OPERATOR":case"NUMBER":case"FUNCTION":case"COMMA":case"STRING":o.push({value:r.value,color:yf[r.type]||"#000"});break;case"REFERENCE":const{xc:e,sheetName:i}=Zo(r.value);o.push({value:r.value,color:this.rangeColor(e,i)||"#000"});break;case"SYMBOL":let s=r.value;["TRUE","FALSE"].includes(s.toUpperCase())?o.push({value:r.value,color:yf.NUMBER}):o.push({value:r.value,color:"#000"});break;case"LEFT_PAREN":case"RIGHT_PAREN":t&&["LEFT_PAREN","RIGHT_PAREN"].includes(t.type)&&t.parenIndex&&t.parenIndex===r.parenIndex?o.push({value:r.value,color:yf.MATCHING_PAREN}):o.push({value:r.value,color:yf[r.type]||"#000"});break;default:o.push({value:r.value,color:"#000"})}this.env.model.getters.showSelectionIndicator()&&i===s&&i===r.end&&(o[o.length-1].class=Ef)}return o}splitHtmlContentIntoLines(e){const t=[];let o=[];for(const i of e)if(i.value.includes(me)){const e=i.value.split(me),s=e.pop();for(const s of e)o.push({color:i.color,value:s}),t.push(o),o=[];o.push({...i,value:s})}else o.push(i);o.length&&t.push(o);const i=[];for(const e of t)e.every(this.isContentEmpty)?i.push([e[0]]):i.push(e.filter((e=>!this.isContentEmpty(e))));return i}isContentEmpty(e){return!(e.value||e.class)}rangeColor(e,t){if("inactive"===this.props.focus)return;const o=this.env.model.getters.getHighlights(),i=t?this.env.model.getters.getSheetIdByName(t):this.env.model.getters.getCurrentEditedCell().sheetId,s=o.find((t=>{if(t.sheetId!==i)return!1;let o=this.env.model.getters.getRangeFromSheetXC(i,e).zone;return o=1===yi(o)?this.env.model.getters.expandZone(i,o):o,hi(o,t.zone)}));return s&&s.color?s.color:void 0}processTokenAtCursor(){let e=this.env.model.getters.getCurrentContent();if(this.autoCompleteState.showProvider=!1,this.functionDescriptionState.showDescription=!1,e.startsWith("=")){const e=this.env.model.getters.getTokenAtCursor();if(e){const{xc:t}=Zo(e.value);if("FUNCTION"===e.type||"SYMBOL"===e.type&&!Bo.test(t))this.showAutocomplete(e.value);else if(e.functionContext&&"UNKNOWN"!==e.type){const t=e.functionContext,o=t.parent.toUpperCase(),i=Cf[o],s=t.argPosition;this.functionDescriptionState.functionName=o,this.functionDescriptionState.functionDescription=i,this.functionDescriptionState.argToFocus=i.getArgToFocus(s+1)-1,this.functionDescriptionState.showDescription=!0}}}}autoComplete(e){if(e){const t=this.env.model.getters.getTokenAtCursor();if(t){let o=t.end,i=t.end;["SYMBOL","FUNCTION"].includes(t.type)&&(o=t.start);const s=this.env.model.getters.getCurrentTokens();if(s.length){e+="(";const o=s.map((e=>e.start)).indexOf(t.start);if(o+1<s.length){"LEFT_PAREN"===s[o+1].type&&i++}}this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:o,end:i})}this.env.model.dispatch("REPLACE_COMPOSER_CURSOR_SELECTION",{text:e})}this.processTokenAtCursor()}}If.props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerContentFocused:Function,inputStyle:{type:String,optional:!0},rect:{type:Object,optional:!0},delimitation:{type:Object,optional:!0},onComposerUnmounted:{type:Function,optional:!0}};const Rf=3*.4*window.devicePixelRatio||1;Oi`
1162
+ `;class If extends t.Component{static template="o-spreadsheet-Composer";static components={TextValueProvider:bf,FunctionDescriptionProvider:Sf};static defaultProps={inputStyle:"",isDefaultFocus:!1};composerRef=t.useRef("o_composer");contentHelper=new vf(this.composerRef.el);composerState=t.useState({positionStart:0,positionEnd:0});autoCompleteState=t.useState({showProvider:!1,values:[],selectedIndex:0});functionDescriptionState=t.useState({showDescription:!1,functionName:"",functionDescription:{},argToFocus:0});isKeyStillDown=!1;compositionActive=!1;get assistantStyle(){if(this.props.delimitation&&this.props.rect){const{x:e,y:t,height:o}=this.props.rect;let i={};return t>this.props.delimitation.height-(t+o)&&(i.top="-3px",i.transform="translate(0, -100%)"),e+300>this.props.delimitation.width&&(i.right="0px"),i.width="300px",Fi(i)}return Fi({width:"300px"})}shouldProcessInputEvents=!1;tokens=[];keyMapping={ArrowUp:this.processArrowKeys,ArrowDown:this.processArrowKeys,ArrowLeft:this.processArrowKeys,ArrowRight:this.processArrowKeys,Enter:this.processEnterKey,Escape:this.processEscapeKey,F2:()=>console.warn("Not implemented"),F4:this.processF4Key,Tab:e=>this.processTabKey(e)};setup(){t.onMounted((()=>{const e=this.composerRef.el;this.props.isDefaultFocus&&this.env.focusableElement.setFocusableElement(e),this.contentHelper.updateEl(e),this.processContent(),this.contentHelper.scrollSelectionIntoView()})),t.onPatched((()=>{this.isKeyStillDown||this.processContent()}))}processArrowKeys(e){if(this.env.model.getters.isSelectingForComposer()||"inactive"===this.env.model.getters.getEditionMode())return this.functionDescriptionState.showDescription=!1,e.preventDefault(),e.stopPropagation(),void Dm(e,this.env.model.selection);const t=this.env.model.getters.getCurrentContent();"cellFocus"!==this.props.focus||this.autoCompleteState.showProvider||t.startsWith("=")?(e.stopPropagation(),this.handleArrowKeysForAutocomplete(e)):this.env.model.dispatch("STOP_EDITION")}handleArrowKeysForAutocomplete(e){["ArrowUp","ArrowDown"].includes(e.key)&&this.autoCompleteState.showProvider&&(e.preventDefault(),"ArrowUp"===e.key?(this.autoCompleteState.selectedIndex--,this.autoCompleteState.selectedIndex<0&&(this.autoCompleteState.selectedIndex=this.autoCompleteState.values.length-1)):this.autoCompleteState.selectedIndex=(this.autoCompleteState.selectedIndex+1)%this.autoCompleteState.values.length),this.updateCursorIfNeeded()}processTabKey(e){if(e.preventDefault(),e.stopPropagation(),"inactive"!==this.env.model.getters.getEditionMode()){if(this.autoCompleteState.showProvider){const e=this.autoCompleteState.values[this.autoCompleteState.selectedIndex]?.text;if(e)return void this.autoComplete(e)}else this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION");this.env.model.dispatch("STOP_EDITION")}const t=e.shiftKey?"left":"right";this.env.model.selection.moveAnchorCell(t,1)}processEnterKey(e){if(e.preventDefault(),e.stopPropagation(),e.altKey||e.ctrlKey){const e=this.contentHelper.getCurrentSelection(),t=this.env.model.getters.getCurrentContent(),o=t.slice(0,e.start)+me+t.slice(e.end);return this.env.model.dispatch("SET_CURRENT_CONTENT",{content:o,selection:{start:e.start+1,end:e.start+1}}),this.processContent(),void this.contentHelper.scrollSelectionIntoView()}if(this.isKeyStillDown=!1,this.autoCompleteState.showProvider){const e=this.autoCompleteState.values[this.autoCompleteState.selectedIndex]?.text;if(e)return void this.autoComplete(e)}this.env.model.dispatch("STOP_EDITION");const t=e.shiftKey?"up":"down";this.env.model.selection.moveAnchorCell(t,1)}processEscapeKey(){this.env.model.dispatch("STOP_EDITION",{cancel:!0})}processF4Key(){this.env.model.dispatch("CYCLE_EDITION_REFERENCES"),this.processContent()}onCompositionStart(){this.compositionActive=!0}onCompositionEnd(){this.compositionActive=!1}onKeydown(e){if("inactive"===this.env.model.getters.getEditionMode())return;let t=this.keyMapping[e.key];t?t.call(this,e):(e.stopPropagation(),this.updateCursorIfNeeded())}updateCursorIfNeeded(){if(!(this.env.model.getters.isSelectingForComposer()||"inactive"===this.env.model.getters.getEditionMode())){const{start:e,end:t}=this.contentHelper.getCurrentSelection();this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:e,end:t}),this.isKeyStillDown=!0}}onPaste(e){"inactive"!==this.env.model.getters.getEditionMode()&&e.stopPropagation()}onInput(e){if(!this.shouldProcessInputEvents)return;if("insertFromPaste"===e.inputType&&"inactive"===this.env.model.getters.getEditionMode())return;let t;if(e.stopPropagation(),t="inactive"===this.env.model.getters.getEditionMode()?e.data||"":this.contentHelper.getText(),"inactive"===this.props.focus)return this.props.onComposerCellFocused?.(t);this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION"),this.env.model.dispatch("SET_CURRENT_CONTENT",{content:t,selection:this.contentHelper.getCurrentSelection()})}onKeyup(e){if(this.isKeyStillDown=!1,"inactive"===this.props.focus||["Control","Alt","Shift","Tab","Enter","F4"].includes(e.key))return;if(this.autoCompleteState.showProvider&&["ArrowUp","ArrowDown"].includes(e.key))return;if(this.env.model.getters.isSelectingForComposer()&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return;if(e.preventDefault(),e.stopPropagation(),this.autoCompleteState.showProvider=!1,e.ctrlKey&&" "===e.key)return this.showAutocomplete(""),void this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION");const{start:t,end:o}=this.env.model.getters.getComposerSelection(),{start:i,end:s}=this.contentHelper.getCurrentSelection();i===t&&s===o||this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",this.contentHelper.getCurrentSelection()),this.processTokenAtCursor(),this.processContent()}showAutocomplete(e){this.autoCompleteState.showProvider=!0;let t=Object.entries(Ug.content).filter((([e,{hidden:t}])=>!t)).map((([e,{description:t}])=>({text:e,description:t})));t=e?"true"===e.toLowerCase()||"false"===e.toLowerCase()?[]:Ko(e,t,(e=>e.text)):t.sort(((e,t)=>e.text.localeCompare(t.text))),this.autoCompleteState.values=t.slice(0,10),this.autoCompleteState.selectedIndex=0}onMousedown(e){e.button>0||this.contentHelper.removeSelection()}onClick(){if(this.env.model.getters.isReadonly())return;const e=this.contentHelper.getCurrentSelection();this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION"),this.props.onComposerContentFocused(),this.props.focus,this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",e),this.processTokenAtCursor()}onBlur(){this.isKeyStillDown=!1}processContent(){if(this.compositionActive)return;const e=this.composerRef.el?.scrollTop||0;this.contentHelper.removeAll(),this.shouldProcessInputEvents=!1,"inactive"!==this.props.focus&&(this.contentHelper.el.focus(),this.contentHelper.selectRange(0,0));const t=this.getContentLines();if(0!==t.length&&0!==t.length[0]){this.contentHelper.setText(t);const{start:o,end:i}=this.env.model.getters.getComposerSelection();"inactive"!==this.props.focus&&this.contentHelper.selectRange(o,i),function(e,t){e&&(e.scrollTop=t)}(this.composerRef.el,e)}this.shouldProcessInputEvents=!0}getContentLines(){let e=this.env.model.getters.getCurrentContent();const t=e.startsWith("=")&&this.env.model.getters.getCurrentTokens().length>0;return""===e?[]:t&&"inactive"!==this.props.focus?this.splitHtmlContentIntoLines(this.getColoredTokens()):this.splitHtmlContentIntoLines([{value:e}])}getColoredTokens(){const e=this.env.model.getters.getCurrentTokens(),t=this.env.model.getters.getTokenAtCursor(),o=[],{end:i,start:s}=this.env.model.getters.getComposerSelection();for(const n of e){switch(n.type){case"OPERATOR":case"NUMBER":case"FUNCTION":case"COMMA":case"STRING":o.push({value:n.value,color:yf[n.type]||"#000"});break;case"REFERENCE":const{xc:e,sheetName:i}=Zo(n.value);o.push({value:n.value,color:this.rangeColor(e,i)||"#000"});break;case"SYMBOL":let s=n.value;["TRUE","FALSE"].includes(s.toUpperCase())?o.push({value:n.value,color:yf.NUMBER}):o.push({value:n.value,color:"#000"});break;case"LEFT_PAREN":case"RIGHT_PAREN":t&&["LEFT_PAREN","RIGHT_PAREN"].includes(t.type)&&t.parenIndex&&t.parenIndex===n.parenIndex?o.push({value:n.value,color:yf.MATCHING_PAREN}):o.push({value:n.value,color:yf[n.type]||"#000"});break;default:o.push({value:n.value,color:"#000"})}this.env.model.getters.showSelectionIndicator()&&i===s&&i===n.end&&(o[o.length-1].class=Ef)}return o}splitHtmlContentIntoLines(e){const t=[];let o=[];for(const i of e)if(i.value.includes(me)){const e=i.value.split(me),s=e.pop();for(const s of e)o.push({color:i.color,value:s}),t.push(o),o=[];o.push({...i,value:s})}else o.push(i);o.length&&t.push(o);const i=[];for(const e of t)e.every(this.isContentEmpty)?i.push([e[0]]):i.push(e.filter((e=>!this.isContentEmpty(e))));return i}isContentEmpty(e){return!(e.value||e.class)}rangeColor(e,t){if("inactive"===this.props.focus)return;const o=this.env.model.getters.getHighlights(),i=t?this.env.model.getters.getSheetIdByName(t):this.env.model.getters.getCurrentEditedCell()?.sheetId,s=o.find((t=>{if(t.sheetId!==i)return!1;let o=this.env.model.getters.getRangeFromSheetXC(i,e).zone;return o=1===yi(o)?this.env.model.getters.expandZone(i,o):o,hi(o,t.zone)}));return s&&s.color?s.color:void 0}processTokenAtCursor(){let e=this.env.model.getters.getCurrentContent();if(this.autoCompleteState.showProvider=!1,this.functionDescriptionState.showDescription=!1,e.startsWith("=")){const e=this.env.model.getters.getTokenAtCursor();if(e){const{xc:t}=Zo(e.value);if("FUNCTION"===e.type||"SYMBOL"===e.type&&!Bo.test(t))this.showAutocomplete(e.value);else if(e.functionContext&&"UNKNOWN"!==e.type){const t=e.functionContext,o=t.parent.toUpperCase(),i=Cf[o],s=t.argPosition;this.functionDescriptionState.functionName=o,this.functionDescriptionState.functionDescription=i,this.functionDescriptionState.argToFocus=i.getArgToFocus(s+1)-1,this.functionDescriptionState.showDescription=!0}}}}autoComplete(e){if(e){const t=this.env.model.getters.getTokenAtCursor();if(t){let o=t.end,i=t.end;["SYMBOL","FUNCTION"].includes(t.type)&&(o=t.start);const s=this.env.model.getters.getCurrentTokens();if(s.length){e+="(";const o=s.map((e=>e.start)).indexOf(t.start);if(o+1<s.length){"LEFT_PAREN"===s[o+1].type&&i++}}this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:o,end:i})}this.env.model.dispatch("REPLACE_COMPOSER_CURSOR_SELECTION",{text:e})}this.processTokenAtCursor()}}If.props={inputStyle:{type:String,optional:!0},rect:{type:Object,optional:!0},delimitation:{type:Object,optional:!0},focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerCellFocused:{type:Function,optional:!0},onComposerContentFocused:Function,isDefaultFocus:{type:Boolean,optional:!0}};const Rf=3*.4*window.devicePixelRatio||1;Oi`
1163
1163
  div.o-grid-composer {
1164
1164
  z-index: ${ue.GridComposer};
1165
1165
  box-sizing: border-box;
@@ -1180,7 +1180,7 @@
1180
1180
  padding: 6px 7px;
1181
1181
  border-radius: 4px;
1182
1182
  }
1183
- `;class Tf extends t.Component{static template="o-spreadsheet-GridComposer";static components={Composer:If};gridComposerRef;zone;rect;isCellReferenceVisible;composerState;setup(){this.gridComposerRef=t.useRef("gridComposer"),this.composerState=t.useState({rect:void 0,delimitation:void 0});const{sheetId:e,col:o,row:i}=this.env.model.getters.getActivePosition();this.zone=this.env.model.getters.expandZone(e,wi({col:o,row:i})),this.rect=this.env.model.getters.getVisibleRect(this.zone),this.isCellReferenceVisible=!1,t.onMounted((()=>{const e=this.gridComposerRef.el;this.composerState.rect={x:this.rect.x,y:this.rect.y,width:e.clientWidth,height:e.clientHeight},this.composerState.delimitation={width:e.parentElement.clientWidth,height:e.parentElement.clientHeight}})),t.onWillUpdateProps((()=>{if(this.isCellReferenceVisible)return;const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone();vt(this.env.model.getters.getVisibleRect(t),this.rect)&&e===this.env.model.getters.getCurrentEditedCell().sheetId||(this.isCellReferenceVisible=!0)}))}get shouldDisplayCellReference(){return this.isCellReferenceVisible}get cellReference(){const{col:e,row:t,sheetId:o}=this.env.model.getters.getCurrentEditedCell();return`${o!==this.env.model.getters.getActiveSheetId()?$e(this.env.model.getters.getSheetName(o))+"!":""}${Gt(e,t)}`}get cellReferenceStyle(){const{x:e,y:t}=this.rect;return Fi({left:e-Rf+"px",top:t-28+"px"})}get containerStyle(){const e=this.env.model.getters.getCurrentContent().startsWith("="),t=this.env.model.getters.getActiveCell(),o=this.env.model.getters.getActivePosition(),i=this.env.model.getters.getCellComputedStyle(o),{x:s,y:r,width:n,height:a}=this.rect,l=!e&&i.fillColor||"#ffffff",c=!e&&i.textColor||"#000000",h=!e&&i.fontSize||10,d=!e&&i.bold?"bold":void 0,u=!e&&i.italic?"italic":"normal",g=e?"none":Mi(i);let p="left";return e||(p=i.align||t.defaultAlign),Fi({left:s-1+"px",top:`${r}px`,"min-width":`${n+1}px`,"min-height":`${a+1}px`,background:l,color:c,"font-size":`${je(h)}px`,"font-weight":d,"font-style":u,"text-decoration":g,"text-align":p})}get composerStyle(){const e=this.props.gridDims.height-this.rect.y;return Fi({"max-width":`${this.props.gridDims.width-this.rect.x}px`,"max-height":`${e}px`})}}Tf.props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerUnmounted:Function,onComposerContentFocused:Function,gridDims:Object};const Af=Oi`
1183
+ `;class Tf extends t.Component{static template="o-spreadsheet-GridComposer";static components={Composer:If};rect=this.defaultRect;isEditing=!1;isCellReferenceVisible;get defaultRect(){return{x:0,y:0,width:0,height:0}}setup(){t.onWillUpdateProps((()=>{this.updateComponentPosition(),this.updateCellReferenceVisibility()}))}get shouldDisplayCellReference(){return this.isCellReferenceVisible}get cellReference(){if(!this.env.model.getters.getCurrentEditedCell())return"";const{col:e,row:t,sheetId:o}=this.env.model.getters.getCurrentEditedCell();return`${o!==this.env.model.getters.getActiveSheetId()?$e(this.env.model.getters.getSheetName(o))+"!":""}${Gt(e,t)}`}get cellReferenceStyle(){const{x:e,y:t}=this.rect;return Fi({left:e-Rf+"px",top:t-28+"px"})}get composerProps(){const{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.props.focus,isDefaultFocus:!0,onComposerContentFocused:this.props.onComposerContentFocused,onComposerCellFocused:this.props.onComposerCellFocused}}get containerStyle(){if("inactive"===this.env.model.getters.getEditionMode()||!this.rect)return"\n position: absolute;\n z-index: -1000;\n ";const e=this.env.model.getters.getCurrentContent().startsWith("="),t=this.env.model.getters.getActiveCell(),o=this.env.model.getters.getActivePosition(),i=this.env.model.getters.getCellComputedStyle(o),{x:s,y:n,width:r,height:a}=this.rect,l=!e&&i.fillColor||"#ffffff",c=!e&&i.textColor||"#000000",h=!e&&i.fontSize||10,d=!e&&i.bold?"bold":void 0,u=!e&&i.italic?"italic":"normal",g=e?"none":Mi(i);let p="left";e||(p=i.align||t.defaultAlign);const m=this.props.gridDims.height-this.rect.y;return Fi({left:s-1+"px",top:`${n}px`,"min-width":`${r+1}px`,"min-height":`${a+1}px`,"max-width":`${this.props.gridDims.width-this.rect.x}px`,"max-height":`${m}px`,background:l,color:c,"font-size":`${je(h)}px`,"font-weight":d,"font-style":u,"text-decoration":g,"text-align":p})}updateComponentPosition(){const e="inactive"!==this.env.model.getters.getEditionMode();if(this.isEditing!==e){if(this.isEditing=e,!e)return this.rect=this.defaultRect,void this.env.focusableElement.focus();const t=this.env.model.getters.getActivePosition(),o=this.env.model.getters.expandZone(t.sheetId,wi(t));this.rect=this.env.model.getters.getVisibleRect(o)}}updateCellReferenceVisibility(){if(this.isCellReferenceVisible||"inactive"===this.env.model.getters.getEditionMode())return;const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone();vt(this.env.model.getters.getVisibleRect(t),this.rect)&&e===this.env.model.getters.getCurrentEditedCell().sheetId||(this.isCellReferenceVisible=!0)}}Tf.props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerContentFocused:Function,gridDims:Object,onComposerCellFocused:Function};const Af=Oi`
1184
1184
  .o-filter-icon {
1185
1185
  color: ${T};
1186
1186
  position: absolute;
@@ -1194,7 +1194,7 @@
1194
1194
  background: ${T};
1195
1195
  color: #fff;
1196
1196
  }
1197
- `;class Of extends t.Component{static style=Af;static template="o-spreadsheet-FilterIcon";get style(){const{x:e,y:t}=this.props.position;return`top:${t}px;left:${e}px`}}Of.props={position:Object,isActive:Boolean,onClick:Function};const Mf=Oi``;class Nf extends t.Component{static style=Mf;static template="o-spreadsheet-FilterIconsOverlay";static components={FilterIcon:Of};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}),r=this.getIconVerticalPosition(o,s);return{x:i.end-W+this.props.gridPosition.x-2-1,y:r+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 _f(e,t){return{...t,...Df(e,{x:t.x,y:t.y})}}function Ff(e,t){return{...t,...Lf(e,{x:t.x,y:t.y})}}function Df(e,{x:t,y:o}){const{x:i,y:s}=e.getMainViewportCoordinates(),{scrollX:r,scrollY:n}=e.getActiveSheetScrollInfo();return{x:t=t<i?t:t-r,y:o=o<s?o:o-n}}function Lf(e,{x:t,y:o}){const{x:i,y:s}=e.getMainViewportCoordinates(),{scrollX:r,scrollY:n}=e.getActiveSheetScrollInfo();return{x:t=i&&t<i?t:t+r,y:o=s&&o<s?o:o+n}}function kf(e,t,o){return Math.min(Math.max(e,t),o)}Nf.props={gridPosition:{type:Object,optional:!0}};const Pf=5;function Uf(e,t,o){return o.map((e=>zf(t,e))).filter((o=>function(e,t,o){const{x:i,y:s}=e.getMainViewportCoordinates(),r=[];switch(o.axisType){case"top":case"bottom":case"vCenter":if(t.y<s)return!0;r.push({x:t.x,y:o.position}),r.push({x:t.x+t.width,y:o.position});break;case"left":case"right":case"hCenter":if(t.x<i)return!0;r.push({x:o.position,y:t.y}),r.push({x:o.position,y:t.y+t.height})}return r.some(e.isPositionVisible)}(e,t,o))).map((o=>function(e,t,o){const i=_f(e,t);return zf(i,o.axisType)}(e,t,o)))}function Vf(e,t,o,i,s){const r=Uf(e,t,o);let n;for(const t of i){const o=Uf(e,t,s);for(const e of r)for(const i of o){if(a=e.position,l=i.position,!(Math.abs(a-l)<=Pf))continue;const o=e.position-i.position;n&&o===n.snapOffset?n.matchedFigIds.push(t.id):(!n||Math.abs(o)<=Math.abs(n.snapOffset))&&(n={matchedFigIds:[t.id],snapOffset:o,snappedAxisType:e.axisType,position:i.position})}}var a,l;return n}function zf(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}}Oi`
1197
+ `;class Of extends t.Component{static style=Af;static template="o-spreadsheet-FilterIcon";get style(){const{x:e,y:t}=this.props.position;return`top:${t}px;left:${e}px`}}Of.props={position:Object,isActive:Boolean,onClick:Function};const Mf=Oi``;class Nf extends t.Component{static style=Mf;static template="o-spreadsheet-FilterIconsOverlay";static components={FilterIcon:Of};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 _f(e,t){return{...t,...Df(e,{x:t.x,y:t.y})}}function Ff(e,t){return{...t,...Lf(e,{x:t.x,y:t.y})}}function Df(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 Lf(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 kf(e,t,o){return Math.min(Math.max(e,t),o)}Nf.props={gridPosition:{type:Object,optional:!0}};const Pf=5;function Uf(e,t,o){return o.map((e=>zf(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=_f(e,t);return zf(i,o.axisType)}(e,t,o)))}function Vf(e,t,o,i,s){const n=Uf(e,t,o);let r;for(const t of i){const o=Uf(e,t,s);for(const e of n)for(const i of o){if(a=e.position,l=i.position,!(Math.abs(a-l)<=Pf))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 zf(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}}Oi`
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 Bf extends t.Component{static template="o-spreadsheet-FiguresContainer";static components={FigureComponent:df};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 Fi({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(),r=["bottomRight","topRight"].includes(e)?i:0,n=t-r,a=["bottomRight","bottomLeft"].includes(e)?s:0;return{x:r,y:a,width:n,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 Fi({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:r,y:n}=_f(this.env.model.getters,e),a={...e,x:r,y:n};uf((t=>{const o=this.env.model.getters,r=function({x:e,y:t},{x:o,y:i},s,{x:r,y:n},{maxX:a,maxY:l},{scrollX:c,scrollY:h}){const d=r?0:-c,u=n?0:-h,g=e-o,p=kf(s.x+g,d,a-s.width-c),m=t-i,f=kf(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()),n=this.getOtherFigures(e.id),l=function(e,t,o){const i={...t},s=Vf(e,i,["hCenter","right","left"],o,["hCenter","right","left"]),r=Vf(e,i,["vCenter","bottom","top"],o,["vCenter","bottom","top"]),{y:n,x:a}=e.getMainViewportCoordinates(),{scrollY:l,scrollX:c}=e.getActiveSheetScrollInfo();if(r){i.y-=r.snapOffset;const e=t.y<n,o=i.y<n;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:r}}(o,Ff(o,r),n);this.dnd.draggedFigure=_f(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}=Ff(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:r,y:n}=_f(this.env.model.getters,e),a={...e,x:r,y:n},l=Gn.get(e.tag).keepRatio||!1,c=Gn.get(e.tag).minFigSize||80;uf((i=>{const r={x:i.clientX,y:i.clientY},n=function(e,t,o,{x:i,y:s},{x:r,y:n},a,l){let{x:c,y:h,width:d,height:u}=e;if(a&&0!=t&&0!=o){const a=Math.min(t*(r-i),e.width-l),g=Math.min(o*(n-s),e.height-l),p=Math.min(a/e.width,g/e.height);d=e.width*(1-p),u=e.height*(1-p),t<0&&(c=e.x+e.width*p),o<0&&(h=e.y+e.height*p)}else{const a=Math.max(t*(i-r),l-e.width),g=Math.max(o*(s-n),l-e.height);d=e.width+a,u=e.height+g,t<0&&(c=e.x-a),o<0&&(h=e.y-g)}return c<0&&(d+=c,c=0),h<0&&(u+=h,h=0),{...e,x:c,y:h,width:d,height:u}}(a,t,o,r,s,l,c),h=this.getOtherFigures(e.id),d=function(e,t,o,i,s){const r={...i},n=Vf(e,r,[-1===t?"left":"right"],s,["right","left"]);n&&(1===t?r.width-=n.snapOffset:-1===t&&(r.x-=n.snapOffset,r.width+=n.snapOffset));const a=Vf(e,r,[-1===o?"top":"bottom"],s,["bottom","top"]);return a&&(1===o?r.height-=a.snapOffset:-1===o&&(r.y-=a.snapOffset,r.height+=a.snapOffset)),r.x=Math.round(r.x),r.y=Math.round(r.y),r.height=Math.round(r.height),r.width=Math.round(r.width),{snappedFigure:r,verticalSnapLine:n,horizontalSnapLine:a}}(this.env.model.getters,t,o,n,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:r}=Ff(this.env.model.getters,this.dnd.draggedFigure);const n={x:s,y:r};t&&(n.width=this.dnd.draggedFigure.width),o&&(n.height=this.dnd.draggedFigure.height),this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:e.id,...n}),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?"":Fi({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=_f(this.env.model.getters,e),o=this.getFigureContainer(e);return hr(t,this.getContainerRect(o))})).filter(dt),o=function(...e){return ur(li(...e.map(dr)))}(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)?Fi({top:e.position-t.y+"px",left:"0px",width:"100%"}):Fi({top:"0px",left:e.position-t.x+"px",height:"100%"}):""}}function Hf(e,o,i){let s={col:void 0,row:void 0};const{Date:r}=window;let n=0,a=0,l=0;function c(){return{col:e.model.getters.getColIndex(n),row:e.model.getters.getRowIndex(a)}}const{pause:h,resume:d}=function(e,o){let i;const{setInterval:s,clearInterval:r}=window;return t.useEffect((()=>(i=s(e,o),()=>r(i))),(()=>[o])),{pause:()=>{r(i),i=void 0},resume:()=>{void 0===i&&(i=s(e,o))}}}((function(){const{col:e,row:t}=c(),o=r.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&&(n=e.offsetX,a=e.offsetY,l=r.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}Bf.props={onFigureDeleted:Function};class $f extends t.Component{static template="o-spreadsheet-GridOverlay";static components={FiguresContainer:Bf};static defaultProps={onCellHovered:()=>{},onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{},onFigureDeleted:()=>{}};gridOverlay;setup(){this.gridOverlay=t.useRef("gridOverlay"),Hf(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,r=null;function n(e){1===e.touches.length&&(s=e.touches[0].clientX,r=e.touches[0].clientY)}function a(){s=null,r=null}function l(e){if(1!==e.touches.length)return;i()&&(e.preventDefault(),e.stopPropagation());const t=e.touches[0].clientX,n=e.touches[0].clientY;o(s-t,r-n),s=t,r=n}t.onMounted((()=>{e.el.addEventListener("touchstart",n),e.el.addEventListener("touchend",a),e.el.addEventListener("touchmove",l)})),t.onWillUnmount((()=>{e.el.removeEventListener("touchstart",n),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:ar(e)})}onDoubleClick(e){const[t,o]=this.getCartesianCoordinates(e);this.props.onCellDoubleClicked(t,o)}onContextMenu(e){e.preventDefault();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)]}}$f.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 Wf extends t.Component{static template="o-spreadsheet-GridPopover";static components={Popover:gr};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}}}}Wf.props={hoveredCell:Object,onClosePopover:Function,onMouseWheel:Function,gridRect:Object};class Gf 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,r=this._getMaxSize();uf((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>r&&(this.state.draggerLinePosition=r,this.state.delta=r-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;gf(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,ar(e)),this.lastSelectedElementIndex=t;gf(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(ar(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)}}Oi`
1210
+ `;class Bf extends t.Component{static template="o-spreadsheet-FiguresContainer";static components={FigureComponent:df};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 Fi({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 Fi({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}=_f(this.env.model.getters,e),a={...e,x:n,y:r};uf((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=kf(s.x+g,d,a-s.width-c),m=t-i,f=kf(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=Vf(e,i,["hCenter","right","left"],o,["hCenter","right","left"]),n=Vf(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,Ff(o,n),r);this.dnd.draggedFigure=_f(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}=Ff(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}=_f(this.env.model.getters,e),a={...e,x:n,y:r},l=Gr.get(e.tag).keepRatio||!1,c=Gr.get(e.tag).minFigSize||80;uf((i=>{const n={x:i.clientX,y:i.clientY},r=function(e,t,o,{x:i,y:s},{x:n,y:r},a,l){let{x:c,y:h,width:d,height:u}=e;if(a&&0!=t&&0!=o){const a=Math.min(t*(n-i),e.width-l),g=Math.min(o*(r-s),e.height-l),p=Math.min(a/e.width,g/e.height);d=e.width*(1-p),u=e.height*(1-p),t<0&&(c=e.x+e.width*p),o<0&&(h=e.y+e.height*p)}else{const a=Math.max(t*(i-n),l-e.width),g=Math.max(o*(s-r),l-e.height);d=e.width+a,u=e.height+g,t<0&&(c=e.x-a),o<0&&(h=e.y-g)}return c<0&&(d+=c,c=0),h<0&&(u+=h,h=0),{...e,x:c,y:h,width:d,height:u}}(a,t,o,n,s,l,c),h=this.getOtherFigures(e.id),d=function(e,t,o,i,s){const n={...i},r=Vf(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=Vf(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}=Ff(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?"":Fi({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=_f(this.env.model.getters,e),o=this.getFigureContainer(e);return dn(t,this.getContainerRect(o))})).filter(dt),o=function(...e){return gn(li(...e.map(un)))}(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)?Fi({top:e.position-t.y+"px",left:"0px",width:"100%"}):Fi({top:"0px",left:e.position-t.x+"px",height:"100%"}):""}}function Hf(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}Bf.props={onFigureDeleted:Function};class $f extends t.Component{static template="o-spreadsheet-GridOverlay";static components={FiguresContainer:Bf};static defaultProps={onCellHovered:()=>{},onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{},onFigureDeleted:()=>{}};gridOverlay;setup(){this.gridOverlay=t.useRef("gridOverlay"),Hf(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:ln(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)]}}$f.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 Wf extends t.Component{static template="o-spreadsheet-GridPopover";static components={Popover:pn};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}}}}Wf.props={hoveredCell:Object,onClosePopover:Function,onMouseWheel:Function,gridRect:Object};class Gf 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();uf((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;gf(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,ln(e)),this.lastSelectedElementIndex=t;gf(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(ln(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)}}Oi`
1211
1211
  .o-col-resizer {
1212
1212
  position: absolute;
1213
1213
  top: 0;
@@ -1266,7 +1266,7 @@
1266
1266
  top: calc(${V}px / 2 - ${U}px / 2);
1267
1267
  }
1268
1268
  }
1269
- `,Gf.props={onOpenContextMenu:Function};class qf extends Gf{static template="o-spreadsheet-ColResizer";colResizerRef;setup(){super.setup(),this.colResizerRef=t.useRef("colResizer"),this.PADDING=15,this.MAX_SIZE_MARGIN=90,this.MIN_ELEMENT_SIZE=5}_getEvOffset(e){return e.offsetX}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().left}_getClientPosition(e){return e.clientX}_getElementIndex(e){return this.env.model.getters.getColIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().left}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().right}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollCol(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getColDimensionsInViewport(this.env.model.getters.getActiveSheetId(),e)}_getElementSize(e){return this.env.model.getters.getColSize(this.env.model.getters.getActiveSheetId(),e)}_getMaxSize(){return this.colResizerRef.el.clientWidth}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),o=this.env.model.getters.getActiveCols();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"COL",sheetId:this.env.model.getters.getActiveSheetId(),elements:o.has(e)?[...o]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),o=this._getSelectedZoneEnd();for(let i=t;i<=o;i++)e.push(i);const i=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"COL",base:this.state.base,elements:e,position:this.state.position});!i.isSuccessful&&i.reasons.includes(2)&&this.env.raiseError(an)}_selectElement(e,t){this.env.model.selection.selectColumn(e,t?"newAnchor":"overrideSelection")}_increaseSelection(e){this.env.model.selection.selectColumn(e,"updateAnchor")}_fitElementSize(e){const t=this.env.model.getters.getActiveCols();this.env.model.dispatch("AUTORESIZE_COLUMNS",{sheetId:this.env.model.getters.getActiveSheetId(),cols:t.has(e)?[...t]:[e]})}_getType(){return"COL"}_getActiveElements(){return this.env.model.getters.getActiveCols()}_getPreviousVisibleElement(e){const t=this.env.model.getters.getActiveSheetId();let o;for(o=e-1;o>=0&&this.env.model.getters.isColHidden(t,o);o--);return o}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),elements:e,dimension:"COL"})}unhideStyleValue(e){return this._getDimensionsInViewport(e).start}}Oi`
1269
+ `,Gf.props={onOpenContextMenu:Function};class qf extends Gf{static template="o-spreadsheet-ColResizer";colResizerRef;setup(){super.setup(),this.colResizerRef=t.useRef("colResizer"),this.PADDING=15,this.MAX_SIZE_MARGIN=90,this.MIN_ELEMENT_SIZE=5}_getEvOffset(e){return e.offsetX}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().left}_getClientPosition(e){return e.clientX}_getElementIndex(e){return this.env.model.getters.getColIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().left}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().right}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollCol(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getColDimensionsInViewport(this.env.model.getters.getActiveSheetId(),e)}_getElementSize(e){return this.env.model.getters.getColSize(this.env.model.getters.getActiveSheetId(),e)}_getMaxSize(){return this.colResizerRef.el.clientWidth}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),o=this.env.model.getters.getActiveCols();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"COL",sheetId:this.env.model.getters.getActiveSheetId(),elements:o.has(e)?[...o]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),o=this._getSelectedZoneEnd();for(let i=t;i<=o;i++)e.push(i);const i=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"COL",base:this.state.base,elements:e,position:this.state.position});!i.isSuccessful&&i.reasons.includes(2)&&this.env.raiseError(ar)}_selectElement(e,t){this.env.model.selection.selectColumn(e,t?"newAnchor":"overrideSelection")}_increaseSelection(e){this.env.model.selection.selectColumn(e,"updateAnchor")}_fitElementSize(e){const t=this.env.model.getters.getActiveCols();this.env.model.dispatch("AUTORESIZE_COLUMNS",{sheetId:this.env.model.getters.getActiveSheetId(),cols:t.has(e)?[...t]:[e]})}_getType(){return"COL"}_getActiveElements(){return this.env.model.getters.getActiveCols()}_getPreviousVisibleElement(e){const t=this.env.model.getters.getActiveSheetId();let o;for(o=e-1;o>=0&&this.env.model.getters.isColHidden(t,o);o--);return o}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),elements:e,dimension:"COL"})}unhideStyleValue(e){return this._getDimensionsInViewport(e).start}}Oi`
1270
1270
  .o-row-resizer {
1271
1271
  position: absolute;
1272
1272
  top: ${F}px;
@@ -1327,7 +1327,7 @@
1327
1327
  background-color: lightgrey;
1328
1328
  }
1329
1329
  }
1330
- `,qf.props={onOpenContextMenu:Function};class Zf extends Gf{static template="o-spreadsheet-RowResizer";setup(){super.setup(),this.rowResizerRef=t.useRef("rowResizer"),this.PADDING=5,this.MAX_SIZE_MARGIN=60,this.MIN_ELEMENT_SIZE=10}rowResizerRef;_getEvOffset(e){return e.offsetY}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().top}_getClientPosition(e){return e.clientY}_getElementIndex(e){return this.env.model.getters.getRowIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().top}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().bottom}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollRow(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getRowDimensionsInViewport(this.env.model.getters.getActiveSheetId(),e)}_getElementSize(e){return this.env.model.getters.getRowSize(this.env.model.getters.getActiveSheetId(),e)}_getMaxSize(){return this.rowResizerRef.el.clientHeight}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),o=this.env.model.getters.getActiveRows();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"ROW",sheetId:this.env.model.getters.getActiveSheetId(),elements:o.has(e)?[...o]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),o=this._getSelectedZoneEnd();for(let i=t;i<=o;i++)e.push(i);const i=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",base:this.state.base,elements:e,position:this.state.position});!i.isSuccessful&&i.reasons.includes(2)&&this.env.raiseError(an)}_selectElement(e,t){this.env.model.selection.selectRow(e,t?"newAnchor":"overrideSelection")}_increaseSelection(e){this.env.model.selection.selectRow(e,"updateAnchor")}_fitElementSize(e){const t=this.env.model.getters.getActiveRows();this.env.model.dispatch("AUTORESIZE_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),rows:t.has(e)?[...t]:[e]})}_getType(){return"ROW"}_getActiveElements(){return this.env.model.getters.getActiveRows()}_getPreviousVisibleElement(e){const t=this.env.model.getters.getActiveSheetId();let o;for(o=e-1;o>=0&&this.env.model.getters.isRowHidden(t,o);o--);return o}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",elements:e})}unhideStyleValue(e){return this._getDimensionsInViewport(e).start}}Oi`
1330
+ `,qf.props={onOpenContextMenu:Function};class Zf extends Gf{static template="o-spreadsheet-RowResizer";setup(){super.setup(),this.rowResizerRef=t.useRef("rowResizer"),this.PADDING=5,this.MAX_SIZE_MARGIN=60,this.MIN_ELEMENT_SIZE=10}rowResizerRef;_getEvOffset(e){return e.offsetY}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().top}_getClientPosition(e){return e.clientY}_getElementIndex(e){return this.env.model.getters.getRowIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().top}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().bottom}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollRow(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getRowDimensionsInViewport(this.env.model.getters.getActiveSheetId(),e)}_getElementSize(e){return this.env.model.getters.getRowSize(this.env.model.getters.getActiveSheetId(),e)}_getMaxSize(){return this.rowResizerRef.el.clientHeight}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),o=this.env.model.getters.getActiveRows();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"ROW",sheetId:this.env.model.getters.getActiveSheetId(),elements:o.has(e)?[...o]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),o=this._getSelectedZoneEnd();for(let i=t;i<=o;i++)e.push(i);const i=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",base:this.state.base,elements:e,position:this.state.position});!i.isSuccessful&&i.reasons.includes(2)&&this.env.raiseError(ar)}_selectElement(e,t){this.env.model.selection.selectRow(e,t?"newAnchor":"overrideSelection")}_increaseSelection(e){this.env.model.selection.selectRow(e,"updateAnchor")}_fitElementSize(e){const t=this.env.model.getters.getActiveRows();this.env.model.dispatch("AUTORESIZE_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),rows:t.has(e)?[...t]:[e]})}_getType(){return"ROW"}_getActiveElements(){return this.env.model.getters.getActiveRows()}_getPreviousVisibleElement(e){const t=this.env.model.getters.getActiveSheetId();let o;for(o=e-1;o>=0&&this.env.model.getters.isRowHidden(t,o);o--);return o}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",elements:e})}unhideStyleValue(e){return this._getDimensionsInViewport(e).start}}Oi`
1331
1331
  .o-overlay {
1332
1332
  .all {
1333
1333
  position: absolute;
@@ -1338,7 +1338,7 @@
1338
1338
  height: ${F}px;
1339
1339
  }
1340
1340
  }
1341
- `,Zf.props={onOpenContextMenu:Function};class jf extends t.Component{static template="o-spreadsheet-HeadersOverlay";static components={ColResizer:qf,RowResizer:Zf};selectAll(){this.env.model.selection.selectAll()}}function Yf(e,o,i){const s=t.useRef(e);t.useEffect((function(){const e=s.el,t=window.devicePixelRatio||1,r=e.getContext("2d",{alpha:!1}),n={ctx:r,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;`),r.translate(-m,-m),r.scale(t,t),o.drawGrid(n)}))}function Xf(e){function t(e,t){return e*(0===t?1:k)}return o=>{const i=t(o.shiftKey&&!nr()?o.deltaY:o.deltaX,o.deltaMode),s=t(o.shiftKey&&!nr()?o.deltaX:o.deltaY,o.deltaMode);e(i,s)}}jf.props={onOpenContextMenu:Function},Oi`
1341
+ `,Zf.props={onOpenContextMenu:Function};class jf extends t.Component{static template="o-spreadsheet-HeadersOverlay";static components={ColResizer:qf,RowResizer:Zf};selectAll(){this.env.model.selection.selectAll()}}function Yf(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 Xf(e){function t(e,t){return e*(0===t?1:k)}return o=>{const i=t(o.shiftKey&&!an()?o.deltaY:o.deltaX,o.deltaMode),s=t(o.shiftKey&&!an()?o.deltaX:o.deltaY,o.deltaMode);e(i,s)}}jf.props={onOpenContextMenu:Function},Oi`
1342
1342
  .o-border {
1343
1343
  position: absolute;
1344
1344
  &:hover {
@@ -1348,7 +1348,7 @@
1348
1348
  .o-moving {
1349
1349
  cursor: grabbing;
1350
1350
  }
1351
- `;class Kf extends t.Component{static template="o-spreadsheet-Border";get style(){const e=["n","w","e"].includes(this.props.orientation),t=["n","w","s"].includes(this.props.orientation),o=["n","s"].includes(this.props.orientation),i=["w","e"].includes(this.props.orientation),s=this.props.zone,r=this.env.model.getters.getVisibleRect(s),n=r.x,a=r.x+r.width-4,l=r.y,c=r.y+r.height-4;return Fi({left:`${t?n:a}px`,top:`${e?l:c}px`,width:`${o?a-n:4}px`,height:`${i?c-l:4}px`})}onMouseDown(e){this.props.onMoveHighlight(e.clientX,e.clientY)}}Kf.props={zone:Object,orientation:String,isMoving:Boolean,onMoveHighlight:Function},Oi`
1351
+ `;class Kf extends t.Component{static template="o-spreadsheet-Border";get style(){const e=["n","w","e"].includes(this.props.orientation),t=["n","w","s"].includes(this.props.orientation),o=["n","s"].includes(this.props.orientation),i=["w","e"].includes(this.props.orientation),s=this.props.zone,n=this.env.model.getters.getVisibleRect(s),r=n.x,a=n.x+n.width-4,l=n.y,c=n.y+n.height-4;return Fi({left:`${t?r:a}px`,top:`${e?l:c}px`,width:`${o?a-r:4}px`,height:`${i?c-l:4}px`})}onMouseDown(e){this.props.onMoveHighlight(e.clientX,e.clientY)}}Kf.props={zone:Object,orientation:String,isMoving:Boolean,onMoveHighlight:Function},Oi`
1352
1352
  .o-corner {
1353
1353
  position: absolute;
1354
1354
  height: 6px;
@@ -1374,7 +1374,7 @@
1374
1374
  .o-highlight {
1375
1375
  z-index: ${ue.Highlight};
1376
1376
  }
1377
- `;class Jf extends t.Component{static template="o-spreadsheet-Highlight";static components={Corner:Qf,Border:Kf};highlightState=t.useState({shiftingMode:"none"});onResizeHighlight(e,t){const o=this.env.model.getters.getActiveSheet();this.highlightState.shiftingMode="isResizing";const i=this.props.zone,s=e?i.right:i.left,r=t?i.bottom:i.top;let n=e?i.left:i.right,a=t?i.top:i.bottom,l=i;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(o.id,l)});gf(this.env,((e,t)=>{if(n!==e||a!==t){const i=this.env.model.getters.getActiveSheetId();n=We(-1===e?n:e,0,this.env.model.getters.getNumberCols(i)-1),a=We(-1===t?a:t,0,this.env.model.getters.getNumberRows(i)-1);let c={left:Math.min(s,n),top:Math.min(r,a),right:Math.max(s,n),bottom:Math.max(r,a)};c=this.env.model.getters.expandZone(i,c),hi(c,l)||(this.env.model.dispatch("CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(o.id,c)}),l=c)}}),(()=>{this.highlightState.shiftingMode="none",this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION")}))}onMoveHighlight(e,t){this.highlightState.shiftingMode="isMoving";const o=this.props.zone,i=ir(),s=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getColIndex(e-i.left),n=this.env.model.getters.getRowIndex(t-i.top),a=-o.left,l=this.env.model.getters.getNumberCols(s)-o.right-1,c=-o.top,h=this.env.model.getters.getNumberRows(s)-o.bottom-1;let d=o;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(s,d)});let u=r,g=n;gf(this.env,((e,t)=>{if(u!==e||g!==t){u=-1===e?u:e,g=-1===t?g:t;const i=We(u-r,a,l),p=We(g-n,c,h);let m={left:o.left+i,top:o.top+p,right:o.right+i,bottom:o.bottom+p};m=this.env.model.getters.expandZone(s,m),hi(m,d)||(this.env.model.dispatch("CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(s,m)}),d=m)}}),(()=>{this.highlightState.shiftingMode="none",this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION")}))}}Jf.props={zone:Object,color:String};class eb{direction;el;constructor(e,t){this.el=e,this.direction=t}get scroll(){return"horizontal"===this.direction?this.el.scrollLeft:this.el.scrollTop}set scroll(e){"horizontal"===this.direction?this.el.scrollLeft=e:this.el.scrollTop=e}}Oi`
1377
+ `;class Jf extends t.Component{static template="o-spreadsheet-Highlight";static components={Corner:Qf,Border:Kf};highlightState=t.useState({shiftingMode:"none"});onResizeHighlight(e,t){const o=this.env.model.getters.getActiveSheet();this.highlightState.shiftingMode="isResizing";const i=this.props.zone,s=e?i.right:i.left,n=t?i.bottom:i.top;let r=e?i.left:i.right,a=t?i.top:i.bottom,l=i;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(o.id,l)});gf(this.env,((e,t)=>{if(r!==e||a!==t){const i=this.env.model.getters.getActiveSheetId();r=We(-1===e?r:e,0,this.env.model.getters.getNumberCols(i)-1),a=We(-1===t?a:t,0,this.env.model.getters.getNumberRows(i)-1);let c={left:Math.min(s,r),top:Math.min(n,a),right:Math.max(s,r),bottom:Math.max(n,a)};c=this.env.model.getters.expandZone(i,c),hi(c,l)||(this.env.model.dispatch("CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(o.id,c)}),l=c)}}),(()=>{this.highlightState.shiftingMode="none",this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION")}))}onMoveHighlight(e,t){this.highlightState.shiftingMode="isMoving";const o=this.props.zone,i=sn(),s=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getColIndex(e-i.left),r=this.env.model.getters.getRowIndex(t-i.top),a=-o.left,l=this.env.model.getters.getNumberCols(s)-o.right-1,c=-o.top,h=this.env.model.getters.getNumberRows(s)-o.bottom-1;let d=o;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(s,d)});let u=n,g=r;gf(this.env,((e,t)=>{if(u!==e||g!==t){u=-1===e?u:e,g=-1===t?g:t;const i=We(u-n,a,l),p=We(g-r,c,h);let m={left:o.left+i,top:o.top+p,right:o.right+i,bottom:o.bottom+p};m=this.env.model.getters.expandZone(s,m),hi(m,d)||(this.env.model.dispatch("CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(s,m)}),d=m)}}),(()=>{this.highlightState.shiftingMode="none",this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION")}))}}Jf.props={zone:Object,color:String};class eb{direction;el;constructor(e,t){this.el=e,this.direction=t}get scroll(){return"horizontal"===this.direction?this.el.scrollLeft:this.el.scrollTop}set scroll(e){"horizontal"===this.direction?this.el.scrollLeft=e:this.el.scrollTop=e}}Oi`
1378
1378
  .o-scrollbar {
1379
1379
  position: absolute;
1380
1380
  overflow: auto;
@@ -1414,13 +1414,13 @@
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})}}ib.props={topOffset:{type:Number,optional:!0}};const sb={ROW:Mm,COL:Tm,CELL:up};class rb extends t.Component{static template="o-spreadsheet-Grid";static components={GridComposer:Tf,GridOverlay:$f,GridPopover:Wf,HeadersOverlay:jf,Menu:br,Autofill:pf,ClientTag:ff,Highlight:Jf,Popover:gr,VerticalScrollBar:ib,HorizontalScrollBar:ob,FilterIconsOverlay:Nf};HEADER_HEIGHT=F;HEADER_WIDTH=D;menuState;gridRef;hiddenInput;onMouseWheel;canvasPosition;hoveredCell;setup(){this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.hiddenInput=t.useRef("hiddenInput"),this.canvasPosition=cr(this.gridRef),this.hoveredCell=t.useState({col:void 0,row:void 0}),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),t.useExternalListener(document.body,"cut",this.copy.bind(this,!0)),t.useExternalListener(document.body,"copy",this.copy.bind(this,!1)),t.useExternalListener(document.body,"paste",this.paste),t.onMounted((()=>this.focus())),this.props.exposeFocus((()=>this.focus())),Yf("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimensionWithHeaders())),t.useEffect((()=>this.focus()),(()=>[this.env.model.getters.getActiveSheetId()])),this.onMouseWheel=Xf(((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 Fi({top:"26px",left:"48px",height:"calc(100% - 41px)",width:"calc(100% - 63px)"})}onClosePopover(){this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.focus()}keyDownMapping={ENTER:()=>{this.env.model.getters.getActiveCell().type===ws.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===ws.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":()=>Sa(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&&Gi(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":()=>ga(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?ba(this.env):s&&!i&&fa(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":()=>Ea(this.env)};focus(){this.env.model.getters.getSelectedFigureId()||"inactive"!==this.env.model.getters.getEditionMode()||this.hiddenInput.el?.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,r=t;gf(this.env,((e,t,o)=>{o.preventDefault(),(e!==s&&-1!=e||t!==r&&-1!=t)&&(s=-1===e?s:e,r=-1===t?r:t,this.env.model.selection.setAnchorCorner(s,r))}),(()=>{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===ws.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(),Dm(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="";ar(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}onInput(e){(e.isComposing||"insertFromPaste"!==e.inputType)&&e.data&&(e.preventDefault(),e.stopPropagation(),this.props.onGridComposerCellFocused(e.data))}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left: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:r,y:n,width:a,height:l}=this.env.model.getters.getVisibleRect(t);this.toggleContextMenu(s,r+a,n+l)}onCellRightClicked(e,t,{x:o,y:i}){const s=this.env.model.getters.getSelectedZones();let r="CELL";ui(e,t,s[s.length-1])?this.env.model.getters.getActiveCols().has(e)?r="COL":this.env.model.getters.getActiveRows().has(t)&&(r="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(r,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=sb[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?oa(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(xs.PlainText)>-1){const e=t.getData(xs.PlainText),o=this.env.model.getters.getSelectedZones();this.env.model.getters.getClipboardTextContent()===e?aa(this.env,o):la(this.env,o,e)}}else this.displayWarningCopyPasteNotSupported()}displayWarningCopyPasteNotSupported(){this.env.raiseError(r("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.focus()}}rb.props={sidePanelIsOpen:Boolean,exposeFocus:Function,focusComposer:String,onComposerContentFocused:Function,onGridComposerCellFocused:Function};class nb{xmlString;constructor(e){this.xmlString=e}toString(){return this.xmlString}}const ab=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart"],lb="000000",cb={arrow:"3Arrows",smiley:"3Symbols",dot:"3TrafficLights1"},hb={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"},db="http://schemas.openxmlformats.org/drawingml/2006/main",ub="http://schemas.openxmlformats.org/drawingml/2006/chart",gb={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"},pb={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"},mb="http://schemas.openxmlformats.org/officeDocument/2006/relationships",fb=.75,bb=.1317,vb=8.43,Sb=12.75,Cb=30,Eb=100,wb=164,xb={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}]},yb=["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"],Ib="[Content_Types].xml";var Rb;!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"}(Rb||(Rb={}));class Tb{_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 Ab=["thin"],Ob=["general","left","center","right"],Mb=["top","center","bottom"],Nb=["Arial"],_b=["solid"],Fb=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWith","containsBlanks","notContainsBlanks"],Db={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},Lb={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"},kb={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"},Pb={top:"top",center:"middle",bottom:"bottom",justify:"middle",distributed:"middle"},Ub={top:"top",middle:"center",bottom:"bottom"};const Vb={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},zb={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},Bb={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"},Hb={b:"bottom",t:"top",l:"left",r:"right",tr:"right"},$b={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},Wb={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"},Gb={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},qb={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},Zb={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"},jb={"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 Yb(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=lb;else{if(!e.indexed)return;t=Zb[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=kt(e),i=Ut(o);t<0&&(i.l=i.l*(1+t));t>0&&(i.l=i.l*(1-t)+(100-100*(1-t)));return Lt(Pt(i))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function Xb(e,t){const o=e.split("/"),i=t.split("/");let s="",r=0;for(let e=0;e<o.length-1;e++)o[e]===i[e]?r++:s+="../";return s+=i.slice(r).join("/"),s}function Kb(e,t=0){const o={};for(let i=0;i<e.length;i++)e[i]&&(o[i+t]=e[i]);return o}function Qb(e){const t=[];for(let o of Object.keys(e).map(Number))t[o]=e[o];return t}function Jb(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,((e,t)=>String.fromCharCode(parseInt(t,16))))}const ev=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function tv(e,t,o){if(0===e)return;let i=Gb[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 ev.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 mo(0,e),!0}catch(e){return!1}}(e))return e}catch(e){}o.generateNotSupportedWarning(Rb.NumFmtIdNotSupported,i||`nmFmtId ${e}`)}function ov(e,t){const o=e.borders.map((e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(Rb.DiagonalBorderNotSupported)}(e,t);const o={top:iv(e.top,t),bottom:iv(e.bottom,t),left:iv(e.left,t),right:iv(e.right,t)};return Object.keys(o).forEach((e=>void 0===o[e]&&delete o[e])),o}));return Kb(o,1)}function iv(e,t){if(!e)return;!function(e,t){Ab.includes(e.style)||t.generateNotSupportedWarning(Rb.BorderStyleNotSupported,e.style,Ab)}(e,t);const o=Lb[e.style];return o?{style:o,color:Yb(e.color)}:void 0}function sv(e,t){return Kb(e.styles.map((o=>rv({fontStyle:e.fonts[o.fontId],fillStyle:e.fills[o.fillId],alignment:o.alignment},t))),1)}function rv(e,t){return function(e,t,o){e&&e.name&&!Nb.includes(e.name)&&o.generateNotSupportedWarning(Rb.FontNotSupported,e.name,Nb);t&&t.patternType&&!_b.includes(t.patternType)&&o.generateNotSupportedWarning(Rb.FillStyleNotSupported,t.patternType,_b)}(e?.fontStyle,e?.fillStyle,t),function(e,t){e&&!Ob.includes(e)&&t.generateNotSupportedWarning(Rb.HorizontalAlignmentNotSupported,e,Ob)}(e?.alignment?.horizontal,t),function(e,t){e&&!Mb.includes(e)&&t.generateNotSupportedWarning(Rb.VerticalAlignmentNotSupported,e,Mb)}(e?.alignment?.vertical,t),{bold:e.fontStyle?.bold,italic:e.fontStyle?.italic,strikethrough:e.fontStyle?.strike,underline:e.fontStyle?.underline,verticalAlign:e.alignment?.vertical?Pb[e.alignment.vertical]:void 0,align:e.alignment?.horizontal?kb[e.alignment.horizontal]:void 0,fillColor:"solid"===e.fillStyle?.patternType?Yb(e.fillStyle?.fgColor):Yb(e.fillStyle?.bgColor),textColor:Yb(e.fontStyle?.color),fontSize:e.fontStyle?.size,wrapping:e.alignment?.wrapText?"wrap":"overflow"}}function nv(e,t){const o=[];for(let i of e.styles){const s=tv(i.numFmtId,e.numFmts,t);s&&(o[i.numFmtId]=s)}return Kb(o,1)}function av(e,t,o){const i=[];let s=1;for(let n of e){if(0===n.cfRules.length)continue;dv(n,t,o);const e=n.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=lv(s++,n);t&&i.push(t);continue;case"iconSet":const c=cv(s++,n,o);c&&i.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;a=Vb[e.type],l.push(e.text);break;case"containsBlanks":case"notContainsBlanks":a=Vb[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;a=(r=e.operator).slice(0,1).toUpperCase()+r.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:n.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:a,values:l,style:rv({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},o)}})}}var r;return i}function lv(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=Yb(o.colors[e])||"#FFFFFF",9===s.length&&(s=s.slice(0,7)),parseInt(s.replace("#",""),16)),type:zb[o.cfvos[e].type],value:o.cfvos[e].value});var s;const r=i[0],n=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:r,midpoint:a,maximum:n}}}function cv(e,t,o){const i=t.cfRules[0].iconSet;if(!i)return;let s=i.cfvos,r=i.cfIcons;if(s.length<3||r&&r.length<3)return;s.length>3&&(s=[s[0],s[Math.floor(s.length/2)],s[s.length-1]]),r&&r.length>3&&(r=[r[0],r[Math.floor(r.length/2)],r[r.length-1]]);const n=[];for(let e=1;e<=2;e++){const t=zb[s[e].type];if("value"===t)return;n.push({value:s[e].value||"",operator:s[e].gte?"ge":"gt",type:t})}let a={lower:r?hv(r[0].iconSet,r[0].iconId):hv(i.iconSet,0),middle:r?hv(r[1].iconSet,r[1].iconId):hv(i.iconSet,1),upper:r?hv(r[2].iconSet,r[2].iconId):hv(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(Rb.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=ef.dots.good;break;case"middle":a[e]=ef.dots.neutral;break;case"lower":a[e]=ef.dots.bad}return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"IconSetRule",icons:a,upperInflectionPoint:n[1],lowerInflectionPoint:n[0]}}}function hv(e,t){const o=Bb[e];return o?0===t?ef[o].bad:1===t?ef[o].neutral:ef[o].good:""}function dv(e,t,o){if(e.cfRules.length>1&&o.generateNotSupportedWarning(Rb.MultipleRulesCfNotSupported),Fb.includes(e.cfRules[0].type)||o.generateNotSupportedWarning(Rb.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const i=t[e.cfRules[0].dxfId];i.border&&o.generateNotSupportedWarning(Rb.CfFormatBorderNotSupported),i.alignment&&o.generateNotSupportedWarning(Rb.CfFormatAlignmentNotSupported),i.numFmt&&o.generateNotSupportedWarning(Rb.CfFormatNumFmtNotSupported)}}class uv{scope;code="";constructor(e=new pv){this.scope=e}append(...e){this.code+=e.map((e=>e.toString())).join("\n")+"\n"}return(e){return new gv(this.scope,this.code,e)}toString(){return mv(this.code)}}class gv{scope;returnExpression;code;constructor(e,t,o){this.scope=e,this.returnExpression=o,this.code=mv(t)}toString(){return this.code}wrapInClosure(){const e=this.scope.nextVariableName(),t=new uv(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 uv(this.scope);return t.append(this.code),t.append(`const ${e} = ${this.returnExpression};`),t.return(e)}}class pv{nextId=1;declaredVariables=new Set;nextVariableName(){const e="_"+this.nextId++;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}}function mv(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 fv=Ug.content,bv=["%"],vv="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(bv);function Sv(e){e=It(e);const t=new Mv(e),o=[];for(;!t.isOver();){let e=Av(t)||wv(t)||xv(t)||Iv(t)||Cv(t)||Ov(t)||yv(t)||Tv(t);e||(e={type:"UNKNOWN",value:t.shift()}),o.push(e)}return o}function Cv(e){return"?"===e.current()?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const Ev={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function wv(e){if(e.current()in Ev){const t=e.shift();return{type:Ev[t],value:t}}return null}function xv(e){for(let t of vv)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:"OPERATOR",value:t};return null}function yv(e){const t=e.remaining().match(Xt);return t?(e.advanceBy(t[0].length),{type:"NUMBER",value:t[0]}):null}function Iv(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 Rv=/\w|\.|!|\$/;function Tv(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()&&Rv.test(e.current());)t+=e.shift();if(t.length){const e=t;if(e.toUpperCase()in fv)return{type:"FUNCTION",value:e};return Bo.test(e)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}function Av(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 Ov(e){return e.currentStartsWith(J)?(e.advanceBy(J.length),{type:"INVALID_REFERENCE",value:J}):null}class Mv{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 Nv=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,_v=["-","+"],Fv=["%"],Dv=["*","+","&"],Lv={"^":30,"%":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function kv(e){const t=e.shift();if(!t)throw new h(de);switch(t.type){case"DEBUGGER":const o=Vv(e,1e3);return o.debug=!0,o;case"NUMBER":return{type:"NUMBER",value:so(t.value)};case"STRING":return{type:"STRING",value:Ve(t.value)};case"FUNCTION":const i=function(e){Uv(e,"LEFT_PAREN",r("Missing opening parenthesis"));const t=e[0];if("RIGHT_PAREN"===t?.type)return Uv(e,"RIGHT_PAREN"),[];const o=[];o.push(Pv(e));for(;"RIGHT_PAREN"!==e[0]?.type;)Uv(e,"COMMA",r("Wrong function call")),o.push(Pv(e));return Uv(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&&Nv.test(t.value)&&"LEFT_PAREN"===e[0]?.type)throw new p(t.value);throw new h(r("Invalid formula"));case"LEFT_PAREN":const s=Vv(e);return Uv(e,"RIGHT_PAREN",r("Missing closing parenthesis")),s;case"OPERATOR":const n=t.value;if(_v.includes(n))return{type:"UNARY_OPERATION",value:n,operand:Vv(e,Lv[n])};throw new h(r("Unexpected token: %s",t.value));default:throw new h(r("Unexpected token: %s",t.value))}}function Pv(e){const t=e[0];return"COMMA"===t?.type||"RIGHT_PAREN"===t?.type?{type:"EMPTY",value:""}:Vv(e)}function Uv(e,t,o=de){const i=e.shift();if(!i||i.type!==t)throw new h(o)}function Vv(e,t=0){if(0===e.length)throw new h(de);let o=kv(e);for(;"OPERATOR"===e[0]?.type&&Lv[e[0].value]>t;){const t=e.shift().value;if(Fv.includes(t))o={type:"UNARY_OPERATION",value:t,operand:o,postfix:!0};else{o={type:"BIN_OPERATION",value:t,left:o,right:Vv(e,Lv[t])}}}return o}function zv(e){return Bv(Sv(e))}function Bv(e){"="===(e=e.filter((e=>"SPACE"!==e.type)))[0].value&&e.splice(0,1);const t=Vv(e);if(e.length)throw new h(de);return t}function Hv(e,t,o){switch(t===e.type&&(e=o(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>Hv(e,t,o)))};case"UNARY_OPERATION":return{...e,operand:Hv(e.operand,t,o)};case"BIN_OPERATION":return{...e,right:Hv(e.right,t,o),left:Hv(e.left,t,o)};default:return e}}function $v(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>$v(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?Wv(e)+e.value:e.value+Gv(e);case"BIN_OPERATION":return Wv(e)+e.value+Gv(e)}}function Wv(e){const t=e.value,o="left"in e?e.left:e.operand,i=o.value;return"BIN_OPERATION"===o.type&&Lv[i]<Lv[t]?`(${$v(o)})`:$v(o)}function Gv(e){const t=e.value,o="right"in e?e.right:e.operand,i=Lv[o.value],s=Lv[t];let r=!1;return"BIN_OPERATION"!==o.type?r=!1:i<s?r=!0:i!==s||Dv.includes(t)||(r=!0),r?`(${$v(o)})`:$v(o)}var qv;!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"}(qv||(qv={}));const Zv=(e,t=(()=>!0))=>[{goTo:e,guard:t}],jv=(e,t=(()=>!0))=>({goTo:e,guard:t}),Yv={[qv.LeftRef]:{REFERENCE:Zv(qv.Separator),NUMBER:Zv(qv.FullRowSeparator),SYMBOL:[jv(qv.FullColumnSeparator,(e=>Ho(e.value))),jv(qv.FullRowSeparator,(e=>$o(e.value)))]},[qv.FullColumnSeparator]:{SPACE:Zv(qv.FullColumnSeparator),OPERATOR:Zv(qv.RightColumnRef,(e=>":"===e.value))},[qv.FullRowSeparator]:{SPACE:Zv(qv.FullRowSeparator),OPERATOR:Zv(qv.RightRowRef,(e=>":"===e.value))},[qv.Separator]:{SPACE:Zv(qv.Separator),OPERATOR:Zv(qv.RightRef,(e=>":"===e.value))},[qv.RightRef]:{SPACE:Zv(qv.RightRef),NUMBER:Zv(qv.Found),REFERENCE:Zv(qv.Found,(e=>qo(e.value))),SYMBOL:Zv(qv.Found,(e=>Wo(e.value)||Go(e.value)))},[qv.RightColumnRef]:{SPACE:Zv(qv.RightColumnRef),SYMBOL:Zv(qv.Found,(e=>Wo(e.value))),REFERENCE:Zv(qv.Found,(e=>qo(e.value)))},[qv.RightRowRef]:{SPACE:Zv(qv.RightRowRef),NUMBER:Zv(qv.Found),REFERENCE:Zv(qv.Found,(e=>qo(e.value))),SYMBOL:Zv(qv.Found,(e=>Go(e.value)))},[qv.Found]:{}};function Xv(e){let t=0,o=Yv[qv.LeftRef];const i=[];for(;void 0!==o;){const s=e[t++];if(!s)return null;const r=o[s.type]?.find((e=>e.guard(s))),n=r?r.goTo:void 0;switch(n){case void 0:return null;case qv.Found:return i.push(s),e.splice(0,t),{type:"REFERENCE",value:pt(i.map((e=>e.value)))};default:o=Yv[n],i.push(s)}}return null}function Kv(e){const t=Sv(e),o=[];for(;t.length;)o.push(Xv(t)||t.shift());return o}const Qv=Ug.content,Jv={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},eS={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"},tS={};function oS(e){const t=Kv(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=so(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(so(e.value))}|`;case"REFERENCE":case"INVALID_REFERENCE":return`|${t.indexOf(e.value)}|`;case"SPACE":return"";default:return e.value}})))}(t,o,i);if(!tS[s]){const n=Bv([...t]),a=new pv;if("BIN_OPERATION"===n.type&&":"===n.value)throw new h(r("Invalid formula"));if("EMPTY"===n.type)throw new h(r("Invalid formula"));const l=g(n),c=new uv;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=Qv[e.value.toUpperCase()],o=e.args,i=o.length;if(i<t.minArgRequired)throw new h(r("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(r("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(r("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 n=[];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(r("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});n.push(u?f.wrapInClosure():f)}}return n}function g(e,t=!1,s=!1,n={}){const l=new uv(a);if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&t)throw new h(r("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 r=o.indexOf(e.value);return s?l.return(`range(deps[${r}])`):l.return(`ref(deps[${r}], ${t?"true":"false"}, "${n.functionName||Jv["="]}", ${n.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=eS[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=Jv[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")}}tS[s]={execute:d}}return{execute:tS[s].execute,dependencies:o,constantValues:i,tokens:t}}function iS(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}))}(Kv(e))))}function sS(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function rS(e){return Math.round(fb*e*100)/100}function nS(e){return Math.round(bb*e*100)/100}function aS(e){if(e)return{style:e.style,color:{rgb:e.color}}}function lS(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=Sv(e.content||""),o=Ug.content;if(!t.filter((e=>"FUNCTION"===e.type)).every((e=>o[e.value.toUpperCase()].isExported)))return e.computedFormat}return}(e,t),s={};if(e.border){const o=t.borders[e.border];s.left=aS(o.left),s.right=aS(o.right),s.bottom=aS(o.bottom),s.top=aS(o.top)}const r={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:s||{},alignment:{horizontal:o.align,vertical:o.verticalAlign?Ub[o.verticalAlign]:void 0,wrapText:"wrap"===o.wrapping}};return r.font.strike=!!o?.strikethrough||void 0,r.font.underline=!!o?.underline||void 0,r.font.bold=!!o?.bold||void 0,r.font.italic=!!o?.italic||void 0,r}function cS(e,t){const{id:o}=dS(t.font,e.fonts),{id:i}=dS(t.fill,e.fills),{id:s}=dS(t.border,e.borders),r=function(e,t){if(!e)return 0;let o=qb[e.format];if(!o){const{id:i}=dS(e,t);o=i+wb}return o}(t.numFmt,e.numFmts),n={fontId:o,fillId:i,borderId:s,numFmtId:r,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal,wrapText:t.alignment.wrapText}},{id:a}=dS(n,e.styles);return a}function hS(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 dS(e,t){for(let[o,i]of Object.entries(t))if(JSON.stringify(i)===JSON.stringify(e))return{id:parseInt(o,10),list:t};let o=t.findIndex((t=>JSON.stringify(t)===JSON.stringify(e)));return-1===o&&(t.push(e),o=t.length-1),{id:o,list:t}}const uS=[];function gS(e){const t=uS.findIndex((t=>t===e));return-1===t?(uS.push(e),uS.length):t+1}const pS=[];function mS(e){const t=pS.findIndex((t=>t===e));return-1===t?(pS.push(e),pS.length):t+1}function fS(e){return Math.round(914400*e/96)}function bS(e,t,o){let i,s,r=e;if(({xc:r,sheetName:i}=Zo(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 n=ei(r);return void 0===n.right&&(n.right=o.sheets[s].colNumber),void 0===n.bottom&&(n.bottom=o.sheets[s].rowNumber),(n.right-n.left+1)*(n.bottom-n.top+1)}function vS(e){return Math.round(96*e/914400)}function SS(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+=vb}return o/bb}function CS(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+=Sb}return o/fb}function ES(e){let t=1;return e.figures.map((o=>function(e,t,o){const i=SS(e.anchors[0].col,o)+vS(e.anchors[0].colOffset),s=SS(e.anchors[1].col,o)+vS(e.anchors[1].colOffset),r=CS(e.anchors[0].row,o)+vS(e.anchors[0].rowOffset),n=CS(e.anchors[1].row,o)+vS(e.anchors[1].rowOffset),a=s-i,l=n-r,c=wS(e.data);return c?{id:t,x:i,y:r,width:a,height:l,tag:"chart",data:wS(e.data)}:void 0}(o,(t++).toString(),e))).filter(dt)}function wS(e){const t=void 0!==e.dataSets[0].label,o=e.labelRange?xS(e.labelRange,t):void 0;let i=e.dataSets.map((e=>xS(e.range,t)));return"pie"===e.type&&i.reverse(),{dataSets:i,dataSetsHaveTitle:t,labelRange:o,title:e.title||"",type:e.type,background:Yb({rgb:e.backgroundColor})||"#FFFFFF",verticalAxisPosition:e.verticalAxisPosition,legendPosition:e.legendPosition,stacked:e.stacked||!1,aggregated:!1,cumulative:e.cumulative||!1,labelsAsText:!1}}function xS(e,t){let{sheetName:o,xc:i}=Zo(e);o=o?$e(o)+"!":"";let s=ei(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+ii(s)}const yS=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),IS=new RegExp(/SUBTOTAL\(([0-9]*),/g),RS=new RegExp(Lo.source,"ig");function TS(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:"="+OS(i.xc,o[i.formula.sharedIndex]),i.formula.content=AS(i.formula.content,t))}function AS(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(IS,((e,t)=>{const o=Wb[t];return o?o+"(":e}))).replace(yS,((e,o,i,s)=>{o=Number(o)-1,s=s.replace(/\$/g,"");const r=t.externalBooks[o].sheetNames.findIndex((e=>e===i));if(-1===r)return e;const n=t.externalBooks[o].datasets.find((e=>e.sheetId===r))?.data;if(!n)return e;const a=n&&n[s];return(Number(a)?a:`"${a}"`)||e}))}function OS(e,t){const o=Wt(t.refCellXc);let i,s=t.formula.slice();do{if(i=RS.exec(s),i){const t=Wt(i[0].replace("$","")),r=Wt(e),n={colFixed:i[0].startsWith("$"),rowFixed:i[0].includes("$",1)},a={col:r.col-o.col,row:r.row-o.row},l={col:n.colFixed?t.col:t.col+a.col,row:n.rowFixed?t.row:t.row+a.row};s=s.slice(0,i.index)+Gt(l.col,l.row,n)+s.slice(i.index+i[0].length)}}while(i);return s}function MS(e,t){return e.sheets.map((o=>{TS(o,e);const i=function(e){const t=[0,0];for(let o of e.rows)t[0]=Math.max(t[0],...o.cells.map((e=>Wt(e.xc).col))),t[1]=Math.max(t[1],o.index);return t[0]=Math.max(t[0],Cb),t[1]=Math.max(t[1],Eb),t}(o),s=o.sheetViews[0];return{id:o.sheetName,areGridLinesVisible:!s||s.showGridLines,name:o.sheetName,colNumber:i[0],rowNumber:i[1],cells:FS(o,e,i,t),merges:o.merges,cols:NS(o,i[0]),rows:_S(o,i[1]),conditionalFormats:av(o.cfs,e.dxfs,t),figures:ES(o),isVisible:o.isVisible,panes:s?{xSplit:s.pane.xSplit,ySplit:s.pane.ySplit}:{xSplit:0,ySplit:0},filterTables:[]}}))}function NS(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 r;r=t&&t.width?t.width:e.sheetFormat?.defaultColWidth?e.sheetFormat.defaultColWidth:vb,o[s-1]={size:(i=r,i?Math.round(i/bb*100)/100:i),isHidden:t?.hidden}}var i;return o}function _S(e,t){const o={};for(let s=1;s<t+1;s++){const t=e.rows.find((e=>e.index===s));let r;r=t&&t.height?t.height:e.sheetFormat?.defaultRowHeight?e.sheetFormat.defaultRowHeight:Sb,o[s-1]={size:(i=r,i?Math.round(i/fb*100)/100:i),isHidden:t?.hidden}}var i;return o}function FS(e,t,o,i){const s={},r=t.sharedStrings.map((e=>e.replace(/\n/g,"")));const n=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:DS(e,n,r,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=Gt(e-1,i.index-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}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 r=1;r<=o[1];r++){const o=Gt(e-1,r-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}return s}function DS(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(Rb.BadlyFormattedHyperlink);const s=e.relTarget?e.relTarget:ct(Zo(e.location).sheetName);return rt(i,s)}(t[e.xc],s,i)),e.formula&&(s=e.formula.content),s}const LS={fillColor:"#000000",textColor:"#ffffff",bold:!0},kS={bold:!0},PS={style:"thin",color:"#000000FF"};function US(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=Qb(e.styles),i=Qb(e.borders);for(let s of t.sheets)for(let t of s.tables){const r=e.sheets.find((e=>e.name===s.sheetName));if(!r)continue;const n=ti(t.ref);for(let e=0;e<t.headerRowCount;e++)VS(LS,{...n,bottom:n.top+e},r.cells,o);for(let e=0;e<t.totalsRowCount;e++)VS(kS,{...n,top:n.bottom-e},r.cells,o);t.style?.showFirstColumn&&VS(kS,{...n,right:n.left},r.cells,o),t.style?.showLastColumn&&VS(kS,{...n,left:n.right},r.cells,o);for(let e=n.left;e<=n.right;e++)for(let o=n.top;o<=n.bottom;o++){const s=Gt(e,o),a=r.cells[s],l={left:e===n.left||t.style?.showColumnStripes?PS:void 0,right:e===n.right?PS:void 0,top:o===n.top||t.style?.showRowStripes||o>n.bottom-t.totalsRowCount?PS:void 0,bottom:o===n.bottom?PS: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:r.cells[s]={border:h}}}e.styles=Kb(o),e.borders=Kb(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 vi(ti(t.ref))){const s=Gt(i.col,i.row),r=o.cells[s];if(r&&r.content&&r.content.startsWith("=")){let o;for(;-1!==(o=r.content.indexOf(e));){let i=r.content.slice(o+e.length),n=i.indexOf("]");i.startsWith("[")&&(n=i.indexOf("]",n+1),n=i.indexOf("]",n+1)),i=i.slice(0,n);const a=zS(i,t,s);r.content=r.content.slice(0,o)+a+r.content.slice(e.length+o+n+1)}}}}}}(e.sheets,t.sheets)}function VS(e,t,o,i){for(let s=t.left;s<=t.right;s++)for(let r=t.top;r<=t.bottom;r++){const t=Gt(s,r),n=o[t],a=n?.style?{...i[n.style],...e}:e;let l=i.findIndex((e=>vt(e,a)));-1===l&&(l=i.length,i.push(a)),n?n.style=l:o[t]={style:l}}}function zS(e,t,o){const i=e.split(","),s=ti(t.ref),r={...s};let n=!0;if(1===i.length){const e=t.cols.findIndex((e=>e.name===i[0]));r.left=r.right=e+s.left,t.headerRowCount&&(r.top+=t.headerRowCount),t.totalsRowCount&&(r.bottom-=1)}else{switch(i[0].slice(1,i[0].length-1)){case"#All":r.top=t.headerRowCount?s.top+t.headerRowCount:s.top,r.bottom=s.bottom;break;case"#Data":r.top=t.headerRowCount?s.top+t.headerRowCount:s.top,r.bottom=t.totalsRowCount?s.bottom+1:s.bottom;break;case"#This Row":r.top=r.bottom=Wt(o).row;break;case"#Headers":r.top=r.bottom=s.top,t.headerRowCount||(n=!1);break;case"#Totals":r.top=r.bottom=s.bottom,t.totalsRowCount||(n=!1)}const e=i[1].slice(1,i[1].length-1),a=t.cols.findIndex((t=>t.name===e));r.left=r.right=a+s.left}return n?r.top!==r.bottom?ii(r):Gt(r.left,r.top):J}function BS(e,t,o){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:o}}function HS(e){return String(e).replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\'/g,"&apos;").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"")}function $S(e){return new nb(e.map((([e,t])=>`${e}="${HS(t)}"`)).join(" "))}function WS(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"),r=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${r}`)}return o}function GS(e,t){return ZS`
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})}}ib.props={topOffset:{type:Number,optional:!0}};const sb={ROW:Mm,COL:Tm,CELL:up};class nb extends t.Component{static template="o-spreadsheet-Grid";static components={GridComposer:Tf,GridOverlay:$f,GridPopover:Wf,HeadersOverlay:jf,Menu:vn,Autofill:pf,ClientTag:ff,Highlight:Jf,Popover:pn,VerticalScrollBar:ib,HorizontalScrollBar:ob,FilterIconsOverlay:Nf};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=hn(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())),Yf("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimensionWithHeaders())),t.useEffect((()=>this.focusDefaultElement()),(()=>[this.env.model.getters.getActiveSheetId()])),this.onMouseWheel=Xf(((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 Fi({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===ws.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===ws.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":()=>Sa(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&&Gi(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":()=>ga(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?ba(this.env):s&&!i&&fa(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":()=>Ea(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;gf(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===ws.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(),Dm(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="";ln(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,height:l}=this.env.model.getters.getVisibleRect(t);this.toggleContextMenu(s,n+a,r+l)}onCellRightClicked(e,t,{x:o,y:i}){const s=this.env.model.getters.getSelectedZones();let n="CELL";ui(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=sb[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?oa(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(xs.PlainText)>-1){const e=t.getData(xs.PlainText),o=this.env.model.getters.getSelectedZones();this.env.model.getters.getClipboardTextContent()===e?aa(this.env,o):la(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()}}nb.props={sidePanelIsOpen:Boolean,exposeFocus:Function,focusComposer:String,onComposerContentFocused:Function,onGridComposerCellFocused:Function};class rb{xmlString;constructor(e){this.xmlString=e}toString(){return this.xmlString}}const ab=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart"],lb="000000",cb={arrow:"3Arrows",smiley:"3Symbols",dot:"3TrafficLights1"},hb={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"},db="http://schemas.openxmlformats.org/drawingml/2006/main",ub="http://schemas.openxmlformats.org/drawingml/2006/chart",gb={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"},pb={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"},mb="http://schemas.openxmlformats.org/officeDocument/2006/relationships",fb=.75,bb=.1317,vb=8.43,Sb=12.75,Cb=30,Eb=100,wb=164,xb={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}]},yb=["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"],Ib="[Content_Types].xml";var Rb;!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"}(Rb||(Rb={}));class Tb{_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 Ab=["thin"],Ob=["general","left","center","right"],Mb=["top","center","bottom"],Nb=["Arial"],_b=["solid"],Fb=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWith","containsBlanks","notContainsBlanks"],Db={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},Lb={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"},kb={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"},Pb={top:"top",center:"middle",bottom:"bottom",justify:"middle",distributed:"middle"},Ub={top:"top",middle:"center",bottom:"bottom"};const Vb={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},zb={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},Bb={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"},Hb={b:"bottom",t:"top",l:"left",r:"right",tr:"right"},$b={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},Wb={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"},Gb={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},qb={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},Zb={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"},jb={"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 Yb(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=lb;else{if(!e.indexed)return;t=Zb[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=kt(e),i=Ut(o);t<0&&(i.l=i.l*(1+t));t>0&&(i.l=i.l*(1-t)+(100-100*(1-t)));return Lt(Pt(i))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function Xb(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 Kb(e,t=0){const o={};for(let i=0;i<e.length;i++)e[i]&&(o[i+t]=e[i]);return o}function Qb(e){const t=[];for(let o of Object.keys(e).map(Number))t[o]=e[o];return t}function Jb(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,((e,t)=>String.fromCharCode(parseInt(t,16))))}const ev=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function tv(e,t,o){if(0===e)return;let i=Gb[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 ev.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 mo(0,e),!0}catch(e){return!1}}(e))return e}catch(e){}o.generateNotSupportedWarning(Rb.NumFmtIdNotSupported,i||`nmFmtId ${e}`)}function ov(e,t){const o=e.borders.map((e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(Rb.DiagonalBorderNotSupported)}(e,t);const o={top:iv(e.top,t),bottom:iv(e.bottom,t),left:iv(e.left,t),right:iv(e.right,t)};return Object.keys(o).forEach((e=>void 0===o[e]&&delete o[e])),o}));return Kb(o,1)}function iv(e,t){if(!e)return;!function(e,t){Ab.includes(e.style)||t.generateNotSupportedWarning(Rb.BorderStyleNotSupported,e.style,Ab)}(e,t);const o=Lb[e.style];return o?{style:o,color:Yb(e.color)}:void 0}function sv(e,t){return Kb(e.styles.map((o=>nv({fontStyle:e.fonts[o.fontId],fillStyle:e.fills[o.fillId],alignment:o.alignment},t))),1)}function nv(e,t){return function(e,t,o){e&&e.name&&!Nb.includes(e.name)&&o.generateNotSupportedWarning(Rb.FontNotSupported,e.name,Nb);t&&t.patternType&&!_b.includes(t.patternType)&&o.generateNotSupportedWarning(Rb.FillStyleNotSupported,t.patternType,_b)}(e?.fontStyle,e?.fillStyle,t),function(e,t){e&&!Ob.includes(e)&&t.generateNotSupportedWarning(Rb.HorizontalAlignmentNotSupported,e,Ob)}(e?.alignment?.horizontal,t),function(e,t){e&&!Mb.includes(e)&&t.generateNotSupportedWarning(Rb.VerticalAlignmentNotSupported,e,Mb)}(e?.alignment?.vertical,t),{bold:e.fontStyle?.bold,italic:e.fontStyle?.italic,strikethrough:e.fontStyle?.strike,underline:e.fontStyle?.underline,verticalAlign:e.alignment?.vertical?Pb[e.alignment.vertical]:void 0,align:e.alignment?.horizontal?kb[e.alignment.horizontal]:void 0,fillColor:"solid"===e.fillStyle?.patternType?Yb(e.fillStyle?.fgColor):Yb(e.fillStyle?.bgColor),textColor:Yb(e.fontStyle?.color),fontSize:e.fontStyle?.size,wrapping:e.alignment?.wrapText?"wrap":"overflow"}}function rv(e,t){const o=[];for(let i of e.styles){const s=tv(i.numFmtId,e.numFmts,t);s&&(o[i.numFmtId]=s)}return Kb(o,1)}function av(e,t,o){const i=[];let s=1;for(let r of e){if(0===r.cfRules.length)continue;dv(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=lv(s++,r);t&&i.push(t);continue;case"iconSet":const c=cv(s++,r,o);c&&i.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;a=Vb[e.type],l.push(e.text);break;case"containsBlanks":case"notContainsBlanks":a=Vb[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:nv({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},o)}})}}var n;return i}function lv(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=Yb(o.colors[e])||"#FFFFFF",9===s.length&&(s=s.slice(0,7)),parseInt(s.replace("#",""),16)),type:zb[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 cv(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=zb[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?hv(n[0].iconSet,n[0].iconId):hv(i.iconSet,0),middle:n?hv(n[1].iconSet,n[1].iconId):hv(i.iconSet,1),upper:n?hv(n[2].iconSet,n[2].iconId):hv(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(Rb.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=ef.dots.good;break;case"middle":a[e]=ef.dots.neutral;break;case"lower":a[e]=ef.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 hv(e,t){const o=Bb[e];return o?0===t?ef[o].bad:1===t?ef[o].neutral:ef[o].good:""}function dv(e,t,o){if(e.cfRules.length>1&&o.generateNotSupportedWarning(Rb.MultipleRulesCfNotSupported),Fb.includes(e.cfRules[0].type)||o.generateNotSupportedWarning(Rb.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const i=t[e.cfRules[0].dxfId];i.border&&o.generateNotSupportedWarning(Rb.CfFormatBorderNotSupported),i.alignment&&o.generateNotSupportedWarning(Rb.CfFormatAlignmentNotSupported),i.numFmt&&o.generateNotSupportedWarning(Rb.CfFormatNumFmtNotSupported)}}class uv{scope;code="";constructor(e=new pv){this.scope=e}append(...e){this.code+=e.map((e=>e.toString())).join("\n")+"\n"}return(e){return new gv(this.scope,this.code,e)}toString(){return mv(this.code)}}class gv{scope;returnExpression;code;constructor(e,t,o){this.scope=e,this.returnExpression=o,this.code=mv(t)}toString(){return this.code}wrapInClosure(){const e=this.scope.nextVariableName(),t=new uv(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 uv(this.scope);return t.append(this.code),t.append(`const ${e} = ${this.returnExpression};`),t.return(e)}}class pv{nextId=1;declaredVariables=new Set;nextVariableName(){const e="_"+this.nextId++;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}}function mv(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 fv=Ug.content,bv=["%"],vv="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(bv);function Sv(e){e=It(e);const t=new Mv(e),o=[];for(;!t.isOver();){let e=Av(t)||wv(t)||xv(t)||Iv(t)||Cv(t)||Ov(t)||yv(t)||Tv(t);e||(e={type:"UNKNOWN",value:t.shift()}),o.push(e)}return o}function Cv(e){return"?"===e.current()?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const Ev={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function wv(e){if(e.current()in Ev){const t=e.shift();return{type:Ev[t],value:t}}return null}function xv(e){for(let t of vv)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:"OPERATOR",value:t};return null}function yv(e){const t=e.remaining().match(Xt);return t?(e.advanceBy(t[0].length),{type:"NUMBER",value:t[0]}):null}function Iv(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 Rv=/\w|\.|!|\$/;function Tv(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()&&Rv.test(e.current());)t+=e.shift();if(t.length){const e=t;if(e.toUpperCase()in fv)return{type:"FUNCTION",value:e};return Bo.test(e)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}function Av(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 Ov(e){return e.currentStartsWith(J)?(e.advanceBy(J.length),{type:"INVALID_REFERENCE",value:J}):null}class Mv{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 Nv=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,_v=["-","+"],Fv=["%"],Dv=["*","+","&"],Lv={"^":30,"%":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function kv(e){const t=e.shift();if(!t)throw new h(de);switch(t.type){case"DEBUGGER":const o=Vv(e,1e3);return o.debug=!0,o;case"NUMBER":return{type:"NUMBER",value:so(t.value)};case"STRING":return{type:"STRING",value:Ve(t.value)};case"FUNCTION":const i=function(e){Uv(e,"LEFT_PAREN",n("Missing opening parenthesis"));const t=e[0];if("RIGHT_PAREN"===t?.type)return Uv(e,"RIGHT_PAREN"),[];const o=[];o.push(Pv(e));for(;"RIGHT_PAREN"!==e[0]?.type;)Uv(e,"COMMA",n("Wrong function call")),o.push(Pv(e));return Uv(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&&Nv.test(t.value)&&"LEFT_PAREN"===e[0]?.type)throw new p(t.value);throw new h(n("Invalid formula"));case"LEFT_PAREN":const s=Vv(e);return Uv(e,"RIGHT_PAREN",n("Missing closing parenthesis")),s;case"OPERATOR":const r=t.value;if(_v.includes(r))return{type:"UNARY_OPERATION",value:r,operand:Vv(e,Lv[r])};throw new h(n("Unexpected token: %s",t.value));default:throw new h(n("Unexpected token: %s",t.value))}}function Pv(e){const t=e[0];return"COMMA"===t?.type||"RIGHT_PAREN"===t?.type?{type:"EMPTY",value:""}:Vv(e)}function Uv(e,t,o=de){const i=e.shift();if(!i||i.type!==t)throw new h(o)}function Vv(e,t=0){if(0===e.length)throw new h(de);let o=kv(e);for(;"OPERATOR"===e[0]?.type&&Lv[e[0].value]>t;){const t=e.shift().value;if(Fv.includes(t))o={type:"UNARY_OPERATION",value:t,operand:o,postfix:!0};else{o={type:"BIN_OPERATION",value:t,left:o,right:Vv(e,Lv[t])}}}return o}function zv(e){return Bv(Sv(e))}function Bv(e){"="===(e=e.filter((e=>"SPACE"!==e.type)))[0].value&&e.splice(0,1);const t=Vv(e);if(e.length)throw new h(de);return t}function Hv(e,t,o){switch(t===e.type&&(e=o(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>Hv(e,t,o)))};case"UNARY_OPERATION":return{...e,operand:Hv(e.operand,t,o)};case"BIN_OPERATION":return{...e,right:Hv(e.right,t,o),left:Hv(e.left,t,o)};default:return e}}function $v(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>$v(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?Wv(e)+e.value:e.value+Gv(e);case"BIN_OPERATION":return Wv(e)+e.value+Gv(e)}}function Wv(e){const t=e.value,o="left"in e?e.left:e.operand,i=o.value;return"BIN_OPERATION"===o.type&&Lv[i]<Lv[t]?`(${$v(o)})`:$v(o)}function Gv(e){const t=e.value,o="right"in e?e.right:e.operand,i=Lv[o.value],s=Lv[t];let n=!1;return"BIN_OPERATION"!==o.type?n=!1:i<s?n=!0:i!==s||Dv.includes(t)||(n=!0),n?`(${$v(o)})`:$v(o)}var qv;!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"}(qv||(qv={}));const Zv=(e,t=(()=>!0))=>[{goTo:e,guard:t}],jv=(e,t=(()=>!0))=>({goTo:e,guard:t}),Yv={[qv.LeftRef]:{REFERENCE:Zv(qv.Separator),NUMBER:Zv(qv.FullRowSeparator),SYMBOL:[jv(qv.FullColumnSeparator,(e=>Ho(e.value))),jv(qv.FullRowSeparator,(e=>$o(e.value)))]},[qv.FullColumnSeparator]:{SPACE:Zv(qv.FullColumnSeparator),OPERATOR:Zv(qv.RightColumnRef,(e=>":"===e.value))},[qv.FullRowSeparator]:{SPACE:Zv(qv.FullRowSeparator),OPERATOR:Zv(qv.RightRowRef,(e=>":"===e.value))},[qv.Separator]:{SPACE:Zv(qv.Separator),OPERATOR:Zv(qv.RightRef,(e=>":"===e.value))},[qv.RightRef]:{SPACE:Zv(qv.RightRef),NUMBER:Zv(qv.Found),REFERENCE:Zv(qv.Found,(e=>qo(e.value))),SYMBOL:Zv(qv.Found,(e=>Wo(e.value)||Go(e.value)))},[qv.RightColumnRef]:{SPACE:Zv(qv.RightColumnRef),SYMBOL:Zv(qv.Found,(e=>Wo(e.value))),REFERENCE:Zv(qv.Found,(e=>qo(e.value)))},[qv.RightRowRef]:{SPACE:Zv(qv.RightRowRef),NUMBER:Zv(qv.Found),REFERENCE:Zv(qv.Found,(e=>qo(e.value))),SYMBOL:Zv(qv.Found,(e=>Go(e.value)))},[qv.Found]:{}};function Xv(e){let t=0,o=Yv[qv.LeftRef];const 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 qv.Found:return i.push(s),e.splice(0,t),{type:"REFERENCE",value:pt(i.map((e=>e.value)))};default:o=Yv[r],i.push(s)}}return null}function Kv(e){const t=Sv(e),o=[];for(;t.length;)o.push(Xv(t)||t.shift());return o}const Qv=Ug.content,Jv={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},eS={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"},tS={};function oS(e){const t=Kv(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=so(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(so(e.value))}|`;case"REFERENCE":case"INVALID_REFERENCE":return`|${t.indexOf(e.value)}|`;case"SPACE":return"";default:return e.value}})))}(t,o,i);if(!tS[s]){const r=Bv([...t]),a=new pv;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 uv;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=Qv[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 uv(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||Jv["="]}", ${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=eS[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=Jv[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")}}tS[s]={execute:d}}return{execute:tS[s].execute,dependencies:o,constantValues:i,tokens:t}}function iS(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}))}(Kv(e))))}function sS(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function nS(e){return Math.round(fb*e*100)/100}function rS(e){return Math.round(bb*e*100)/100}function aS(e){if(e)return{style:e.style,color:{rgb:e.color}}}function lS(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=Sv(e.content||""),o=Ug.content;if(!t.filter((e=>"FUNCTION"===e.type)).every((e=>o[e.value.toUpperCase()].isExported)))return e.computedFormat}return}(e,t),s={};if(e.border){const o=t.borders[e.border];s.left=aS(o.left),s.right=aS(o.right),s.bottom=aS(o.bottom),s.top=aS(o.top)}const n={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:s||{},alignment:{horizontal:o.align,vertical:o.verticalAlign?Ub[o.verticalAlign]:void 0,wrapText:"wrap"===o.wrapping}};return n.font.strike=!!o?.strikethrough||void 0,n.font.underline=!!o?.underline||void 0,n.font.bold=!!o?.bold||void 0,n.font.italic=!!o?.italic||void 0,n}function cS(e,t){const{id:o}=dS(t.font,e.fonts),{id:i}=dS(t.fill,e.fills),{id:s}=dS(t.border,e.borders),n=function(e,t){if(!e)return 0;let o=qb[e.format];if(!o){const{id:i}=dS(e,t);o=i+wb}return o}(t.numFmt,e.numFmts),r={fontId:o,fillId:i,borderId:s,numFmtId:n,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal,wrapText:t.alignment.wrapText}},{id:a}=dS(r,e.styles);return a}function hS(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 dS(e,t){for(let[o,i]of Object.entries(t))if(JSON.stringify(i)===JSON.stringify(e))return{id:parseInt(o,10),list:t};let o=t.findIndex((t=>JSON.stringify(t)===JSON.stringify(e)));return-1===o&&(t.push(e),o=t.length-1),{id:o,list:t}}const uS=[];function gS(e){const t=uS.findIndex((t=>t===e));return-1===t?(uS.push(e),uS.length):t+1}const pS=[];function mS(e){const t=pS.findIndex((t=>t===e));return-1===t?(pS.push(e),pS.length):t+1}function fS(e){return Math.round(914400*e/96)}function bS(e,t,o){let i,s,n=e;if(({xc:n,sheetName:i}=Zo(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=ei(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 vS(e){return Math.round(96*e/914400)}function SS(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+=vb}return o/bb}function CS(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+=Sb}return o/fb}function ES(e){let t=1;return e.figures.map((o=>function(e,t,o){const i=SS(e.anchors[0].col,o)+vS(e.anchors[0].colOffset),s=SS(e.anchors[1].col,o)+vS(e.anchors[1].colOffset),n=CS(e.anchors[0].row,o)+vS(e.anchors[0].rowOffset),r=CS(e.anchors[1].row,o)+vS(e.anchors[1].rowOffset),a=s-i,l=r-n,c=wS(e.data);return c?{id:t,x:i,y:n,width:a,height:l,tag:"chart",data:wS(e.data)}:void 0}(o,(t++).toString(),e))).filter(dt)}function wS(e){const t=void 0!==e.dataSets[0].label,o=e.labelRange?xS(e.labelRange,t):void 0;let i=e.dataSets.map((e=>xS(e.range,t)));return"pie"===e.type&&i.reverse(),{dataSets:i,dataSetsHaveTitle:t,labelRange:o,title:e.title||"",type:e.type,background:Yb({rgb:e.backgroundColor})||"#FFFFFF",verticalAxisPosition:e.verticalAxisPosition,legendPosition:e.legendPosition,stacked:e.stacked||!1,aggregated:!1,cumulative:e.cumulative||!1,labelsAsText:!1}}function xS(e,t){let{sheetName:o,xc:i}=Zo(e);o=o?$e(o)+"!":"";let s=ei(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+ii(s)}const yS=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),IS=new RegExp(/SUBTOTAL\(([0-9]*),/g),RS=new RegExp(Lo.source,"ig");function TS(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:"="+OS(i.xc,o[i.formula.sharedIndex]),i.formula.content=AS(i.formula.content,t))}function AS(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(IS,((e,t)=>{const o=Wb[t];return o?o+"(":e}))).replace(yS,((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 OS(e,t){const o=Wt(t.refCellXc);let i,s=t.formula.slice();do{if(i=RS.exec(s),i){const t=Wt(i[0].replace("$","")),n=Wt(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)+Gt(l.col,l.row,r)+s.slice(i.index+i[0].length)}}while(i);return s}function MS(e,t){return e.sheets.map((o=>{TS(o,e);const i=function(e){const t=[0,0];for(let o of e.rows)t[0]=Math.max(t[0],...o.cells.map((e=>Wt(e.xc).col))),t[1]=Math.max(t[1],o.index);return t[0]=Math.max(t[0],Cb),t[1]=Math.max(t[1],Eb),t}(o),s=o.sheetViews[0];return{id:o.sheetName,areGridLinesVisible:!s||s.showGridLines,name:o.sheetName,colNumber:i[0],rowNumber:i[1],cells:FS(o,e,i,t),merges:o.merges,cols:NS(o,i[0]),rows:_S(o,i[1]),conditionalFormats:av(o.cfs,e.dxfs,t),figures:ES(o),isVisible:o.isVisible,panes:s?{xSplit:s.pane.xSplit,ySplit:s.pane.ySplit}:{xSplit:0,ySplit:0},filterTables:[]}}))}function NS(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:vb,o[s-1]={size:(i=n,i?Math.round(i/bb*100)/100:i),isHidden:t?.hidden}}var i;return o}function _S(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:Sb,o[s-1]={size:(i=n,i?Math.round(i/fb*100)/100:i),isHidden:t?.hidden}}var i;return o}function FS(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:DS(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=Gt(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=Gt(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 DS(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(Rb.BadlyFormattedHyperlink);const s=e.relTarget?e.relTarget:ct(Zo(e.location).sheetName);return nt(i,s)}(t[e.xc],s,i)),e.formula&&(s=e.formula.content),s}const LS={fillColor:"#000000",textColor:"#ffffff",bold:!0},kS={bold:!0},PS={style:"thin",color:"#000000FF"};function US(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=Qb(e.styles),i=Qb(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=ti(t.ref);for(let e=0;e<t.headerRowCount;e++)VS(LS,{...r,bottom:r.top+e},n.cells,o);for(let e=0;e<t.totalsRowCount;e++)VS(kS,{...r,top:r.bottom-e},n.cells,o);t.style?.showFirstColumn&&VS(kS,{...r,right:r.left},n.cells,o),t.style?.showLastColumn&&VS(kS,{...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=Gt(e,o),a=n.cells[s],l={left:e===r.left||t.style?.showColumnStripes?PS:void 0,right:e===r.right?PS:void 0,top:o===r.top||t.style?.showRowStripes||o>r.bottom-t.totalsRowCount?PS:void 0,bottom:o===r.bottom?PS: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=Kb(o),e.borders=Kb(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 vi(ti(t.ref))){const s=Gt(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=zS(i,t,s);n.content=n.content.slice(0,o)+a+n.content.slice(e.length+o+r+1)}}}}}}(e.sheets,t.sheets)}function VS(e,t,o,i){for(let s=t.left;s<=t.right;s++)for(let n=t.top;n<=t.bottom;n++){const t=Gt(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 zS(e,t,o){const i=e.split(","),s=ti(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=Wt(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?ii(n):Gt(n.left,n.top):J}function BS(e,t,o){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:o}}function HS(e){return String(e).replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\'/g,"&apos;").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"")}function $S(e){return new rb(e.map((([e,t])=>`${e}="${HS(t)}"`)).join(" "))}function WS(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 GS(e,t){return ZS`
1418
1418
  <Override ContentType="${t}" PartName="${e}" />
1419
- `}function qS(e){return new nb(e.join("\n"))}function ZS(e,...t){let o=[e[0]];for(let i=0;i<t.length;i++){const s=t[i]instanceof nb?t[i]:HS(t[i]);o.push(s+e[i+1])}return new nb(pt(o))}function jS(e){return e.replace(/[a-z0-9]+:(?=[a-z0-9]+)/gi,"")}function YS(e){return e.replace(/([a-z0-9]+):(?=[a-z0-9]+)/gi,"$1\\:")}class XS{value;constructor(e){this.value=e}asString(){return Jb(String(this.value))}asBool(){return"true"===this.value||"false"!==this.value&&Boolean(Number(this.value))}asNum(){return Number(this.value)}}class KS{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 XS(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?Jb(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 r=s?this.extractAttr(s,o,i)?.asString():i?.default;return void 0!==r?new XS(r):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?jS(t):YS(t),e.querySelector(t)}querySelectorAll(e,t){return t=this.areNamespaceIgnored?jS(t):YS(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 QS extends KS{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:lb}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:lb}).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 JS extends KS{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 eC extends KS{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},(e=>{const t=this.getChartType(e);if(!$b[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:$b[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:Hb[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=jS(e.tagName);if(ab.some((e=>e===t)))return t}throw new Error("Unknown chart type")}}class tC extends KS{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},(e=>{if("twoCellAnchor"!==jS(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 eC(o,this.xlsxFileStructure,this.warningManager).extractChart();if(!i)throw new Error("Unable to extract chart definition");return i}}class oC extends KS{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 iC extends KS{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 sC extends KS{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=Xb(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=Xb(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 JS(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 tC(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 iC(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 oC(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:vb.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:Sb.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:Db[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 rC extends KS{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,r=s&&"0"!==s.attributes.val?.value,n=this.querySelector(e,"b")||void 0,a=n&&"0"!==n.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:r,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"),r=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:r?this.extractAlignment(r):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 nC extends KS{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 aC(e,t){const o=function(e,t){const o=t[Ib],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=lC(i,t);o.push({file:{fileName:i,xml:t[i]},rels:e?{fileName:e,xml:t[e]}:void 0})}return o}(o,t)}function lC(e,t){if(e===Ib)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 cC{warningManager;xmls;constructor(e){this.warningManager=new Tb,this.xmls={};for(let t of Object.keys(e))(t.endsWith(".xml")||t.endsWith(".rels"))&&(this.xmls[t]=WS(new nb(e[t])))}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new QS(e.theme,e,this.warningManager).getTheme():void 0,o=e.sharedStrings?new QS(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 sC(o,e,this.warningManager,t).getSheet())),s=e.externalLinks.map((t=>new nC(t,e,this.warningManager).getExternalBook())),r=new rC(e,this.warningManager,t);return{fonts:r.getFonts(),fills:r.getFills(),borders:r.getBorders(),dxfs:r.getDxfs(),numFmts:r.getNumFormats(),styles:r.getStyles(),sheets:i,sharedStrings:o,externalBooks:s}}buildXlsxFileStructure(){const e={sheets:aC(gb.sheet,this.xmls),workbook:aC(gb.workbook,this.xmls)[0],styles:aC(gb.styles,this.xmls)[0],sharedStrings:aC(gb.sharedStrings,this.xmls)[0],theme:aC(gb.themes,this.xmls)[0],charts:aC(gb.chart,this.xmls),figures:aC(gb.drawing,this.xmls),tables:aC(gb.table,this.xmls),pivots:aC(gb.pivot,this.xmls),externalLinks:aC(gb.externalLink,this.xmls)};if(!e.workbook.rels)throw Error(r("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:12,sheets:MS(e,this.warningManager),styles:sv(e,this.warningManager),formats:nv(e,this.warningManager),borders:ov(e,this.warningManager),entities:{},revisionId:ee};return US(t,e),Object.keys(e.styles).map((t=>{e.styles[t]=Ct(e.styles[t])})),t}}function hC(e){const t=Kv(e);let o=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&Lo.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 dC=13,uC="Sheet1";function gC(e,t){if(!e)return vC();if(e["[Content_Types].xml"]){const o=new cC(e);if(e=o.convertXlsx(),t)for(let e of o.warningManager.warnings.sort())console.warn(e)}return"version"in e&&e.version<dC&&(e=function(e){for(let t=pC.findIndex((t=>t.from===e.version));t<pC.length;t++)e=pC[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,o=new Jo;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(vC(),e,{version:dC}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(bC(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(bC(uC,"Sheet1"));return e}(e),e}(e),e}const pC=[{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=hC(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=ti(e.dataRange),o=e.labelCell+":"+Gt(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 r=1,n=s;for(;t.includes(n);)n=`${s}${r}`,r++;i.name=n,t.push(n);const a=t=>{if(void 0===t)return t;let o=t.replace(e,n),i=t;for(;i!==o;)i=o,o=i.replace(e,n);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:"Change Border description structure",from:12,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 mC(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:uC};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=fC(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=fC(t,"SET_DECIMAL")),t}function fC(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 bC(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[],filterTables:[],isVisible:!0}}function vC(e="Sheet1"){return{version:dC,sheets:[bC(uC,e)],entities:{},styles:{},formats:{},borders:{},revisionId:ee,uniqueFigureIds:!0}}function SC(e,t){return{...bC(e,t),charts:[],images:[]}}class CC{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 EC extends CC{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 wC(e){return""===e?NaN:Number(e)}class xC{id;zone;filters;constructor(e){this.filters=[],this.zone=e;const t=new Jo;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 yC(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 xC(this.zone)}}class yC{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 IC(e){return Object.entries(e).map((([e,t])=>t?RC(parseInt(e,10),t):void 0)).filter(dt).map((e=>Gt(e.left,e.top)+":"+Gt(e.right,e.bottom)))}function RC(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}class TC{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 r=Qe(s);this.executeOnAllRanges((s=>{if(s.sheetId!==e.sheetId)return{changeType:"NONE"};let n=s,a="NONE";for(let e of r){const r=Math.min(...e),l=Math.max(...e);if(s.zone[t]<=r&&r<=s.zone[o]){const e=Math.min(s.zone[o],l)-r+1;a="RESIZE",n=this.createAdaptedRange(n,i,a,-e)}else if(s.zone[t]>=r&&s.zone[o]<=l)a="REMOVE",n=s.clone({...this.getInvalidRange()});else if(s.zone[t]<=l&&s.zone[o]>=l){const e=l-s.zone[t]+1;a="RESIZE",n=this.createAdaptedRange(n,i,a,-e),n=this.createAdaptedRange(n,i,"MOVE",-(s.zone[t]-r))}else r<s.zone[t]&&(a="MOVE",n=this.createAdaptedRange(n,i,a,-(l-r+1)))}return"NONE"!==a?{changeType:a,range:n}:{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||!gi(o.zone,t))return{changeType:"NONE"};const i=e.targetSheetId,s=e.col-t.left,r=e.row-t.top,n=this.createAdaptedRange(o,"both","MOVE",[s,r]),a=e.sheetId!==i||n.prefixSheet;return{changeType:"MOVE",range:n.clone({sheetId:i,prefixSheet:a})}}));break}}}finalize(){}verifyRangeRemoved(e){return t=>{const o=e(t);return"NONE"===o.changeType||oi(o.range.zone)?o:{range:o.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,o,i){const s=Si(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=>jo.fromRange(e,this.getters)));return s.map((e=>{if(!oi(e.zone))return e;const s=e.prefixSheet?e.sheetId:i,r={...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:r}).orderZone()}))}getRangeFromSheetXC(e,t){if(!Bo.test(t))return new jo({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}=Zo(t)),o&&(s=!0));const r=ei(i),n=jo.getRangeParts(i,r),a=o&&!this.getters.getSheetIdByName(o)?o:void 0,l=this.getters.getSheetIdByName(o)||e;return new jo({prefixSheet:s,zone:r,sheetId:l,invalidSheetName:a,parts:n},this.getters.getSheetSize).orderZone()}getSelectionRangeString(e,t){const o=jo.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){if(!e)return J;if(e.invalidXc)return e.invalidXc;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 o=jo.fromRange(e,this.getters);let i=o.sheetId!==t||o.invalidSheetName||o.prefixSheet,s="";if(i&&(s=o.invalidSheetName?o.invalidSheetName:$e(this.getters.getSheetName(o.sheetId))),i&&!s)return J;let r=this.getRangePartString(o,0);return o.parts&&2===o.parts.length&&(o.zone.top!==o.zone.bottom||o.zone.left!==o.zone.right||o.parts[0].rowFixed||o.parts[0].colFixed||o.parts[1].rowFixed||o.parts[1].colFixed)&&(r+=":",r+=this.getRangePartString(o,1)),`${i?s+"!":""}${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 jo(t,this.getters.getSheetSize)}getRangePartString(e,t){const o=e.parts&&e.parts[t].colFixed?"$":"",i=Vt(0===t?e.zone.left:e.zone.right),s=e.parts&&e.parts[t].rowFixed?"$":"",r=String(0===t?e.zone.top+1:e.zone.bottom+1);let n="";return n=e.isFullCol?0===t&&e.unboundedZone.hasHeader?o+i+s+r:o+i:e.isFullRow?0===t&&e.unboundedZone.hasHeader?o+i+s+r:s+r:o+i+s+r,n}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:J}}}class AC extends CC{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 OC=Ug.mapping;class MC{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;offsetScrollbarX;offsetScrollbarY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,o,i,s,r){this.getters=e,this.sheetId=t,this.boundaries=o,this.viewportWidth=i.width,this.viewportHeight=i.height,this.offsetScrollbarX=r.x,this.offsetScrollbarY=r.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:r}=this.getters.getRowDimensions(this.sheetId,t),n=this.searchHeaderIndex("COL",o-this.viewportWidth,0),a=this.getters.getColSize(this.sheetId,n),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-r)),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);ui(i,this.boundaries.top,this.boundaries)&&this.adjustPositionX(i),ui(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,r=this.searchHeaderIndex("COL",s-this.viewportWidth-this.offsetCorrectionX,this.boundaries.left,!0);this.offsetX=this.getters.getColDimensions(t,r).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,r=this.searchHeaderIndex("ROW",s-this.viewportHeight-this.offsetCorrectionY,this.boundaries.top,!0);this.offsetY=this.getters.getRowDimensions(t,r).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=ci(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 r=this.sheetId,n=this.getters.getNumberHeaders(r,e);for(let a=o;a<=n-1;a++){const o=i||"COL"!==e?a<this.top&&a>this.bottom:a<this.left&&a>this.right;if(!this.getters.isHeaderHidden(r,e,a)&&!o&&(s+="COL"===e?this.getters.getColSize(r,a):this.getters.getRowSize(r,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 NC{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}=Hs.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 _C{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 FC(e,t){return{...e,definition:Qn(e.definition,t)}}function DC(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}_m.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],FC),_m.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],FC),_m.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const o=t.sheetId;if(e.targetSheetId===o||e.sheetId===o)return;return e})),_m.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),_m.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})),_m.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)di(i,e)||o.push({...i});if(o.length)return{...e,target:o};return})),_m.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],DC),_m.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],DC),_m.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(di(e,o))return;return e}));const LC=[{match:function(e){return"sheetId"in e},fn:UC},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const o=UC(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;const i=[];for(const o of e.target){const e=Pr(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=UC(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)&&ui(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=UC(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=Pr(s._zone,t);e&&i!==s._sheetId&&o.push({...s,_zone:e})}if(!o.length)return"IGNORE_COMMAND";return{...e,ranges:o}}}];function kC(e,t){const o=_m.getTransformation(e.type,t.type);return o?o(e,t):function(e,t){for(const{match:o,fn:i}of LC)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 PC(e,t){let o=[...e];for(const e of t)o=o.map((t=>kC(t,e))).filter(dt);return o}function UC(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 VC{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,o,i,s,r){this.rootCommand=i,this.timestamp=r,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 zC extends Error{}class BC extends _C{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;uuidGenerator=new Jo;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,r=arguments,n=o&&!i;clearTimeout(i),i=setTimeout((function(){i=null,o||e.apply(s,r)}),t),n&&e.apply(s,r)}}(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,o){if(!t.length||!o.length||!this.canApplyOptimisticUpdate())return;const i=new VC(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 zC("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 VC(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:PC(o,t)})}break;case"SNAPSHOT_CREATED":{const t=new VC(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 HC=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];var $C;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}($C||($C={}));class WC extends AC{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())}allowDispatch(e){switch(e.type){case"ADD_EMPTY_RANGE":if(this.inputHasSingleRange&&1===this.ranges.length)return 30;break;case"CHANGE_RANGE":if(this.inputHasSingleRange&&e.value.split(",").length>1)return 30}return 0}handleEvent(e){const t=ii(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,wi({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:At[(o+t)%At.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}=Zo(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}=Zo(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 GC=[qC,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 qC(e,t){return"sheetId"in t?{...Be(t),sheetId:e.getActiveSheetId()}:t}const ZC=new Jo;function jC(e,t){const o=e.getSelectedZone();return{...qC(e,t),elements:"COL"===t.dimension?Ke(o.left,o.right+1):Ke(o.top,o.bottom+1)}}function YC(e,t){const o=e.getSelectedZone();return{...Be(t),zone:o}}function XC(e,t){const o=Be(t),i=e.getSelectedZone(),{top:s,bottom:r,left:n,right:a}=i;return"cols"in o?o.cols=Ke(n,a+1):"rows"in o&&(o.rows=Ke(s,r+1)),o}const KC=new Ui;KC.add("UPDATE_CELL",JC),KC.add("CLEAR_CELL",JC),KC.add("DELETE_CONTENT",JC),KC.add("ADD_MERGE",JC),KC.add("REMOVE_MERGE",JC),KC.add("SET_FORMATTING",JC),KC.add("CLEAR_FORMATTING",JC),KC.add("SET_BORDER",JC),KC.add("CREATE_FILTER_TABLE",JC),KC.add("REMOVE_FILTER_TABLE",JC),KC.add("HIDE_SHEET",JC),KC.add("ADD_COLUMNS_ROWS",(function(e,t){const o=e.getActivePosition();return{...qC(e,t),base:"COL"===t.dimension?o.col:o.row}})),KC.add("REMOVE_COLUMNS_ROWS",jC),KC.add("HIDE_COLUMNS_ROWS",jC),KC.add("RESIZE_COLUMNS_ROWS",jC),KC.add("CREATE_SHEET",(function(e,t){const o=Be(t);o.sheetId=ZC.uuidv4();const i=t.name||e.getSheet(e.getActiveSheetId()).name,s=i.match(/(.+?)\d*$/)?.[1]||i;return o.name=e.getNextSheetName(s),o})),KC.add("CREATE_FIGURE",(function(e,t){const o=qC(e,t);return o.figure.id=ZC.uuidv4(),o})),KC.add("CREATE_CHART",(function(e,t){return{...qC(e,t),id:ZC.uuidv4()}})),KC.add("CREATE_IMAGE",(function(e,t){return{...qC(e,t),figureId:ZC.uuidv4()}}));const QC=new Ui;function JC(e,t){let o=Be(t);for(const t of GC)o=t(e,o);return o}function eE(e,t){if(!t)return;if(!KC.contains(t.type))return;return KC.get(t.type)(e,t)}function tE(e,t){if(e.rootCommand&&"object"==typeof e.rootCommand)return As(e.rootCommand)?eE(t,e.rootCommand):function(e,t,o){if(!QC.contains(t.type))return;return QC.get(t.type)(e,t,o)}(t,e.rootCommand,e.commands)}QC.add("STOP_EDITION",(function(e,t,o){return o.map((t=>eE(e,t))).filter(dt)})),QC.add("PASTE",(function(e,t){return{type:"REPEAT_PASTE",pasteOption:Be(t.pasteOption),target:e.getSelectedZones()}})),QC.add("INSERT_CELL",YC),QC.add("DELETE_CELL",YC),QC.add("AUTORESIZE_COLUMNS",XC),QC.add("AUTORESIZE_ROWS",XC),QC.add("SORT_CELLS",(function(e,t){const o=e.getSelectedZone();return{...qC(e,t),col:o.left,row:o.top,zone:o}})),QC.add("SUM_SELECTION",JC),QC.add("SET_DECIMAL",JC);class oE{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(),r=t+i-this.getters.getNumberRows(s);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(s)-1,sheetId:s,quantity:r,position:"after"});const n=e+o-this.getters.getNumberCols(s);n>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(s)-1,sheetId:s,quantity:n,position:"after"})}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class iE extends oE{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 r=new Set(e.map((e=>e.left))),n=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===r.size&&1===n.size?function(e){return e.reduce(((e,t)=>{const o=e.length;for(let i=0;i<o;i++)if(di(e[i],t))return e[i]=li(e[i],t),e;return e[o]=t,e}),[])}(e):[e[e.length-1]],h=c.map((e=>vi(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:r,ySplit:n}=this.getters.getPaneDivisions(o);for(const t of this.getPasteZones(e))if(t.left<r&&t.right>=r||t.top<n&&t.bottom>=n)return 75;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)),r=Math.max(1,Math.floor((i.bottom+1-i.top)/o)),n=[];for(let e=0;e<s;e++)for(let s=0;s<r;s++){const r=i.top+s*o,a=i.left+e*t;n.push({left:a,top:r,bottom:r+o-1,right:a+t-1})}return n}getPasteZones(e){const t=this.cells;if(!t.length||!t[0].length)return e;const o=[],i=t.length,s=t[0].length,r=e[e.length-1],n=r.left,a=r.top,l=Math.max(1,Math.floor((r.right+1-n)/s)),c=Math.max(1,Math.floor((r.bottom+1-a)/i));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)o.push({left:n,top:a,right:n-1+e*s,bottom:a-1+t*i});return o}selectPastedZone(e,t,o,i){const s=i[0],r=s.left,n=s.top;if(t>1||e>1||o){const s=this.pastedZones(i,e,t),a=o?s[0]:li(...s);this.selection.selectZone({cell:{col:r,row:n},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,r="onlyValue"!==o?.pasteOption&&o?.shouldPasteCF,n=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:n};"CUT"!==this.operation&&this.pasteMergeIfExist(s.position,c),this.pasteCell(s,c,this.operation,o),r&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{originPosition:s.position,targetPosition:c,operation:this.operation})}}}pasteCell(e,t,o,i){const{sheetId:s,col:r,row:n}=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:r,row:n,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=mo(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=r-e.position.col,i=n-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 r=this.getters.createAdaptedRanges(t.dependencies,o,i,e);return this.getters.buildFormulaContent(e,t,r)}pasteMergeIfExist(e,t){let{sheetId:o,col:i,row:s}=e;const{col:r,row:n}=this.getters.getMainCellPosition(e);if(r===i&&n===s){const r=this.getters.getMerge(e);if(!r)return;({sheetId:o,col:i,row:s}=t),this.dispatch("ADD_MERGE",{sheetId:o,force:!0,target:[{left:i,top:s,right:i+r.right-r.left,bottom:s+r.bottom-r.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=Si(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{[xs.PlainText]:this.getPlainTextContent(),[xs.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="${Fi(Ni(o.style))}">`+HS(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:r}=this.getters.getVisibleRect(e);s>0&&r>0&&t.strokeRect(o,i,s,r)}}}}class sE{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 rE(o,t,this.sheetId,i);break;case"image":this.copiedFigureContent=new nE(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?73:void 0!==t?.pasteOption?22:0}paste(e){const t=this.getters.getActiveSheetId(),{width:o,height:i}=this.copiedFigure,s=this.getters.getNumberCols(t),r=this.getters.getNumberRows(t),n=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,r-1).end,h={x:l<o?0:Math.min(n,l-o),y:c<i?0:Math.min(a,c-i)},d=(new Jo).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{[xs.PlainText]:"\t"}}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class rE{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 nE{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 aE extends oE{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:r,numberOfRows:n}=fi(o),a=this.getters.getActiveSheetId();this.addMissingDimensions(r,n,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+r-1,bottom:s+n-1};this.selection.selectZone({cell:{col:i,row:s},zone:l})}getClipboardContent(){return{[xs.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 lE(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:o}=Zo(e.value),[i,s]=t.split(":"),r=o?`${$e(o)}!`:"",n=cE(i),a=s?`:${cE(s)}`:"";return{...e,value:r+n+a}}function cE(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=hE(e,"colrow");break;case"colrow":e=hE(e,"row");break;case"row":e=hE(e,"col");break;case"col":e=hE(e,"none")}return e}function hE(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 dE=r("The cell you are trying to edit has been deleted.");const uE=[{name:r("Sum"),types:[ws.number],compute:e=>Kl.compute([e])},{name:r("Avg"),types:[ws.number],compute:e=>lc.compute([e])},{name:r("Min"),types:[ws.number],compute:e=>Ic.compute([e])},{name:r("Max"),types:[ws.number],compute:e=>Ec.compute([e])},{name:r("Count"),types:[ws.number,ws.text,ws.boolean,ws.error],compute:e=>fc.compute([e])},{name:r("Count Numbers"),types:[ws.number,ws.text,ws.boolean,ws.error],compute:e=>mc.compute([e])}];const gE=(new Ui).add("sheet",class extends EC{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?86:e.quantity<=0?87:0;case"REMOVE_COLUMNS_ROWS":{const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return Math.min(...e.elements)<0||Math.max(...e.elements)>t?86:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?8:0}case"FREEZE_ROWS":return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case"FREEZE_COLUMNS":return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return 0}}handle(e){switch(e.type){case"SET_GRID_LINES_VISIBILITY":this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case"DELETE_CONTENT":this.clearZones(e.sheetId,e.target);break;case"CREATE_SHEET":const t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update("sheetIdsMapName",t.name,t.id);break;case"MOVE_SHEET":this.moveSheet(e.sheetId,e.delta);break;case"RENAME_SHEET":this.renameSheet(this.sheets[e.sheetId],e.name);break;case"HIDE_SHEET":this.hideSheet(e.sheetId);break;case"SHOW_SHEET":this.showSheet(e.sheetId);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case"UPDATE_CELL_POSITION":this.updateCellPosition(e);break;case"FREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,e.quantity,"COL");break;case"FREEZE_ROWS":this.setPaneDivisions(e.sheetId,e.quantity,"ROW");break;case"UNFREEZE_ROWS":this.setPaneDivisions(e.sheetId,0,"ROW");break;case"UNFREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,0,"COL");break;case"UNFREEZE_COLUMNS_ROWS":this.setPaneDivisions(e.sheetId,0,"COL"),this.setPaneDivisions(e.sheetId,0,"ROW")}}import(e){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),r={id:t.id,name:e,numberOfCols:o,rows:Qo(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(r.id),this.sheets[r.id]=r}}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,r=this.getters.getNumberHeaders(e,t);if(!s)return!1;return St(o,Ke(s,r))}isEmpty(e,t){return vi(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(oi))return 25;if(t.length){const o=this.getSheetZone(e);return t.every((e=>gi(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 r={id:e,name:t,numberOfCols:o,rows:Qo(i),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},n=this.orderedSheetIds.slice();n.splice(s,0,r.id);const a=this.sheets;return this.history.update("orderedSheetIds",n),this.history.update("sheets",Object.assign({},a,{[r.id]:r})),r}moveSheet(e,t){const o=this.orderedSheetIds.slice(),i=o.findIndex((t=>t===e)),s=o.splice(i,1);let r=this.findIndexOfTargetSheet(i,t);o.splice(r,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(r("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:74}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?0:74}checkRowFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let o of t)if(o.top<e.quantity&&e.quantity<=o.bottom)return 65;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 65;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 r=this.orderedSheetIds.slice(),n=r.indexOf(e);r.splice(n+1,0,s.id),this.history.update("orderedSheetIds",r),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=r("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 r=Object.assign({},this.sheetIdsMapName);delete r[t],this.history.update("sheetIdsMapName",r)}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 r=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",r+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 r=Number(s),n=i.cells[s];n&&(r===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:r,row:o}),r>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:n,col:r-1,row:o}))}}}moveCellsOnAddition(e,t,o,i){const s=[];for(let r=0;r<e.rows.length;r++){const n=e.rows[r];if("rows"!==i||r>=t)for(let a in n.cells){const l=Number(a),c=n.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:r+("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 r=e.rows[s];if(s>=t&&s<=o)for(let t in r.cells){const o=Number(t);r.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:o,row:s})}if(s>o)for(let t in r.cells){const o=Number(t),n=r.cells[t];n&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:n,col:o,row:s-i})}}}updateRowsStructureOnDeletion(e,t,o){const i=[],s=e.rows.map((e=>e.cells)).reverse();for(let r in e.rows){const e=Number(r);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(Wt);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 EC{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?66:Math.min(...e.elements)<0||Math.max(...e.elements)>o?86:0}case"REMOVE_COLUMNS_ROWS":return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?8:0:27}return 0}handle(e){switch(e.type){case"CREATE_SHEET":const t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update("hiddenHeaders",e.sheetId,t);break;case"DUPLICATE_SHEET":this.history.update("hiddenHeaders",e.sheetIdTo,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 EC{static getters=["doesZonesContainFilter","getFilter","getFilters","getFilterTable","getFilterTables","getFilterTablesInZone","getFilterId"];tables={};allowDispatch(e){switch(e.type){case"CREATE_FILTER_TABLE":if(!Ii(...e.target))return 81;const t=li(...e.target),o=()=>this.getFilterTables(e.sheetId).some((e=>di(e.zone,t)))?78:0,i=()=>{const o=this.getters.getMergesInZone(e.sheetId,t);for(let e of o)if(di(t,e))return 80;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(di(o.zone,t))return 80}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break;case"DUPLICATE_SHEET":const 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=li(...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=>!ci(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=>ui(t,o,e.zone)))}getFilterTablesInZone(e,t){return this.getFilterTables(e).filter((e=>gi(e.zone,t)))}doesZonesContainFilter(e,t){for(const o of t)for(const t of this.getFilterTables(e))if(ci(o,t.zone))return!0;return!1}onAddColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const o=si(t.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),i=[];for(const o of t.filters){const t=si(o.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);i.push(new yC(o.id,t))}if(i.length<fi(o).numberOfCols){for(let e=o.left;e<=o.right;e++)i.find((t=>t.col===e))||i.push(new yC(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=ai(t.zone,"COL"===e.dimension?"left":"top",e.elements);if(o){if(ii(o)!==ii(t.zone)){const i=[];for(const o of t.filters){const t=ai(o.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.elements);t&&i.push(new yC(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 xC(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 r=s.zone;if(!(r.bottom+1===i&&o>=r.left&&o<=r.right))return!1;for(const e of Ke(r.left,r.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(ti(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:ii(e.zone)})}exportForExcel(e){this.export(e)}}).add("cell",class extends EC{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.checkCellOutOfSheet(e);case"CLEAR_CELL":return this.checkValidations(e,this.chainValidations(this.checkCellOutOfSheet,this.checkUselessClearCell));default:return 0}}handle(e){switch(e.type){case"SET_FORMATTING":"style"in e&&this.setStyle(e.sheetId,e.target,e.style),"format"in e&&void 0!==e.format&&this.setFormatter(e.sheetId,e.target,e.format);break;case"CLEAR_FORMATTING":this.clearFormatting(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case"UPDATE_CELL":this.updateCell(e.sheetId,e.col,e.row,e);break;case"CLEAR_CELL":this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col,row:e.row,content:"",style:null,format:""})}}setFormatter(e,t,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:r}=Wt(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:r,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[Gt(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,r=t.format&&i[t.format]||void 0,n=this.getNextUid();return this.createCell(n,t?.content||"",r,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){const i=o||t.dependencies;let s=0;return pt(t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=i[s++];return this.getters.getRangeString(t,e)}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=Gt((t=this.getters.expandZone(e,t)).left,t.top,o[0]),s=Gt(t.right,t.bottom,o.length>1?o[1]:o[0]),r=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),n=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=r.col===n.col&&r.row===n.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}),r=this.getters.getCell(s);return r&&(r.style&&(i.style=r.style),r.format&&(i.format=r.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}),r="content"in i||"formula"in i,n=r?It(i?.content):s?.content||"";let a;a=void 0!==i.style?i.style||void 0:s?s.style:void 0;let l=("format"in i?i.format:s&&s.format)||To(n);if((r&&!n&&!i.formula||!r&&(!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,n,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,isFormula:!1}}createFormulaCell(e,t,o,i,s){const r=oS(t);return r.dependencies.length?this.createFormulaCellWithDependencies(e,r,o,i,s):{id:e,content:t,style:i,format:o,isFormula:!0,compiledFormula:r,dependencies:[]}}createFormulaCellWithDependencies(e,t,o,i,s){const r=t.dependencies.map((e=>this.getters.getRangeFromSheetXC(s,e))),n=this.buildFormulaContent.bind(this);return{id:e,get content(){return n(s,{dependencies:this.dependencies,compiledFormula:this.compiledFormula})},style:i,format:o,isFormula:!0,compiledFormula:t,dependencies:r}}createErrorFormula(e,t,o,i,s){return{id:e,content:t,style:i,format:o,isFormula:!0,compiledFormula:{dependencies:[],tokens:Sv(t),execute:function(){throw s}},dependencies:[]}}checkCellOutOfSheet(e){const{sheetId:t,col:o,row:i}=e;if(!this.getters.tryGetSheet(t))return 27;return ui(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:93}}).add("merge",class extends EC{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 vi(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){return vi(t).some((({col:t,row:o})=>void 0!==this.getMerge({sheetId:e,col:t,row:o})))}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:r}=t,n={left:o,right:i,top:s,bottom:r};for(let t in this.merges[e]){const o=this.getMergeById(e,parseInt(t));o&&di(o,n)&&(n=li(o,n))}return hi(n,t)?n:this.expandZone(e,n)}isInSameMerge(e,t,o,i,s){const r=this.getMerge({sheetId:e,col:t,row:o}),n=this.getMerge({sheetId:e,col:i,row:s});return!(!r||!n)&&hi(r,n)}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 hi(t,o);const{numberOfCols:i,numberOfRows:s}=fi(t);return 1===i&&1===s}isMergeDestructive(e,t){let{left:o,right:i,top:s,bottom:r}=t;i=We(i,0,this.getters.getNumberCols(e)-1),r=We(r,0,this.getters.getNumberRows(e)-1);for(let t=s;t<=r;t++)for(let r=o;r<=i;r++)if(r!==o||t!==s){const o=this.getters.getCell({sheetId:e,col:r,row:t});if(o&&""!==o.content)return!0}return!1}getMergeById(e,t){const o=this.merges[e]?.[t];return void 0!==o?RC(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&&di(t,o))return 65;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 75;return 0}checkMergedContentUpdate(e){const{col:t,row:o,content:i}=e;if(void 0===i)return 0;const{col:s,row:r}=this.getMainCellPosition(e);return s===t&&r===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||!hi(e,s))return 5}return 0}addMerge(e,t){let{left:o,right:i,top:s,bottom:r}=t;i=We(i,0,this.getters.getNumberCols(e)-1),r=We(r,0,this.getters.getNumberRows(e)-1);if(Gt(o,s)===Gt(i,r))return;const n=this.getters.getCell({sheetId:e,col:o,row:s});let a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,ii({left:o,top:s,right:i,bottom:r})));let l=new Set;for(let t=s;t<=r;t++)for(let r=o;r<=i;r++){r===o&&t===s||this.dispatch("UPDATE_CELL",{sheetId:e,col:r,row:t,style:n?n.style:null,content:""});const i=this.getMerge({sheetId:e,col:r,row:t});i&&l.add(i.id),this.history.update("mergeCellMap",e,r,t,a)}for(let t of l){const{top:o,bottom:i,left:s,right:r}=this.getMergeById(e,t);for(let t=o;t<=i;t++)for(let o=s;o<=r;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:r}=t,n=this.getMerge({sheetId:e,col:o,row:i});if(void 0!==n&&hi(t,n)){this.history.update("merges",e,n.id,void 0);for(let t=i;t<=s;t++)for(let i=o;i<=r;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,r=t(s);switch(r.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,o);break;default:const{numberOfCols:t,numberOfRows:s}=fi(r.range.zone);1===t&&1===s?this.removeMerge(e,o):this.history.update("merges",e,parseInt(i,10),r.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:o,row:i}of vi(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,ti(o))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...IC(e))}}exportForExcel(e){this.export(e)}}).add("headerSize",class extends EC{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=Math.min(...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),r=this.getCellHeight(s);r>i&&r>k&&(i=r)}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 EC{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)"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 r=this.getCellBorder({sheetId:e,col:t,row:s}),n=this.getCellBorder({sheetId:e,col:o,row:s});if(r&&n){const t=this.getCommonSides(r,n);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 r=this.getCellBorder({sheetId:e,col:s,row:t}),n=this.getCellBorder({sheetId:e,col:s,row:o});if(r&&n){const t=this.getCommonSides(r,n);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 r=this.borders[e];r&&this.getColumnsWithBorders(e).forEach((n=>{const a=r[n]?.[t+o]?.[i],l=r[n]?.[t]?.[i];this.history.update("borders",e,n,t+o,i,s?l:l||a),this.history.update("borders",e,n,t,i,void 0)}))}moveBordersOfColumn(e,t,o,i,{destructive:s}={destructive:!0}){const r=this.borders[e];r&&this.getRowsRange(e).forEach((n=>{const a=r[t+o]?.[n]?.[i],l=r[t]?.[n]?.[i];this.history.update("borders",e,t+o,n,i,s?l:l||a),this.history.update("borders",e,t,n,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:r}=t,n=this.getCellBorder({sheetId:e,col:o,row:s}),a=this.getCellBorder({sheetId:e,col:i,row:r});this.clearBorders(e,[t]),n?.top&&this.setBorders(e,[{...t,bottom:s}],"top",n.top),n?.left&&this.setBorders(e,[{...t,right:o}],"left",n.left),a?.bottom?this.setBorders(e,[{...t,top:r}],"bottom",a.bottom):n?.bottom&&this.setBorders(e,[{...t,top:r}],"bottom",n.bottom),a?.right?this.setBorders(e,[{...t,left:i}],"right",a.right):n?.right&&this.setBorders(e,[{...t,left:i}],"right",n.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)?93: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:r,row:n}=Wt(o);this.setBorder(t.id,r,n,s,!1)}}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,ti(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 r=Gt(e,o),n=t.cells[r],a=i(s);n?n.border=a:t.cells[r]={border:a}}}e.borders=o}exportForExcel(e){this.export(e)}}).add("conditional formatting",class extends EC{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){this.export(e)}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)ui(t,o,e.zone)&&i.push(s);return new Set(i.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e)))}}mapToConditionalFormatInternal(e,t){const 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 71;const s="up"===t?i-1:i+1;return s<0||s>=this.cfRules[o].length?71:0}checkEmptyRange(e){return e.ranges.length?0:24}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber(2,["Between","NotBetween"]),this.checkOperatorArgsNumber(1,["BeginsWith","ContainsText","EndsWith","GreaterThan","GreaterThanOrEqual","LessThan","LessThanOrEqual","NotContains"]),this.checkOperatorArgsNumber(0,["IsEmpty","IsNotEmpty"]));case"ColorScaleRule":return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case"IconSetRule":return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)))}return 0}checkOperatorArgsNumber(e,t){if(e>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");return o=>{if(t.includes(o.operator)){const t=[],i=e=>void 0===e||""===e;return e>=1&&i(o.values[0])&&t.push(51),e>=2&&i(o.values[1])&&t.push(52),t.length?t:0}return 0}}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return 53;case"max":return 55;case"mid":return 54;case"upperInflectionPoint":return 56;case"lowerInflectionPoint":return 57}return 0}checkFormulaCompilation(e,t){if("formula"!==e.type)return 0;try{oS(e.value||"")}catch(e){switch(t){case"min":return 58;case"max":return 60;case"mid":return 59;case"upperInflectionPoint":return 61;case"lowerInflectionPoint":return 62}}return 0}checkThresholds(e){return this.batchValidations((t=>e(t.minimum,"min")),(t=>e(t.maximum,"max")),(t=>t.midpoint?e(t.midpoint,"mid"):0))}checkInflectionPoints(e){return this.batchValidations((t=>e(t.lowerInflectionPoint,"lowerInflectionPoint")),(t=>e(t.upperInflectionPoint,"upperInflectionPoint")))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,o=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(o)?48: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&&wC(t)>=wC(o)?47: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&&wC(t)>=wC(o)?49: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&&wC(t)>=wC(o)?50: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 EC{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}}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]?70:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>t?.[e]))?82: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 EC{static getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];charts={};createChart=function(e){const t=Vn.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(o,i,s){const r=t.find((e=>e.match(i.type)));if(!r)throw new Error(`No builder for this chart: ${i.type}`);return r.createChart(i,s,e)}}(this.getters);validateChartDefinition=e=>function(e,t){const o=Vn.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)?84:0}checkChartExists(e){return this.getters.getFigureSheetId(e.id)?0:85}}).add("image",class extends EC{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}}),pE=(new Ui).add("ui_sheet",class extends AC{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 r="",n=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)""!==r&&(s.push(r),r="",n=t),i.forEach((e=>{s.push(e)})),r=a,n=t-l;else{const e=""===r?a:" "+a,i=qe(this.ctx,e,o);i<=n?(r+=e,n-=i):(s.push(r),r=a,n=t-l)}}""!==r&&s.push(r)}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 r=t;r<o;r++)this.getters.isHeaderHidden(i,e,r)||(s+="COL"===e?this.getters.getColSize(i,r):this.getters.getRowSize(i,r));return s}getColMaxWidth(e,t){const o=vi(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,...o)}splitWordToSpecificWidth(e,t,o,i){if(qe(e,t,i)<=o)return[t];const s=[];let r="";for(let n of t){qe(e,r+n,i)>o?(s.push(r),r=n):r+=n}return s.push(r),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?92:t&&o.length>0?this.getters.checkZonesExistInSheet(t,o):0}}).add("header_visibility_ui",class extends AC{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 AC{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 AC{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){if("FOCUS_RANGE"===e.type){const t=this.currentInput?.getIndex(e.rangeId);if(this.focusedInputId===e.id&&this.currentInput?.focusedRangeIndex===t)return 29}return this.currentInput?this.currentInput.allowDispatch(e):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:wi({col:0,row:0})},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}break;case"FOCUS_RANGE":case"CHANGE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id],o=t.ranges.find((t=>t.id===e.rangeId)),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}=Zo(e);return null!==t.match(Bo)&&(!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 WC(this.config,t,o),0===t.length){const t=this.inputs[e],o={zone:wi({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 AC{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}=fi(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 r=this.getHighlights();for(let e of r.filter(((e,t)=>r.findIndex((t=>hi(t.zone,e.zone)&&t.sheetId===i))===t))){const{x:o,y:i,width:r,height:n}=this.getters.getVisibleRect(e.zone);r>0&&n>0&&(t.strokeStyle=e.color,t.strokeRect(o+s/2,i+s/2,r-s,n-s),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(o+s,i+s,r-2*s,n-2*s))}}}).add("grid renderer",class extends AC{static layers=[0,7];static getters=["getColDimensionsInViewport","getRowDimensionsInViewport"];boxes=[];getColDimensionsInViewport(e,t){const o=Math.min(...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=Math.min(...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 r=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),n=r?.1*o:0;if(r)for(const e of this.boxes)t.strokeStyle="#E2E3E3",t.lineWidth=o,t.strokeRect(e.x+n,e.y+n,e.width-2*n,e.height-2*n)}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,r;const n=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,r=l-2*o):"right"===i?(s=e.x+e.width-o/2,r=2*o-l):(s=(e.clipRect?.x||e.x+e.width/2-e.content.width/2)+o/2,r=l-2*o),t.fillStyle="#ffffff",t.fillRect(s,n,r,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:r,height:n}=e;t.left&&o(t.left,i,s,i,s+n),t.top&&o(t.top,i,s,i+r,s),t.right&&o(t.right,i+r,s,i+r,s+n),t.bottom&&o(t.bottom,i,s+n,i+r,s+n)}}function o({style:e,color:o},i,s,r,n){switch(t.strokeStyle=o,e){case"medium":t.lineWidth=2,s+=(i+=s===n?-.5:.5)===(r+=s===n?1.5:.5)?-.5:.5,n+=i===r?1.5:.5;break;case"thick":t.lineWidth=3,s===n&&(i--,r++),i===r&&(s--,n++);break;case"dashed":t.lineWidth=1,t.setLineDash([1,3]);break;case"dotted":t.lineWidth=1,s===n&&(i+=.5,r+=.5),i===r&&(s+=.5,n+=.5),t.setLineDash([1,1]);break;default:t.lineWidth=1}t.beginPath(),t.moveTo(i,s),t.lineTo(r,n),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||{},r=e.content.align||"left",n=Ye(s);n!==i&&(i=n,t.font=n),t.fillStyle=s.textColor||"#000";let a=e.x;if(a+="left"===r?B+(e.image?e.image.size+z:0):"right"===r?e.width-B-(e.isFilterHeader?20:0):e.width/2,t.textAlign=r,e.clipRect){t.save(),t.beginPath();const{x:o,y:i,width:s,height:r}=e.clipRect;t.rect(o,i,s,r),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 n=a;"right"===r?n-=e:"center"===r&&(n-=e/2),s.strikethrough&&t.fillRect(n,h+l/2,e,2.6*o),s.underline&&t.fillRect(n,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:r}=e.image.clipIcon;t.rect(o,i,s,r),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),r=e.height>s+2*B,n=e.verticalAlign||Y;if(r){if("middle"===n)return i+(e.height-s)/2;if("bottom"===n)return i+e.height-s-B}return i+B}drawHeaders(e){const{ctx:t,thinLineWidth:o}=e,i=this.getters.getSheetViewVisibleCols(),s=i[0],r=i[i.length-1],n=this.getters.getSheetViewVisibleRows(),a=n[0],l=n[n.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<=r;e++){const o={left:e,right:e,top:0,bottom:f-1},{x:i,width:s}=this.getters.getVisibleRect(o),r=this.getters.doesZonesContainFilter(p,[o]),n=E.has(e),a=u.has(e);t.fillStyle=n?r?T:S:a?r?O:v:r?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),r=this.getters.doesZonesContainFilter(p,[o]),n=w.has(e),a=g.has(e);t.fillStyle=n?r?T:S:a?r?O:v:r?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=Vt(e);t.fillStyle=E.has(e)?"#fff":C;let r=this.getHeaderOffset("COL",s,e);t.fillText(i,r+o/2,13),t.moveTo(r+o,0),t.lineTo(r+o,F)}for(const e of n){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(),r=this.getters.isDashboard()?0:D,n=this.getters.isDashboard()?0:F;t.lineWidth=6*o,t.strokeStyle="#BCBCBC",t.beginPath(),i&&(t.moveTo(r+i,0),t.lineTo(r+i,n)),s&&(t.moveTo(0,n+s),t.lineTo(r,n+s)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:o}=e,{x:i,y:s}=this.getters.getMainViewportCoordinates(),r=this.getters.getSheetViewVisibleCols(),n=r[0],a=r[r.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:n,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),r=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==ws.empty||this.getters.isInMerge(e)||r?.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),r=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==ws.empty||this.getters.isInMerge(e)||r?.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===ws.number?"center"!==o?"left":o:o||i.defaultAlign}createZoneBox(e,t,o){const{left:i,right:s}=o,r=t.left,n=t.top,a={sheetId:e,col:r,row:n},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===ws.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:Jm[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===ws.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=r):(e=this.findNextEmptyCol(r,s,n),o=this.findPreviousEmptyCol(r,i,n),f.isOverflow=!0),T){case"left":{const o=wi({col:e,row:n}),{x:i,y:s,width:r,height:a}=this.getters.getVisibleRect(li(t,o));(r<R||v>a||y.length>1)&&(f.clipRect={x:i,y:s,width:r,height:a});break}case"right":{const e=wi({col:o,row:n}),{x:i,y:s,width:r,height:a}=this.getters.getVisibleRect(li(t,e));(r<R||v>a||y.length>1)&&(f.clipRect={x:i,y:s,width:r,height:a});break}case"center":{const i={...t,left:o,right:e},{x:s,y:r,height:n,width:a}=this.getters.getVisibleRect(i),l=R/2,c=f.x+f.width/2;if(s+a<c+l||s>c-l||v>n||y.length>1){const e=s>c-l?s:c-l,t=s+a-e;f.clipRect={x:e,y:r,width:t,height:n}}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(),r={left:o,right:i,top:s[0],bottom:s[s.length-1]},n=this.getters.getActiveSheetId();for(const o of s)for(const i of t){const t={sheetId:n,col:i,row:o};this.getters.isInMerge(t)||e.push(this.createZoneBox(n,wi(t),r))}for(const t of this.getters.getMerges(n))if(!this.getters.isMergeHidden(n,t)&&di(t,r)){const o=this.createZoneBox(n,t,r),i=this.getters.getCellBorder({sheetId:n,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 AC{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:45;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(Gt(i,e));const r=this.createGenerator(s);for(let t=o.top;t<=o.bottom;t++)this.computeNewCell(r,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(Gt(i,e));const r=this.createGenerator(s);for(let t=o.bottom;t>=o.top;t--)this.computeNewCell(r,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(Gt(e,i));const r=this.createGenerator(s);for(let t=o.right;t>=o.left;t--)this.computeNewCell(r,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(Gt(e,i));const r=this.createGenerator(s);for(let t=o.left;t<=o.right;t++)this.computeNewCell(r,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(ui(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.getEvaluatedCell(e).type!==ws.empty||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.getEvaluatedCell(e).type!==ws.empty||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:r,origin:n}=e.next(),{content:a,style:l,border:c,format:h}=s;this.tooltip=r,i&&this.dispatch("AUTOFILL_CELL",{originCol:n.col,originRow:n.row,col:t,row:o,content:a,style:l,border:c,format:h})}getRule(e,t){const o=$s.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}=Wt(t),r=this.getters.getCell({sheetId:i,col:e,row:s});o.push({col:e,row:s,cell:r,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 NC(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",r=i.left.number>0?"left":"right";return Math.abs(i[s].number)>=Math.abs(i[r].number)?i[s].value:i[r].value}autoFillMerge(e,t,o,i){const s=this.getters.getActiveSheetId(),r={sheetId:s,col:o,row:i},n={sheetId:s,col:e,row:t};if(this.getters.isInMerge(r)&&!this.getters.isInMerge(n)){const e=this.getters.getMerge(r);e&&this.dispatch("REMOVE_MERGE",{sheetId:s,target:[e]})}const a=this.getters.getMerge(n);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:r,height:n}=this.getters.getVisibleRect(this.autofillZone);r>0&&n>0&&(t.strokeStyle="black",t.lineWidth=o,t.setLineDash([3]),t.strokeRect(i,s,r,n),t.setLineDash([]))}}).add("find_and_replace",class extends AC{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($C.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell($C.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($C.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),r=this.getters.isColHidden(e,t),n=this.getters.isRowHidden(e,s);if(!r&&!n&&(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:r}=e;if(i?.isFormula&&!this.searchOptions.searchFormulas)return;const n=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),a=this.getSearchableString({sheetId:o,col:s,row:r}).replace(n,t);this.dispatch("UPDATE_CELL",{sheetId:o,col:s,row:r,content:a})}replace(e){if(null===this.selectedMatchIndex)return;const t=this.searchMatches[this.selectedMatchIndex];this.replaceMatch(t,e),this.selectNextCell($C.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,r=i?i.right:e.col,n=i?i.top:e.row,a=i?i.bottom:e.row,{x:l,y:c,width:h,height:d}=this.getters.getVisibleRect({top:n,left:s,right:r,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 AC{static getters=["getContiguousZone"];allowDispatch(e){if("SORT_CELLS"===e.type){if(!ui(e.col,e.row,e.zone))throw new Error(r("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 vi(t).some((({col:t,row:o})=>!this.getters.isInMerge({sheetId:e,col:t,row:o})))?63:0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const o=this.getters.getMerges(e).filter((e=>di(e,t))),i=fi(o[0]);let[s,r]=[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===r}))?0:63}expand(e,t){const{left:o,right:i,top:s,bottom:r}=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,r)}}checkExpandedValues(e,t){const o=this.expand(e,t);let i;if(this.getters.doesIntersectMerge(e,o)){const{left:t,right:s,top:r,bottom:n}=o;for(let o=t;o<=s;o++)for(let t=r;t<=n;t++){const{col:s,row:r}=this.getters.getMainCellPosition({sheetId:e,col:o,row:t});if(i=this.getters.getEvaluatedCell({sheetId:e,col:s,row:r}),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:r,right:n}=t,a=!1;for(;!a;)a=!0,i>0&&(o=this.checkExpandedValues(e,{left:r-1,right:n+1,top:i-1,bottom:i-1}),o&&(a=!1,i--)),r>0&&(o=this.checkExpandedValues(e,{left:r-1,right:r-1,top:i-1,bottom:s+1}),o&&(a=!1,r--)),n<this.getters.getNumberCols(e)-1&&(o=this.checkExpandedValues(e,{left:n+1,right:n+1,top:i-1,bottom:s+1}),o&&(a=!1,n++)),s<this.getters.getNumberRows(e)-1&&(o=this.checkExpandedValues(e,{left:r-1,right:n+1,top:s+1,bottom:s+1}),o&&(a=!1,s++));return{left:r,right:n,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]===ws.empty&&(o=o.slice(1)),!o.some((e=>e[0]===ws.empty))&&!!o.some((e=>e[1]!==ws.empty&&e[0]!==e[1]))}sortZone(e,t,o,i,s){const[r,n]=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+=n),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===ws.empty)),r=i.filter((e=>e.type!==ws.empty));o&&(r.push(...s.map((e=>({...e,type:ws.number,value:0})))),s=[]);const n="descending"===t?-1:1;return r.sort(((e,t)=>{let o=ea.indexOf(e.type)-ea.indexOf(t.type);return 0===o&&(o=e.type===ws.text||e.type===ws.error?e.value.localeCompare(t.value):e.value-t.value),n*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*r,u=l.top+t*n,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=[],r=Ke(t.left,t.right+1,o),n=Ke(t.top,t.bottom+1,i);for(const t of r){const o=[];s.push(o);for(const i of n)o.push({sheetId:e,col:t,row:i})}return s}}).add("automatic_sum",class extends AC{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}=ui(o.col,o.row,t)?o:{col:t.left,row:t.top},r=this.findAdjacentData(e,i,s);return r?this.getters.isSingleCellOrMerge(e,t)||bi(li(r,t))?[{position:{col:i,row:s},zone:r}]:this.sumDimensions(e,li(r,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}),r=this.findSuitableZoneToSum(i,s.col,s.row);if(r)return this.getters.expandZone(e,r)}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 r=this.findVerticalZone(e,t,o);if(this.isZoneValid(r))return r;const n=this.findHorizontalZone(e,t,o);return this.isZoneValid(n)?n: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),r=s.filter((e=>i[e]&&!i[e].isAutoSummable)),n=Math.max(...r),a=Qe(s.filter((e=>this.isNumber(i[e]))))[0]||[];return Math.max(...a)<n?1/0:Math.min(...a)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===ws.number&&!(e.format&&Eo(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 bi(t)?(o.add(1===fi(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)},vi(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)},vi(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 AC{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 vi(i)){const i=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==i){const s=Oo(i,o);this.dispatch("SET_FORMATTING",{sheetId:e,target:[wi(t)],format:s})}}}getCellNumberFormat(e){for(const t of[e]){const e=this.getters.getEvaluatedCell(t);if(!(e.type!==ws.number||e.format&&Eo(e.format)))return e.format||Ro(e.value)}}}).add("split_to_columns",class extends AC{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===ws.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,r=s[e],n=o.left,a=this.getters.getCell({sheetId:i,col:n,row:t});if(1!==r.length||r[0]!==a?.content)for(const[e,o]of r.entries())this.dispatch("UPDATE_CELL",{sheetId:i,col:n+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 r=this.getters.getEvaluatedCell({sheetId:o,col:e.left,row:s}).formattedValue;i.push(this.splitAndRemoveTrailingEmpty(r,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},r=this.getters.getMergesInZone(o,s);this.dispatch("REMOVE_MERGE",{sheetId:o,target:r})}addColsToAvoidCollisions(e,t){const o=this.getters.getActiveSheetId();let i=0;for(const s of Ke(e.top,e.bottom+1)){const r={sheetId:o,col:e.left,row:s},n=t[s-e.top],a=this.getColsToAddToAvoidCollision(r,n);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:88}checkNonEmptySelector(e){return""===e.separator?89: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)?90:0}checkSeparatorInSelection({separator:e}){const t=this.getters.getSelectedCells();for(const o of t)if(o.formattedValue.includes(e))return 0;return 91}}).add("cell_popovers",class extends AC{static getters=["getCellPopover","getPersistentPopoverTypeAtPosition","hasOpenedPopover"];persistentPopover;allowDispatch(e){if("OPEN_CELL_POPOVER"===e.type){try{Dr.get(e.popoverType)}catch(e){return 72}return 0}return 0}handle(e){switch(e.type){case"ACTIVATE_SHEET":case"CLOSE_CELL_POPOVER":this.persistentPopover=void 0;break;case"OPEN_CELL_POPOVER":this.persistentPopover={col:e.col,row:e.row,sheetId:this.getters.getActiveSheetId(),type:e.popoverType}}}getCellPopover({col:e,row:t}){const o=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){const e=this.getters.getMainCellPosition(this.persistentPopover),t=Dr.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=Dr.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(wi({col:e,row:t}))}}).add("collaborative",class extends AC{static getters=["getClientsToDisplay","getClient","getConnectedClients","isFullySynchronized"];static layers=[6];availableColors=new Set(HC);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(HC));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 zC)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:r}=e.position,n=this.getters.expandZone(i,{top:s,bottom:s,left:r,right:r}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(n);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 AC{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=tE(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)&&(As(t.rootCommand)?KC.contains(t.rootCommand.type):QC.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"])}}),mE=(new Ui).add("selection",class extends AC{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=>hi(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 r=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map((e=>this.getters.expandZone(r,e))),this.gridSelection.anchor.zone=this.getters.expandZone(r,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones)}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 vi(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!==ws.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 uE){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(vi).flat();for(const{col:s,row:r}of i){const i=this.getters.getEvaluatedCell({sheetId:o,col:s,row:r});i.type===ws.number&&(t++,e+=i.value)}return t<2?null:mo(e)}isSelected(e){return!!this.getters.getSelectedZones().find((t=>hi(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=ni(o,"left",[...e.elements]);let s={left:t.col,right:t.col,top:t.row,bottom:t.row};s=ni(s,"left",[...e.elements]);const r={cell:{col:s.left,row:s.top},zone:i},n=this.gridSelection.zones.map((t=>ni(t,"left",[...e.elements])));this.setSelectionMixin(r,n)}onRowsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,i=ni(o,"top",[...e.elements]);let s={left:t.col,right:t.col,top:t.row,bottom:t.row};s=ni(s,"top",[...e.elements]);const r={cell:{col:s.left,row:s.top},zone:i},n=this.gridSelection.zones.map((t=>ni(t,"top",[...e.elements])));this.setSelectionMixin(r,n)}onAddElements(e){const t="COL"===e.dimension?"left":"top",o=ri(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),i=this.gridSelection.zones.map((o=>ri(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],r=e.base<i,n=r&&o?t:0,a=r&&!o?t:0,l=[{left:o?i+n:0,right:o?s+n:this.getters.getNumberCols(e.sheetId)-1,top:o?0:i+a,bottom:o?this.getters.getNumberRows(e.sheetId)-1:s+a}],c=new iE(l,"CUT",this.getters,this.dispatch,this.selection),h=r?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=r?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,r=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(r(s,o-1,o)||r(s,i,i+1)||r(s,e.base-1,e.base))return 2;const n=[e.base,...e.elements],a=t?this.getters.getNumberCols(s):this.getters.getNumberRows(s);return n.some((e=>e<0||e>=a))?86: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:r}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(o,i,s,r),t.globalCompositeOperation="source-over",t.strokeRect(o,i,s,r)}t.globalCompositeOperation="source-over";const r=this.getActivePosition();let n;t.strokeStyle=E,t.lineWidth=3*o,n=this.getters.isInMerge(r)?this.getters.getMerge(r):wi(r);const{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(n);c>0&&h>0&&t.strokeRect(a,l,c,h)}}).add("clipboard",class extends AC{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 aE(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(!oi(t[0])){for(const{col:t,row:o}of vi(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)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)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 aE(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:As(e)&&(this.status="invisible")}}getClipboardContent(){return this.state?.getClipboardContent()||{[xs.PlainText]:"\t"}}getClipboardTextContent(){return this.state?.getClipboardContent()[xs.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 iE(e,t,this.getters,this.dispatch,this.selection)}getClipboardState(e,t){return this.getters.getSelectedFigureId()?new sE(t,this.getters,this.dispatch):new iE(e,t,this.getters,this.dispatch,this.selection)}drawGrid(e){"visible"===this.status&&this.state&&this.state.drawClipboard(e)}}).add("edition",class extends AC{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}=Zo(e.value),s=i||this.getters.getSheetName(this.sheetId),r=this.getters.getActiveSheetId();if(this.getters.getSheetName(r)!==s)return!1;const n=this.getters.getRangeFromSheetXC(r,o);return hi(this.getters.expandZone(r,n.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,wi({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:dE}));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(lE).map((e=>e.value)).join(""),i=this.currentContent,s=e[0].start,r=e[e.length-1].end,n=i.slice(0,s)+o+i.slice(r),a=n.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:n,selection:l})}validateSelection(e,t,o){return t>=0&&t<=e&&o>=0&&o<=e?0:46}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:dE});const{top:t,left:o}=ni({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:dE});const{top:t,left:o}=ni({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}=ri({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=wi({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("%")&&oo(e)&&(t=t||{start:e.length,end:e.length},e=`${e}%`);const{col:i,row:s,sheetId:r}=this.getters.getActivePosition();this.col=i,this.sheetId=r,this.row=s,this.initialContent=this.getComposerContent({sheetId:r,col:i,row:s}),this.mode="editing",this.setContent(e||this.initialContent,t),this.colorIndexByRange={};const n=wi({col:this.col,row:this.row});this.selection.capture(this,{cell:{col:this.col,row:this.row},zone:n},{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=rt(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:r}=this.getters.getEvaluatedCell(e);switch(s){case ws.text:case ws.empty:return i;case ws.boolean:return r;case ws.error:return t?.content||"";case ws.number:return o&&Eo(o)?r:this.numberComposerContent(i,o)}}numberComposerContent(e,t){return t?.includes("%")?100*e+"%":function(e){const{integerDigits:t,decimalDigits:o}=vo(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("=")?iS(e):[],this.currentTokens.length>100&&o&&this.ui.notifyUI({type:"ERROR",text:r("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&&yi(e.zone)>1?o.push({...t[0]}):2===t.length&&1===yi(e.zone)&&o.pop();const i=e.clone({parts:o});return this.getters.getSelectionRangeString(i,this.getters.getCurrentEditedCell().sheetId)}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,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 r=()=>{for(;i.has(s);)s++;return i.add(s),s};for(const e of t){const t=e in o?o[e]:r();o[e]=t}this.colorIndexByRange=o}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=this.getters.getCurrentEditedCell().sheetId,t=e=>{const t=this.colorIndexByRange[e];return At[t%At.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;return this.currentTokens.filter((e=>"REFERENCE"===e.type)).map((t=>this.getters.getRangeFromSheetXC(e,t.value)))}canStartComposerRangeSelection(){if(this.currentContent.startsWith("=")){const e=this.getTokenAtCursor();if(!e)return!1;const t=this.currentTokens.map((e=>e.start)).indexOf(e.start);let o=t,i=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(i.type)||bv.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))}}),fE=(new Ui).add("evaluation",class extends AC{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(ys.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=oS(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})?ks(""):this.evaluatedCells[e]?.[t]?.[o]?.()||ks("")}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 vi(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:r,sheetId:n}=this.getters.getCellPosition(t),a=this.evaluatedCells[n]?.[s]?.[r];return a||mt((()=>{try{switch(e.isFormula){case!0:return i(e);case!1:return Ds(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||"",r=new c(o,e.message.replace("[[FUNCTION_NAME]]",i),void 0!==e.logLevel?e.logLevel:l.error);return zs(t.content,r)},i=t=>{const o=t.id;if(e.has(o))throw new d;s[2].__originCellXC=()=>{const e=s[2].getters.getCellPosition(o);return Gt(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(r("This formula depends on invalid values"));return ks(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(OC),this.evalContext,{getters:this.getters}),o=this.getters;const i=t=>{const o=e(t);if(o.type===ws.error)throw o.error;return o},s={};return[function(e,t,s,n){if(t)return{value:ii(e.zone)};if(!oi(e.zone))throw new u;if(e.zone.bottom!==e.zone.top||e.zone.left!==e.zone.right)throw new Error(n?r("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",s.toString(),n.toString()):r("Function %s expects its parameters to be single values or single cell references, not ranges.",s.toString()));if(e.invalidSheetName)throw new Error(r("Invalid sheet name: %s",e.invalidSheetName));return function(e){let t;if(!o.tryGetSheet(e.sheetId))throw new Error(r("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){const r=e.sheetId;if(!oi(e.zone))throw new u;const n=o.getSheetZone(r),a=ci(e.zone,n);if(!a)return[[]];const{top:l,left:c,bottom:h,right:d}=a,g=`${r}-${l}-${c}-${h}-${d}`;if(g in s)return s[g];const p=new Array(d-c+1);for(let o=c;o<=d;o++){const s=new Array(h-l+1);for(let r=l;r<=h;r++){const n=t.getters.getCell({sheetId:e.sheetId,col:o,row:r});s[r-l]=n?i(n):void 0}p[o-c]=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,...Wt(e)},i=this.getters.getCell(o);if(i){const s=t.cells[e],r=this.getEvaluatedCell(o);s.value=r.value,s.isFormula=i.isFormula&&!this.isBadExpression(i.content),i.format!==r.format&&(s.computedFormat=r.format)}}}isBadExpression(e){try{return oS(e),!1}catch(e){return!0}}}).add("evaluation_filter",class extends AC{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 79;return 0}handle(e){switch(e.type){case"UNDO":case"REDO":case"UPDATE_CELL":case"EVALUATE_CELLS":case"ACTIVATE_SHEET":case"REMOVE_FILTER_TABLE":case"ADD_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":this.isEvaluationDirty=!0;break;case"START":for(const e of this.getters.getSheetIds()){this.filterValues[e]={};for(const t of this.getters.getFilters(e))this.filterValues[e][t.id]=[]}break;case"CREATE_SHEET":this.filterValues[e.sheetId]={};break;case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":this.updateHiddenRows();break;case"UPDATE_FILTER":this.updateFilter(e),this.updateHiddenRows();break;case"DUPLICATE_SHEET":const t={};for(const 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 r=e.zone;if(ui(o,i,r)){const e=this.intersectZoneWithViewport(t,r);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 r=this.getters.getCellBorder(e),n={...s,...Ct(r||{})};return ut(n)?null:n}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 r=this.getCellValueAsString(e,i.col,s);t.includes(r)&&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=ti(o.range),s=[],r=[];for(const o of Ke(0,fi(i).numberOfCols)){const n={sheetId:t.id,col:i.left+o,row:i.top},a=this.getFilterValues(n),l=this.getters.getFilter(n);if(!l)continue;const c=l.filteredZone?vi(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,r);r.push(u),t.cells[Gt(h.col,h.row)]={...t.cells[Gt(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 AC{static getters=["getChartRuntime","getStyleOfSingleCellChart"];charts={};createRuntimeChart=function(e){const t=Vn.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(ys.has(e.type)||Is.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:Yr(e)};if(!t)return{background:w,fontColor:Yr(w)};const o=t.zone.left,i=t.zone.top,s=t.sheetId,r=this.getters.getCellComputedStyle({sheetId:s,col:o,row:i}),n=r.fillColor||w;return{background:n,fontColor:r.textColor||Yr(n)}}}).add("evaluation_cf",class extends AC{static getters=["getConditionalIcon","getCellComputedStyle"];isStale=!0;computedStyles={};computedIcons={};uuidGenerator=new Jo;handle(e){switch((Is.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,[Gt(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),r=this.computedStyles[t],n=r&&r[o]?.[i],a={...s?.style,...n};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 r=s.left;r<=s.right;r++){const s=this.rulePredicate[o.rule.type];let n=this.getters.getEvaluatedCell({sheetId:e,col:r,row:i});s&&s(n,o.rule)&&(t[r]||(t[r]=[]),t[r][i]=Object.assign(t[r]?.[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===ws.number)).map((e=>e.value));switch(t.type){case"value":return"max"===o?Math.max(...s):Math.min(...s);case"number":return Number(t.value);case"percentage":const e=Math.min(...s);return e+(Math.max(...s)-e)*Number(t.value)/100;case"percentile":return ro(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(),r=this.getters.getRangeFromSheetXC(s,e).zone,n=this.computedIcons[s],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=r.top;e<=r.bottom;e++)for(let l=r.left;l<=r.right;l++){const r=this.getters.getEvaluatedCell({sheetId:s,col:l,row:e});if(r.type!==ws.number)continue;const c=this.computeIcon(r.value,i,t.upperInflectionPoint.operator,o,t.lowerInflectionPoint.operator,a);n[l]||(n[l]=[]),n[l][e]=c}}computeIcon(e,t,o,i,s,r){return"ge"===o&&e>=t||"gt"===o&&e>t?r[0]:"ge"===s&&e>=i||"gt"===s&&e>i?r[1]:r[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 r=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(r,e).zone,a=this.computedStyles[r],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=n.top;e<=n.bottom;e++)for(let t=n.left;t<=n.right;t++){const n=this.getters.getEvaluatedCell({sheetId:r,col:t,row:e});if(n.type===ws.number){const r=We(n.value,o,s);let c;c=2===l.length&&i?r<=i?this.colorCell(r,l[0].minValue,l[0].minColor,l[0].colorDiffUnit):this.colorCell(r,l[1].minValue,l[1].minColor,l[1].colorDiffUnit):this.colorCell(r,l[0].minValue,l[0].minColor,l[0].colorDiffUnit),a[t]||(a[t]=[]),a[t][e]=a[t]?.[e]||{},a[t][e].fillColor=Ot(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,r,n]=i;return Math.round((o>>16)%256-s*(e-t))<<16|Math.round((o>>8)%256-r*(e-t))<<8|Math.round(o%256-n*(e-t))}rulePredicate={CellIsRule:(e,t)=>{if(e.type===ws.error)return!1;const o=t.values.map(Ls);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(r("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),r=s.findIndex((e=>e.id===t.id));let n=[];r>-1&&(n=s[r].ranges),n=n.concat(o);const a=pi(n,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=Gt(t.col,t.row);for(let s of this.getters.getConditionalFormats(e.sheetId))for(let r of s.ranges)if(ui(e.col,e.row,this.getters.getRangeFromSheetXC(e.sheetId,r).zone)){const r=s,n=[];if("CUT"===o&&n.push(Gt(e.col,e.row)),e.sheetId===t.sheetId)this.adaptRules(e.sheetId,r,[i],n);else{this.adaptRules(e.sheetId,r,[],n);const o=this.getCFToCopyTo(t.sheetId,r);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 AC{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":let{col:t,row:o}=Ci(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const i=e.previousAnchor.zone,s=e.anchor.zone,{top:r,bottom:n,left:a,right:l}=this.getters.getActiveMainViewport();i.left===s.left&&i.right===s.right&&(t=a>t||t>l?a:t),i.top===s.top&&i.bottom===s.bottom&&(o=r>o||o>n?r:o)}const i=this.getters.getActiveSheetId();t=Math.min(t,this.getters.getNumberCols(i)-1),o=Math.min(o,this.getters.getNumberRows(i)-1),this.refreshViewport(this.getters.getActiveSheetId(),{col:t,row:o})}}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{top:t}=this.getActiveMainViewport(),o=this.getters.getActiveSheetId(),i=this.clipOffsetY(this.getters.getRowDimensions(o,t).start+this.sheetViewHeight);this.shiftVertically(i);break;case"SHIFT_VIEWPORT_UP":{const{top:e}=this.getActiveMainViewport(),t=this.getters.getActiveSheetId(),o=this.clipOffsetY(this.getters.getRowDimensions(t,e).end-this.sheetViewHeight);this.shiftVertically(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:s,row:r}=this.getters.getActivePosition();this.refreshViewport(this.getters.getActiveSheetId(),{col:s,row:r})}}finalize(){for(const e of this.sheetsWithDirtyViewports)this.resetViewports(e);this.sheetsWithDirtyViewports=new Set,this.setViewports()}setViewports(){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:r}=t.getMaxSize();return{x:this.getters.getColDimensions(e,o).start,y:this.getters.getRowDimensions(e,i).start,width:s,height:r}}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(),r=this.getters.getSheetViewVisibleRows();if(o<t)return-this.getColRowOffsetInViewport(e,o,t);let n=0;const a="COL"===e?s:r;for(let s=t;s<o;s++)a.includes(s)&&(n+="COL"===e?this.getters.getColSize(i,s):this.getters.getRowSize(i,s));return n}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,r=0;const{xSplit:n}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(i=!0,r=Yt(e-a),s=1):e<l&&o>=l&&c>0?(i=!0,r=Yt(l-e),s=-1):n&&t<l&&e>l&&(i=!0,r=Yt(e),s="reset"),{canEdgeScroll:i,direction:s,delay:r}}getEdgeScrollRow(e,t,o){let i=!1,s=0,r=0;const{ySplit:n}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(i=!0,r=Yt(e-a),s=1):e<l&&o>=l&&c>0?(i=!0,r=Yt(l-e),s=-1):n&&t<l&&e>l&&(i=!0,r=Yt(e),s="reset"),{canEdgeScroll:i,direction:s,delay:r}}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))),r=Math.max(...o.map((e=>e.x+e.width)))-i,n=Math.max(...o.map((e=>e.y+e.height)))-s;return{x:i+this.gridOffsetX,y:s+this.gridOffsetY,width:r,height:n}}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?68: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?76:0}checkScrollingDirection({offsetX:e,offsetY:t}){const o=this.getMainInternalViewport(this.getters.getActiveSheetId());return!o.canScrollHorizontally&&e>0||!o.canScrollVertically&&t>0?69:0}getMainViewport(e){const t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){const e=this.getters.getSheetIds();for(let t of Object.keys(this.viewports))e.includes(t)||delete this.viewports[t]}resetSheetViews(){for(let e of Object.keys(this.viewports)){const t=this.getters.getSheetPosition(e);this.resetViewports(e);const 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))))}clipOffsetY(e){const{height:t}=this.getMainViewportRect(),o=t-this.sheetViewHeight;return e=Math.min(e,o),e=Math.max(e,0)}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),r=this.getters.getColRowOffset("COL",0,t,e),n=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 MC(this.getters,e,{left:0,right:t-1,top:0,bottom:o-1},{width:r,height:n},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:o&&new MC(this.getters,e,{left:t,right:i-1,top:0,bottom:o-1},{width:this.sheetViewWidth-r,height:n},{canScrollHorizontally:c,canScrollVertically:!1},{x:c?d.x:0,y:0})||void 0,bottomLeft:t&&new MC(this.getters,e,{left:0,right:t-1,top:o,bottom:s-1},{width:r,height:this.sheetViewHeight-n},{canScrollHorizontally:!1,canScrollVertically:h},{x:0,y:h?d.y:0})||void 0,bottomRight:new MC(this.getters,e,{left:t,right:i-1,top:o,bottom:s-1},{width:this.sheetViewWidth-r,height:this.sheetViewHeight-n},{canScrollHorizontally:c,canScrollVertically:h},{x:c?d.x:0,y:h?d.y:0})};this.viewports[e]=u}refreshViewport(e,t){Object.values(this.getSubViewports(e)).forEach((e=>{e.adjustViewportZone(),e.adjustPosition(t)}))}shiftVertically(e){const{top:t}=this.getActiveMainViewport(),{scrollX:o}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(o,e);const{anchor:i}=this.getters.getSelection(),s=this.getActiveMainViewport().top-t;this.selection.selectCell(i.cell.col,i.cell.row+s)}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],o=this.getters.getFigures(e),{scrollX:i,scrollY:s}=this.getActiveSheetScrollInfo(),{x:r,y:n}=this.getters.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const e of o)e.x>=r&&(e.x+e.width<=r+i||e.x>=a+i+r)||e.y>=n&&(e.y+e.height<=n+s||e.y>=l+s+n)||t.push(e);return t}isPositionVisible(e){const{scrollX:t,scrollY:o}=this.getters.getActiveSheetScrollInfo(),{x:i,y:s}=this.getters.getMainViewportCoordinates(),{width:r,height:n}=this.getters.getSheetViewDimension();return!(e.x>=i&&(e.x<i+t||e.x>r+t+i))&&!(e.y>=s&&(e.y<s+o||e.y>n+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 AC{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:Ft(255,0,0),colors:[]},{leadColor:Ft(255,128,0),colors:[]},{leadColor:Ft(128,128,0),colors:[]},{leadColor:Ft(128,255,0),colors:[]},{leadColor:Ft(0,255,0),colors:[]},{leadColor:Ft(0,255,128),colors:[]},{leadColor:Ft(0,255,255),colors:[]},{leadColor:Ft(0,127,255),colors:[]},{leadColor:Ft(0,0,255),colors:[]},{leadColor:Ft(127,0,255),colors:[]},{leadColor:Ft(128,0,128),colors:[]},{leadColor:Ft(255,0,128),colors:[]}];for(const o of e.map(kt)){let e=500,i=0;t.forEach(((t,s)=>{const r=(n=o,a=t.leadColor,Math.sqrt(Math.pow(n.r-a.r,2)+Math.pow(n.g-a.g,2)+Math.pow(n.b-a.b,2)));var n,a;e>r&&(e=r,i=s)})),t[i].colors.push(o)}return t.map((e=>e.colors.sort(((e,t)=>Ut(e).s-Ut(t).s)))).flat().map(Lt)}([...new Set([...new Set([...e,...this.customColors])].filter(Nt).map(Mt))]).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(Ot(t.minimum.color)),o.push(t.midpoint?Ot(t.midpoint.color):void 0),o.push(Ot(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=Mt(e);e&&!_.includes(t)&&this.customColors.add(t)}}),bE=new Ui;bE.add("link",{condition:(e,t)=>!!t.model.getters.getEvaluatedCell(e).link,execute:(e,t)=>Gi(t.model.getters.getEvaluatedCell(e).link,t),sequence:5});class vE{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)}))}}const SE=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];Oi`
1419
+ `}function qS(e){return new rb(e.join("\n"))}function ZS(e,...t){let o=[e[0]];for(let i=0;i<t.length;i++){const s=t[i]instanceof rb?t[i]:HS(t[i]);o.push(s+e[i+1])}return new rb(pt(o))}function jS(e){return e.replace(/[a-z0-9]+:(?=[a-z0-9]+)/gi,"")}function YS(e){return e.replace(/([a-z0-9]+):(?=[a-z0-9]+)/gi,"$1\\:")}class XS{value;constructor(e){this.value=e}asString(){return Jb(String(this.value))}asBool(){return"true"===this.value||"false"!==this.value&&Boolean(Number(this.value))}asNum(){return Number(this.value)}}class KS{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 XS(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?Jb(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 XS(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?jS(t):YS(t),e.querySelector(t)}querySelectorAll(e,t){return t=this.areNamespaceIgnored?jS(t):YS(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 QS extends KS{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:lb}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:lb}).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 JS extends KS{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 eC extends KS{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},(e=>{const t=this.getChartType(e);if(!$b[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:$b[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:Hb[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=jS(e.tagName);if(ab.some((e=>e===t)))return t}throw new Error("Unknown chart type")}}class tC extends KS{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},(e=>{if("twoCellAnchor"!==jS(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 eC(o,this.xlsxFileStructure,this.warningManager).extractChart();if(!i)throw new Error("Unable to extract chart definition");return i}}class oC extends KS{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 iC extends KS{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 sC extends KS{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=Xb(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=Xb(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 JS(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 tC(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 iC(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 oC(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:vb.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:Sb.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:Db[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 nC extends KS{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 rC extends KS{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 aC(e,t){const o=function(e,t){const o=t[Ib],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=lC(i,t);o.push({file:{fileName:i,xml:t[i]},rels:e?{fileName:e,xml:t[e]}:void 0})}return o}(o,t)}function lC(e,t){if(e===Ib)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 cC{warningManager;xmls;constructor(e){this.warningManager=new Tb,this.xmls={};for(let t of Object.keys(e))(t.endsWith(".xml")||t.endsWith(".rels"))&&(this.xmls[t]=WS(new rb(e[t])))}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new QS(e.theme,e,this.warningManager).getTheme():void 0,o=e.sharedStrings?new QS(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 sC(o,e,this.warningManager,t).getSheet())),s=e.externalLinks.map((t=>new rC(t,e,this.warningManager).getExternalBook())),n=new nC(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:aC(gb.sheet,this.xmls),workbook:aC(gb.workbook,this.xmls)[0],styles:aC(gb.styles,this.xmls)[0],sharedStrings:aC(gb.sharedStrings,this.xmls)[0],theme:aC(gb.themes,this.xmls)[0],charts:aC(gb.chart,this.xmls),figures:aC(gb.drawing,this.xmls),tables:aC(gb.table,this.xmls),pivots:aC(gb.pivot,this.xmls),externalLinks:aC(gb.externalLink,this.xmls)};if(!e.workbook.rels)throw Error(n("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:12,sheets:MS(e,this.warningManager),styles:sv(e,this.warningManager),formats:rv(e,this.warningManager),borders:ov(e,this.warningManager),entities:{},revisionId:ee};return US(t,e),Object.keys(e.styles).map((t=>{e.styles[t]=Ct(e.styles[t])})),t}}function hC(e){const t=Kv(e);let o=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&Lo.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 dC=13,uC="Sheet1";function gC(e,t){if(!e)return vC();if(e["[Content_Types].xml"]){const o=new cC(e);if(e=o.convertXlsx(),t)for(let e of o.warningManager.warnings.sort())console.warn(e)}return"version"in e&&e.version<dC&&(e=function(e){for(let t=pC.findIndex((t=>t.from===e.version));t<pC.length;t++)e=pC[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,o=new Jo;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(vC(),e,{version:dC}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(bC(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(bC(uC,"Sheet1"));return e}(e),e}(e),e}const pC=[{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=hC(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=ti(e.dataRange),o=e.labelCell+":"+Gt(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=ti(o.range),i=e.findIndex((e=>di(e,t)));-1!==i?e[i]=t:e.push(t)}t.filterTables=e.map((e=>({range:ii(e)})))}return e}},{description:"Change Border description structure",from:12,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 mC(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:uC};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=fC(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=fC(t,"SET_DECIMAL")),t}function fC(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 bC(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[],filterTables:[],isVisible:!0}}function vC(e="Sheet1"){return{version:dC,sheets:[bC(uC,e)],entities:{},styles:{},formats:{},borders:{},revisionId:ee,uniqueFigureIds:!0}}function SC(e,t){return{...bC(e,t),charts:[],images:[]}}class CC{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 EC extends CC{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 wC(e){return""===e?NaN:Number(e)}class xC{id;zone;filters;constructor(e){this.filters=[],this.zone=e;const t=new Jo;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 yC(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 xC(this.zone)}}class yC{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 IC(e){return Object.entries(e).map((([e,t])=>t?RC(parseInt(e,10),t):void 0)).filter(dt).map((e=>Gt(e.left,e.top)+":"+Gt(e.right,e.bottom)))}function RC(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}class TC{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=Math.min(...e),l=Math.max(...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||!gi(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||oi(o.range.zone)?o:{range:o.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,o,i){const s=Si(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=>jo.fromRange(e,this.getters)));return s.map((e=>{if(!oi(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(!Bo.test(t))return new jo({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}=Zo(t)),o&&(s=!0));const n=ei(i),r=jo.getRangeParts(i,n),a=o&&!this.getters.getSheetIdByName(o)?o:void 0,l=this.getters.getSheetIdByName(o)||e;return new jo({prefixSheet:s,zone:n,sheetId:l,invalidSheetName:a,parts:r},this.getters.getSheetSize).orderZone()}getSelectionRangeString(e,t){const o=jo.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(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=jo.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 jo(t,this.getters.getSheetSize)}getRangePartString(e,t,o=!1){const i=e.parts&&e.parts[t]?.colFixed?"$":"",s=Vt(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 AC extends CC{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 OC=Ug.mapping;class MC{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);ui(i,this.boundaries.top,this.boundaries)&&this.adjustPositionX(i),ui(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=ci(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 NC{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}=Hs.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 _C{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 FC(e,t){return{...e,definition:Qr(e.definition,t)}}function DC(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}_m.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],FC),_m.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],FC),_m.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const o=t.sheetId;if(e.targetSheetId===o||e.sheetId===o)return;return e})),_m.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),_m.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})),_m.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)di(i,e)||o.push({...i});if(o.length)return{...e,target:o};return})),_m.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],DC),_m.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],DC),_m.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(di(e,o))return;return e}));const LC=[{match:function(e){return"sheetId"in e},fn:UC},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const o=UC(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;const i=[];for(const o of e.target){const e=Un(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=UC(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)&&ui(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=UC(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=Un(s._zone,t);e&&i!==s._sheetId&&o.push({...s,_zone:e})}if(!o.length)return"IGNORE_COMMAND";return{...e,ranges:o}}}];function kC(e,t){const o=_m.getTransformation(e.type,t.type);return o?o(e,t):function(e,t){for(const{match:o,fn:i}of LC)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 PC(e,t){let o=[...e];for(const e of t)o=o.map((t=>kC(t,e))).filter(dt);return o}function UC(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 VC{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 zC extends Error{}class BC extends _C{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;uuidGenerator=new Jo;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 VC(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 zC("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 VC(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:PC(o,t)})}break;case"SNAPSHOT_CREATED":{const t=new VC(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 HC=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];var $C;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}($C||($C={}));class WC extends AC{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=ii(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,wi({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:At[(o+t)%At.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}=Zo(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}=Zo(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 GC=[qC,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 qC(e,t){return"sheetId"in t?{...Be(t),sheetId:e.getActiveSheetId()}:t}const ZC=new Jo;function jC(e,t){const o=e.getSelectedZone();return{...qC(e,t),elements:"COL"===t.dimension?Ke(o.left,o.right+1):Ke(o.top,o.bottom+1)}}function YC(e,t){const o=e.getSelectedZone();return{...Be(t),zone:o}}function XC(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 KC=new Ui;KC.add("UPDATE_CELL",JC),KC.add("CLEAR_CELL",JC),KC.add("DELETE_CONTENT",JC),KC.add("ADD_MERGE",JC),KC.add("REMOVE_MERGE",JC),KC.add("SET_FORMATTING",JC),KC.add("CLEAR_FORMATTING",JC),KC.add("SET_BORDER",JC),KC.add("CREATE_FILTER_TABLE",JC),KC.add("REMOVE_FILTER_TABLE",JC),KC.add("HIDE_SHEET",JC),KC.add("ADD_COLUMNS_ROWS",(function(e,t){const o=e.getActivePosition();return{...qC(e,t),base:"COL"===t.dimension?o.col:o.row}})),KC.add("REMOVE_COLUMNS_ROWS",jC),KC.add("HIDE_COLUMNS_ROWS",jC),KC.add("RESIZE_COLUMNS_ROWS",jC),KC.add("CREATE_SHEET",(function(e,t){const o=Be(t);o.sheetId=ZC.uuidv4();const i=t.name||e.getSheet(e.getActiveSheetId()).name,s=i.match(/(.+?)\d*$/)?.[1]||i;return o.name=e.getNextSheetName(s),o})),KC.add("CREATE_FIGURE",(function(e,t){const o=qC(e,t);return o.figure.id=ZC.uuidv4(),o})),KC.add("CREATE_CHART",(function(e,t){return{...qC(e,t),id:ZC.uuidv4()}})),KC.add("CREATE_IMAGE",(function(e,t){return{...qC(e,t),figureId:ZC.uuidv4()}}));const QC=new Ui;function JC(e,t){let o=Be(t);for(const t of GC)o=t(e,o);return o}function eE(e,t){if(!t)return;if(!KC.contains(t.type))return;return KC.get(t.type)(e,t)}function tE(e,t){if(e.rootCommand&&"object"==typeof e.rootCommand)return As(e.rootCommand)?eE(t,e.rootCommand):function(e,t,o){if(!QC.contains(t.type))return;return QC.get(t.type)(e,t,o)}(t,e.rootCommand,e.commands)}QC.add("STOP_EDITION",(function(e,t,o){return o.map((t=>eE(e,t))).filter(dt)})),QC.add("PASTE",(function(e,t){return{type:"REPEAT_PASTE",pasteOption:Be(t.pasteOption),target:e.getSelectedZones()}})),QC.add("INSERT_CELL",YC),QC.add("DELETE_CELL",YC),QC.add("AUTORESIZE_COLUMNS",XC),QC.add("AUTORESIZE_ROWS",XC),QC.add("SORT_CELLS",(function(e,t){const o=e.getSelectedZone();return{...qC(e,t),col:o.left,row:o.top,zone:o}})),QC.add("SUM_SELECTION",JC),QC.add("SET_DECIMAL",JC);class oE{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 iE extends oE{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(di(e[i],t))return e[i]=li(e[i],t),e;return e[o]=t,e}),[])}(e):[e[e.length-1]],h=c.map((e=>vi(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]:li(...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=mo(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=Si(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{[xs.PlainText]:this.getPlainTextContent(),[xs.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="${Fi(Ni(o.style))}">`+HS(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 sE{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 nE(o,t,this.sheetId,i);break;case"image":this.copiedFigureContent=new rE(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 Jo).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{[xs.PlainText]:"\t"}}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class nE{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 rE{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 aE extends oE{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}=fi(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{[xs.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 lE(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:o}=Zo(e.value),[i,s]=t.split(":"),n=o?`${$e(o)}!`:"",r=cE(i),a=s?`:${cE(s)}`:"";return{...e,value:n+r+a}}function cE(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=hE(e,"colrow");break;case"colrow":e=hE(e,"row");break;case"row":e=hE(e,"col");break;case"col":e=hE(e,"none")}return e}function hE(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 dE=n("The cell you are trying to edit has been deleted.");const uE=[{name:n("Sum"),types:[ws.number],compute:e=>Kl.compute([e])},{name:n("Avg"),types:[ws.number],compute:e=>lc.compute([e])},{name:n("Min"),types:[ws.number],compute:e=>Ic.compute([e])},{name:n("Max"),types:[ws.number],compute:e=>Ec.compute([e])},{name:n("Count"),types:[ws.number,ws.text,ws.boolean,ws.error],compute:e=>fc.compute([e])},{name:n("Count Numbers"),types:[ws.number,ws.text,ws.boolean,ws.error],compute:e=>mc.compute([e])}];const gE=(new Ui).add("sheet",class extends EC{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 Math.min(...e.elements)<0||Math.max(...e.elements)>t?87:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?8:0}case"FREEZE_ROWS":return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case"FREEZE_COLUMNS":return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return 0}}handle(e){switch(e.type){case"SET_GRID_LINES_VISIBILITY":this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case"DELETE_CONTENT":this.clearZones(e.sheetId,e.target);break;case"CREATE_SHEET":const t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update("sheetIdsMapName",t.name,t.id);break;case"MOVE_SHEET":this.moveSheet(e.sheetId,e.delta);break;case"RENAME_SHEET":this.renameSheet(this.sheets[e.sheetId],e.name);break;case"HIDE_SHEET":this.hideSheet(e.sheetId);break;case"SHOW_SHEET":this.showSheet(e.sheetId);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case"UPDATE_CELL_POSITION":this.updateCellPosition(e);break;case"FREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,e.quantity,"COL");break;case"FREEZE_ROWS":this.setPaneDivisions(e.sheetId,e.quantity,"ROW");break;case"UNFREEZE_ROWS":this.setPaneDivisions(e.sheetId,0,"ROW");break;case"UNFREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,0,"COL");break;case"UNFREEZE_COLUMNS_ROWS":this.setPaneDivisions(e.sheetId,0,"COL"),this.setPaneDivisions(e.sheetId,0,"ROW")}}import(e){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:Qo(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 vi(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(oi))return 25;if(t.length){const o=this.getSheetZone(e);return t.every((e=>gi(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:Qo(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(Wt);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 EC{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:Math.min(...e.elements)<0||Math.max(...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 EC{static getters=["doesZonesContainFilter","getFilter","getFilters","getFilterTable","getFilterTables","getFilterTablesInZone","getFilterId"];tables={};allowDispatch(e){switch(e.type){case"CREATE_FILTER_TABLE":if(!Ii(...e.target))return 82;const t=li(...e.target),o=()=>this.getFilterTables(e.sheetId).some((e=>di(e.zone,t)))?79:0,i=()=>{const o=this.getters.getMergesInZone(e.sheetId,t);for(let e of o)if(di(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(di(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=li(...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=>!ci(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=>ui(t,o,e.zone)))}getFilterTablesInZone(e,t){return this.getFilterTables(e).filter((e=>gi(e.zone,t)))}doesZonesContainFilter(e,t){for(const o of t)for(const t of this.getFilterTables(e))if(ci(o,t.zone))return!0;return!1}onAddColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const o=si(t.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),i=[];for(const o of t.filters){const t=si(o.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);i.push(new yC(o.id,t))}if(i.length<fi(o).numberOfCols){for(let e=o.left;e<=o.right;e++)i.find((t=>t.col===e))||i.push(new yC(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=ai(t.zone,"COL"===e.dimension?"left":"top",e.elements);if(o){if(ii(o)!==ii(t.zone)){const i=[];for(const o of t.filters){const t=ai(o.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.elements);t&&i.push(new yC(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 xC(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(ti(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:ii(e.zone)})}exportForExcel(e){this.export(e)}}).add("cell",class extends EC{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.checkCellOutOfSheet(e);case"CLEAR_CELL":return this.checkValidations(e,this.chainValidations(this.checkCellOutOfSheet,this.checkUselessClearCell));default:return 0}}handle(e){switch(e.type){case"SET_FORMATTING":"style"in e&&this.setStyle(e.sheetId,e.target,e.style),"format"in e&&void 0!==e.format&&this.setFormatter(e.sheetId,e.target,e.format);break;case"CLEAR_FORMATTING":this.clearFormatting(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case"UPDATE_CELL":this.updateCell(e.sheetId,e.col,e.row,e);break;case"CLEAR_CELL":this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col,row:e.row,content:"",style:null,format:""})}}setFormatter(e,t,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}=Wt(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[Gt(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=Gt((t=this.getters.expandZone(e,t)).left,t.top,o[0]),s=Gt(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;let l=("format"in i?i.format:s&&s.format)||To(r);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,isFormula:!1}}createFormulaCell(e,t,o,i,s){const n=oS(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:Sv(t),execute:function(){throw s}},dependencies:[]}}checkCellOutOfSheet(e){const{sheetId:t,col:o,row:i}=e;if(!this.getters.tryGetSheet(t))return 27;return ui(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}}).add("merge",class extends EC{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 vi(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){return vi(t).some((({col:t,row:o})=>void 0!==this.getMerge({sheetId:e,col:t,row:o})))}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&&di(o,r)&&(r=li(o,r))}return hi(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)&&hi(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 hi(t,o);const{numberOfCols:i,numberOfRows:s}=fi(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?RC(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&&di(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||!hi(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(Gt(o,s)===Gt(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,ii({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&&hi(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}=fi(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 vi(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,ti(o))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...IC(e))}}exportForExcel(e){this.export(e)}}).add("headerSize",class extends EC{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=Math.min(...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 EC{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)"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}=Wt(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,ti(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=Gt(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 EC{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)ui(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{oS(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&&wC(t)>=wC(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&&wC(t)>=wC(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&&wC(t)>=wC(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 EC{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}}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 EC{static getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];charts={};createChart=function(e){const t=Vr.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=Vr.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 EC{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}}),pE=(new Ui).add("ui_sheet",class extends AC{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=vi(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,...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 AC{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 AC{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 AC{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:wi({col:0,row:0})},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}break;case"FOCUS_RANGE":case"CHANGE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id],o=t.ranges.find((t=>t.id===e.rangeId)),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}=Zo(e);return null!==t.match(Bo)&&(!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 WC(this.config,t,o),0===t.length){const t=this.inputs[e],o={zone:wi({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 AC{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}=fi(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=>hi(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 AC{static layers=[0,7];static getters=["getColDimensionsInViewport","getRowDimensionsInViewport"];boxes=[];getColDimensionsInViewport(e,t){const o=Math.min(...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=Math.min(...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=Vt(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!==ws.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!==ws.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===ws.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===ws.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:Jm[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===ws.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=wi({col:e,row:r}),{x:i,y:s,width:n,height:a}=this.getters.getVisibleRect(li(t,o));(n<R||v>a||y.length>1)&&(f.clipRect={x:i,y:s,width:n,height:a});break}case"right":{const e=wi({col:o,row:r}),{x:i,y:s,width:n,height:a}=this.getters.getVisibleRect(li(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,wi(t),n))}for(const t of this.getters.getMerges(r))if(!this.getters.isMergeHidden(r,t)&&di(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 AC{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(Gt(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(Gt(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(Gt(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(Gt(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(ui(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.getEvaluatedCell(e).type!==ws.empty||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.getEvaluatedCell(e).type!==ws.empty||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=$s.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}=Wt(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 NC(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 AC{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($C.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell($C.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($C.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($C.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 AC{static getters=["getContiguousZone"];allowDispatch(e){if("SORT_CELLS"===e.type){if(!ui(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 vi(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=>di(e,t))),i=fi(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]===ws.empty&&(o=o.slice(1)),!o.some((e=>e[0]===ws.empty))&&!!o.some((e=>e[1]!==ws.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===ws.empty)),n=i.filter((e=>e.type!==ws.empty));o&&(n.push(...s.map((e=>({...e,type:ws.number,value:0})))),s=[]);const r="descending"===t?-1:1;return n.sort(((e,t)=>{let o=ea.indexOf(e.type)-ea.indexOf(t.type);return 0===o&&(o=e.type===ws.text||e.type===ws.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 AC{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}=ui(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)||bi(li(n,t))?[{position:{col:i,row:s},zone:n}]:this.sumDimensions(e,li(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=s.filter((e=>i[e]&&!i[e].isAutoSummable)),r=Math.max(...n),a=Qe(s.filter((e=>this.isNumber(i[e]))))[0]||[];return Math.max(...a)<r?1/0:Math.min(...a)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===ws.number&&!(e.format&&Eo(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 bi(t)?(o.add(1===fi(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)},vi(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)},vi(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 AC{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 vi(i)){const i=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==i){const s=Oo(i,o);this.dispatch("SET_FORMATTING",{sheetId:e,target:[wi(t)],format:s})}}}getCellNumberFormat(e){for(const t of[e]){const e=this.getters.getEvaluatedCell(t);if(!(e.type!==ws.number||e.format&&Eo(e.format)))return e.format||Ro(e.value)}}}).add("split_to_columns",class extends AC{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===ws.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 AC{static getters=["getCellPopover","getPersistentPopoverTypeAtPosition","hasOpenedPopover"];persistentPopover;allowDispatch(e){if("OPEN_CELL_POPOVER"===e.type){try{Ln.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=Ln.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=Ln.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(wi({col:e,row:t}))}}).add("collaborative",class extends AC{static getters=["getClientsToDisplay","getClient","getConnectedClients","isFullySynchronized"];static layers=[6];availableColors=new Set(HC);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(HC));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 zC)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 AC{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=tE(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)&&(As(t.rootCommand)?KC.contains(t.rootCommand.type):QC.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"])}}),mE=(new Ui).add("selection",class extends AC{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=>hi(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.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 vi(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!==ws.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 uE){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(vi).flat();for(const{col:s,row:n}of i){const i=this.getters.getEvaluatedCell({sheetId:o,col:s,row:n});i.type===ws.number&&(t++,e+=i.value)}return t<2?null:mo(e)}isSelected(e){return!!this.getters.getSelectedZones().find((t=>hi(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=ri(o,"left",[...e.elements]);let s={left:t.col,right:t.col,top:t.row,bottom:t.row};s=ri(s,"left",[...e.elements]);const n={cell:{col:s.left,row:s.top},zone:i},r=this.gridSelection.zones.map((t=>ri(t,"left",[...e.elements])));this.setSelectionMixin(n,r)}onRowsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,i=ri(o,"top",[...e.elements]);let s={left:t.col,right:t.col,top:t.row,bottom:t.row};s=ri(s,"top",[...e.elements]);const n={cell:{col:s.left,row:s.top},zone:i},r=this.gridSelection.zones.map((t=>ri(t,"top",[...e.elements])));this.setSelectionMixin(n,r)}onAddElements(e){const t="COL"===e.dimension?"left":"top",o=ni(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),i=this.gridSelection.zones.map((o=>ni(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 iE(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):wi(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 AC{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 aE(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(!oi(t[0])){for(const{col:t,row:o}of vi(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)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)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 aE(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:As(e)&&(this.status="invisible")}}getClipboardContent(){return this.state?.getClipboardContent()||{[xs.PlainText]:"\t"}}getClipboardTextContent(){return this.state?.getClipboardContent()[xs.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 iE(e,t,this.getters,this.dispatch,this.selection)}getClipboardState(e,t){return this.getters.getSelectedFigureId()?new sE(t,this.getters,this.dispatch):new iE(e,t,this.getters,this.dispatch,this.selection)}drawGrid(e){"visible"===this.status&&this.state&&this.state.drawClipboard(e)}}).add("edition",class extends AC{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}=Zo(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 hi(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,wi({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:dE}));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(lE).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:dE});const{top:t,left:o}=ri({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:dE});const{top:t,left:o}=ri({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}=ni({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=wi({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("%")&&oo(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=wi({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 ws.text:case ws.empty:return i;case ws.boolean:return n;case ws.error:return t?.content||"";case ws.number:return o&&Eo(o)?n:this.numberComposerContent(i,o)}}numberComposerContent(e,t){return t?.includes("%")?100*e+"%":function(e){const{integerDigits:t,decimalDigits:o}=vo(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("=")?iS(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&&yi(e.zone)>1?o.push({...t[0]}):2===t.length&&1===yi(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 At[t%At.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)||bv.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))}}),fE=(new Ui).add("evaluation",class extends AC{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(ys.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=oS(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})?ks(""):this.evaluatedCells[e]?.[t]?.[o]?.()||ks("")}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 vi(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 Ds(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 zs(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 Gt(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 ks(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(OC),this.evalContext,{getters:this.getters}),o=this.getters;const i=t=>{const o=e(t);if(o.type===ws.error)throw o.error;return o},s={};function r(e){if(!oi(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:ii(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=ci(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,...Wt(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 oS(e),!1}catch(e){return!0}}}).add("evaluation_filter",class extends AC{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(ui(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=ti(o.range),s=[],n=[];for(const o of Ke(0,fi(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?vi(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[Gt(h.col,h.row)]={...t.cells[Gt(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 AC{static getters=["getChartRuntime","getStyleOfSingleCellChart"];charts={};createRuntimeChart=function(e){const t=Vr.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(ys.has(e.type)||Is.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:Xn(e)};if(!t)return{background:w,fontColor:Xn(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||Xn(r)}}}).add("evaluation_cf",class extends AC{static getters=["getConditionalIcon","getCellComputedStyle"];isStale=!0;computedStyles={};computedIcons={};uuidGenerator=new Jo;handle(e){switch((Is.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,[Gt(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===ws.number)).map((e=>e.value));switch(t.type){case"value":return"max"===o?Math.max(...s):Math.min(...s);case"number":return Number(t.value);case"percentage":const e=Math.min(...s);return e+(Math.max(...s)-e)*Number(t.value)/100;case"percentile":return no(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!==ws.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===ws.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=Ot(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===ws.error)return!1;const o=t.values.map(Ls);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=pi(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=Gt(t.col,t.row);for(let s of this.getters.getConditionalFormats(e.sheetId))for(let n of s.ranges)if(ui(e.col,e.row,this.getters.getRangeFromSheetXC(e.sheetId,n).zone)){const n=s,r=[];if("CUT"===o&&r.push(Gt(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 AC{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":let{col:t,row:o}=Ci(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const i=e.previousAnchor.zone,s=e.anchor.zone,{top:n,bottom:r,left:a,right:l}=this.getters.getActiveMainViewport();i.left===s.left&&i.right===s.right&&(t=a>t||t>l?a:t),i.top===s.top&&i.bottom===s.bottom&&(o=n>o||o>r?n:o)}const i=this.getters.getActiveSheetId();t=Math.min(t,this.getters.getNumberCols(i)-1),o=Math.min(o,this.getters.getNumberRows(i)-1),this.refreshViewport(this.getters.getActiveSheetId(),{col:t,row:o})}}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{top:t}=this.getActiveMainViewport(),o=this.getters.getActiveSheetId(),i=this.clipOffsetY(this.getters.getRowDimensions(o,t).start+this.sheetViewHeight);this.shiftVertically(i);break;case"SHIFT_VIEWPORT_UP":{const{top:e}=this.getActiveMainViewport(),t=this.getters.getActiveSheetId(),o=this.clipOffsetY(this.getters.getRowDimensions(t,e).end-this.sheetViewHeight);this.shiftVertically(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:s,row:n}=this.getters.getActivePosition();this.refreshViewport(this.getters.getActiveSheetId(),{col:s,row:n})}}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=Yt(e-a),s=1):e<l&&o>=l&&c>0?(i=!0,n=Yt(l-e),s=-1):r&&t<l&&e>l&&(i=!0,n=Yt(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=Yt(e-a),s=1):e<l&&o>=l&&c>0?(i=!0,n=Yt(l-e),s=-1):r&&t<l&&e>l&&(i=!0,n=Yt(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))))}clipOffsetY(e){const{height:t}=this.getMainViewportRect(),o=t-this.sheetViewHeight;return e=Math.min(e,o),e=Math.max(e,0)}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 MC(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 MC(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 MC(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 MC(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{top:t}=this.getActiveMainViewport(),{scrollX:o}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(o,e);const{anchor:i}=this.getters.getSelection(),s=this.getActiveMainViewport().top-t;this.selection.selectCell(i.cell.col,i.cell.row+s)}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 AC{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:Ft(255,0,0),colors:[]},{leadColor:Ft(255,128,0),colors:[]},{leadColor:Ft(128,128,0),colors:[]},{leadColor:Ft(128,255,0),colors:[]},{leadColor:Ft(0,255,0),colors:[]},{leadColor:Ft(0,255,128),colors:[]},{leadColor:Ft(0,255,255),colors:[]},{leadColor:Ft(0,127,255),colors:[]},{leadColor:Ft(0,0,255),colors:[]},{leadColor:Ft(127,0,255),colors:[]},{leadColor:Ft(128,0,128),colors:[]},{leadColor:Ft(255,0,128),colors:[]}];for(const o of e.map(kt)){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)=>Ut(e).s-Ut(t).s)))).flat().map(Lt)}([...new Set([...new Set([...e,...this.customColors])].filter(Nt).map(Mt))]).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(Ot(t.minimum.color)),o.push(t.midpoint?Ot(t.midpoint.color):void 0),o.push(Ot(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=Mt(e);e&&!_.includes(t)&&this.customColors.add(t)}}),bE=new Ui;bE.add("link",{condition:(e,t)=>!!t.model.getters.getEvaluatedCell(e).link,execute:(e,t)=>Gi(t.model.getters.getEvaluatedCell(e).link,t),sequence:5});class vE{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 SE{focusableElement=void 0;setFocusableElement(e){this.focusableElement=e}focus(){this.focusableElement?.focus()}}const CE=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];Oi`
1420
1420
  .o-ripple {
1421
1421
  z-index: 1;
1422
1422
  }
1423
- `;class CE extends t.Component{static template="o-spreadsheet-RippleEffect";rippleRef=t.useRef("ripple");setup(){let e;t.onMounted((()=>{const t=this.rippleRef.el;t&&t.animate&&(e=t.animate(SE,{duration:this.props.duration,easing:"ease-out"}),e.addEventListener("finish",this.props.onAnimationEnd))})),t.onWillUnmount((()=>{e?.removeEventListener("finish",this.props.onAnimationEnd)}))}get rippleStyle(){const{x:e,y:t,width:o,height:i}=this.props;return Fi({transform:"scale(0)",left:e,top:t,"margin-left":`${-o/2+(this.props.offsetX||0)}px`,"margin-top":`${-i/2+(this.props.offsetY||0)}px`,width:`${o}px`,height:`${i}px`,background:this.props.color,"border-radius":"100%",opacity:`${this.props.opacity}`})}}CE.props={x:String,y:String,color:String,opacity:Number,duration:Number,width:Number,height:Number,offsetY:Number,offsetX:Number,allowOverflow:Boolean,onAnimationEnd:Function,style:String};class EE extends t.Component{static template="o-spreadsheet-Ripple";static components={RippleEffect:CE};static defaultProps={color:"#aaaaaa",opacity:.4,duration:800,enabled:!0,onAnimationEnd:()=>{},class:""};childContainer=t.useRef("childContainer");state=t.useState({ripples:[]});currentId=1;onClick(e){if(!this.props.enabled)return;if(!this.childContainer.el)return;const t=this.getRippleChildRectInfo(),{x:o,y:i,width:s,height:r}=t,n=Math.max(s,r),a={x:e.clientX-o,y:e.clientY-i,width:this.props.width||2.85*n,height:this.props.height||2.85*n};this.state.ripples.push({rippleRect:a,id:this.currentId++})}getRippleStyle(){const e=this.childContainer.el;if(!e||1!==e.childElementCount||!e.firstElementChild)return"";const t=this.getRippleChildRectInfo();return Fi({top:t.marginTop+"px",left:t.marginLeft+"px",width:t.width+"px",height:t.height+"px"})}getRippleChildRectInfo(){const e=this.childContainer.el;if(!e)throw new Error("No child container element found");if(1!==e.childElementCount||!e.firstElementChild){return{...sr(e),marginLeft:0,marginTop:0}}const t=e.firstElementChild,o=function(e){const t=window.getComputedStyle(e);return{top:parseInt(t.marginTop,10)||0,bottom:parseInt(t.marginBottom,10)||0,left:parseInt(t.marginLeft,10)||0,right:parseInt(t.marginRight,10)||0}}(t);return{...sr(t),marginLeft:o.left,marginTop:o.top}}removeRipple(e){const t=this.state.ripples.findIndex((t=>t.id===e));-1!==t&&this.state.ripples.splice(t,1)}getRippleEffectProps(e){const t=this.state.ripples.find((t=>t.id===e))?.rippleRect;if(!t)throw new Error("Cannot find a ripple with the id "+e);return{color:this.props.color,opacity:this.props.opacity,duration:this.props.duration,x:this.props.ignoreClickPosition?"50%":t.x+"px",y:this.props.ignoreClickPosition?"50%":t.y+"px",width:t.width,height:t.height,offsetX:this.props.offsetX||0,offsetY:this.props.offsetY||0,allowOverflow:this.props.allowOverflow||!1,style:this.getRippleStyle(),onAnimationEnd:()=>this.removeRipple(e)}}}EE.props={color:{type:String,optional:!0},opacity:{type:Number,optional:!0},duration:{type:Number,optional:!0},ignoreClickPosition:{type:Boolean,optional:!0},width:{type:Number,optional:!0},height:{type:Number,optional:!0},offsetY:{type:Number,optional:!0},offsetX:{type:Number,optional:!0},allowOverflow:{type:Boolean,optional:!0},enabled:{type:Boolean,optional:!0},onAnimationEnd:{type:Function,optional:!0},slots:Object,class:{type:String,optional:!0}},Oi`
1423
+ `;class EE extends t.Component{static template="o-spreadsheet-RippleEffect";rippleRef=t.useRef("ripple");setup(){let e;t.onMounted((()=>{const t=this.rippleRef.el;t&&t.animate&&(e=t.animate(CE,{duration:this.props.duration,easing:"ease-out"}),e.addEventListener("finish",this.props.onAnimationEnd))})),t.onWillUnmount((()=>{e?.removeEventListener("finish",this.props.onAnimationEnd)}))}get rippleStyle(){const{x:e,y:t,width:o,height:i}=this.props;return Fi({transform:"scale(0)",left:e,top:t,"margin-left":`${-o/2+(this.props.offsetX||0)}px`,"margin-top":`${-i/2+(this.props.offsetY||0)}px`,width:`${o}px`,height:`${i}px`,background:this.props.color,"border-radius":"100%",opacity:`${this.props.opacity}`})}}EE.props={x:String,y:String,color:String,opacity:Number,duration:Number,width:Number,height:Number,offsetY:Number,offsetX:Number,allowOverflow:Boolean,onAnimationEnd:Function,style:String};class wE extends t.Component{static template="o-spreadsheet-Ripple";static components={RippleEffect:EE};static defaultProps={color:"#aaaaaa",opacity:.4,duration:800,enabled:!0,onAnimationEnd:()=>{},class:""};childContainer=t.useRef("childContainer");state=t.useState({ripples:[]});currentId=1;onClick(e){if(!this.props.enabled)return;if(!this.childContainer.el)return;const t=this.getRippleChildRectInfo(),{x:o,y:i,width:s,height:n}=t,r=Math.max(s,n),a={x:e.clientX-o,y:e.clientY-i,width:this.props.width||2.85*r,height:this.props.height||2.85*r};this.state.ripples.push({rippleRect:a,id:this.currentId++})}getRippleStyle(){const e=this.childContainer.el;if(!e||1!==e.childElementCount||!e.firstElementChild)return"";const t=this.getRippleChildRectInfo();return Fi({top:t.marginTop+"px",left:t.marginLeft+"px",width:t.width+"px",height:t.height+"px"})}getRippleChildRectInfo(){const e=this.childContainer.el;if(!e)throw new Error("No child container element found");if(1!==e.childElementCount||!e.firstElementChild){return{...nn(e),marginLeft:0,marginTop:0}}const t=e.firstElementChild,o=function(e){const t=window.getComputedStyle(e);return{top:parseInt(t.marginTop,10)||0,bottom:parseInt(t.marginBottom,10)||0,left:parseInt(t.marginLeft,10)||0,right:parseInt(t.marginRight,10)||0}}(t);return{...nn(t),marginLeft:o.left,marginTop:o.top}}removeRipple(e){const t=this.state.ripples.findIndex((t=>t.id===e));-1!==t&&this.state.ripples.splice(t,1)}getRippleEffectProps(e){const t=this.state.ripples.find((t=>t.id===e))?.rippleRect;if(!t)throw new Error("Cannot find a ripple with the id "+e);return{color:this.props.color,opacity:this.props.opacity,duration:this.props.duration,x:this.props.ignoreClickPosition?"50%":t.x+"px",y:this.props.ignoreClickPosition?"50%":t.y+"px",width:t.width,height:t.height,offsetX:this.props.offsetX||0,offsetY:this.props.offsetY||0,allowOverflow:this.props.allowOverflow||!1,style:this.getRippleStyle(),onAnimationEnd:()=>this.removeRipple(e)}}}wE.props={color:{type:String,optional:!0},opacity:{type:Number,optional:!0},duration:{type:Number,optional:!0},ignoreClickPosition:{type:Boolean,optional:!0},width:{type:Number,optional:!0},height:{type:Number,optional:!0},offsetY:{type:Number,optional:!0},offsetX:{type:Number,optional:!0},allowOverflow:{type:Boolean,optional:!0},enabled:{type:Boolean,optional:!0},onAnimationEnd:{type:Function,optional:!0},slots:Object,class:{type:String,optional:!0}},Oi`
1424
1424
  .o-sheet {
1425
1425
  padding: 0 15px;
1426
1426
  padding-right: 10px;
@@ -1460,7 +1460,7 @@
1460
1460
  }
1461
1461
  }
1462
1462
  }
1463
- `;class wE extends t.Component{static template="o-spreadsheet-BottomBarSheet";static components={Ripple:EE};static defaultProps={onMouseDown:()=>{},style:""};state=t.useState({isEditing:!1});sheetDivRef=t.useRef("sheetDiv");sheetNameRef=t.useRef("sheetNameSpan");editionState="initializing";setup(){t.onMounted((()=>{this.isSheetActive&&this.scrollToSheet()})),t.onPatched((()=>{this.sheetNameRef.el&&this.state.isEditing&&"initializing"===this.editionState&&(this.editionState="editing",this.focusInputAndSelectContent())}))}focusInputAndSelectContent(){if(!this.state.isEditing||!this.sheetNameRef.el)return;this.sheetNameRef.el.focus();const e=window.getSelection();e&&this.sheetNameRef.el.firstChild&&e.setBaseAndExtent(this.sheetNameRef.el.firstChild,0,this.sheetNameRef.el.firstChild,this.sheetNameRef.el.textContent?.length||0)}scrollToSheet(){this.sheetDivRef.el?.scrollIntoView?.()}onFocusOut(){this.state.isEditing&&"initializing"!==this.editionState&&this.stopEdition()}onMouseDown(e){this.activateSheet(),this.props.onMouseDown(e)}activateSheet(){this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:this.props.sheetId}),this.scrollToSheet()}onDblClick(){this.startEdition()}onKeyDown(e){this.state.isEditing&&("Enter"===e.key&&(e.preventDefault(),this.stopEdition()),"Escape"===e.key&&this.cancelEdition())}onClickSheetName(e){this.state.isEditing&&e.stopPropagation()}startEdition(){this.state.isEditing=!0,this.editionState="initializing"}stopEdition(){if(!this.state.isEditing)return;this.state.isEditing=!1,this.editionState="initializing",this.sheetNameRef.el?.blur();const e=this.getInputContent()||"";!function(e,t,o,i){const s=e.model.getters.getSheetName(t);if(null===o||o===s)return;const n=e.model.dispatch("RENAME_SHEET",{sheetId:t,name:o});n.reasons.includes(10)?e.raiseError(r("The sheet name cannot be empty."),i):n.reasons.includes(11)?e.raiseError(r("A sheet with the name %s already exists. Please select another name.",o),i):n.reasons.includes(13)&&e.raiseError(r("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",le.join(" ")),i)}(this.env,this.props.sheetId,e,(()=>this.startEdition()))}cancelEdition(){this.state.isEditing=!1,this.editionState="initializing",this.sheetNameRef.el?.blur(),this.setInputContent(this.sheetName)}onIconClick(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}onContextMenu(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}getInputContent(){return this.sheetNameRef.el?.textContent}setInputContent(e){this.sheetNameRef.el&&(this.sheetNameRef.el.textContent=e)}get contextMenuRegistry(){return function(e){const t=new Mr;return t.add("delete",{...Er,sequence:10}).add("duplicate",{...wr,sequence:20}).add("rename",{...xr(e),sequence:30}).add("move_right",{...yr,sequence:40}).add("move_left",{...Ir,sequence:50}).add("hide_sheet",{...Rr,sequence:60}),t}({renameSheetCallback:()=>{this.scrollToSheet(),this.startEdition()}})}get isSheetActive(){return this.env.model.getters.getActiveSheetId()===this.props.sheetId}get sheetName(){return this.env.model.getters.getSheetName(this.props.sheetId)}}wE.props={sheetId:String,openContextMenu:Function,style:{type:String,optional:!0},onMouseDown:{type:Function,optional:!0}},Oi`
1463
+ `;class xE extends t.Component{static template="o-spreadsheet-BottomBarSheet";static components={Ripple:wE};static defaultProps={onMouseDown:()=>{},style:""};state=t.useState({isEditing:!1});sheetDivRef=t.useRef("sheetDiv");sheetNameRef=t.useRef("sheetNameSpan");editionState="initializing";setup(){t.onMounted((()=>{this.isSheetActive&&this.scrollToSheet()})),t.onPatched((()=>{this.sheetNameRef.el&&this.state.isEditing&&"initializing"===this.editionState&&(this.editionState="editing",this.focusInputAndSelectContent())}))}focusInputAndSelectContent(){if(!this.state.isEditing||!this.sheetNameRef.el)return;this.sheetNameRef.el.focus();const e=window.getSelection();e&&this.sheetNameRef.el.firstChild&&e.setBaseAndExtent(this.sheetNameRef.el.firstChild,0,this.sheetNameRef.el.firstChild,this.sheetNameRef.el.textContent?.length||0)}scrollToSheet(){this.sheetDivRef.el?.scrollIntoView?.()}onFocusOut(){this.state.isEditing&&"initializing"!==this.editionState&&this.stopEdition()}onMouseDown(e){this.activateSheet(),this.props.onMouseDown(e)}activateSheet(){this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:this.props.sheetId}),this.scrollToSheet()}onDblClick(){this.startEdition()}onKeyDown(e){this.state.isEditing&&("Enter"===e.key&&(e.preventDefault(),this.stopEdition()),"Escape"===e.key&&this.cancelEdition())}onClickSheetName(e){this.state.isEditing&&e.stopPropagation()}startEdition(){this.state.isEditing=!0,this.editionState="initializing"}stopEdition(){if(!this.state.isEditing)return;this.state.isEditing=!1,this.editionState="initializing",this.sheetNameRef.el?.blur();const e=this.getInputContent()||"";!function(e,t,o,i){const s=e.model.getters.getSheetName(t);if(null===o||o===s)return;const r=e.model.dispatch("RENAME_SHEET",{sheetId:t,name:o});r.reasons.includes(10)?e.raiseError(n("The sheet name cannot be empty."),i):r.reasons.includes(11)?e.raiseError(n("A sheet with the name %s already exists. Please select another name.",o),i):r.reasons.includes(13)&&e.raiseError(n("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",le.join(" ")),i)}(this.env,this.props.sheetId,e,(()=>this.startEdition()))}cancelEdition(){this.state.isEditing=!1,this.editionState="initializing",this.sheetNameRef.el?.blur(),this.setInputContent(this.sheetName)}onIconClick(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}onContextMenu(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}getInputContent(){return this.sheetNameRef.el?.textContent}setInputContent(e){this.sheetNameRef.el&&(this.sheetNameRef.el.textContent=e)}get contextMenuRegistry(){return function(e){const t=new Nn;return t.add("delete",{...wn,sequence:10}).add("duplicate",{...xn,sequence:20}).add("rename",{...yn(e),sequence:30}).add("move_right",{...In,sequence:40}).add("move_left",{...Rn,sequence:50}).add("hide_sheet",{...Tn,sequence:60}),t}({renameSheetCallback:()=>{this.scrollToSheet(),this.startEdition()}})}get isSheetActive(){return this.env.model.getters.getActiveSheetId()===this.props.sheetId}get sheetName(){return this.env.model.getters.getSheetName(this.props.sheetId)}}xE.props={sheetId:String,openContextMenu:Function,style:{type:String,optional:!0},onMouseDown:{type:Function,optional:!0}},Oi`
1464
1464
  .o-selection-statistic {
1465
1465
  margin-right: 20px;
1466
1466
  padding: 4px 4px 4px 8px;
@@ -1470,7 +1470,7 @@
1470
1470
  background-color: rgba(0, 0, 0, 0.08) !important;
1471
1471
  }
1472
1472
  }
1473
- `;class xE extends t.Component{static template="o-spreadsheet-BottomBarStatisic";static components={Ripple:EE};selectedStatisticFn="";statisticFnResults={};setup(){this.statisticFnResults=this.env.model.getters.getStatisticFnResults(),t.onWillUpdateProps((()=>{const e=this.env.model.getters.getStatisticFnResults();vt(e,this.statisticFnResults)||this.props.closeContextMenu(),this.statisticFnResults=e}))}getSelectedStatistic(){if(!Object.values(this.statisticFnResults).every((e=>void 0===e)))return""===this.selectedStatisticFn&&(this.selectedStatisticFn=Object.keys(this.statisticFnResults)[0]),this.getComposedFnName(this.selectedStatisticFn,this.statisticFnResults[this.selectedStatisticFn])}listSelectionStatistics(e){const t=new Mr;let o=0;for(let[e,i]of Object.entries(this.statisticFnResults))t.add(e,{name:this.getComposedFnName(e,i),sequence:o,isReadonlyAllowed:!0,execute:()=>{this.selectedStatisticFn=e}}),o++;const i=e.currentTarget,{top:s,left:r,width:n}=i.getBoundingClientRect();this.props.openContextMenu(r+n,s,t)}getComposedFnName(e,t){return e+": "+(void 0!==t?mo(t):"__")}}xE.props={openContextMenu:Function,closeContextMenu:Function};class yE{draggedItemId;items;containerEl;initialMousePosition;currentMousePosition;minPosition;maxPosition;edgeScrollIntervalId;edgeScrollOffset=0;onChange;onCancel;onDragEnd;deadZone;constructor(e){this.items=e.items.map((e=>({...e,positionAtStart:e.position}))),this.draggedItemId=e.draggedItemId,this.containerEl=e.containerEl,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onDragEnd=e.onDragEnd,this.initialMousePosition=e.mouseX,this.currentMousePosition=e.mouseX,this.minPosition=this.items[0].position,this.maxPosition=this.items[this.items.length-1].position+this.items[this.items.length-1].size,uf(this.onMouseMove.bind(this),this.onMouseUp.bind(this))}onMouseMove(e){if(0!==e.button)return void this.onCancel();const t=e.clientX;t<this.containerRect.left||t>this.containerRect.right?this.startEdgeScroll(t<this.containerRect.left?-1:1):(this.stopEdgeScroll(),this.moveDraggedItemToPosition(t+this.edgeScrollOffset))}moveDraggedItemToPosition(e){this.currentMousePosition=e;const t=this.getHoveredItemIndex(e,this.items),o=this.items.findIndex((e=>e.id===this.draggedItemId)),i=this.items[o];if(this.deadZone&&this.isInZone(e,this.deadZone))return void this.onChange(this.getItemsPositions());if(this.isInZone(e,{start:i.position,end:i.position+i.size})&&(this.deadZone=void 0),o===t)return void this.onChange(this.getItemsPositions());const s=Math.min(o,t),r=Math.max(o,t),n=Math.sign(t-o);let a=0;for(let e=s;e<=r;e++)e!==o&&(this.items[e].position-=n*i.size,a+=this.items[e].size);i.position+=n*a,this.items.sort(((e,t)=>e.position-t.position)),this.deadZone=n>0?{start:e,end:i.position}:{start:i.position+i.size,end:e},this.onChange(this.getItemsPositions())}onMouseUp(e){0!==e.button&&this.onCancel();const t=this.items.findIndex((e=>e.id===this.draggedItemId));this.onDragEnd(this.draggedItemId,t),this.stopEdgeScroll()}startEdgeScroll(e){this.edgeScrollIntervalId||(this.edgeScrollIntervalId=window.setInterval((()=>{const t=3*e;let o=this.currentMousePosition+t;o<this.minPosition?o=this.minPosition:o>this.maxPosition&&(o=this.maxPosition),this.edgeScrollOffset+=o-this.currentMousePosition,this.moveDraggedItemToPosition(o),this.containerEl.scrollLeft+=t}),5))}stopEdgeScroll(){window.clearInterval(this.edgeScrollIntervalId),this.edgeScrollIntervalId=void 0}getHoveredItemIndex(e,t){return e<=this.minPosition?0:e>=this.maxPosition?t.length-1:t.findIndex((t=>t.position+t.size>=e))}getItemsPositions(){const e={};for(let t of this.items){if(t.id!==this.draggedItemId){e[t.id]=t.position-t.positionAtStart;continue}let o=this.currentMousePosition-this.initialMousePosition;o=Math.max(this.minPosition-t.positionAtStart,o),o=Math.min(this.maxPosition-t.positionAtStart-t.size,o),e[t.id]=o}return e}get containerRect(){return this.containerEl.getBoundingClientRect()}isInZone(e,t){return e>=t.start&&e<=t.end}destroy(){this.stopEdgeScroll()}}Oi`
1473
+ `;class yE extends t.Component{static template="o-spreadsheet-BottomBarStatisic";static components={Ripple:wE};selectedStatisticFn="";statisticFnResults={};setup(){this.statisticFnResults=this.env.model.getters.getStatisticFnResults(),t.onWillUpdateProps((()=>{const e=this.env.model.getters.getStatisticFnResults();vt(e,this.statisticFnResults)||this.props.closeContextMenu(),this.statisticFnResults=e}))}getSelectedStatistic(){if(!Object.values(this.statisticFnResults).every((e=>void 0===e)))return""===this.selectedStatisticFn&&(this.selectedStatisticFn=Object.keys(this.statisticFnResults)[0]),this.getComposedFnName(this.selectedStatisticFn,this.statisticFnResults[this.selectedStatisticFn])}listSelectionStatistics(e){const t=new Nn;let o=0;for(let[e,i]of Object.entries(this.statisticFnResults))t.add(e,{name:this.getComposedFnName(e,i),sequence:o,isReadonlyAllowed:!0,execute:()=>{this.selectedStatisticFn=e}}),o++;const i=e.currentTarget,{top:s,left:n,width:r}=i.getBoundingClientRect();this.props.openContextMenu(n+r,s,t)}getComposedFnName(e,t){return e+": "+(void 0!==t?mo(t):"__")}}yE.props={openContextMenu:Function,closeContextMenu:Function};class IE{draggedItemId;items;containerEl;initialMousePosition;currentMousePosition;minPosition;maxPosition;edgeScrollIntervalId;edgeScrollOffset=0;onChange;onCancel;onDragEnd;deadZone;constructor(e){this.items=e.items.map((e=>({...e,positionAtStart:e.position}))),this.draggedItemId=e.draggedItemId,this.containerEl=e.containerEl,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onDragEnd=e.onDragEnd,this.initialMousePosition=e.mouseX,this.currentMousePosition=e.mouseX,this.minPosition=this.items[0].position,this.maxPosition=this.items[this.items.length-1].position+this.items[this.items.length-1].size,uf(this.onMouseMove.bind(this),this.onMouseUp.bind(this))}onMouseMove(e){if(0!==e.button)return void this.onCancel();const t=e.clientX;t<this.containerRect.left||t>this.containerRect.right?this.startEdgeScroll(t<this.containerRect.left?-1:1):(this.stopEdgeScroll(),this.moveDraggedItemToPosition(t+this.edgeScrollOffset))}moveDraggedItemToPosition(e){this.currentMousePosition=e;const t=this.getHoveredItemIndex(e,this.items),o=this.items.findIndex((e=>e.id===this.draggedItemId)),i=this.items[o];if(this.deadZone&&this.isInZone(e,this.deadZone))return void this.onChange(this.getItemsPositions());if(this.isInZone(e,{start:i.position,end:i.position+i.size})&&(this.deadZone=void 0),o===t)return void this.onChange(this.getItemsPositions());const s=Math.min(o,t),n=Math.max(o,t),r=Math.sign(t-o);let a=0;for(let e=s;e<=n;e++)e!==o&&(this.items[e].position-=r*i.size,a+=this.items[e].size);i.position+=r*a,this.items.sort(((e,t)=>e.position-t.position)),this.deadZone=r>0?{start:e,end:i.position}:{start:i.position+i.size,end:e},this.onChange(this.getItemsPositions())}onMouseUp(e){0!==e.button&&this.onCancel();const t=this.items.findIndex((e=>e.id===this.draggedItemId));this.onDragEnd(this.draggedItemId,t),this.stopEdgeScroll()}startEdgeScroll(e){this.edgeScrollIntervalId||(this.edgeScrollIntervalId=window.setInterval((()=>{const t=3*e;let o=this.currentMousePosition+t;o<this.minPosition?o=this.minPosition:o>this.maxPosition&&(o=this.maxPosition),this.edgeScrollOffset+=o-this.currentMousePosition,this.moveDraggedItemToPosition(o),this.containerEl.scrollLeft+=t}),5))}stopEdgeScroll(){window.clearInterval(this.edgeScrollIntervalId),this.edgeScrollIntervalId=void 0}getHoveredItemIndex(e,t){return e<=this.minPosition?0:e>=this.maxPosition?t.length-1:t.findIndex((t=>t.position+t.size>=e))}getItemsPositions(){const e={};for(let t of this.items){if(t.id!==this.draggedItemId){e[t.id]=t.position-t.positionAtStart;continue}let o=this.currentMousePosition-this.initialMousePosition;o=Math.max(this.minPosition-t.positionAtStart,o),o=Math.min(this.maxPosition-t.positionAtStart-t.size,o),e[t.id]=o}return e}get containerRect(){return this.containerEl.getBoundingClientRect()}isInZone(e,t){return e>=t.start&&e<=t.end}destroy(){this.stopEdgeScroll()}}Oi`
1474
1474
  .o-spreadsheet-bottom-bar {
1475
1475
  color: ${C};
1476
1476
  background-color: ${f};
@@ -1512,12 +1512,12 @@
1512
1512
  }
1513
1513
  }
1514
1514
  }
1515
- `;class IE extends t.Component{static template="o-spreadsheet-BottomBar";static components={Menu:br,Ripple:EE,BottomBarSheet:wE,BottomBarStatistic:xE};bottomBarRef=t.useRef("bottomBar");sheetListRef=t.useRef("sheetList");dndHelper;targetScroll=void 0;state=t.useState({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1});menuMaxHeight=250;menuState=t.useState({isOpen:!1,menuId:void 0,position:null,menuItems:[]});sheetState=t.useState({sheetList:this.getVisibleSheets(),isDnd:!1,sheetDndPositions:void 0});setup(){t.onWillUpdateProps((()=>{this.updateScrollState();const e=this.getVisibleSheets();this.sheetState.isDnd&&!vt(this.sheetState.sheetList,e)&&this.stopDragging(),this.sheetState.sheetList=e})),t.onWillUnmount((()=>{this.dndHelper?.destroy()}))}isDragged(e){return this.sheetState.isDnd&&this.dndHelper?.draggedItemId===e}clickAddSheet(e){const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSheetIds().findIndex((e=>e===t))+1,i=this.env.model.uuidGenerator.uuidv4(),s=this.env.model.getters.getNextSheetName(this.env._t("Sheet"));this.env.model.dispatch("CREATE_SHEET",{sheetId:i,position:o,name:s}),this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:i})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map((e=>{const t=this.env.model.getters.getSheet(e);return{id:t.id,name:t.name}}))}getSheets(){return this.sheetState.sheetList}clickListSheets(e){const t=new Mr,o=this.env.model.getters.getActiveSheetId();let i=0;for(const e of this.env.model.getters.getSheetIds()){const s=this.env.model.getters.getSheet(e);t.add(e,{name:s.name,sequence:i,isReadonlyAllowed:!0,textColor:s.isVisible?void 0:"grey",execute:t=>{t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:o,sheetIdTo:e})}}),i++}const s=e.currentTarget,{left:r}=s.getBoundingClientRect(),n=this.bottomBarRef.el.getBoundingClientRect().top;this.openContextMenu(r,n,"listSheets",t)}openContextMenu(e,t,o,i){this.menuState.isOpen=!0,this.menuState.menuId=o,this.menuState.menuItems=i.getMenuItems(),this.menuState.position={x:e,y:t}}onSheetContextMenu(e,t,o){const i=o.currentTarget,{top:s,left:r}=i.getBoundingClientRect();o.closedMenuId!==e?this.openContextMenu(r,s,e,t):this.closeMenu()}closeMenu(){this.menuState.isOpen=!1,this.menuState.menuId=void 0,this.menuState.menuItems=[],this.menuState.position=null}closeContextMenuWithId(e){this.menuState.menuId===e&&this.closeMenu()}onWheel(e){this.targetScroll=void 0;e.currentTarget.scrollLeft+=.5*e.deltaY}onScroll(){this.updateScrollState(),this.targetScroll===this.sheetListCurrentScroll&&(this.targetScroll=void 0)}onArrowLeft(e){if(!this.state.isSheetListScrollableLeft)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll-this.sheetListWidth;this.scrollSheetListTo(Math.max(0,t))}onArrowRight(e){if(!this.state.isSheetListScrollableRight)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll+this.sheetListWidth;this.scrollSheetListTo(Math.min(this.sheetListMaxScroll,t))}updateScrollState(){this.state.isSheetListScrollableLeft=this.sheetListCurrentScroll>0,this.state.isSheetListScrollableRight=this.sheetListCurrentScroll<this.sheetListMaxScroll}scrollSheetListTo(e){this.sheetListRef.el&&(this.targetScroll=e,this.sheetListRef.el.scrollTo({top:0,left:e,behavior:"smooth"}))}onSheetMouseDown(e,t){if(0!==t.button)return;this.closeMenu();const o=t.clientX;document.body.style.cursor="move";const i=this.getVisibleSheets(),s=this.getSheetItemRects(),r=i.map(((e,t)=>({id:e.id,size:s[t].width,position:s[t].x})));this.dndHelper=new yE({draggedItemId:e,mouseX:o,items:r,containerEl:this.sheetListRef.el,onChange:e=>{this.sheetState.isDnd=!0,this.sheetState.sheetDndPositions=e},onCancel:()=>this.stopDragging(),onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){const o=t-this.sheetState.sheetList.findIndex((t=>t.id===e));e&&0!==o&&this.env.model.dispatch("MOVE_SHEET",{sheetId:e,delta:o}),this.stopDragging()}getSheetStyle(e){const t={};return this.sheetState.isDnd&&(t.position="relative",t.left=(this.sheetState.sheetDndPositions?.[e]||0)+"px",t.transition="left 0.5s",t.cursor="move"),this.isDragged(e)&&(t.transition="left 0s",t["z-index"]="1000"),Fi(t)}stopDragging(){document.body.style.cursor="",this.sheetState.sheetList=this.getVisibleSheets(),this.sheetState.isDnd=!1,this.sheetState.sheetDndPositions=void 0,this.dndHelper=void 0}getSheetItemRects(){return Array.from(this.bottomBarRef.el.querySelectorAll(".o-sheet")).map((e=>e.getBoundingClientRect())).map((e=>({x:e.x,width:e.width-1,y:e.y,height:e.height})))}getSheetClasses(e){let t="";return this.isDragged(e)&&(t+="dragged "),this.sheetState.isDnd&&(t+="dragging "),t}get sheetListCurrentScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollLeft:0}get sheetListWidth(){return this.sheetListRef.el?this.sheetListRef.el.clientWidth:0}get sheetListMaxScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollWidth-this.sheetListRef.el.clientWidth:0}}IE.props={onClick:Function},Oi`
1515
+ `;class RE extends t.Component{static template="o-spreadsheet-BottomBar";static components={Menu:vn,Ripple:wE,BottomBarSheet:xE,BottomBarStatistic:yE};bottomBarRef=t.useRef("bottomBar");sheetListRef=t.useRef("sheetList");dndHelper;targetScroll=void 0;state=t.useState({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1});menuMaxHeight=250;menuState=t.useState({isOpen:!1,menuId:void 0,position:null,menuItems:[]});sheetState=t.useState({sheetList:this.getVisibleSheets(),isDnd:!1,sheetDndPositions:void 0});setup(){t.onWillUpdateProps((()=>{this.updateScrollState();const e=this.getVisibleSheets();this.sheetState.isDnd&&!vt(this.sheetState.sheetList,e)&&this.stopDragging(),this.sheetState.sheetList=e})),t.onWillUnmount((()=>{this.dndHelper?.destroy()}))}isDragged(e){return this.sheetState.isDnd&&this.dndHelper?.draggedItemId===e}clickAddSheet(e){const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSheetIds().findIndex((e=>e===t))+1,i=this.env.model.uuidGenerator.uuidv4(),s=this.env.model.getters.getNextSheetName(this.env._t("Sheet"));this.env.model.dispatch("CREATE_SHEET",{sheetId:i,position:o,name:s}),this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:i})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map((e=>{const t=this.env.model.getters.getSheet(e);return{id:t.id,name:t.name}}))}getSheets(){return this.sheetState.sheetList}clickListSheets(e){const t=new Nn,o=this.env.model.getters.getActiveSheetId();let i=0;for(const e of this.env.model.getters.getSheetIds()){const s=this.env.model.getters.getSheet(e);t.add(e,{name:s.name,sequence:i,isReadonlyAllowed:!0,textColor:s.isVisible?void 0:"grey",execute:t=>{t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:o,sheetIdTo:e})}}),i++}const s=e.currentTarget,{left:n}=s.getBoundingClientRect(),r=this.bottomBarRef.el.getBoundingClientRect().top;this.openContextMenu(n,r,"listSheets",t)}openContextMenu(e,t,o,i){this.menuState.isOpen=!0,this.menuState.menuId=o,this.menuState.menuItems=i.getMenuItems(),this.menuState.position={x:e,y:t}}onSheetContextMenu(e,t,o){const i=o.currentTarget,{top:s,left:n}=i.getBoundingClientRect();o.closedMenuId!==e?this.openContextMenu(n,s,e,t):this.closeMenu()}closeMenu(){this.menuState.isOpen=!1,this.menuState.menuId=void 0,this.menuState.menuItems=[],this.menuState.position=null}closeContextMenuWithId(e){this.menuState.menuId===e&&this.closeMenu()}onWheel(e){this.targetScroll=void 0;e.currentTarget.scrollLeft+=.5*e.deltaY}onScroll(){this.updateScrollState(),this.targetScroll===this.sheetListCurrentScroll&&(this.targetScroll=void 0)}onArrowLeft(e){if(!this.state.isSheetListScrollableLeft)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll-this.sheetListWidth;this.scrollSheetListTo(Math.max(0,t))}onArrowRight(e){if(!this.state.isSheetListScrollableRight)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll+this.sheetListWidth;this.scrollSheetListTo(Math.min(this.sheetListMaxScroll,t))}updateScrollState(){this.state.isSheetListScrollableLeft=this.sheetListCurrentScroll>0,this.state.isSheetListScrollableRight=this.sheetListCurrentScroll<this.sheetListMaxScroll}scrollSheetListTo(e){this.sheetListRef.el&&(this.targetScroll=e,this.sheetListRef.el.scrollTo({top:0,left:e,behavior:"smooth"}))}onSheetMouseDown(e,t){if(0!==t.button)return;this.closeMenu();const o=t.clientX;document.body.style.cursor="move";const i=this.getVisibleSheets(),s=this.getSheetItemRects(),n=i.map(((e,t)=>({id:e.id,size:s[t].width,position:s[t].x})));this.dndHelper=new IE({draggedItemId:e,mouseX:o,items:n,containerEl:this.sheetListRef.el,onChange:e=>{this.sheetState.isDnd=!0,this.sheetState.sheetDndPositions=e},onCancel:()=>this.stopDragging(),onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){const o=t-this.sheetState.sheetList.findIndex((t=>t.id===e));e&&0!==o&&this.env.model.dispatch("MOVE_SHEET",{sheetId:e,delta:o}),this.stopDragging()}getSheetStyle(e){const t={};return this.sheetState.isDnd&&(t.position="relative",t.left=(this.sheetState.sheetDndPositions?.[e]||0)+"px",t.transition="left 0.5s",t.cursor="move"),this.isDragged(e)&&(t.transition="left 0s",t["z-index"]="1000"),Fi(t)}stopDragging(){document.body.style.cursor="",this.sheetState.sheetList=this.getVisibleSheets(),this.sheetState.isDnd=!1,this.sheetState.sheetDndPositions=void 0,this.dndHelper=void 0}getSheetItemRects(){return Array.from(this.bottomBarRef.el.querySelectorAll(".o-sheet")).map((e=>e.getBoundingClientRect())).map((e=>({x:e.x,width:e.width-1,y:e.y,height:e.height})))}getSheetClasses(e){let t="";return this.isDragged(e)&&(t+="dragged "),this.sheetState.isDnd&&(t+="dragging "),t}get sheetListCurrentScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollLeft:0}get sheetListWidth(){return this.sheetListRef.el?this.sheetListRef.el.clientWidth:0}get sheetListMaxScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollWidth-this.sheetListRef.el.clientWidth:0}}RE.props={onClick:Function},Oi`
1516
1516
  .o-dashboard-clickable-cell {
1517
1517
  position: absolute;
1518
1518
  cursor: pointer;
1519
1519
  }
1520
- `;let RE=1;class TE extends t.Component{static template="o-spreadsheet-SpreadsheetDashboard";static components={GridOverlay:$f,GridPopover:Wf,Popover:gr,VerticalScrollBar:ib,HorizontalScrollBar:ob,FilterIconsOverlay:Nf};onMouseWheel;canvasPosition;hoveredCell;setup(){const e=t.useRef("grid");this.canvasPosition=cr(e),this.hoveredCell=t.useState({col:void 0,row:void 0}),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),Yf("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimension())),this.onMouseWheel=Xf(((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 gridContainer(){const e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e),{end:o}=this.env.model.getters.getColDimensions(e,t);return Fi({"max-width":`${o}px`})}get gridOverlayDimensions(){return Fi({height:"100%",width:"100%"})}getCellClickableStyle(e){return Fi({top:`${e.y}px`,left:`${e.x}px`,width:`${e.width}px`,height:`${e.height}px`})}getClickableCells(){const e=[],t=this.env.model.getters.getActiveSheetId();for(const o of this.env.model.getters.getSheetViewVisibleCols())for(const i of this.env.model.getters.getSheetViewVisibleRows()){const s={sheetId:t,col:o,row:i},r=this.getClickableAction(s);if(!r)continue;let n;n=this.env.model.getters.isInMerge(s)?this.env.model.getters.getMerge(s):wi({col:o,row:i});const a=this.env.model.getters.getVisibleRect(n);e.push({coordinates:a,position:{col:o,row:i},action:r,tKey:`${RE}-${o}-${i}`})}return RE++,e}getClickableAction(e){for(const t of bE.getAll().sort(((e,t)=>e.sequence-t.sequence)))if(t.condition(e,this.env))return t.execute;return!1}selectClickableCell(e){const{position:t,action:o}=e;o({...t,sheetId:this.env.model.getters.getActiveSheetId()},this.env)}onClosePopover(){this.env.model.dispatch("CLOSE_CELL_POPOVER")}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t,height:e,gridOffsetX:0,gridOffsetY:0})}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})}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}}TE.props={},Oi`
1520
+ `;let TE=1;class AE extends t.Component{static template="o-spreadsheet-SpreadsheetDashboard";static components={GridOverlay:$f,GridPopover:Wf,Popover:pn,VerticalScrollBar:ib,HorizontalScrollBar:ob,FilterIconsOverlay:Nf};onMouseWheel;canvasPosition;hoveredCell;setup(){const e=t.useRef("grid");this.canvasPosition=hn(e),this.hoveredCell=t.useState({col:void 0,row:void 0}),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),Yf("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimension())),this.onMouseWheel=Xf(((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 gridContainer(){const e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e),{end:o}=this.env.model.getters.getColDimensions(e,t);return Fi({"max-width":`${o}px`})}get gridOverlayDimensions(){return Fi({height:"100%",width:"100%"})}getCellClickableStyle(e){return Fi({top:`${e.y}px`,left:`${e.x}px`,width:`${e.width}px`,height:`${e.height}px`})}getClickableCells(){const e=[],t=this.env.model.getters.getActiveSheetId();for(const o of this.env.model.getters.getSheetViewVisibleCols())for(const i of this.env.model.getters.getSheetViewVisibleRows()){const s={sheetId:t,col:o,row:i},n=this.getClickableAction(s);if(!n)continue;let r;r=this.env.model.getters.isInMerge(s)?this.env.model.getters.getMerge(s):wi({col:o,row:i});const a=this.env.model.getters.getVisibleRect(r);e.push({coordinates:a,position:{col:o,row:i},action:n,tKey:`${TE}-${o}-${i}`})}return TE++,e}getClickableAction(e){for(const t of bE.getAll().sort(((e,t)=>e.sequence-t.sequence)))if(t.condition(e,this.env))return t.execute;return!1}selectClickableCell(e){const{position:t,action:o}=e;o({...t,sheetId:this.env.model.getters.getActiveSheetId()},this.env)}onClosePopover(){this.env.model.dispatch("CLOSE_CELL_POPOVER")}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t,height:e,gridOffsetX:0,gridOffsetY:0})}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})}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}}AE.props={},Oi`
1521
1521
  .o-sidePanel {
1522
1522
  display: flex;
1523
1523
  flex-direction: column;
@@ -1702,7 +1702,7 @@
1702
1702
  }
1703
1703
  }
1704
1704
  }
1705
- `;class AE extends t.Component{static template="o-spreadsheet-SidePanel";state;setup(){this.state=t.useState({panel:cf.get(this.props.component)}),t.onWillUpdateProps((e=>this.state.panel=cf.get(e.component)))}getTitle(){return"function"==typeof this.state.panel.title?this.state.panel.title(this.env):this.state.panel.title}}AE.props={component:String,panelProps:{type:Object,optional:!0},onCloseSidePanel:Function},Oi`
1705
+ `;class OE extends t.Component{static template="o-spreadsheet-SidePanel";state;setup(){this.state=t.useState({panel:cf.get(this.props.component)}),t.onWillUpdateProps((e=>this.state.panel=cf.get(e.component)))}getTitle(){return"function"==typeof this.state.panel.title?this.state.panel.title(this.env):this.state.panel.title}}OE.props={component:String,panelProps:{type:Object,optional:!0},onCloseSidePanel:Function},Oi`
1706
1706
  .o-menu-item-button {
1707
1707
  display: flex;
1708
1708
  justify-content: center;
@@ -1715,7 +1715,7 @@
1715
1715
  opacity: 0.6;
1716
1716
  cursor: default;
1717
1717
  }
1718
- `;class OE extends t.Component{static template="o-spreadsheet-ActionButton";actionButton=Or(this.props.action);setup(){t.onWillUpdateProps((()=>this.actionButton=Or(this.props.action)))}get isVisible(){return this.actionButton.isVisible(this.env)}get isEnabled(){return this.actionButton.isEnabled(this.env)}get isActive(){return this.actionButton.isActive?.(this.env)}get title(){const e=this.actionButton.name(this.env),t=this.actionButton.description;return e+(t?` (${t})`:"")}get iconTitle(){return this.actionButton.icon}onClick(e){this.isEnabled&&(this.props.onClick?.(e),this.actionButton.execute?.(this.env))}get buttonStyle(){return this.props.selectedColor?Fi({"border-bottom":`4px solid ${this.props.selectedColor}`,height:"16px","margin-top":"2px"}):""}}OE.props={action:Object,hasTriangleDownIcon:{type:Boolean,optional:!0},selectedColor:{type:String,optional:!0},class:{type:String,optional:!0},onClick:{type:Function,optional:!0}};const ME=[[["all","o-spreadsheet-Icon.BORDERS"],["hv","o-spreadsheet-Icon.BORDER_HV"],["h","o-spreadsheet-Icon.BORDER_H"],["v","o-spreadsheet-Icon.BORDER_V"],["external","o-spreadsheet-Icon.BORDER_EXTERNAL"]],[["left","o-spreadsheet-Icon.BORDER_LEFT"],["top","o-spreadsheet-Icon.BORDER_TOP"],["right","o-spreadsheet-Icon.BORDER_RIGHT"],["bottom","o-spreadsheet-Icon.BORDER_BOTTOM"],["clear","o-spreadsheet-Icon.BORDER_CLEAR"]]];Oi`
1718
+ `;class ME extends t.Component{static template="o-spreadsheet-ActionButton";actionButton=Mn(this.props.action);setup(){t.onWillUpdateProps((()=>this.actionButton=Mn(this.props.action)))}get isVisible(){return this.actionButton.isVisible(this.env)}get isEnabled(){return this.actionButton.isEnabled(this.env)}get isActive(){return this.actionButton.isActive?.(this.env)}get title(){const e=this.actionButton.name(this.env),t=this.actionButton.description;return e+(t?` (${t})`:"")}get iconTitle(){return this.actionButton.icon}onClick(e){this.isEnabled&&(this.props.onClick?.(e),this.actionButton.execute?.(this.env))}get buttonStyle(){return this.props.selectedColor?Fi({"border-bottom":`4px solid ${this.props.selectedColor}`,height:"16px","margin-top":"2px"}):""}}ME.props={action:Object,hasTriangleDownIcon:{type:Boolean,optional:!0},selectedColor:{type:String,optional:!0},class:{type:String,optional:!0},onClick:{type:Function,optional:!0}};const NE=[[["all","o-spreadsheet-Icon.BORDERS"],["hv","o-spreadsheet-Icon.BORDER_HV"],["h","o-spreadsheet-Icon.BORDER_H"],["v","o-spreadsheet-Icon.BORDER_V"],["external","o-spreadsheet-Icon.BORDER_EXTERNAL"]],[["left","o-spreadsheet-Icon.BORDER_LEFT"],["top","o-spreadsheet-Icon.BORDER_TOP"],["right","o-spreadsheet-Icon.BORDER_RIGHT"],["bottom","o-spreadsheet-Icon.BORDER_BOTTOM"],["clear","o-spreadsheet-Icon.BORDER_CLEAR"]]];Oi`
1719
1719
  .o-border-selector {
1720
1720
  padding: 4px;
1721
1721
  background-color: white;
@@ -1783,7 +1783,7 @@
1783
1783
  margin: 5px 0px 0px 0px !important;
1784
1784
  height: 25px !important;
1785
1785
  }
1786
- `;class NE extends t.Component{static template="o-spreadsheet-BorderEditor";static components={ColorPickerWidget:$m,Popover:gr};BORDER_POSITIONS=ME;lineStyleButtonRef=t.useRef("lineStyleButton");borderStyles=Ns;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}}}NE.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 _E extends t.Component{static template="o-spreadsheet-BorderEditorWidget";static components={BorderEditor:NE};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}})}}_E.props={toggleBorderEditor:Function,showBorderEditor:Boolean,disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};Oi`
1786
+ `;class _E extends t.Component{static template="o-spreadsheet-BorderEditor";static components={ColorPickerWidget:$m,Popover:pn};BORDER_POSITIONS=NE;lineStyleButtonRef=t.useRef("lineStyleButton");borderStyles=Ns;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}}}_E.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 FE extends t.Component{static template="o-spreadsheet-BorderEditorWidget";static components={BorderEditor:_E};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}})}}FE.props={toggleBorderEditor:Function,showBorderEditor:Boolean,disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};Oi`
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 FE extends t.Component{static template="o-spreadsheet-TopBarComposer";static components={Composer:If};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",Fi(e)}get containerStyle(){return"inactive"===this.props.focus?Fi({"border-color":M,"border-right":"none"}):Fi({"border-color":E})}}FE.props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerContentFocused:Function},Oi`
1799
+ `;class DE extends t.Component{static template="o-spreadsheet-TopBarComposer";static components={Composer:If};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",Fi(e)}get containerStyle(){return"inactive"===this.props.focus?Fi({"border-color":M,"border-right":"none"}):Fi({"border-color":E})}}DE.props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerContentFocused:Function},Oi`
1800
1800
  .o-font-size-editor {
1801
1801
  height: calc(100% - 4px);
1802
1802
  input.o-font-size {
@@ -1820,7 +1820,7 @@
1820
1820
  background-color: rgba(0, 0, 0, 0.08);
1821
1821
  }
1822
1822
  }
1823
- `;class DE extends t.Component{static template="o-spreadsheet-FontSizeEditor";static components={};fontSizes=fe;dropdown=t.useState({isOpen:!1});inputRef=t.useRef("inputFontSize");rootEditorRef=t.useRef("FontSizeEditor");setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}onExternalClick(e){or(this.rootEditorRef.el,e)||this.closeFontList()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||Z}toggleFontList(){this.dropdown.isOpen?this.closeFontList():(this.props.onToggle(),this.inputRef.el.focus())}closeFontList(){this.dropdown.isOpen=!1}setSize(e){const t=We(Math.floor(parseFloat(e)),1,400);ua(this.env,{fontSize:t}),this.closeFontList()}setSizeFromInput(e){this.setSize(e.target.value)}setSizeFromList(e){this.setSize(e)}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if("Enter"===e.key||"Escape"===e.key){this.closeFontList();const t=e.target;"Escape"===e.key&&(t.value=`${this.currentFontSize}`),this.props.onToggle()}}}DE.props={onToggle:Function,dropdownStyle:String,class:String},Oi`
1823
+ `;class LE extends t.Component{static template="o-spreadsheet-FontSizeEditor";static components={};fontSizes=fe;dropdown=t.useState({isOpen:!1});inputRef=t.useRef("inputFontSize");rootEditorRef=t.useRef("FontSizeEditor");setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}onExternalClick(e){on(this.rootEditorRef.el,e)||this.closeFontList()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||Z}toggleFontList(){this.dropdown.isOpen?this.closeFontList():(this.props.onToggle(),this.inputRef.el.focus())}closeFontList(){this.dropdown.isOpen=!1}setSize(e){const t=We(Math.floor(parseFloat(e)),1,400);ua(this.env,{fontSize:t}),this.closeFontList()}setSizeFromInput(e){this.setSize(e.target.value)}setSizeFromList(e){this.setSize(e)}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if("Enter"===e.key||"Escape"===e.key){this.closeFontList();const t=e.target;"Escape"===e.key&&(t.value=`${this.currentFontSize}`),this.props.onToggle()}}}LE.props={onToggle:Function,dropdownStyle:String,class:String},Oi`
1824
1824
  .o-spreadsheet-topbar {
1825
1825
  line-height: 1.2;
1826
1826
  font-size: 13px;
@@ -1905,7 +1905,7 @@
1905
1905
  }
1906
1906
  }
1907
1907
  }
1908
- `;class LE extends t.Component{static template="o-spreadsheet-TopBar";get dropdownStyle(){return`max-height:${this.props.dropdownMaxHeight}px`}static components={ColorPickerWidget:$m,ColorPicker:Hm,Menu:br,TopBarComposer:FE,FontSizeEditor:DE,ActionButton:OE,BorderEditorWidget:_E};state=t.useState({menuState:{isOpen:!1,position:null,menuItems:[]},activeTool:"",fillColor:"#ffffff",textColor:"#000000"});isSelectingMenu=!1;openedEl=null;menus=[];EDIT=Za;FORMAT=im;VIEW=Rm;formatNumberMenuItemSpec=Om;isntToolbarMenu=!1;setup(){t.useExternalListener(window,"click",this.onExternalClick),t.onWillStart((()=>this.updateCellState())),t.onWillUpdateProps((()=>this.updateCellState()))}get topbarComponents(){return hf.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=Or(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=Nm.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){ua(this.env,{[e]:t}),this.onClick()}}LE.props={onClick:Function,focusComposer:String,onComposerContentFocused:Function,dropdownMaxHeight:Number};class kE{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({[xs.PlainText]:this.getBlob(e,xs.PlainText),[xs.Html]:this.getBlob(e,xs.Html)})]}getBlob(e,t){return new Blob([e[t]||""],{type:t})}}const PE="#000";Oi`
1908
+ `;class kE extends t.Component{static template="o-spreadsheet-TopBar";get dropdownStyle(){return`max-height:${this.props.dropdownMaxHeight}px`}static components={ColorPickerWidget:$m,ColorPicker:Hm,Menu:vn,TopBarComposer:DE,FontSizeEditor:LE,ActionButton:ME,BorderEditorWidget:FE};state=t.useState({menuState:{isOpen:!1,position:null,menuItems:[]},activeTool:"",fillColor:"#ffffff",textColor:"#000000"});isSelectingMenu=!1;openedEl=null;menus=[];EDIT=Za;FORMAT=im;VIEW=Rm;formatNumberMenuItemSpec=Om;isntToolbarMenu=!1;setup(){t.useExternalListener(window,"click",this.onExternalClick),t.onWillStart((()=>this.updateCellState())),t.onWillUpdateProps((()=>this.updateCellState()))}get topbarComponents(){return hf.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=Mn(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=Nm.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){ua(this.env,{[e]:t}),this.onClick()}}kE.props={onClick:Function,focusComposer:String,onComposerContentFocused:Function,dropdownMaxHeight:Number};class PE{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({[xs.PlainText]:this.getBlob(e,xs.PlainText),[xs.Html]:this.getBlob(e,xs.Html)})]}getBlob(e,t){return new Blob([e[t]||""],{type:t})}}const UE="#000";Oi`
1909
1909
  .o-spreadsheet {
1910
1910
  position: relative;
1911
1911
  display: grid;
@@ -1945,9 +1945,9 @@
1945
1945
  }
1946
1946
  &:not(.o-disabled):not(.active):hover {
1947
1947
  background-color: ${x};
1948
- color: ${PE};
1948
+ color: ${UE};
1949
1949
  .o-icon {
1950
- color: ${PE};
1950
+ color: ${UE};
1951
1951
  }
1952
1952
  }
1953
1953
  &.active {
@@ -2008,37 +2008,37 @@
2008
2008
  outline: none;
2009
2009
  }
2010
2010
  }
2011
- `;const UE=e=>e;class VE extends t.Component{static template="o-spreadsheet-Spreadsheet";static components={TopBar:LE,Grid:rb,BottomBar:IE,SidePanel:AE,SpreadsheetDashboard:TE};static _t=UE;sidePanel;composer;_focusGrid;keyDownMapping;isViewportTooSmall=!1;get model(){return this.props.model}getStyle(){return this.env.isDashboard()?"grid-template-rows: auto;":"grid-template-rows: 63px auto 37px"}setup(){this.sidePanel=t.useState({isOpen:!1,panelProps:{}}),this.composer=t.useState({topBarFocus:"inactive",gridFocusMode:"inactive"}),this.keyDownMapping={"CTRL+H":()=>this.toggleSidePanel("FindAndReplace",{}),"CTRL+F":()=>this.toggleSidePanel("FindAndReplace",{})};const e=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:e?new vE(e):void 0,loadCurrencies:this.model.config.external.loadCurrencies,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.openSidePanel.bind(this),toggleSidePanel:this.toggleSidePanel.bind(this),_t:VE._t,clipboard:this.env.clipboard||new kE(navigator.clipboard),startCellEdition:e=>this.onGridComposerCellFocused(e)}),t.useExternalListener(window,"resize",(()=>this.render(!0))),t.useExternalListener(window,"beforeunload",this.unbindModelEvents.bind(this)),this.bindModelEvents(),t.onMounted((()=>{this.checkViewportSize()})),t.onWillUnmount((()=>this.unbindModelEvents())),t.onPatched((()=>{this.checkViewportSize()}))}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}bindModelEvents(){this.model.on("update",this,(()=>this.render(!0))),this.model.on("notify-ui",this,this.onNotifyUI)}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(isFinite(e)&&isFinite(t))if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.env.notifyUser({text:r("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),tag:"viewportTooSmall"}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}onNotifyUI(e){if("ERROR"===e.type)this.env.raiseError(e.text)}openSidePanel(e,t){this.sidePanel.isOpen&&e!==this.sidePanel.component&&this.sidePanel.panelProps?.onCloseSidePanel?.(),this.sidePanel.component=e,this.sidePanel.panelProps=t,this.sidePanel.isOpen=!0}closeSidePanel(){this.sidePanel.isOpen=!1,this.focusGrid(),this.sidePanel.panelProps?.onCloseSidePanel?.()}toggleSidePanel(e,t){this.sidePanel.isOpen&&e===this.sidePanel.component?(this.sidePanel.isOpen=!1,this.focusGrid()):this.openSidePanel(e,t)}focusGrid(){if(!this._focusGrid)throw new Error("_focusGrid should be exposed by the grid component");this._focusGrid()}onKeydown(e){let t="";ar(e)&&(t+="CTRL+"),t+=e.key.toUpperCase();let o=this.keyDownMapping[t];if(o)return e.preventDefault(),e.stopPropagation(),void o()}onTopBarComposerFocused(e){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="contentFocus",this.composer.gridFocusMode="inactive",this.setComposerContent({selection:e}||{}))}onGridComposerContentFocused(){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="contentFocus",this.setComposerContent({}))}onGridComposerCellFocused(e,t){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="cellFocus",this.setComposerContent({content:e,selection:t}||{}))}setComposerContent({content:e,selection:t}){"inactive"===this.model.getters.getEditionMode()?this.model.dispatch("START_EDITION",{text:e,selection:t}):e&&this.model.dispatch("SET_CURRENT_CONTENT",{content:e,selection:t})}get gridHeight(){const{height:e}=this.env.model.getters.getSheetViewDimension();return e}}VE.props={model:Object};class zE{listeners=[];sendMessage(e){for(const{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter((t=>t.id!==e))}}function BE(e){return Yn.get(e.type)(e)}function HE(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class $E{buildTransformation;operations;constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find((t=>t.id===e));if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(const o of this.operations){if(o.id===e)return e;if(o.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const o=this.buildTransformation.with(e.data),{before:i,operation:s,after:r}=this.locateOperation(t);this.operations=[...i,s,e,...r.map((e=>e.transformed(o)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new $E(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:o}=this.locateOperation(e);this.operations=t.concat([o])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class WE{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new GE(this.id,mt((()=>e(this.data))))}}class GE{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new GE(this.id,this.lazyData.map(e))}}class qE{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new qE(function*(e,t){for(const o of e)if(yield o,o.operation.id===t)return}(this.operations,e))}stopBefore(e){return new qE(function*(e,t){for(const o of e){if(o.operation.id===t)return;yield o}}(this.operations,e))}startAfter(e){return new qE(function*(e,t){let o=!0;for(const i of e)o||(yield i),i.operation.id===t&&(o=!1)}(this.operations,e))}}class ZE{buildTransformation;branches;branchingOperationIds=new Map;constructor(e,t){this.buildTransformation=e,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new qE(Je(this._execution(e),this._execution(e)))}revertedExecution(e){return new qE(Je(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){const o=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),o&&this.insertPrevious(e,t,o)}insertOperationAfter(e,t,o){e.insert(t,o),this.updateNextWith(e,t,o),this.insertPrevious(e,t,o)}undo(e,t){const o=this.buildTransformation.without(t.data),i=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const s=e.fork(t.id);i&&this.branchingOperationIds.set(s,i),this.insertBranchAfter(e,s),this.transform(s,o)}redo(e){const t=this.nextBranch(e);if(!t)return;const o=this.nextBranch(t);this.removeBranchFromTree(t);const i=this.branchingOperationIds.get(t);i?this.branchingOperationIds.set(e,i):this.branchingOperationIds.delete(e),o&&this.rebaseUp(o)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const o of this.revertedExecution(e))if(o.operation.id===t)return o;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:o}=this.findPreviousBranchingOperation(e);if(!t||!o)return;const i=this.buildTransformation.without(o.data),s=t.fork(o.id);this.branchingOperationIds.set(s,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,s),s.transform(i);const r=this.nextBranch(s);r&&this.rebaseUp(r)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const o=this.branches.findIndex((t=>t===e));this.branches.splice(o+1,0,t)}updateNextWith(e,t,o){const i=this.branchingOperationIds.get(e),s=this.nextBranch(e);if(i&&s)if(e.getFirstOperationAmong(o,i)===i){const r=this.addToNextBranch(e,s,i,t,o);this.updateNextWith(s,r,o)}else{const e=this.buildTransformation.with(t.data);this.transform(s,e)}}addToNextBranch(e,t,o,i,s){let r=i;return s===o?(r=this.getTransformedOperation(e,o,i),t.prepend(r)):t.contains(s)?(r=this.getTransformedOperation(e,o,i),t.insert(r,s)):t.append(i),r}getTransformedOperation(e,t,o){const i=e.getOperation(t),s=this.buildTransformation.without(i.data);return o.transformed(s)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const o=this.nextBranch(e);o&&this.transform(o,t)}insertPrevious(e,t,o){const{previousBranch:i,branchingOperation:s}=this.findPreviousBranchingOperation(e);if(!i||!s)return;const r=this.buildTransformation.with(s.data),n=e.fork(o);n.transform(r),i.cutAfter(o),i.appendBranch(n);const a=t.transformed(r);this.insertPrevious(i,a,o)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const o=this.branchingOperationIds.get(t);return o?{previousBranch:t,branchingOperation:t.getOperation(o)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let o=!!t;const i=e.getOperations();for(let s=i.length-1;s>=0;s--){const r=i[s];r.id===t&&(o=!1),o||(yield{operation:r,branch:e,isCancelled:!this.shouldExecute(e,r)})}const s=this.previousBranch(e);yield*s?this._revertedExecution(s):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class jE{HEAD_BRANCH;HEAD_OPERATION;tree;applyOperation;revertOperation;buildEmpty;buildTransformation;constructor(e){this.applyOperation=e.applyOperation,this.revertOperation=e.revertOperation,this.buildEmpty=e.buildEmpty,this.buildTransformation=e.buildTransformation,this.HEAD_BRANCH=new $E(this.buildTransformation),this.tree=new ZE(this.buildTransformation,this.HEAD_BRANCH);const t=e.initialOperationId,o=new WE(t,this.buildEmpty(t));this.tree.insertOperationLast(this.HEAD_BRANCH,o),this.HEAD_OPERATION=o}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const o=new WE(e,t),i=this.tree.getLastBranch();this.tree.insertOperationLast(i,o),this.HEAD_BRANCH=i,this.HEAD_OPERATION=o}insert(e,t,o){const i=new WE(e,t);this.revertTo(o),this.tree.insertOperationAfter(this.HEAD_BRANCH,i,o),this.fastForward()}undo(e,t,o){const{branch:i,operation:s}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(i,s),this.fastForward(),this.insert(t,this.buildEmpty(t),o)}redo(e,t,o){const{branch:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(i),this.fastForward(),this.insert(t,this.buildEmpty(t),o)}drop(e){this.revertBefore(e),this.tree.drop(e)}getRevertedExecution(){const e=[],t=this.tree.revertedExecution(this.HEAD_BRANCH);for(const{operation:o}of t)e.push(o.data);return e}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:o,isCancelled:i}of e)i||this.revertOperation(o.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:o,isCancelled:i}of e)i||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=o}}function YE(e){return new jE({initialOperationId:e.initialRevisionId,applyOperation:t=>{const o=t.commands.slice(),{changes:i}=e.recordChanges((()=>{for(const t of o)e.dispatch(t)}));t.setChanges(i)},revertOperation:e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){XE(t.changes[e],"before")}}([e]),buildEmpty:e=>new VC(e,"empty",[]),buildTransformation:{with:e=>t=>new VC(t.id,t.clientId,PC(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new VC(t.id,t.clientId,PC(t.commands,e.commands.map(BE).flat()),t.rootCommand,void 0,t.timestamp)}})}function XE(e,t){let o=e.path[0];const i=e.path[e.path.length-1];for(let t=1;t<e.path.slice(0,-1).length;t++){const i=e.path[t];if(void 0===o[i]){const s=e.path[t+1];o[i]=HE(s)}o=o[i]}void 0===e[t]?delete o[i]:o[i]=e[t]}class KE{observers=[];defaultSubscription;mainSubscription;registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||(this.mainSubscription=this.defaultSubscription)}observe(e,t){this.observers.push({owner:e,callbacks:t})}capture(e,t){if(this.observers.find((t=>t.owner===e)))throw new Error("You are already subscribed forever");this.mainSubscription?.owner&&this.mainSubscription.owner!==e&&this.mainSubscription.callbacks.release?.(),this.mainSubscription={owner:e,callbacks:t}}release(e){this.mainSubscription?.owner!==e||this.observers.find((t=>t.owner===e))||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){this.mainSubscription!==this.defaultSubscription&&(this.mainSubscription?.callbacks.release?.(),this.mainSubscription=this.defaultSubscription)}isListening(e){return this.mainSubscription?.owner===e}send(e){this.mainSubscription?.callbacks.handleEvent(e),[...this.observers].forEach((t=>t.callbacks.handleEvent(e)))}}class QE{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new KE,this.anchor={cell:{col:0,row:0},zone:wi({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,o){this.stream.capture(e,o),this.anchor=t}registerAsDefault(e,t,o){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,o),this.defaultAnchor=t,this.capture(e,t,o)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}selectZone(e){return this.modifyAnchor(e,"overrideSelection","ZonesSelected")}modifyAnchor(e,t,o){const i=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(i,e.zone)},this.processEvent({type:o,anchor:e,mode:t})}selectCell(e,t){const o=wi({col:e,row:t});return this.selectZone({zone:o,cell:{col:e,row:t}})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new Os(83);const{col:o,row:i}=this.getNextAvailablePosition(e,t);return this.selectCell(o,i)}setAnchorCorner(e,t){const o=this.getters.getActiveSheetId(),{col:i,row:s}=this.anchor.cell,r={left:Math.min(i,e),top:Math.min(s,t),right:Math.max(i,e),bottom:Math.max(s,t)},n={zone:this.getters.expandZone(o,r),cell:{col:i,row:s}};return this.processEvent({type:"AlterZone",mode:"updateAnchor",anchor:n})}addCellToSelection(e,t){const o=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:o,col:e,row:t}));const i=this.getters.expandZone(o,wi({col:e,row:t}));return this.processEvent({type:"ZonesSelected",anchor:{zone:i,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new Os(83);const o=this.getters.getActiveSheetId(),i=this.anchor,{col:s,row:r}=i.cell,{left:n,right:a,top:l,bottom:c}=i.zone,h=this.getStartingPosition(e);let[d,u]=this.deltaToTarget(h,e,t);if(0===d&&0===u)return Os.Success;let g=i.zone;const p=e=>{e=Ei(e);const{left:t,right:i,top:s,bottom:r}=this.getters.expandZone(o,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(o)-1,i),top:Math.max(0,s),bottom:Math.min(this.getters.getNumberRows(o)-1,r)}},{col:m,row:f}=this.getReferencePosition();let b=0;for(;null!==g;){if(b++,d<0){const e=this.getNextAvailableCol(d,a-(b-1),f);g=m<=a-b?p({top:l,left:n,bottom:c,right:e}):null}if(d>0){const e=this.getNextAvailableCol(d,n+(b-1),f);g=n+b<=m?p({top:l,left:e,bottom:c,right:a}):null}if(u<0){const e=this.getNextAvailableRow(u,m,c-(b-1));g=f<=c-b?p({top:l,left:n,bottom:e,right:a}):null}if(u>0){const e=this.getNextAvailableRow(u,m,l+(b-1));g=l+b<=f?p({top:e,left:n,bottom:c,right:a}):null}if(g=g?Ei(g):g,g&&!hi(g,i.zone))return this.processEvent({type:"ZonesSelected",mode:"updateAnchor",anchor:{zone:g,cell:{col:s,row:r}}})}g=p(li({top:r,bottom:r,left:s,right:s},Ei({top:this.getNextAvailableRow(u,m,l),left:this.getNextAvailableCol(d,n,f),bottom:this.getNextAvailableRow(u,m,c),right:this.getNextAvailableCol(d,a,f)})));const v={zone:g,cell:{col:s,row:r}};return this.processEvent({type:"ZonesSelected",anchor:v,mode:"updateAnchor"})}selectColumn(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.getNumberRows(o)-1;let s={left:e,right:e,top:0,bottom:i};const r=this.getters.findFirstVisibleColRowIndex(o,"ROW");let n,a;switch(t){case"overrideSelection":case"newAnchor":n=e,a=r;break;case"updateAnchor":({col:n,row:a}=this.anchor.cell),s=li(s,{left:n,right:n,top:r,bottom:i})}return this.processEvent({type:"HeadersSelected",anchor:{zone:s,cell:{col:n,row:a}},mode:t})}selectRow(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.getNumberCols(o)-1;let s={top:e,bottom:e,left:0,right:i};const r=this.getters.findFirstVisibleColRowIndex(o,"COL");let n,a;switch(t){case"overrideSelection":case"newAnchor":n=r,a=e;break;case"updateAnchor":({col:n,row:a}=this.anchor.cell),s=li(s,{left:r,right:i,top:a,bottom:a})}return this.processEvent({type:"HeadersSelected",anchor:{zone:s,cell:{col:n,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(hi(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:wi(t.cell)},"updateAnchor","AlterZone");const o=this.expandZoneToTable(t.zone);return vt(o,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:o},"updateAnchor","AlterZone")}selectTableAroundSelection(){const e=this.expandZoneToTable(this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:e},"updateAnchor","AlterZone")}selectAll(){const e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({type:"HeadersSelected",mode:"overrideSelection",anchor:{zone:t,cell:this.anchor.cell}})}isListening(e){return this.stream.isListening(e)}processEvent(e){const t={...e,previousAnchor:Be(this.anchor)},o=this.checkEventAnchorZone(t);return 0!==o?new Os(o):(this.anchor=t.anchor,this.stream.send(t),Os.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:o}=e;if(!ui(t.col,t.row,o))return 16;const{left:i,right:s,top:r,bottom:n}=o,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",i,s);return void 0===this.getters.findVisibleHeader(a,"ROW",r,n)||void 0===l?17:0}checkAnchorZoneOrThrow(e){if(16===this.checkAnchorZone(e))throw new Error(s("The provided anchor is invalid. The cell must be part of the zone."))}getNextAvailablePosition(e,t=1){const{col:o,row:i}=this.anchor.cell,s=this.deltaToTarget({col:o,row:i},e,t);return{col:this.getNextAvailableCol(s[0],o,i),row:this.getNextAvailableRow(s[1],o,i)}}getNextAvailableCol(e,t,o){const i=this.getters.getActiveSheetId(),s={col:t,row:o};return this.getNextAvailableHeader(e,"COL",t,s,(e=>this.getters.isInSameMerge(i,t,o,e,o)))}getNextAvailableRow(e,t,o){const i=this.getters.getActiveSheetId(),s={col:t,row:o};return this.getNextAvailableHeader(e,"ROW",o,s,(e=>this.getters.isInSameMerge(i,t,o,t,e)))}getNextAvailableHeader(e,t,o,i,s){const r=this.getters.getActiveSheetId();if(0===e)return o;const n=Math.sign(e);let a=o+e;for(;s(a);)a+=n;for(;this.getters.isHeaderHidden(r,t,a);)a+=n;return a<0||a>this.getters.getNumberHeaders(r,t)-1?this.getters.isHeaderHidden(r,t,o)?this.getNextAvailableHeader(-n,t,o,i,s):o:a}getReferencePosition(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:o,right:i,top:s,bottom:r}=t.zone,{col:n,row:a}=t.cell;return{col:this.getters.isColHidden(e,n)&&this.getters.findVisibleHeader(e,"COL",o,i)||n,row:this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",s,r)||a}}deltaToTarget(e,t,o){switch(t){case"up":return"end"!==o?[0,-o]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==o?[0,o]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==o?[-o,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==o?[o,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:o}=this.getPosition();const i=this.anchor.zone;switch(e){case"down":case"up":o=o===i.top?i.bottom:i.top;break;case"left":case"right":t=t===i.right?i.left:i.right}return{col:t,row:o}}getEndOfCluster(e,t,o){const i=this.getters.getActiveSheet();let s=e;const r=this.getNextCellPosition(e,t,o);let n=this.isCellEmpty(s,i.id)||this.isCellEmpty(r,i.id)?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(s,t,o);if(s.col===e.col&&s.row===e.row)break;const r=this.isCellEmpty(e,i.id);if("endOfCluster"===n&&r)break;if("nextCluster"===n&&!r){s=e;break}s=e}return"cols"===t?s.col:s.row}isCellEmpty({col:e,row:t},o=this.getters.getActiveSheetId()){const i=this.getters.getMainCellPosition({sheetId:o,col:e,row:t});return this.getters.getEvaluatedCell(i).type===ws.empty}getNextCellPosition(e,t,o){const i="cols"===t?"col":"row",s={...e},r="cols"===t?this.getNextAvailableCol(o,s.col,s.row):this.getNextAvailableRow(o,s.col,s.row);return s[i]=r,{col:s.col,row:s.row}}getPosition(){return{...this.anchor.cell}}expandZoneToTable(e){const t=e=>{for(const t of Ke(e.left,e.right+1)){if(!this.isCellEmpty({col:t,row:e.top-1}))return{...e,top:e.top-1};if(!this.isCellEmpty({col:t,row:e.bottom+1}))return{...e,bottom:e.bottom+1}}for(const t of Ke(e.top,e.bottom+1)){if(!this.isCellEmpty({col:e.left-1,row:t}))return{...e,left:e.left-1};if(!this.isCellEmpty({col:e.right+1,row:t}))return{...e,right:e.right+1}}return e};let o=!1,i=e;do{o=!1;const e=t(i);hi(i,e)||(o=!0,i=e)}while(o);return i}}class JE{changes=[];commands=[];recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop();let o=e[0],i=e[e.length-1];const s=e.length-2;for(let t=1;t<=s;t++){const i=e[t];if(void 0===o[i]){const s=e[t+1];o[i]=HE(s)}o=o[i]}o[i]!==t&&(this.changes.push({path:e,before:o[i],after:t}),void 0===t?delete o[i]:o[i]=t)}}const ew=17781237,tw=88853993;function ow(e,t,o){const i=[["xmlns:r",mb],["xmlns:a",db],["xmlns:c",ub]],s=iw({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let r=ZS``;e.data.title&&(r=ZS`
2011
+ `;const VE=e=>e;class zE extends t.Component{static template="o-spreadsheet-Spreadsheet";static components={TopBar:kE,Grid:nb,BottomBar:RE,SidePanel:OE,SpreadsheetDashboard:AE};static _t=VE;sidePanel;composer;_focusGrid;keyDownMapping;isViewportTooSmall=!1;get model(){return this.props.model}getStyle(){return this.env.isDashboard()?"grid-template-rows: auto;":"grid-template-rows: 63px auto 37px"}setup(){this.sidePanel=t.useState({isOpen:!1,panelProps:{}}),this.composer=t.useState({topBarFocus:"inactive",gridFocusMode:"inactive"}),this.keyDownMapping={"CTRL+H":()=>this.toggleSidePanel("FindAndReplace",{}),"CTRL+F":()=>this.toggleSidePanel("FindAndReplace",{})};const e=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:e?new vE(e):void 0,loadCurrencies:this.model.config.external.loadCurrencies,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.openSidePanel.bind(this),toggleSidePanel:this.toggleSidePanel.bind(this),_t:zE._t,clipboard:this.env.clipboard||new PE(navigator.clipboard),startCellEdition:e=>this.onGridComposerCellFocused(e),focusableElement:new SE}),t.useExternalListener(window,"resize",(()=>this.render(!0))),t.useExternalListener(window,"beforeunload",this.unbindModelEvents.bind(this)),this.bindModelEvents(),t.onMounted((()=>{this.checkViewportSize()})),t.onWillUnmount((()=>this.unbindModelEvents())),t.onPatched((()=>{this.checkViewportSize()}))}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}bindModelEvents(){this.model.on("update",this,(()=>this.render(!0))),this.model.on("notify-ui",this,this.onNotifyUI)}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(isFinite(e)&&isFinite(t))if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.env.notifyUser({text:n("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),tag:"viewportTooSmall"}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}onNotifyUI(e){if("ERROR"===e.type)this.env.raiseError(e.text)}openSidePanel(e,t){this.sidePanel.isOpen&&e!==this.sidePanel.component&&this.sidePanel.panelProps?.onCloseSidePanel?.(),this.sidePanel.component=e,this.sidePanel.panelProps=t,this.sidePanel.isOpen=!0}closeSidePanel(){this.sidePanel.isOpen=!1,this.focusGrid(),this.sidePanel.panelProps?.onCloseSidePanel?.()}toggleSidePanel(e,t){this.sidePanel.isOpen&&e===this.sidePanel.component?(this.sidePanel.isOpen=!1,this.focusGrid()):this.openSidePanel(e,t)}focusGrid(){if(!this._focusGrid)throw new Error("_focusGrid should be exposed by the grid component");this._focusGrid()}onKeydown(e){let t="";ln(e)&&(t+="CTRL+"),t+=e.key.toUpperCase();let o=this.keyDownMapping[t];if(o)return e.preventDefault(),e.stopPropagation(),void o()}onTopBarComposerFocused(e){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="contentFocus",this.composer.gridFocusMode="inactive",this.setComposerContent({selection:e}))}onGridComposerContentFocused(e){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="contentFocus",this.setComposerContent({selection:e}))}onGridComposerCellFocused(e,t){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="cellFocus",this.setComposerContent({content:e,selection:t}||{}))}setComposerContent({content:e,selection:t}){"inactive"===this.model.getters.getEditionMode()?this.model.dispatch("START_EDITION",{text:e,selection:t}):e&&this.model.dispatch("SET_CURRENT_CONTENT",{content:e,selection:t})}get gridHeight(){const{height:e}=this.env.model.getters.getSheetViewDimension();return e}}zE.props={model:Object};class BE{listeners=[];sendMessage(e){for(const{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter((t=>t.id!==e))}}function HE(e){return Yr.get(e.type)(e)}function $E(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class WE{buildTransformation;operations;constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find((t=>t.id===e));if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(const o of this.operations){if(o.id===e)return e;if(o.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const o=this.buildTransformation.with(e.data),{before:i,operation:s,after:n}=this.locateOperation(t);this.operations=[...i,s,e,...n.map((e=>e.transformed(o)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new WE(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:o}=this.locateOperation(e);this.operations=t.concat([o])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class GE{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new qE(this.id,mt((()=>e(this.data))))}}class qE{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new qE(this.id,this.lazyData.map(e))}}class ZE{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new ZE(function*(e,t){for(const o of e)if(yield o,o.operation.id===t)return}(this.operations,e))}stopBefore(e){return new ZE(function*(e,t){for(const o of e){if(o.operation.id===t)return;yield o}}(this.operations,e))}startAfter(e){return new ZE(function*(e,t){let o=!0;for(const i of e)o||(yield i),i.operation.id===t&&(o=!1)}(this.operations,e))}}class jE{buildTransformation;branches;branchingOperationIds=new Map;constructor(e,t){this.buildTransformation=e,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new ZE(Je(this._execution(e),this._execution(e)))}revertedExecution(e){return new ZE(Je(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){const o=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),o&&this.insertPrevious(e,t,o)}insertOperationAfter(e,t,o){e.insert(t,o),this.updateNextWith(e,t,o),this.insertPrevious(e,t,o)}undo(e,t){const o=this.buildTransformation.without(t.data),i=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const s=e.fork(t.id);i&&this.branchingOperationIds.set(s,i),this.insertBranchAfter(e,s),this.transform(s,o)}redo(e){const t=this.nextBranch(e);if(!t)return;const o=this.nextBranch(t);this.removeBranchFromTree(t);const i=this.branchingOperationIds.get(t);i?this.branchingOperationIds.set(e,i):this.branchingOperationIds.delete(e),o&&this.rebaseUp(o)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const o of this.revertedExecution(e))if(o.operation.id===t)return o;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:o}=this.findPreviousBranchingOperation(e);if(!t||!o)return;const i=this.buildTransformation.without(o.data),s=t.fork(o.id);this.branchingOperationIds.set(s,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,s),s.transform(i);const n=this.nextBranch(s);n&&this.rebaseUp(n)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const o=this.branches.findIndex((t=>t===e));this.branches.splice(o+1,0,t)}updateNextWith(e,t,o){const i=this.branchingOperationIds.get(e),s=this.nextBranch(e);if(i&&s)if(e.getFirstOperationAmong(o,i)===i){const n=this.addToNextBranch(e,s,i,t,o);this.updateNextWith(s,n,o)}else{const e=this.buildTransformation.with(t.data);this.transform(s,e)}}addToNextBranch(e,t,o,i,s){let n=i;return s===o?(n=this.getTransformedOperation(e,o,i),t.prepend(n)):t.contains(s)?(n=this.getTransformedOperation(e,o,i),t.insert(n,s)):t.append(i),n}getTransformedOperation(e,t,o){const i=e.getOperation(t),s=this.buildTransformation.without(i.data);return o.transformed(s)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const o=this.nextBranch(e);o&&this.transform(o,t)}insertPrevious(e,t,o){const{previousBranch:i,branchingOperation:s}=this.findPreviousBranchingOperation(e);if(!i||!s)return;const n=this.buildTransformation.with(s.data),r=e.fork(o);r.transform(n),i.cutAfter(o),i.appendBranch(r);const a=t.transformed(n);this.insertPrevious(i,a,o)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const o=this.branchingOperationIds.get(t);return o?{previousBranch:t,branchingOperation:t.getOperation(o)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let o=!!t;const i=e.getOperations();for(let s=i.length-1;s>=0;s--){const n=i[s];n.id===t&&(o=!1),o||(yield{operation:n,branch:e,isCancelled:!this.shouldExecute(e,n)})}const s=this.previousBranch(e);yield*s?this._revertedExecution(s):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class YE{HEAD_BRANCH;HEAD_OPERATION;tree;applyOperation;revertOperation;buildEmpty;buildTransformation;constructor(e){this.applyOperation=e.applyOperation,this.revertOperation=e.revertOperation,this.buildEmpty=e.buildEmpty,this.buildTransformation=e.buildTransformation,this.HEAD_BRANCH=new WE(this.buildTransformation),this.tree=new jE(this.buildTransformation,this.HEAD_BRANCH);const t=e.initialOperationId,o=new GE(t,this.buildEmpty(t));this.tree.insertOperationLast(this.HEAD_BRANCH,o),this.HEAD_OPERATION=o}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const o=new GE(e,t),i=this.tree.getLastBranch();this.tree.insertOperationLast(i,o),this.HEAD_BRANCH=i,this.HEAD_OPERATION=o}insert(e,t,o){const i=new GE(e,t);this.revertTo(o),this.tree.insertOperationAfter(this.HEAD_BRANCH,i,o),this.fastForward()}undo(e,t,o){const{branch:i,operation:s}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(i,s),this.fastForward(),this.insert(t,this.buildEmpty(t),o)}redo(e,t,o){const{branch:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(i),this.fastForward(),this.insert(t,this.buildEmpty(t),o)}drop(e){this.revertBefore(e),this.tree.drop(e)}getRevertedExecution(){const e=[],t=this.tree.revertedExecution(this.HEAD_BRANCH);for(const{operation:o}of t)e.push(o.data);return e}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:o,isCancelled:i}of e)i||this.revertOperation(o.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:o,isCancelled:i}of e)i||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=o}}function XE(e){return new YE({initialOperationId:e.initialRevisionId,applyOperation:t=>{const o=t.commands.slice(),{changes:i}=e.recordChanges((()=>{for(const t of o)e.dispatch(t)}));t.setChanges(i)},revertOperation:e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){KE(t.changes[e],"before")}}([e]),buildEmpty:e=>new VC(e,"empty",[]),buildTransformation:{with:e=>t=>new VC(t.id,t.clientId,PC(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new VC(t.id,t.clientId,PC(t.commands,e.commands.map(HE).flat()),t.rootCommand,void 0,t.timestamp)}})}function KE(e,t){let o=e.path[0];const i=e.path[e.path.length-1];for(let t=1;t<e.path.slice(0,-1).length;t++){const i=e.path[t];if(void 0===o[i]){const s=e.path[t+1];o[i]=$E(s)}o=o[i]}void 0===e[t]?delete o[i]:o[i]=e[t]}class QE{observers=[];defaultSubscription;mainSubscription;registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||(this.mainSubscription=this.defaultSubscription)}observe(e,t){this.observers.push({owner:e,callbacks:t})}capture(e,t){if(this.observers.find((t=>t.owner===e)))throw new Error("You are already subscribed forever");this.mainSubscription?.owner&&this.mainSubscription.owner!==e&&this.mainSubscription.callbacks.release?.(),this.mainSubscription={owner:e,callbacks:t}}release(e){this.mainSubscription?.owner!==e||this.observers.find((t=>t.owner===e))||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){this.mainSubscription!==this.defaultSubscription&&(this.mainSubscription?.callbacks.release?.(),this.mainSubscription=this.defaultSubscription)}isListening(e){return this.mainSubscription?.owner===e}send(e){this.mainSubscription?.callbacks.handleEvent(e),[...this.observers].forEach((t=>t.callbacks.handleEvent(e)))}}class JE{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new QE,this.anchor={cell:{col:0,row:0},zone:wi({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,o){this.stream.capture(e,o),this.anchor=t}registerAsDefault(e,t,o){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,o),this.defaultAnchor=t,this.capture(e,t,o)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}selectZone(e){return this.modifyAnchor(e,"overrideSelection","ZonesSelected")}modifyAnchor(e,t,o){const i=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(i,e.zone)},this.processEvent({type:o,anchor:e,mode:t})}selectCell(e,t){const o=wi({col:e,row:t});return this.selectZone({zone:o,cell:{col:e,row:t}})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new Os(84);const{col:o,row:i}=this.getNextAvailablePosition(e,t);return this.selectCell(o,i)}setAnchorCorner(e,t){const o=this.getters.getActiveSheetId(),{col:i,row:s}=this.anchor.cell,n={left:Math.min(i,e),top:Math.min(s,t),right:Math.max(i,e),bottom:Math.max(s,t)},r={zone:this.getters.expandZone(o,n),cell:{col:i,row:s}};return this.processEvent({type:"AlterZone",mode:"updateAnchor",anchor:r})}addCellToSelection(e,t){const o=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:o,col:e,row:t}));const i=this.getters.expandZone(o,wi({col:e,row:t}));return this.processEvent({type:"ZonesSelected",anchor:{zone:i,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new Os(84);const o=this.getters.getActiveSheetId(),i=this.anchor,{col:s,row:n}=i.cell,{left:r,right:a,top:l,bottom:c}=i.zone,h=this.getStartingPosition(e);let[d,u]=this.deltaToTarget(h,e,t);if(0===d&&0===u)return Os.Success;let g=i.zone;const p=e=>{e=Ei(e);const{left:t,right:i,top:s,bottom:n}=this.getters.expandZone(o,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(o)-1,i),top:Math.max(0,s),bottom:Math.min(this.getters.getNumberRows(o)-1,n)}},{col:m,row:f}=this.getReferencePosition();let b=0;for(;null!==g;){if(b++,d<0){const e=this.getNextAvailableCol(d,a-(b-1),f);g=m<=a-b?p({top:l,left:r,bottom:c,right:e}):null}if(d>0){const e=this.getNextAvailableCol(d,r+(b-1),f);g=r+b<=m?p({top:l,left:e,bottom:c,right:a}):null}if(u<0){const e=this.getNextAvailableRow(u,m,c-(b-1));g=f<=c-b?p({top:l,left:r,bottom:e,right:a}):null}if(u>0){const e=this.getNextAvailableRow(u,m,l+(b-1));g=l+b<=f?p({top:e,left:r,bottom:c,right:a}):null}if(g=g?Ei(g):g,g&&!hi(g,i.zone))return this.processEvent({type:"ZonesSelected",mode:"updateAnchor",anchor:{zone:g,cell:{col:s,row:n}}})}g=p(li({top:n,bottom:n,left:s,right:s},Ei({top:this.getNextAvailableRow(u,m,l),left:this.getNextAvailableCol(d,r,f),bottom:this.getNextAvailableRow(u,m,c),right:this.getNextAvailableCol(d,a,f)})));const v={zone:g,cell:{col:s,row:n}};return this.processEvent({type:"ZonesSelected",anchor:v,mode:"updateAnchor"})}selectColumn(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.getNumberRows(o)-1;let s={left:e,right:e,top:0,bottom:i};const n=this.getters.findFirstVisibleColRowIndex(o,"ROW");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=e,a=n;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),s=li(s,{left:r,right:r,top:n,bottom:i})}return this.processEvent({type:"HeadersSelected",anchor:{zone:s,cell:{col:r,row:a}},mode:t})}selectRow(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.getNumberCols(o)-1;let s={top:e,bottom:e,left:0,right:i};const n=this.getters.findFirstVisibleColRowIndex(o,"COL");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=n,a=e;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),s=li(s,{left:n,right:i,top:a,bottom:a})}return this.processEvent({type:"HeadersSelected",anchor:{zone:s,cell:{col:r,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(hi(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:wi(t.cell)},"updateAnchor","AlterZone");const o=this.expandZoneToTable(t.zone);return vt(o,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:o},"updateAnchor","AlterZone")}selectTableAroundSelection(){const e=this.expandZoneToTable(this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:e},"updateAnchor","AlterZone")}selectAll(){const e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({type:"HeadersSelected",mode:"overrideSelection",anchor:{zone:t,cell:this.anchor.cell}})}isListening(e){return this.stream.isListening(e)}processEvent(e){const t={...e,previousAnchor:Be(this.anchor)},o=this.checkEventAnchorZone(t);return 0!==o?new Os(o):(this.anchor=t.anchor,this.stream.send(t),Os.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:o}=e;if(!ui(t.col,t.row,o))return 16;const{left:i,right:s,top:n,bottom:r}=o,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",i,s);return void 0===this.getters.findVisibleHeader(a,"ROW",n,r)||void 0===l?17:0}checkAnchorZoneOrThrow(e){if(16===this.checkAnchorZone(e))throw new Error(s("The provided anchor is invalid. The cell must be part of the zone."))}getNextAvailablePosition(e,t=1){const{col:o,row:i}=this.anchor.cell,s=this.deltaToTarget({col:o,row:i},e,t);return{col:this.getNextAvailableCol(s[0],o,i),row:this.getNextAvailableRow(s[1],o,i)}}getNextAvailableCol(e,t,o){const i=this.getters.getActiveSheetId(),s={col:t,row:o};return this.getNextAvailableHeader(e,"COL",t,s,(e=>this.getters.isInSameMerge(i,t,o,e,o)))}getNextAvailableRow(e,t,o){const i=this.getters.getActiveSheetId(),s={col:t,row:o};return this.getNextAvailableHeader(e,"ROW",o,s,(e=>this.getters.isInSameMerge(i,t,o,t,e)))}getNextAvailableHeader(e,t,o,i,s){const n=this.getters.getActiveSheetId();if(0===e)return o;const r=Math.sign(e);let a=o+e;for(;s(a);)a+=r;for(;this.getters.isHeaderHidden(n,t,a);)a+=r;return a<0||a>this.getters.getNumberHeaders(n,t)-1?this.getters.isHeaderHidden(n,t,o)?this.getNextAvailableHeader(-r,t,o,i,s):o:a}getReferencePosition(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:o,right:i,top:s,bottom:n}=t.zone,{col:r,row:a}=t.cell;return{col:this.getters.isColHidden(e,r)&&this.getters.findVisibleHeader(e,"COL",o,i)||r,row:this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",s,n)||a}}deltaToTarget(e,t,o){switch(t){case"up":return"end"!==o?[0,-o]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==o?[0,o]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==o?[-o,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==o?[o,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:o}=this.getPosition();const i=this.anchor.zone;switch(e){case"down":case"up":o=o===i.top?i.bottom:i.top;break;case"left":case"right":t=t===i.right?i.left:i.right}return{col:t,row:o}}getEndOfCluster(e,t,o){const i=this.getters.getActiveSheet();let s=e;const n=this.getNextCellPosition(e,t,o);let r=this.isCellEmpty(s,i.id)||this.isCellEmpty(n,i.id)?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(s,t,o);if(s.col===e.col&&s.row===e.row)break;const n=this.isCellEmpty(e,i.id);if("endOfCluster"===r&&n)break;if("nextCluster"===r&&!n){s=e;break}s=e}return"cols"===t?s.col:s.row}isCellEmpty({col:e,row:t},o=this.getters.getActiveSheetId()){const i=this.getters.getMainCellPosition({sheetId:o,col:e,row:t});return this.getters.getEvaluatedCell(i).type===ws.empty}getNextCellPosition(e,t,o){const i="cols"===t?"col":"row",s={...e},n="cols"===t?this.getNextAvailableCol(o,s.col,s.row):this.getNextAvailableRow(o,s.col,s.row);return s[i]=n,{col:s.col,row:s.row}}getPosition(){return{...this.anchor.cell}}expandZoneToTable(e){const t=e=>{for(const t of Ke(e.left,e.right+1)){if(!this.isCellEmpty({col:t,row:e.top-1}))return{...e,top:e.top-1};if(!this.isCellEmpty({col:t,row:e.bottom+1}))return{...e,bottom:e.bottom+1}}for(const t of Ke(e.top,e.bottom+1)){if(!this.isCellEmpty({col:e.left-1,row:t}))return{...e,left:e.left-1};if(!this.isCellEmpty({col:e.right+1,row:t}))return{...e,right:e.right+1}}return e};let o=!1,i=e;do{o=!1;const e=t(i);hi(i,e)||(o=!0,i=e)}while(o);return i}}class ew{changes=[];commands=[];recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop();let o=e[0],i=e[e.length-1];const s=e.length-2;for(let t=1;t<=s;t++){const i=e[t];if(void 0===o[i]){const s=e[t+1];o[i]=$E(s)}o=o[i]}o[i]!==t&&(this.changes.push({path:e,before:o[i],after:t}),void 0===t?delete o[i]:o[i]=t)}}const tw=17781237,ow=88853993;function iw(e,t,o){const i=[["xmlns:r",mb],["xmlns:a",db],["xmlns:c",ub]],s=sw({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let n=ZS``;e.data.title&&(n=ZS`
2012
2012
  <c:title>
2013
2013
  ${rw(e.data.title,e.data.fontColor)}
2014
2014
  <c:overlay val="0" />
2015
2015
  </c:title>
2016
- `);let n=ZS``;switch(e.data.type){case"bar":n=function(e){const t=new jr,o=[];for(const[i,s]of Object.entries(e.dataSets)){const r=Lr(t.next()),n=iw({backgroundColor:r,line:{color:r}});o.push(ZS`
2016
+ `);let r=ZS``;switch(e.data.type){case"bar":r=function(e){const t=new Yn,o=[];for(const[i,s]of Object.entries(e.dataSets)){const n=kn(t.next()),r=sw({backgroundColor:n,line:{color:n}});o.push(ZS`
2017
2017
  <c:ser>
2018
2018
  <c:idx val="${i}"/>
2019
2019
  <c:order val="${i}"/>
2020
- ${s.label?ZS`<c:tx>${cw(s.label)}</c:tx>`:""}
2021
- ${n}
2022
- ${e.labelRange?ZS`<c:cat>${cw(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
2020
+ ${s.label?ZS`<c:tx>${hw(s.label)}</c:tx>`:""}
2021
+ ${r}
2022
+ ${e.labelRange?ZS`<c:cat>${hw(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
2023
2023
  <c:val> <!-- x-coordinate values -->
2024
- ${hw(s.range)}
2024
+ ${dw(s.range)}
2025
2025
  </c:val>
2026
2026
  </c:ser>
2027
- `)}const i="left"===e.verticalAxisPosition?"l":"r",s=e.stacked?"stacked":"clustered",r=e.stacked?100:-20;return ZS`
2027
+ `)}const i="left"===e.verticalAxisPosition?"l":"r",s=e.stacked?"stacked":"clustered",n=e.stacked?100:-20;return ZS`
2028
2028
  <c:barChart>
2029
2029
  <c:barDir val="col"/>
2030
2030
  <c:grouping val="${s}"/>
2031
- <c:overlap val="${r}"/>
2031
+ <c:overlap val="${n}"/>
2032
2032
  <c:gapWidth val="70"/>
2033
2033
  <!-- each data marker in the series does not have a different color -->
2034
2034
  <c:varyColors val="0"/>
2035
2035
  ${qS(o)}
2036
- <c:axId val="${ew}" />
2037
2036
  <c:axId val="${tw}" />
2037
+ <c:axId val="${ow}" />
2038
2038
  </c:barChart>
2039
- ${lw("b","c:catAx",ew,tw,{fontColor:e.fontColor})}
2040
- ${lw(i,"c:valAx",tw,ew,{fontColor:e.fontColor})}
2041
- `}(e.data);break;case"line":n=function(e){const t=new jr,o=[];for(const[i,s]of Object.entries(e.dataSets)){const r=iw({line:{width:2.5,style:"solid",color:Lr(t.next())}});o.push(ZS`
2039
+ ${cw("b","c:catAx",tw,ow,{fontColor:e.fontColor})}
2040
+ ${cw(i,"c:valAx",ow,tw,{fontColor:e.fontColor})}
2041
+ `}(e.data);break;case"line":r=function(e){const t=new Yn,o=[];for(const[i,s]of Object.entries(e.dataSets)){const n=sw({line:{width:2.5,style:"solid",color:kn(t.next())}});o.push(ZS`
2042
2042
  <c:ser>
2043
2043
  <c:idx val="${i}"/>
2044
2044
  <c:order val="${i}"/>
@@ -2047,11 +2047,11 @@
2047
2047
  <c:symbol val="circle" />
2048
2048
  <c:size val="5"/>
2049
2049
  </c:marker>
2050
- ${s.label?ZS`<c:tx>${cw(s.label)}</c:tx>`:""}
2051
- ${r}
2052
- ${e.labelRange?ZS`<c:cat>${cw(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
2050
+ ${s.label?ZS`<c:tx>${hw(s.label)}</c:tx>`:""}
2051
+ ${n}
2052
+ ${e.labelRange?ZS`<c:cat>${hw(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
2053
2053
  <c:val> <!-- x-coordinate values -->
2054
- ${hw(s.range)}
2054
+ ${dw(s.range)}
2055
2055
  </c:val>
2056
2056
  </c:ser>
2057
2057
  `)}const i="left"===e.verticalAxisPosition?"l":"r",s=e.stacked?"stacked":"standard";return ZS`
@@ -2060,12 +2060,12 @@
2060
2060
  <!-- each data marker in the series does not have a different color -->
2061
2061
  <c:varyColors val="0"/>
2062
2062
  ${qS(o)}
2063
- <c:axId val="${ew}" />
2064
2063
  <c:axId val="${tw}" />
2064
+ <c:axId val="${ow}" />
2065
2065
  </c:lineChart>
2066
- ${lw("b","c:catAx",ew,tw,{fontColor:e.fontColor})}
2067
- ${lw(i,"c:valAx",tw,ew,{fontColor:e.fontColor})}
2068
- `}(e.data);break;case"pie":n=function(e,t,o,{holeSize:i}={holeSize:50}){const s=new jr,r=Math.max(...e.dataSets.map((e=>bS(e.range,t,o)))),n=Ke(0,r).map((()=>Lr(s.next()))),a=[];for(const[i,s]of Object.entries(e.dataSets).reverse()){const r=bS(s.range,t,o),l=[];for(const e of Ke(0,r)){const t=iw({backgroundColor:n[e],line:{color:"FFFFFF",width:1.5}});l.push(ZS`
2066
+ ${cw("b","c:catAx",tw,ow,{fontColor:e.fontColor})}
2067
+ ${cw(i,"c:valAx",ow,tw,{fontColor:e.fontColor})}
2068
+ `}(e.data);break;case"pie":r=function(e,t,o,{holeSize:i}={holeSize:50}){const s=new Yn,n=Math.max(...e.dataSets.map((e=>bS(e.range,t,o)))),r=Ke(0,n).map((()=>kn(s.next()))),a=[];for(const[i,s]of Object.entries(e.dataSets).reverse()){const n=bS(s.range,t,o),l=[];for(const e of Ke(0,n)){const t=sw({backgroundColor:r[e],line:{color:"FFFFFF",width:1.5}});l.push(ZS`
2069
2069
  <c:dPt>
2070
2070
  <c:idx val="${e}"/>
2071
2071
  ${t}
@@ -2074,19 +2074,19 @@
2074
2074
  <c:ser>
2075
2075
  <c:idx val="${i}"/>
2076
2076
  <c:order val="${i}"/>
2077
- ${s.label?ZS`<c:tx>${cw(s.label)}</c:tx>`:""}
2077
+ ${s.label?ZS`<c:tx>${hw(s.label)}</c:tx>`:""}
2078
2078
  ${qS(l)}
2079
- ${aw({showLeaderLines:!0})}
2080
- ${e.labelRange?ZS`<c:cat>${cw(e.labelRange)}</c:cat>`:""}
2079
+ ${lw({showLeaderLines:!0})}
2080
+ ${e.labelRange?ZS`<c:cat>${hw(e.labelRange)}</c:cat>`:""}
2081
2081
  <c:val>
2082
- ${hw(s.range)}
2082
+ ${dw(s.range)}
2083
2083
  </c:val>
2084
2084
  </c:ser>
2085
2085
  `)}return ZS`
2086
2086
  <c:doughnutChart>
2087
2087
  <c:varyColors val="1" />
2088
2088
  <c:holeSize val="${i}" />
2089
- ${aw()}
2089
+ ${lw()}
2090
2090
  ${qS(a)}
2091
2091
  </c:doughnutChart>
2092
2092
  `}(e.data,t,o,{holeSize:0})}let a="t";switch(e.data.legendPosition){case"bottom":a="b";break;case"left":a="l";break;case"right":a="r";break;case"top":a="t"}const l=e.data.fontColor,c=ZS`
@@ -2095,34 +2095,34 @@
2095
2095
  <!-- <manualLayout/> to manually position the chart in the figure container -->
2096
2096
  ${s}
2097
2097
  <c:chart>
2098
- ${r}
2098
+ ${n}
2099
2099
  <c:autoTitleDeleted val="0" />
2100
2100
  <c:plotArea>
2101
2101
  <!-- how the chart element is placed on the chart -->
2102
2102
  <c:layout />
2103
- ${n}
2104
- ${iw({backgroundColor:e.data.backgroundColor})}
2103
+ ${r}
2104
+ ${sw({backgroundColor:e.data.backgroundColor})}
2105
2105
  </c:plotArea>
2106
2106
  ${function(e,t){return ZS`
2107
2107
  <c:legend>
2108
2108
  <c:legendPos val="${e}"/>
2109
2109
  <c:overlay val="0"/>
2110
- ${nw(10,t)}
2110
+ ${aw(10,t)}
2111
2111
  </c:legend>
2112
2112
  `}(a,l)}
2113
2113
  </c:chart>
2114
2114
  </c:chartSpace>
2115
- `;return WS(c)}function iw(e){return ZS`
2115
+ `;return WS(c)}function sw(e){return ZS`
2116
2116
  <c:spPr>
2117
- ${e.backgroundColor?sw(e.backgroundColor):""}
2117
+ ${e.backgroundColor?nw(e.backgroundColor):""}
2118
2118
  ${e.line?function(e){const t=[["cmpd","sng"]];e.width&&t.push(["w",fS(e.width)]);const o=e.style?ZS`<a:prstDash val="${e.style}"/>`:"";return ZS`
2119
2119
  <a:ln ${$S(t)}>
2120
- ${sw(e.color)}
2120
+ ${nw(e.color)}
2121
2121
  ${o}
2122
2122
  </a:ln>
2123
2123
  `}(e.line):""}
2124
2124
  </c:spPr>
2125
- `}function sw(e){return ZS`
2125
+ `}function nw(e){return ZS`
2126
2126
  <a:solidFill>
2127
2127
  <a:srgbClr val="${e}"/>
2128
2128
  </a:solidFill>
@@ -2134,7 +2134,7 @@
2134
2134
  <a:p>
2135
2135
  <a:pPr lvl="0">
2136
2136
  <a:defRPr b="0">
2137
- ${sw(t)}
2137
+ ${nw(t)}
2138
2138
  <a:latin typeface="+mn-lt"/>
2139
2139
  </a:defRPr>
2140
2140
  </a:pPr>
@@ -2145,20 +2145,20 @@
2145
2145
  </a:p>
2146
2146
  </c:rich>
2147
2147
  </c:tx>
2148
- `}function nw(e=12,t="000000",o=!1,i=!1){return ZS`
2148
+ `}function aw(e=12,t="000000",o=!1,i=!1){return ZS`
2149
2149
  <c:txPr>
2150
2150
  <a:bodyPr/>
2151
2151
  <a:lstStyle/>
2152
2152
  <a:p>
2153
2153
  <a:pPr lvl="0">
2154
2154
  <a:defRPr ${$S([["b",o?"1":"0"],["i",i?"1":"0"],["sz",100*e]])}>
2155
- ${sw(t)}
2155
+ ${nw(t)}
2156
2156
  <a:latin typeface="+mn-lt"/>
2157
2157
  </a:defRPr>
2158
2158
  </a:pPr>
2159
2159
  </a:p>
2160
2160
  </c:txPr>
2161
- `}function aw({showLeaderLines:e}={showLeaderLines:!1}){return ZS`
2161
+ `}function lw({showLeaderLines:e}={showLeaderLines:!1}){return ZS`
2162
2162
  <dLbls>
2163
2163
  <c:showLegendKey val="0"/>
2164
2164
  <c:showVal val="0"/>
@@ -2168,7 +2168,7 @@
2168
2168
  <c:showBubbleSize val="0"/>
2169
2169
  <c:showLeaderLines val="${e?"1":"0"}"/>
2170
2170
  </dLbls>
2171
- `}function lw(e,t,o,i,{fontColor:s}){return ZS`
2171
+ `}function cw(e,t,o,i,{fontColor:s}){return ZS`
2172
2172
  <${t}>
2173
2173
  <c:axId val="${o}"/>
2174
2174
  <c:crossAx val="${i}"/> <!-- reference to the other axe of the chart -->
@@ -2179,7 +2179,7 @@
2179
2179
  <c:axPos val="${e}" />
2180
2180
  ${function(e="B7B7B7"){return ZS`
2181
2181
  <c:majorGridlines>
2182
- ${iw({line:{color:e}})}
2182
+ ${sw({line:{color:e}})}
2183
2183
  </c:majorGridlines>
2184
2184
  `}()}
2185
2185
  <c:majorTickMark val="out" />
@@ -2188,30 +2188,25 @@
2188
2188
  <c:title>
2189
2189
  ${rw("")}
2190
2190
  </c:title>
2191
- ${nw(10,s)}
2191
+ ${aw(10,s)}
2192
2192
  </${t}>
2193
2193
  <!-- <tickLblPos/> omitted -->
2194
- `}function cw(e){return ZS`
2194
+ `}function hw(e){return ZS`
2195
2195
  <c:strRef>
2196
2196
  <c:f>${e}</c:f>
2197
2197
  </c:strRef>
2198
- `}function hw(e){return ZS`
2198
+ `}function dw(e){return ZS`
2199
2199
  <c:numRef>
2200
2200
  <c:f>${e}</c:f>
2201
2201
  <c:numCache />
2202
2202
  </c:numRef>
2203
- `}function dw(e){const t=e.content,o=Ug.content,i=[];let s=ZS``;if(Sv(t).filter((e=>"FUNCTION"===e.type)).every((e=>o[e.value.toUpperCase()].isExported))){let o=ZS``;const r=gw(t);return e.value===a.CircularDependency&&(i.push(["t","str"]),o=ZS`<v>${e.value}</v>`),s=ZS`
2204
- <f>
2205
- ${r}
2206
- </f>
2207
- ${o}
2208
- `,{attrs:i,node:s}}{const t=e.value,o=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n"}}(t);return i.push(["t",o]),s=ZS`<v>${t}</v>`,{attrs:i,node:s}}}function uw(e,t,o=!1){let i=e;const s=[];if(!o&&["TRUE","FALSE"].includes(i.trim()))i="TRUE"===i?"1":"0",s.push(["t","b"]);else if(o||!oo(i)){const{id:o}=dS(e,t);i=o.toString(),s.push(["t","s"])}return{attrs:s,node:ZS`<v>${i}</v>`}}function gw(e){let t;"="===e[0]&&(e=e.slice(1));try{t=zv(e)}catch(t){return e}return t=Hv(t,"STRING",pw),t=Hv(t,"FUNCALL",(e=>e=function(e){const t=e.value.toUpperCase(),o=e.args,i=xb[t];if(i){const s=Ug.content[t].args.filter((e=>!e.optional)),r=s.length-e.args.length;if(r)for(let t=e.args.length;t<s.length;t++){const e=i[t-r];o.push({type:e.type,value:e.value})}}return{...e,args:o}}(e=function(e){const t=e.value.toUpperCase();return{...e,value:yb.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()})))),t?$v(t):e}function pw(e){const t=e.value.replace(new RegExp('"',"g"),""),o=Te(t);if(o){let i=[];return(xe.test(t)||ye.test(t))&&i.push("yyyy-mm-dd"),Ie.test(t)&&i.push("hh:mm:ss"),{...e,value:mo(o.value,i.join(" "))}}return{...e,value:e.value.replace(/\\"/g,'""')}}function mw(e,t){const o=[];for(const i of t)switch(i.rule.type){case"CellIsRule":o.push(fw(i,i.rule,e));break;case"ColorScaleRule":o.push(bw(i,i.rule));break;case"IconSetRule":o.push(vw(i,i.rule));break;default:console.warn(`Conditional formatting ${i.rule.type} not implemented`)}return o}function fw(e,t,o){const i=Sw(e),s=sS(t.operator);i.push(...function(e){const t=sS(e.operator);switch(e.operator){case"ContainsText":case"NotContains":case"BeginsWith":case"EndsWith":return[["type",t],["text",e.values[0]]];case"IsEmpty":case"IsNotEmpty":return[["type",t]];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":case"Between":case"NotBetween":return[["type","cellIs"]]}}(t),["operator",s]);const r=function(e,t){const o=e[0].split(":")[0],i=t.values;switch(t.operator){case"ContainsText":return[`NOT(ISERROR(SEARCH("${i[0]}",${o})))`];case"NotContains":return[`ISERROR(SEARCH("${i[0]}",${o}))`];case"BeginsWith":return[`LEFT(${o},LEN("${i[0]}"))="${i[0]}"`];case"EndsWith":return[`RIGHT(${o},LEN("${i[0]}"))="${i[0]}"`];case"IsEmpty":return[`LEN(TRIM(${o}))=0`];case"IsNotEmpty":return[`LEN(TRIM(${o}))>0`];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":return[i[0]];case"Between":case"NotBetween":return[i[0],i[1]]}}(e.ranges,t).map((e=>ZS`<formula>${e}</formula>`)),n={font:{color:{rgb:t.style.textColor},bold:t.style.bold,italic:t.style.italic,strike:t.style.strikethrough,underline:t.style.underline}};t.style.fillColor&&(n.fill={fgColor:{rgb:t.style.fillColor}});const{id:a}=dS(n,o);return i.push(["dxfId",a]),ZS`
2203
+ `}function uw(e){const t=e.content,o=Ug.content,i=[];let s=ZS``;if(Sv(t).filter((e=>"FUNCTION"===e.type)).every((e=>o[e.value.toUpperCase()].isExported))){let o=ZS``;const n=pw(t);return e.value===a.CircularDependency&&(i.push(["t","str"]),o=ZS`<v>${e.value}</v>`),s=ZS`<f> ${n} </f> ${o}`,{attrs:i,node:s}}{const t=e.value,o=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n"}}(t);return i.push(["t",o]),s=ZS`<v>${t}</v>`,{attrs:i,node:s}}}function gw(e,t,o=!1){let i=e;const s=[];if(!o&&["TRUE","FALSE"].includes(i.trim()))i="TRUE"===i?"1":"0",s.push(["t","b"]);else if(o||!oo(i)){const{id:o}=dS(e,t);i=o.toString(),s.push(["t","s"])}return{attrs:s,node:ZS`<v>${i}</v>`}}function pw(e){let t;"="===e[0]&&(e=e.slice(1));try{t=zv(e)}catch(t){return e}return t=Hv(t,"STRING",mw),t=Hv(t,"FUNCALL",(e=>e=function(e){const t=e.value.toUpperCase(),o=e.args,i=xb[t];if(i){const s=Ug.content[t].args.filter((e=>!e.optional)),n=s.length-e.args.length;if(n)for(let t=e.args.length;t<s.length;t++){const e=i[t-n];o.push({type:e.type,value:e.value})}}return{...e,args:o}}(e=function(e){const t=e.value.toUpperCase();return{...e,value:yb.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()})))),t?$v(t):e}function mw(e){const t=e.value.replace(new RegExp('"',"g"),""),o=Te(t);if(o){let i=[];return(xe.test(t)||ye.test(t))&&i.push("yyyy-mm-dd"),Ie.test(t)&&i.push("hh:mm:ss"),{...e,value:mo(o.value,i.join(" "))}}return{...e,value:e.value.replace(/\\"/g,'""')}}function fw(e,t){const o=[];for(const i of t)switch(i.rule.type){case"CellIsRule":o.push(bw(i,i.rule,e));break;case"ColorScaleRule":o.push(vw(i,i.rule));break;case"IconSetRule":o.push(Sw(i,i.rule));break;default:console.warn(`Conditional formatting ${i.rule.type} not implemented`)}return o}function bw(e,t,o){const i=Cw(e),s=sS(t.operator);i.push(...function(e){const t=sS(e.operator);switch(e.operator){case"ContainsText":case"NotContains":case"BeginsWith":case"EndsWith":return[["type",t],["text",e.values[0]]];case"IsEmpty":case"IsNotEmpty":return[["type",t]];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":case"Between":case"NotBetween":return[["type","cellIs"]]}}(t),["operator",s]);const n=function(e,t){const o=e[0].split(":")[0],i=t.values;switch(t.operator){case"ContainsText":return[`NOT(ISERROR(SEARCH("${i[0]}",${o})))`];case"NotContains":return[`ISERROR(SEARCH("${i[0]}",${o}))`];case"BeginsWith":return[`LEFT(${o},LEN("${i[0]}"))="${i[0]}"`];case"EndsWith":return[`RIGHT(${o},LEN("${i[0]}"))="${i[0]}"`];case"IsEmpty":return[`LEN(TRIM(${o}))=0`];case"IsNotEmpty":return[`LEN(TRIM(${o}))>0`];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":return[i[0]];case"Between":case"NotBetween":return[i[0],i[1]]}}(e.ranges,t).map((e=>ZS`<formula>${e}</formula>`)),r={font:{color:{rgb:t.style.textColor},bold:t.style.bold,italic:t.style.italic,strike:t.style.strikethrough,underline:t.style.underline}};t.style.fillColor&&(r.fill={fgColor:{rgb:t.style.fillColor}});const{id:a}=dS(r,o);return i.push(["dxfId",a]),ZS`
2209
2204
  <conditionalFormatting sqref="${e.ranges.join(" ")}">
2210
2205
  <cfRule ${$S(i)}>
2211
- ${qS(r)}
2206
+ ${qS(n)}
2212
2207
  </cfRule>
2213
2208
  </conditionalFormatting>
2214
- `}function bw(e,t){const o=Sw(e);o.push(["type","colorScale"]);const i=[];for(const s of e.ranges){const e=[],r=[];let n=!0;for(let o of["minimum","midpoint","maximum"]){const i=t[o];i&&("formula"!==i.type?(e.push(Ew(i,o)),r.push([["rgb",Lr(Ot(i.color))]])):n=!1)}if(!n){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const a=e.map((e=>ZS`<cfvo ${$S(e)}/>`)),l=r.map((e=>ZS`<color ${$S(e)}/>`));i.push(ZS`
2209
+ `}function vw(e,t){const o=Cw(e);o.push(["type","colorScale"]);const i=[];for(const s of e.ranges){const e=[],n=[];let r=!0;for(let o of["minimum","midpoint","maximum"]){const i=t[o];i&&("formula"!==i.type?(e.push(ww(i,o)),n.push([["rgb",kn(Ot(i.color))]])):r=!1)}if(!r){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const a=e.map((e=>ZS`<cfvo ${$S(e)}/>`)),l=n.map((e=>ZS`<color ${$S(e)}/>`));i.push(ZS`
2215
2210
  <conditionalFormatting sqref="${s}">
2216
2211
  <cfRule ${$S(o)}>
2217
2212
  <colorScale>
@@ -2220,19 +2215,19 @@
2220
2215
  </colorScale>
2221
2216
  </cfRule>
2222
2217
  </conditionalFormatting>
2223
- `)}return qS(i)}function vw(e,t){const o=Sw(e);o.push(["type","iconSet"]);const i=[];for(const s of e.ranges){const e=[[["type","percent"],["val",0]]];let r=!0;for(let o of["lowerInflectionPoint","upperInflectionPoint"]){if("formula"===t[o].type){r=!1;continue}const i=t[o];e.push([...Ew(i,o),["gte","ge"===i.operator?"1":"0"]])}if(!r){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const n=e.map((e=>ZS`<cfvo ${$S(e)} />`));i.push(ZS`
2218
+ `)}return qS(i)}function Sw(e,t){const o=Cw(e);o.push(["type","iconSet"]);const i=[];for(const s of e.ranges){const e=[[["type","percent"],["val",0]]];let n=!0;for(let o of["lowerInflectionPoint","upperInflectionPoint"]){if("formula"===t[o].type){n=!1;continue}const i=t[o];e.push([...ww(i,o),["gte","ge"===i.operator?"1":"0"]])}if(!n){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const r=e.map((e=>ZS`<cfvo ${$S(e)} />`));i.push(ZS`
2224
2219
  <conditionalFormatting sqref="${s}">
2225
2220
  <cfRule ${$S(o)}>
2226
- <iconSet iconSet="${Cw(t.icons)}">
2227
- ${qS(n)}
2221
+ <iconSet iconSet="${Ew(t.icons)}">
2222
+ ${qS(r)}
2228
2223
  </iconSet>
2229
2224
  </cfRule>
2230
2225
  </conditionalFormatting>
2231
- `)}return qS(i)}function Sw(e){return[["priority",1],["stopIfTrue",e.stopIfTrue?1:0]]}function Cw(e){return cb[Object.keys(cb).find((t=>e.upper.toLowerCase().startsWith(t)))||"dots"]}function Ew(e,t){const o=function(e,t){switch(e){case"value":return"minimum"===t?"min":"max";case"number":return"num";case"percentage":return"percent";default:return e}}(e.type,t),i=[["type",o]];if("min"!==o&&"max"!==o){let t=e.value;if("formula"===o)try{t=gw(e.value)}catch(o){t=e.value}i.push(["val",t])}return i}function ww(e,t,o){const i=[["xmlns:xdr",hb.drawing],["xmlns:r",mb],["xmlns:a",db],["xmlns:c",ub]],s=[];for(const[i,r]of Object.entries(o))switch(r?.tag){case"chart":s.push(Iw(r,t,e[i]));break;case"image":s.push(Rw(r,t,e[i]))}return WS(ZS`
2226
+ `)}return qS(i)}function Cw(e){return[["priority",1],["stopIfTrue",e.stopIfTrue?1:0]]}function Ew(e){return cb[Object.keys(cb).find((t=>e.upper.toLowerCase().startsWith(t)))||"dots"]}function ww(e,t){const o=function(e,t){switch(e){case"value":return"minimum"===t?"min":"max";case"number":return"num";case"percentage":return"percent";default:return e}}(e.type,t),i=[["type",o]];if("min"!==o&&"max"!==o){let t=e.value;if("formula"===o)try{t=pw(e.value)}catch(o){t=e.value}i.push(["val",t])}return i}function xw(e,t,o){const i=[["xmlns:xdr",hb.drawing],["xmlns:r",mb],["xmlns:a",db],["xmlns:c",ub]],s=[];for(const[i,n]of Object.entries(o))switch(n?.tag){case"chart":s.push(Rw(n,t,e[i]));break;case"image":s.push(Tw(n,t,e[i]))}return WS(ZS`
2232
2227
  <xdr:wsDr ${$S(i)}>
2233
2228
  ${qS(s)}
2234
2229
  </xdr:wsDr>
2235
- `)}function xw(e,t){const{x:o,y:i,height:s,width:r}=e,n=Object.values(t.cols),a=Object.values(t.rows),{index:l,offset:c}=yw(n,o),{index:h,offset:d}=yw(n,o+r),{index:u,offset:g}=yw(a,i),{index:p,offset:m}=yw(a,i+s);return{from:{col:l,colOff:c,row:u,rowOff:g},to:{col:h,colOff:d,row:p,rowOff:m}}}function yw(e,t){let o=0;for(const[i,s]of e.entries()){if(o<=t&&t<o+s.size)return{index:i,offset:fS(t-o+te)};i<e.length-1&&(o+=s.size)}return{index:e.length-1,offset:fS(t-o+te)}}function Iw(e,t,o){const{from:i,to:s}=xw(e,t),r=gS(e.id),n=[["id",r],["name",`Chart ${r}`],["title","Chart"]];return ZS`
2230
+ `)}function yw(e,t){const{x:o,y:i,height:s,width:n}=e,r=Object.values(t.cols),a=Object.values(t.rows),{index:l,offset:c}=Iw(r,o),{index:h,offset:d}=Iw(r,o+n),{index:u,offset:g}=Iw(a,i),{index:p,offset:m}=Iw(a,i+s);return{from:{col:l,colOff:c,row:u,rowOff:g},to:{col:h,colOff:d,row:p,rowOff:m}}}function Iw(e,t){let o=0;for(const[i,s]of e.entries()){if(o<=t&&t<o+s.size)return{index:i,offset:fS(t-o+te)};i<e.length-1&&(o+=s.size)}return{index:e.length-1,offset:fS(t-o+te)}}function Rw(e,t,o){const{from:i,to:s}=yw(e,t),n=gS(e.id),r=[["id",n],["name",`Chart ${n}`],["title","Chart"]];return ZS`
2236
2231
  <xdr:twoCellAnchor>
2237
2232
  <xdr:from>
2238
2233
  <xdr:col>${i.col}</xdr:col>
@@ -2248,7 +2243,7 @@
2248
2243
  </xdr:to>
2249
2244
  <xdr:graphicFrame>
2250
2245
  <xdr:nvGraphicFramePr>
2251
- <xdr:cNvPr ${$S(n)} />
2246
+ <xdr:cNvPr ${$S(r)} />
2252
2247
  <xdr:cNvGraphicFramePr />
2253
2248
  </xdr:nvGraphicFramePr>
2254
2249
  <xdr:xfrm>
@@ -2263,7 +2258,7 @@
2263
2258
  </xdr:graphicFrame>
2264
2259
  <xdr:clientData fLocksWithSheet="0"/>
2265
2260
  </xdr:twoCellAnchor>
2266
- `}function Rw(e,t,o){const{from:i,to:s}=xw(e,t),r=mS(e.id),n=[["id",r],["name",`Image ${r}`],["title","Image"]];return ZS`
2261
+ `}function Tw(e,t,o){const{from:i,to:s}=yw(e,t),n=mS(e.id),r=[["id",n],["name",`Image ${n}`],["title","Image"]];return ZS`
2267
2262
  <xdr:twoCellAnchor editAs="oneCell">
2268
2263
  <xdr:from>
2269
2264
  <xdr:col>${i.col}</xdr:col>
@@ -2279,7 +2274,7 @@
2279
2274
  </xdr:to>
2280
2275
  <xdr:pic>
2281
2276
  <xdr:nvPicPr>
2282
- <xdr:cNvPr ${$S(n)}/>
2277
+ <xdr:cNvPr ${$S(r)}/>
2283
2278
  <xdr:cNvPicPr preferRelativeResize="0"/>
2284
2279
  </xdr:nvPicPr>
2285
2280
  <xdr:blipFill>
@@ -2297,79 +2292,77 @@
2297
2292
  </xdr:pic>
2298
2293
  <xdr:clientData fLocksWithSheet="0"/>
2299
2294
  </xdr:twoCellAnchor>
2300
- `}function Tw(e){return ut(e)?ZS``:ZS`
2295
+ `}function Aw(e){return ut(e)?ZS``:ZS`
2301
2296
  <font>
2302
2297
  ${e.bold?ZS`<b />`:""}
2303
2298
  ${e.italic?ZS`<i />`:""}
2304
2299
  ${e.underline?ZS`<u />`:""}
2305
2300
  ${e.strike?ZS`<strike />`:""}
2306
2301
  ${e.size?ZS`<sz val="${e.size}" />`:""}
2307
- ${e.color&&e.color.rgb?ZS`<color rgb="${Lr(e.color.rgb)}" />`:""}
2302
+ ${e.color&&e.color.rgb?ZS`<color rgb="${kn(e.color.rgb)}" />`:""}
2308
2303
  ${e.name?ZS`<name val="${e.name}" />`:""}
2309
2304
  </font>
2310
- `}function Aw(e){return e?$S([["style",e.style]]):ZS``}function Ow(e){return e?ZS`
2311
- <color ${$S([["rgb",Lr(e.color.rgb)]])}/>
2312
- `:ZS``}const Mw=ZS`<tableStyleInfo ${$S([["name","TableStyleLight8"],["showFirstColumn","0"],["showLastColumn","0"],["showRowStripes","0"],["showColumnStripes","0"]])}/>`;function Nw(e,t,o){const i=ZS`
2305
+ `}function Ow(e){return e?$S([["style",e.style]]):ZS``}function Mw(e){return e?ZS`
2306
+ <color ${$S([["rgb",kn(e.color.rgb)]])}/>
2307
+ `:ZS``}const Nw=ZS`<tableStyleInfo ${$S([["name","TableStyleLight8"],["showFirstColumn","0"],["showLastColumn","0"],["showRowStripes","0"],["showColumnStripes","0"]])}/>`;function _w(e,t,o){const i=ZS`
2313
2308
  <table ${$S([["id",t],["name",`Table${t}`],["displayName",`Table${t}`],["ref",e.range],["xmlns",hb.table],["xmlns:xr",hb.revision],["xmlns:xr3",hb.revision3],["xmlns:mc",hb.markupCompatibility]])}>
2314
2309
  ${function(e){const t=[["ref",e.range]];return ZS`
2315
2310
  <autoFilter ${$S(t)}>
2316
2311
  ${qS(function(e){const t=[];for(const o of e.filters){const e=ZS`
2317
2312
  <filterColumn ${$S([["colId",o.colId]])}>
2318
- ${_w(o)}
2313
+ ${Fw(o)}
2319
2314
  </filterColumn>
2320
2315
  `;t.push(e)}return t}(e))}
2321
2316
  </autoFilter>
2322
2317
  `}(e)}
2323
- ${function(e,t){const o=ti(e.range),i=[];for(const e of Ke(0,fi(o).numberOfCols)){const s=Gt(o.left+e,o.top),r=[["id",e+1],["name",t.cells[s]?.content||`col${e}`]];i.push(ZS`<tableColumn ${$S(r)}/>`)}return ZS`
2318
+ ${function(e,t){const o=ti(e.range),i=[];for(const e of Ke(0,fi(o).numberOfCols)){const s=Gt(o.left+e,o.top),n=[["id",e+1],["name",t.cells[s]?.content||`col${e}`]];i.push(ZS`<tableColumn ${$S(n)}/>`)}return ZS`
2324
2319
  <tableColumns ${$S([["count",i.length]])}>
2325
2320
  ${qS(i)}
2326
2321
  </tableColumns>
2327
2322
  `}(e,o)}
2328
- ${Mw}
2323
+ ${Nw}
2329
2324
  </table>
2330
- `;return WS(i)}function _w(e){const t=e.displayedValues.map((e=>ZS`<filter ${$S([["val",e]])}/>`));return ZS`
2325
+ `;return WS(i)}function Fw(e){const t=e.displayedValues.map((e=>ZS`<filter ${$S([["val",e]])}/>`));return ZS`
2331
2326
  <filters ${$S(e.displayBlanks?[["blank",1]]:[])}>
2332
2327
  ${qS(t)}
2333
2328
  </filters>
2334
- `}function Fw(e){if(!Object.values(e).length)return ZS``;const t=[];for(let[o,i]of Object.entries(e)){const e=[["min",parseInt(o)+1],["max",parseInt(o)+1],["width",nS(i.size||L)],["customWidth",1],["hidden",i.isHidden?1:0]];t.push(ZS`
2329
+ `}function Dw(e){if(!Object.values(e).length)return ZS``;const t=[];for(let[o,i]of Object.entries(e)){const e=[["min",parseInt(o)+1],["max",parseInt(o)+1],["width",rS(i.size||L)],["customWidth",1],["hidden",i.isHidden?1:0]];t.push(ZS`
2335
2330
  <col ${$S(e)}/>
2336
2331
  `)}return ZS`
2337
2332
  <cols>
2338
2333
  ${qS(t)}
2339
2334
  </cols>
2340
- `}function Dw(e,t,o){const i=[];for(let s=0;s<o.rowNumber;s++){const r=[["r",s+1]],n=o.rows[s]||{};r.push(["ht",rS(n.size||k)],["customHeight",1],["hidden",n.isHidden?1:0]);const a=[];for(let i=0;i<o.colNumber;i++){const r=Gt(i,s),n=o.cells[r];if(n){const l=[["r",r]],c=cS(e,lS(n,t));l.push(["s",c]);let h=[],d=ZS``;if(n.isFormula)({attrs:h,node:d}=dw(n));else if(n.content&&it(n.content)){const{label:t}=nt(n.content);({attrs:h,node:d}=uw(t,e.sharedStrings))}else if(n.content&&""!==n.content){const t=Lw(i,s,o);({attrs:h,node:d}=uw(n.content,e.sharedStrings,t))}l.push(...h),a.push(ZS`
2341
- <c ${$S(l)}>
2342
- ${d}
2343
- </c>
2344
- `)}}(a.length||n.size!==k||n.isHidden)&&i.push(ZS`
2345
- <row ${$S(r)}>
2335
+ `}function Lw(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",nS(r.size||k)],["customHeight",1],["hidden",r.isHidden?1:0]);const a=[];for(let i=0;i<o.colNumber;i++){const n=Gt(i,s),r=o.cells[n];if(r){const l=[["r",n]],c=cS(e,lS(r,t));l.push(["s",c]);let h=[],d=ZS``;if(r.isFormula)({attrs:h,node:d}=uw(r));else if(r.content&&it(r.content)){const{label:t}=rt(r.content);({attrs:h,node:d}=gw(t,e.sharedStrings))}else if(r.content&&""!==r.content){const t=kw(i,s,o);({attrs:h,node:d}=gw(r.content,e.sharedStrings,t))}l.push(...h),a.push(ZS`<c ${$S(l)}>
2336
+ ${d}
2337
+ </c>`)}}(a.length||r.size!==k||r.isHidden)&&i.push(ZS`
2338
+ <row ${$S(n)}>
2346
2339
  ${qS(a)}
2347
2340
  </row>
2348
2341
  `)}return ZS`
2349
2342
  <sheetData>
2350
2343
  ${qS(i)}
2351
2344
  </sheetData>
2352
- `}function Lw(e,t,o){return o.filterTables.some((o=>{const i=ti(o.range),s={...i,bottom:i.top};return ui(e,t,s)}))}function kw(e,t,o){const i=t.sheets[o].cells,s=[];for(const r in i){const n=i[r]?.content;if(n&&it(n)){const{label:i,url:a}=nt(n);if(lt(a)){const e=ht(a),o=t.sheets.find((t=>t.id===e)),n=[["display",i],["location",o?`${o.name}!A1`:J],["ref",r]];s.push(ZS`
2353
- <hyperlink ${$S(n)}/>
2354
- `)}else{const t=[["r:id",hS(e.relsFiles,`xl/worksheets/_rels/sheet${o}.xml.rels`,{target:Vi(a),type:pb.hyperlink,targetMode:"External"})],["ref",r]];s.push(ZS`
2345
+ `}function kw(e,t,o){return o.filterTables.some((o=>{const i=ti(o.range),s={...i,bottom:i.top};return ui(e,t,s)}))}function Pw(e,t,o){const i=t.sheets[o].cells,s=[];for(const n in i){const r=i[n]?.content;if(r&&it(r)){const{label:i,url:a}=rt(r);if(lt(a)){const e=ht(a),o=t.sheets.find((t=>t.id===e)),r=[["display",i],["location",o?`${o.name}!A1`:J],["ref",n]];s.push(ZS`
2346
+ <hyperlink ${$S(r)}/>
2347
+ `)}else{const t=[["r:id",hS(e.relsFiles,`xl/worksheets/_rels/sheet${o}.xml.rels`,{target:Vi(a),type:pb.hyperlink,targetMode:"External"})],["ref",n]];s.push(ZS`
2355
2348
  <hyperlink ${$S(t)}/>
2356
2349
  `)}}}return s.length?ZS`
2357
2350
  <hyperlinks>
2358
2351
  ${qS(s)}
2359
2352
  </hyperlinks>
2360
- `:ZS``}function Pw(e){if(e.length){const t=e.map((e=>ZS`<mergeCell ref="${e}" />`));return ZS`
2353
+ `:ZS``}function Uw(e){if(e.length){const t=e.map((e=>ZS`<mergeCell ref="${e}" />`));return ZS`
2361
2354
  <mergeCells count="${e.length}">
2362
2355
  ${qS(t)}
2363
2356
  </mergeCells>
2364
- `}return ZS``}function Uw(e){const t=e.panes;let o=ZS``;if(t&&(t.xSplit||t.ySplit)){const e=Gt(t.xSplit,t.ySplit),i=t.xSplit?ZS`xSplit="${t.xSplit}"`:"",s=t.ySplit?ZS`ySplit="${t.ySplit}"`:"",r=t.xSplit?ZS`<selection pane="topRight"/>`:"",n=t.ySplit?ZS`<selection pane="bottomLeft"/>`:"",a=t.xSplit&&t.ySplit?ZS`<selection pane="bottomRight"/>`:"";o=ZS`
2357
+ `}return ZS``}function Vw(e){const t=e.panes;let o=ZS``;if(t&&(t.xSplit||t.ySplit)){const e=Gt(t.xSplit,t.ySplit),i=t.xSplit?ZS`xSplit="${t.xSplit}"`:"",s=t.ySplit?ZS`ySplit="${t.ySplit}"`:"",n=t.xSplit?ZS`<selection pane="topRight"/>`:"",r=t.ySplit?ZS`<selection pane="bottomLeft"/>`:"",a=t.xSplit&&t.ySplit?ZS`<selection pane="bottomRight"/>`:"";o=ZS`
2365
2358
  <pane
2366
2359
  ${i}
2367
2360
  ${s}
2368
2361
  topLeftCell="${e}"
2369
2362
  activePane="${t.xSplit?t.ySplit?"bottomRight":"topRight":"bottomLeft"}"
2370
2363
  state="frozen"/>
2371
- ${r}
2372
2364
  ${n}
2365
+ ${r}
2373
2366
  ${a}
2374
2367
  `}return ZS`
2375
2368
  <sheetViews>
@@ -2377,7 +2370,7 @@
2377
2370
  ${o}
2378
2371
  </sheetView>
2379
2372
  </sheetViews>
2380
- `}function Vw(e){const t=[],o={relsFiles:[],sharedStrings:[],styles:[{fontId:0,fillId:0,numFmtId:0,borderId:0,alignment:{vertical:"bottom"}}],fonts:[{size:Z,family:2,color:{rgb:"000000"},name:"Calibri"}],fills:[{reservedAttribute:"none"},{reservedAttribute:"gray125"}],borders:[{}],numFmts:[],dxfs:[]};return t.push(function(e,t){const o=[["xmlns",hb.workbook],["xmlns:r",mb]],i=[];for(const[o,s]of Object.entries(e.sheets)){const e=[["state",s.isVisible?"visible":"hidden"],["name",s.name],["sheetId",parseInt(o)+1],["r:id",`rId${parseInt(o)+1}`]];i.push(ZS`
2373
+ `}function zw(e){const t=[],o={relsFiles:[],sharedStrings:[],styles:[{fontId:0,fillId:0,numFmtId:0,borderId:0,alignment:{vertical:"bottom"}}],fonts:[{size:Z,family:2,color:{rgb:"000000"},name:"Calibri"}],fills:[{reservedAttribute:"none"},{reservedAttribute:"gray125"}],borders:[{}],numFmts:[],dxfs:[]};return t.push(function(e,t){const o=[["xmlns",hb.workbook],["xmlns:r",mb]],i=[];for(const[o,s]of Object.entries(e.sheets)){const e=[["state",s.isVisible?"visible":"hidden"],["name",s.name],["sheetId",parseInt(o)+1],["r:id",`rId${parseInt(o)+1}`]];i.push(ZS`
2381
2374
  <sheet ${$S(e)} />
2382
2375
  `),hS(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:pb.sheet,target:`worksheets/sheet${o}.xml`})}return BS(WS(ZS`
2383
2376
  <workbook ${$S(o)}>
@@ -2385,15 +2378,15 @@
2385
2378
  ${qS(i)}
2386
2379
  </sheets>
2387
2380
  </workbook>
2388
- `),"xl/workbook.xml","workbook")}(e,o)),t.push(...function(e,t){const o=[];let i=1;for(const[s,r]of Object.entries(e.sheets)){const n=[["xmlns",hb.worksheet],["xmlns:r",mb]],a=[["defaultRowHeight",rS(k)],["defaultColWidth",nS(L)]],l=zw(r,s,i,t,o);i+=r.filterTables.length;let c=ZS``;const h=[];for(const i of r.charts){const r=gS(i.id),n=hS(t.relsFiles,`xl/drawings/_rels/drawing${s}.xml.rels`,{target:`../charts/chart${r}.xml`,type:pb.chart});h.push(n),o.push(BS(ow(i,s,e),`xl/charts/chart${r}.xml`,"chart"))}for(const e of r.images){const i=e.data.mimetype;if(void 0===i)continue;const r=jb[i];if(void 0===r)continue;let n=`image${mS(e.id)}.${r}`;const a=hS(t.relsFiles,`xl/drawings/_rels/drawing${s}.xml.rels`,{target:`../media/${n}`,type:pb.image});h.push(a),o.push({path:`xl/media/${n}`,imageSrc:e.data.path})}const d=[...r.charts,...r.images];if(d.length){const e=hS(t.relsFiles,`xl/worksheets/_rels/sheet${s}.xml.rels`,{target:`../drawings/drawing${s}.xml`,type:pb.drawing});o.push(BS(ww(h,r,d),`xl/drawings/drawing${s}.xml`,"drawing")),c=ZS`<drawing r:id="${e}" />`}const u=ZS`
2389
- <worksheet ${$S(n)}>
2390
- ${Uw(r)}
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",hb.worksheet],["xmlns:r",mb]],a=[["defaultRowHeight",nS(k)],["defaultColWidth",rS(L)]],l=Bw(n,s,i,t,o);i+=n.filterTables.length;let c=ZS``;const h=[];for(const i of n.charts){const n=gS(i.id),r=hS(t.relsFiles,`xl/drawings/_rels/drawing${s}.xml.rels`,{target:`../charts/chart${n}.xml`,type:pb.chart});h.push(r),o.push(BS(iw(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=jb[i];if(void 0===n)continue;let r=`image${mS(e.id)}.${n}`;const a=hS(t.relsFiles,`xl/drawings/_rels/drawing${s}.xml.rels`,{target:`../media/${r}`,type:pb.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=hS(t.relsFiles,`xl/worksheets/_rels/sheet${s}.xml.rels`,{target:`../drawings/drawing${s}.xml`,type:pb.drawing});o.push(BS(xw(h,n,d),`xl/drawings/drawing${s}.xml`,"drawing")),c=ZS`<drawing r:id="${e}" />`}const u=ZS`
2382
+ <worksheet ${$S(r)}>
2383
+ ${Vw(n)}
2391
2384
  <sheetFormatPr ${$S(a)} />
2392
- ${Fw(r.cols)}
2393
- ${Dw(t,e,r)}
2394
- ${Pw(r.merges)}
2395
- ${qS(mw(t.dxfs,r.conditionalFormats))}
2396
- ${kw(t,e,s)}
2385
+ ${Dw(n.cols)}
2386
+ ${Lw(t,e,n)}
2387
+ ${Uw(n.merges)}
2388
+ ${qS(fw(t.dxfs,n.conditionalFormats))}
2389
+ ${Pw(t,e,s)}
2397
2390
  ${c}
2398
2391
  ${l}
2399
2392
  </worksheet>
@@ -2408,7 +2401,7 @@
2408
2401
  `}(e.numFmts)}
2409
2402
  ${o=e.fonts,ZS`
2410
2403
  <fonts count="${o.length}">
2411
- ${qS(Object.values(o).map(Tw))}
2404
+ ${qS(Object.values(o).map(Aw))}
2412
2405
  </fonts>
2413
2406
  `}
2414
2407
  ${function(e){const t=[];for(let o of Object.values(e))void 0!==o.reservedAttribute?t.push(ZS`
@@ -2418,7 +2411,7 @@
2418
2411
  `):t.push(ZS`
2419
2412
  <fill>
2420
2413
  <patternFill patternType="solid">
2421
- <fgColor rgb="${Lr(o.fgColor.rgb)}" />
2414
+ <fgColor rgb="${kn(o.fgColor.rgb)}" />
2422
2415
  <bgColor indexed="64" />
2423
2416
  </patternFill>
2424
2417
  </fill>
@@ -2429,20 +2422,20 @@
2429
2422
  `}(e.fills)}
2430
2423
  ${function(e){const t=[];for(let o of Object.values(e))t.push(ZS`
2431
2424
  <border>
2432
- <left ${Aw(o.left)}>
2433
- ${Ow(o.left)}
2425
+ <left ${Ow(o.left)}>
2426
+ ${Mw(o.left)}
2434
2427
  </left>
2435
- <right ${Aw(o.right)}>
2436
- ${Ow(o.right)}
2428
+ <right ${Ow(o.right)}>
2429
+ ${Mw(o.right)}
2437
2430
  </right>
2438
- <top ${Aw(o.top)}>
2439
- ${Ow(o.top)}
2431
+ <top ${Ow(o.top)}>
2432
+ ${Mw(o.top)}
2440
2433
  </top>
2441
- <bottom ${Aw(o.bottom)}>
2442
- ${Ow(o.bottom)}
2434
+ <bottom ${Ow(o.bottom)}>
2435
+ ${Mw(o.bottom)}
2443
2436
  </bottom>
2444
- <diagonal ${Aw(o.diagonal)}>
2445
- ${Ow(o.diagonal)}
2437
+ <diagonal ${Ow(o.diagonal)}>
2438
+ ${Mw(o.diagonal)}
2446
2439
  </diagonal>
2447
2440
  </border>
2448
2441
  `);return ZS`
@@ -2455,10 +2448,10 @@
2455
2448
  ${qS(t)}
2456
2449
  </cellXfs>
2457
2450
  `}(e.styles)}
2458
- ${function(e){const t=[];for(const o of e){let e=ZS``;o.font&&(e=Tw(o.font));let i=ZS``;o.fill&&(i=ZS`
2451
+ ${function(e){const t=[];for(const o of e){let e=ZS``;o.font&&(e=Aw(o.font));let i=ZS``;o.fill&&(i=ZS`
2459
2452
  <fill>
2460
2453
  <patternFill>
2461
- <bgColor rgb="${Lr(o.fill.fgColor.rgb)}" />
2454
+ <bgColor rgb="${kn(o.fill.fgColor.rgb)}" />
2462
2455
  </patternFill>
2463
2456
  </fill>
2464
2457
  `),t.push(ZS`
@@ -2495,8 +2488,8 @@
2495
2488
  <Relationships xmlns="${hb.Relationships}">
2496
2489
  <Relationship ${$S(e)} />
2497
2490
  </Relationships>
2498
- `),"_rels/.rels")}()),{name:"my_spreadsheet.xlsx",files:t}}function zw(e,t,o,i,s){let r=o;if(!e.filterTables.length)return new nb("");const n=`xl/worksheets/_rels/sheet${t}.xml.rels`,a=[];for(const t of e.filterTables){const o=hS(i.relsFiles,n,{target:`../tables/table${r}.xml`,type:pb.table});s.push(BS(Nw(t,r,e),`xl/tables/table${r}.xml`,"table")),a.push(ZS`<tablePart r:id="${o}" />`),r++}return ZS`
2491
+ `),"_rels/.rels")}()),{name:"my_spreadsheet.xlsx",files:t}}function Bw(e,t,o,i,s){let n=o;if(!e.filterTables.length)return new rb("");const r=`xl/worksheets/_rels/sheet${t}.xml.rels`,a=[];for(const t of e.filterTables){const o=hS(i.relsFiles,r,{target:`../tables/table${n}.xml`,type:pb.table});s.push(BS(_w(t,n,e),`xl/tables/table${n}.xml`,"table")),a.push(ZS`<tablePart r:id="${o}" />`),n++}return ZS`
2499
2492
  <tableParts count="${e.filterTables.length}">
2500
2493
  ${qS(a)}
2501
2494
  </tableParts>
2502
- `}var Bw;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(Bw||(Bw={}));function Hw(e,t={}){const o=Be(t);return o.type=e,o}const $w={},Ww={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:k,SCROLLBAR_WIDTH:P},Gw={autofillModifiersRegistry:Hs,autofillRulesRegistry:$s,cellMenuRegistry:up,colMenuRegistry:Tm,linkMenuRegistry:Nr,functionRegistry:Ug,featurePluginRegistry:pE,statefulUIPluginRegistry:mE,coreViewsPluginRegistry:fE,corePluginRegistry:gE,rowMenuRegistry:Mm,sidePanelRegistry:cf,figureRegistry:Gn,chartSidePanelComponentRegistry:Xm,chartComponentRegistry:zn,chartRegistry:Vn,topbarMenuRegistry:Nm,topbarComponentRegistry:hf,clickableCellRegistry:bE,otRegistry:_m,inverseCommandRegistry:Yn,urlRegistry:zi,cellPopoverRegistry:Dr,numberFormatMenuRegistry:Am,repeatLocalCommandTransformRegistry:QC,repeatCommandTransformRegistry:KC},qw={arg:Xa,toBoolean:ss,toJsDate:rs,toNumber:Xi,toString:es,toXC:Gt,toZone:ti,toCartesian:Wt,numberToLetters:Vt,UuidGenerator:Jo,formatValue:mo,computeTextWidth:qe,createEmptyWorkbookData:vC,createEmptySheet:bC,createEmptyExcelSheet:SC,getDefaultChartJsRuntime:gn,chartFontColor:Yr,ChartColors:jr,EvaluationError:c,CellErrorLevel:l,getFillingMode:bn,rgbaToHex:Lt,colorToRGBA:kt,positionToZone:wi,isDefined:dt,lazy:mt,genericRepeat:JC},Zw={isMarkdownLink:it,parseMarkdownLink:nt,markdownLink:rt,openLink:Gi,urlRepresentation:Wi},jw={ChartPanel:Km,ChartFigure:Hn,ChartJsComponent:Ri,Grid:rb,GridOverlay:$f,ScorecardChart:Li,LineConfigPanel:Zm,LineBarPieDesignPanel:Wm,BarConfigPanel:Um,LineBarPieConfigPanel:Pm,GaugeChartConfigPanel:Gm,GaugeChartDesignPanel:qm,ScorecardChartConfigPanel:jm,ScorecardChartDesignPanel:Ym,FigureComponent:df};e.AbstractChart=kr,e.CorePlugin=EC,e.DispatchResult=Os,e.EvaluationError=c,e.Model=class extends _C{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 Jo,r=!0){super(),i=mC(e,i);const n=gC(e,r);this.state=new JE,this.uuidGenerator=s,this.config=this.setupConfig(o),this.session=this.setupSession(n.revisionId),this.coreGetters={},this.range=new TC(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 QE(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of gE.getAll())this.setupCorePlugin(e,n);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(i);for(let e of mE.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of fE.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 pE.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 BC(YE({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:r("Anonymous").toString()},o=e.transportService||new zE;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=As(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some((e=>0!==e))?new Os(t.flat()):Os.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(Hw(e,t));dispatch=(e,t)=>{const o=Hw(e,t);let i=this.status;if(this.getters.isReadonly()&&(s=o,!Rs.has(s.type)))return new Os(67);var s;if(!this.session.canApplyOptimisticUpdate())return new Os(64);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((()=>{As(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(As(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(As(o))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,o)}return Os.Success};dispatchFromCorePlugin=(e,t)=>{const o=Hw(e,t),i=this.status;this.status=2;const s=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(s,o),this.status=i,Os.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=vC();for(let t of this.handlers)t instanceof EC&&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={...vC(),sheets:[SC(uC,"Sheet1")]};for(let t of this.handlers)t instanceof CC&&t.exportForExcel(e);return e=Be(e),Vw(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.Registry=Ui,e.Revision=VC,e.SPREADSHEET_DIMENSIONS=Ww,e.Spreadsheet=VE,e.UIPlugin=AC,e.__info__=$w,e.addFunction=function(e,t){Ug.add(e,t)},e.astToFormula=$v,e.compile=oS,e.components=jw,e.convertAstNodes=Hv,e.coreTypes=Ts,e.findCellInNewZone=Ci,e.functionCache=tS,e.helpers=qw,e.invalidateEvaluationCommands=ys,e.links=Zw,e.load=gC,e.parse=zv,e.readonlyAllowedCommands=Rs,e.registries=Gw,e.setDefaultSheetViewSize=function(e){ge=e},e.setTranslationMethod=function(e){o=e},e.tokenize=Sv,Object.defineProperty(e,"__esModule",{value:!0}),$w.version="16.3.22",$w.date="2024-01-17T10:24:07.652Z",$w.hash="2c1b136"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
2495
+ `}var Hw;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(Hw||(Hw={}));function $w(e,t={}){const o=Be(t);return o.type=e,o}const Ww={},Gw={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:k,SCROLLBAR_WIDTH:P},qw={autofillModifiersRegistry:Hs,autofillRulesRegistry:$s,cellMenuRegistry:up,colMenuRegistry:Tm,linkMenuRegistry:_n,functionRegistry:Ug,featurePluginRegistry:pE,statefulUIPluginRegistry:mE,coreViewsPluginRegistry:fE,corePluginRegistry:gE,rowMenuRegistry:Mm,sidePanelRegistry:cf,figureRegistry:Gr,chartSidePanelComponentRegistry:Xm,chartComponentRegistry:zr,chartRegistry:Vr,topbarMenuRegistry:Nm,topbarComponentRegistry:hf,clickableCellRegistry:bE,otRegistry:_m,inverseCommandRegistry:Yr,urlRegistry:zi,cellPopoverRegistry:Ln,numberFormatMenuRegistry:Am,repeatLocalCommandTransformRegistry:QC,repeatCommandTransformRegistry:KC},Zw={arg:Xa,toBoolean:ss,toJsDate:ns,toNumber:Xi,toString:es,toXC:Gt,toZone:ti,toCartesian:Wt,numberToLetters:Vt,UuidGenerator:Jo,formatValue:mo,computeTextWidth:qe,createEmptyWorkbookData:vC,createEmptySheet:bC,createEmptyExcelSheet:SC,getDefaultChartJsRuntime:gr,chartFontColor:Xn,ChartColors:Yn,EvaluationError:c,CellErrorLevel:l,getFillingMode:br,rgbaToHex:Lt,colorToRGBA:kt,positionToZone:wi,isDefined:dt,lazy:mt,genericRepeat:JC},jw={isMarkdownLink:it,parseMarkdownLink:rt,markdownLink:nt,openLink:Gi,urlRepresentation:Wi},Yw={ChartPanel:Km,ChartFigure:Hr,ChartJsComponent:Ri,Grid:nb,GridOverlay:$f,ScorecardChart:Li,LineConfigPanel:Zm,LineBarPieDesignPanel:Wm,BarConfigPanel:Um,LineBarPieConfigPanel:Pm,GaugeChartConfigPanel:Gm,GaugeChartDesignPanel:qm,ScorecardChartConfigPanel:jm,ScorecardChartDesignPanel:Ym,FigureComponent:df};e.AbstractChart=Pn,e.CorePlugin=EC,e.DispatchResult=Os,e.EvaluationError=c,e.Model=class extends _C{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 Jo,n=!0){super(),i=mC(e,i);const r=gC(e,n);this.state=new ew,this.uuidGenerator=s,this.config=this.setupConfig(o),this.session=this.setupSession(r.revisionId),this.coreGetters={},this.range=new TC(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 JE(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of gE.getAll())this.setupCorePlugin(e,r);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(i);for(let e of mE.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of fE.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 pE.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 BC(XE({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 BE;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=As(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some((e=>0!==e))?new Os(t.flat()):Os.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($w(e,t));dispatch=(e,t)=>{const o=$w(e,t);let i=this.status;if(this.getters.isReadonly()&&(s=o,!Rs.has(s.type)))return new Os(68);var s;if(!this.session.canApplyOptimisticUpdate())return new Os(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((()=>{As(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(As(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(As(o))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,o)}return Os.Success};dispatchFromCorePlugin=(e,t)=>{const o=$w(e,t),i=this.status;this.status=2;const s=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(s,o),this.status=i,Os.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=vC();for(let t of this.handlers)t instanceof EC&&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={...vC(),sheets:[SC(uC,"Sheet1")]};for(let t of this.handlers)t instanceof CC&&t.exportForExcel(e);return e=Be(e),zw(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.Registry=Ui,e.Revision=VC,e.SPREADSHEET_DIMENSIONS=Gw,e.Spreadsheet=zE,e.UIPlugin=AC,e.__info__=Ww,e.addFunction=function(e,t){Ug.add(e,t)},e.astToFormula=$v,e.compile=oS,e.components=Yw,e.convertAstNodes=Hv,e.coreTypes=Ts,e.findCellInNewZone=Ci,e.functionCache=tS,e.helpers=Zw,e.invalidateEvaluationCommands=ys,e.links=jw,e.load=gC,e.parse=zv,e.readonlyAllowedCommands=Rs,e.registries=qw,e.setDefaultSheetViewSize=function(e){ge=e},e.setTranslationMethod=function(e){o=e},e.tokenize=Sv,Object.defineProperty(e,"__esModule",{value:!0}),Ww.version="16.3.25",Ww.date="2024-02-09T13:07:06.947Z",Ww.hash="b53bf1b"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);