@odoo/o-spreadsheet 16.0.68 → 16.0.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- !function(e,t){"use strict";let i=e=>e;function n(e,...t){if(1===t.length&&"object"==typeof t[0]){const i=t[0];e=e.replace(/\%\(?([^\)]+)\)s/g,((e,t)=>i[t]))}else t.length>0&&(e=e.replace(/\%s/g,(()=>t.shift())));return e}const o=function(e,...t){return n(i(e),...t)},s=function(e,...t){return new r(e,t)};class r extends String{constructor(e,t){super(e),this.values=t}valueOf(){const e=super.valueOf();return n(i(e),...this.values)}toString(){return this.valueOf()}}var a,l;!function(e){e.NotAvailable="#N/A",e.InvalidReference="#REF",e.BadExpression="#BAD_EXPR",e.CircularDependency="#CYCLE",e.UnknownFunction="#NAME?",e.GenericError="#ERROR"}(a||(a={})),function(e){e[e.silent=0]="silent",e[e.error=1]="error"}(l||(l={}));class c extends Error{constructor(e,t,i=l.error){super(t),this.errorType=e,this.logLevel=i}}class h extends c{constructor(e){super(a.BadExpression,e)}}class d extends c{constructor(){super(a.CircularDependency,s("Circular reference"))}}class u extends c{constructor(){super(a.InvalidReference,s("Invalid reference"))}}class g extends c{constructor(){super(a.NotAvailable,s("Data not available"),l.silent)}}class p extends c{constructor(e){super(a.UnknownFunction,s('Unknown function: "%s"',e))}}const m=.5,f="#f5f5f5",v="#F8F9FA",b="#E8EAED",S="#595959",C="#666666",E="#3266ca",w="#FFFFFF",y="#CACACA",x=11982760,R="#01666b",I="#188038",T="#E6F4EA",A="#CEEAD6",O=["#000000","#434343","#666666","#999999","#B7B7B7","#CCCCCC","#D9D9D9","#EFEFEF","#F3F3F3","#FFFFFF","#980000","#FF0000","#FF9900","#FFFF00","#00FF00","#00FFFF","#4A86E8","#0000FF","#9900FF","#FF00FF","#E6B8AF","#F4CCCC","#FCE5CD","#FFF2CC","#D9EAD3","#D0E0E3","#C9DAF8","#CFE2F3","#D9D2E9","#EAD1DC","#DD7E6B","#EA9999","#F9CB9C","#FFE599","#B6D7A8","#A2C4C9","#A4C2F4","#9FC5E8","#B4A7D6","#D5A6BD","#CC4125","#E06666","#F6B26B","#FFD966","#93C47D","#76A5AF","#6D9EEB","#6FA8DC","#8E7CC3","#C27BA0","#A61C00","#CC0000","#E69138","#F1C232","#6AA84F","#45818E","#3C78D8","#3D85C6","#674EA7","#A64D79","#85200C","#990000","#B45F06","#BF9000","#38761D","#134F5C","#1155CC","#0B5394","#351C75","#741B47","#5B0F00","#660000","#783F04","#7F6000","#274E13","#0C343D","#1C4587","#073763","#20124D","#4C1130"],N=26,M=48,_=96,F=23,D=15,k=18,$=14,L=4,P=4,U=3,V=P,z=17,B=250,H=1,W="400",G=10,q="'Roboto', arial",Z=["thin","#000"],j=["thin",I],Y=/[ymdhs:]/,X=a.InvalidReference,K="START_REVISION",Q=20,J=.4,ee=["'","*","?","/","\\","[","]"],te=/'|\*|\?|\/|\\|\[|\]/,ie="|",ne=s("Invalid expression");var oe;!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.ColorPicker=25]="ColorPicker",e[e.IconPicker=25]="IconPicker",e[e.TopBarComposer=30]="TopBarComposer",e[e.Popover=35]="Popover",e[e.ChartAnchor=1e3]="ChartAnchor"}(oe||(oe={}));const se=[{pt:7.5,px:10},{pt:8,px:11},{pt:9,px:12},{pt:10,px:13},{pt:10.5,px:14},{pt:11,px:15},{pt:12,px:16},{pt:14,px:18.7},{pt:15,px:20},{pt:16,px:21.3},{pt:18,px:24},{pt:22,px:29.3},{pt:24,px:32},{pt:26,px:34.7},{pt:36,px:48}],re={};for(let e of se)re[e.pt]=e.px;class ae{constructor(e,t,i,n=0,o=0,s=0){this.jsDate=new Date(Date.UTC(e,t,i,n,o,s,0))}static fromTimestamp(e){const t=new Date(e);return new ae(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds())}static now(){const e=new Date;return new ae(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds())}toString(){return this.jsDate.toString()}getTime(){return this.jsDate.getTime()}getFullYear(){return this.jsDate.getUTCFullYear()}getMonth(){return this.jsDate.getUTCMonth()}getDate(){return this.jsDate.getUTCDate()}getDay(){return this.jsDate.getUTCDay()}getHours(){return this.jsDate.getUTCHours()}getMinutes(){return this.jsDate.getUTCMinutes()}getSeconds(){return this.jsDate.getUTCSeconds()}setFullYear(e){this.jsDate.setFullYear(e)}setDate(e){this.jsDate.setUTCDate(e)}setHours(e){this.jsDate.setUTCHours(e)}setMinutes(e){this.jsDate.setUTCMinutes(e)}setSeconds(e){this.jsDate.setUTCSeconds(e)}}const le=new ae(1899,11,30),ce=864e5,he=2e3,de=ae.now().getFullYear(),ue=ae.fromTimestamp(0).getTime()-le.getTime(),ge=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,pe=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,me=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/,fe={};function ve(e){if(fe[e])return fe[e];const t=function(e){let t;e=e.trim();const i=e.match(me);if(i){if(t=function(e){if(e=e.trim(),me.test(e)){const t=/AM/i.test(e),i=/PM/i.test(e),n=(t||i?e.substring(0,e.length-2).trim():e).split(/:/),o=n.length>=2,s=3===n.length;let r=Number(n[0]),a=o?Number(n[1]):0,l=s?Number(n[2]):0,c=s?"hh:mm:ss":"hh:mm";if(t||i)c+=" a";else if(!o)return null;r>=12&&t?r-=12:r<12&&i&&(r+=12),a+=Math.floor(l/60),l%=60,r+=Math.floor(a/60),a%=60,r>=24&&(c="hhhh:mm:ss");return{value:r/24+a/1440+l/86400,format:c,jsDate:new ae(1899,11,30,r,a,l)}}return null}(i[0]),null===t)return null;e=e.replace(i[0],"").trim()}let n;const o=e.match(ge),s=e.match(pe);if(o||s){let t;if(o?(t=o[0],n=be(t,"mdy")):(t=s[0],n=be(t,"ymd")),null===n)return null;e=e.replace(t,"").trim()}if(""!==e||!n&&!t)return null;if(n&&t)return{value:n.value+t.value,format:n.format+" "+("hhhh:mm:ss"===t.format?"hh:mm:ss":t.format),jsDate:new ae(n.jsDate.getFullYear()+t.jsDate.getFullYear()-1899,n.jsDate.getMonth()+t.jsDate.getMonth()-11,n.jsDate.getDate()+t.jsDate.getDate()-30,n.jsDate.getHours()+t.jsDate.getHours(),n.jsDate.getMinutes()+t.jsDate.getMinutes(),n.jsDate.getSeconds()+t.jsDate.getSeconds())};return n||t}(e);return fe[e]=t,t}function be(e,t){const i="mdy"===t;if(i||"ymd"===t){const t=e.split(/\/|-|\s/),n=i?0:1,o=i?1:2,s=i?2:0,r=Number(t[n]),a=Number(t[o]),l=2===t[n].length&&r<10||2===t[o].length&&a<10,c=t[s]?function(e){const t=Number(e);switch(e.length){case 1:return he+t;case 2:return he+(he+t>de+10?-100:0)+t;case 3:case 4:return t}return 0}(t[s]):de,h=new ae(c,r-1,a),d=e.match(/\/|-|\s/)[0];if(h.getMonth()!==r-1||h.getDate()!==a)return null;const u=h.getTime()-le.getTime();let g=l?`mm${d}dd`:`m${d}d`;return t[s]&&(g=i?g+d+"yyyy":"yyyy"+d+g),{value:Math.round(u/ce),format:g,jsDate:h}}return null}function Se(e){const t=Math.trunc(e);let i=ae.fromTimestamp(t*ce-ue),n=e-t;n=n<0?1+n:n;const o=Math.round(24*n),s=Math.round(24*(n-o/24)*60),r=Math.round(24*(n-o/24-s/24/60)*60*60);return i.setHours(o),i.setMinutes(s),i.setSeconds(r),i}function Ce(e){const t=e.getTime()-le.getTime();return Math.round(t/ce)}function Ee(e){return new ae(e.getFullYear(),e.getMonth()+1,0).getDate()}function we(e){return Ee(e)===e.getDate()}function ye(e,t,i){const n=e.getFullYear(),o=e.getMonth(),s=e.getDate(),r=new ae(n,o+t,1);return i&&s===Ee(e)||s>Ee(r)?r.setDate(Ee(r)):r.setDate(s),r}function xe(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function Re(e,t,i){if(e===t)return 0;if(e>t){const i=t;t=e,e=i}const n=Se(e),o=Se(t);let s=n.getDate(),r=o.getDate();const a=n.getMonth(),l=o.getMonth(),c=n.getFullYear(),h=o.getFullYear();let d=0,u=0;switch(i){case 0:31===s&&(s=30),30===s&&31===r&&(r=30),1===a&&s===(xe(c)?29:28)&&(s=30,1===l&&r===(xe(h)?29:28)&&(r=30)),d=c+(30*a+s)/360,u=h+(30*l+r)/360;break;case 1:let i=365;const n=c===h;if(!n&&!(c+1===h)||!n&&a<l||!n&&a===l&&s<r){let e=0,t=0;for(let i=c;i<=h;i++)e++,t+=xe(i)?366:365;i=t/e}else n?xe(c)&&(i=366):(xe(c)&&a<2&&(i=366),xe(h)&&(l>1||1===l&&29===r)&&(i=366));d=e/i,u=t/i;break;case 2:d=e/360,u=t/360;break;case 3:d=e/365,u=t/365;break;case 4:31===s&&(s=30),31===r&&(r=30),d=c+(30*a+s)/360,u=h+(30*l+r)/360}return u-d}function Ie(e){return'"'===e[0]&&(e=e.slice(1)),'"'===e[e.length-1]&&"\\"!==e[e.length-2]?e.slice(0,e.length-1):e}function Te(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ae(e){const t=Array.isArray(e)?[]:{};switch(typeof e){case"object":if(null===e)return e;if(function(e){return"clone"in e&&e.clone instanceof Function}(e))return e.clone();if(!(function(e){return"object"==typeof e&&(null==e?void 0:e.constructor)===Object}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");for(const i in e)t[i]=Ae(e[i]);return t;case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function Oe(e){return e.startsWith("'")&&(e=e.slice(1,-1).replace(/''/g,"'")),e}function Ne(e){var t;return(null===(t=e.match(/\w/g))||void 0===t?void 0:t.length)!==e.length&&(e=`'${e}'`),e}function Me(e,t,i){return e<t?t:e>i?i:e}function _e(e,t,i){const n=De(i);if(Fe[n]||(Fe[n]={}),void 0===Fe[n][t]){e.save(),e.font=n;const i=e.measureText(t).width;e.restore(),Fe[n][t]=i}return Fe[n][t]}const Fe={};function De(e){return`${e.italic?"italic ":""}${e.bold?"bold":W} ${ke(e)}px ${q}`}function ke(e){const t=e.fontSize||G;if(!re[t])throw new Error("Size of the font is not supported");return re[t]}function $e(e,t,i=1){if(t<=e&&i>0)return[];if(0===i)throw new Error("range() step must not be zero");const n=Math.ceil(Math.abs((t-e)/i)),o=Array(n);for(let t=0;t<n;t++)o[t]=e+t*i;return o}function Le(e){return e.reduce(((e,t,i,n)=>{if(1===Math.abs(t-n[i-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*Pe(e,t){t.next();for(const i of e){const e=t.next();yield{...i,next:e.done?void 0:e.value}}}function Ue(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}function Ve(e){return null!==ve(e)}const ze=/^\[(.+)\]\((.+)\)$/,Be=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function He(e){return ze.test(e)}function We(e,t){return`[${e}](${t})`}function Ge(e){const t=e.match(ze)||[],i=t[1],n=t[2];if(!i||!n)throw new Error(`Could not parse markdown link ${e}.`);return{label:i,url:n}}const qe="o-spreadsheet://";function Ze(e){if(!He(e))return!1;const{url:t}=Ge(e);return t.startsWith(qe)}function je(e){return`${qe}${e}`}function Ye(e){if(e.startsWith(qe))return e.substr(qe.length);throw new Error(`${e} is not a valid sheet link`)}function Xe(e){return void 0!==e}function Ke(e){return void 0!==e&&""!==e}function Qe(e){return void 0===e||Object.values(e).every((e=>"object"==typeof e?Qe(e):!e))}function Je(e,t){for(let[i,n]of Object.entries(t))if(ot(n,e))return parseInt(i,10);const i=Object.keys(t),n=0===i.length?0:lt(i.map((e=>parseInt(e,10))));return t[n+1]=e,n+1}function et(e){let t="";for(let i=0,n=e.length;i<n;i++)t+=e[i];return t}function tt(e){let t,i=!1;const n=()=>(i||(t=e instanceof Function?e():e,i=!0),t);return n.map=e=>tt((()=>e(n()))),n}function it(e,t){let i=e.slice(t).find((e=>e));return i||(i=e.slice(0,t).reverse().find((e=>e))),i||""}function nt(e,t){return"after"===e?t+1:t}function ot(e,t){if(e===t)return!0;if(e&&!t||t&&!e)return!1;if(typeof e!=typeof t)return!1;if("object"!=typeof e)return!1;const i=new Set;Object.keys(e).forEach((e=>i.add(e))),Object.keys(t).forEach((e=>i.add(e)));for(let n of i){if(typeof e[n]!=typeof e[n])return!1;if("object"==typeof e[n]){if(!ot(e[n],t[n]))return!1}else if(e[n]!==t[n])return!1}return!0}function st(e,t){if(e.length<t.length)return!1;const i=new Set(e);return t.every((e=>i.has(e)))}function rt(e){const t={...e};return Object.keys(t).forEach((e=>!t[e]&&delete t[e])),t}function at(e){return e?e.toLowerCase():""}function lt(e){let t=e.length;if(t<1e5)return Math.max(...e);let i=-1/0;for(;t--;)i=e[t]>i?e[t]:i;return i}function ct(e){let t=e.length;if(t<1e5)return Math.min(...e);let i=1/0;for(;t--;)i=e[t]<i?e[t]:i;return i}const ht=/rgba?\(|\s+|\)/gi,dt=/^#([A-F\d]{2}){3,4}$/g,ut=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function gt(e){return mt(e.toString(16).padStart(6,"0"))}let pt=0;function mt(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(ht,"").split(",");let i=255;if(3!==t.length&&4!==t.length)throw new Error("invalid color");if(4===t.length){const e=parseFloat(t.pop()||"1");i=Math.round(255*(e||1))}const n=t.map((e=>parseInt(e,10)));255!==i&&n.push(i);return"#"+et(n.map((e=>e.toString(16).padStart(2,"0")))).toUpperCase()}(e):(t=e.replace("#","").toUpperCase(),3!==t.length&&4!==t.length||(t=t.split("").reduce(((e,t)=>e+t+t),"")),t=`#${t}`),!t.match(dt))throw new Error(`invalid color input: ${e}`);return t}function ft(e){try{return mt(e),!0}catch(e){return!1}}const vt=e=>e>=0&&e<=255;function bt(e,t,i,n=1){if(!vt(e)||!vt(t)||!vt(i)||n<0||n>1)throw new Error(`Invalid RGBA values ${[e,t,i,n]}`);return{a:n,b:i,g:t,r:e}}function St(e){let{r:t,g:i,b:n}=Et(e);t/=255,i/=255,n/=255;const o=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return.2126*o(t)+.7152*o(i)+.0722*o(n)}function Ct(e){let t=e.r.toString(16),i=e.g.toString(16),n=e.b.toString(16),o=Math.round(255*e.a).toString(16);return 1==t.length&&(t="0"+t),1==i.length&&(i="0"+i),1==n.length&&(n="0"+n),1==o.length&&(o="0"+o),"ff"===o&&(o=""),("#"+t+i+n+o).toUpperCase()}function Et(e){let t,i,n,o;if(7===(e=mt(e)).length)t=parseInt(e[1]+e[2],16),i=parseInt(e[3]+e[4],16),n=parseInt(e[5]+e[6],16),o=255;else{if(9!==e.length)throw new Error("Invalid color");t=parseInt(e[1]+e[2],16),i=parseInt(e[3]+e[4],16),n=parseInt(e[5]+e[6],16),o=parseInt(e[7]+e[8],16)}return o=+(o/255).toFixed(3),{a:o,r:t,g:i,b:n}}function wt(e){(e={...e}).s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,i=t*(1-Math.abs(e.h/60%2-1)),n=e.l-t/2,o=0,s=0,r=0;return 0<=e.h&&e.h<60?(o=t,s=i,r=0):60<=e.h&&e.h<120?(o=i,s=t,r=0):120<=e.h&&e.h<180?(o=0,s=t,r=i):180<=e.h&&e.h<240?(o=0,s=i,r=t):240<=e.h&&e.h<300?(o=i,s=0,r=t):300<=e.h&&e.h<360&&(o=t,s=0,r=i),o=Math.round(255*(o+n)),s=Math.round(255*(s+n)),r=Math.round(255*(r+n)),{a:e.a,r:o,g:s,b:r}}function yt(e){const t=e.r/255,i=e.g/255,n=e.b/255;let o=Math.min(t,i,n),s=Math.max(t,i,n),r=s-o,a=0,l=0,c=0;return a=0==r?0:s==t?(i-n)/r%6:s==i?(n-t)/r+2:(t-i)/r+4,a=Math.round(60*a),a<0&&(a+=360),c=(s+o)/2,l=0==r?0:r/(1-Math.abs(2*c-1)),l=+(100*l).toFixed(1),c=+(100*c).toFixed(1),{a:e.a,h:a,s:l,l:c}}const xt=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),Rt=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),It=new RegExp(/^\$?([A-Z]{1,3})+$/,"i"),Tt=new RegExp(/^\$?([0-9]{1,7})+$/,"i"),At=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),Ot=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),Nt=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[xt.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 Mt(e){return At.test(e)}function _t(e){return Ot.test(e)}function Ft(e){return It.test(e)}function Dt(e){return Tt.test(e)}function kt(e){return Rt.test(e)}function $t(e){const t=e.split("!"),i=t.pop();return{sheetName:Oe(t.join("!"))||void 0,xc:i}}function Lt(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Lt(Math.floor(e/26)-1)+Lt(e%26)}function Pt(e){let t=0;const i=e.length;for(let n=0;n<i;n++){t+=(e.charCodeAt(n)-65+(n<i-1?1:0))*26**(i-n-1)}return t}function Ut(e){const t=(e=e.toUpperCase().trim()).match(xt);if(null!==t){const[i,n,o]=t;if(i===e){return{col:Pt(n),row:parseInt(o,10)-1}}}throw new Error(`Invalid cell description: ${e}`)}function Vt(e,t,i={colFixed:!1,rowFixed:!1}){return(i.colFixed?"$":"")+Lt(e)+(i.rowFixed?"$":"")+String(t+1)}const zt=140,Bt=20,Ht=.035;function Wt(e){return Bt+(zt-Bt)*Math.exp(-Ht*(e-1))}const Gt=20,qt=/(\d+?)(?=(\d{3})+(?!\d)|$)/g,Zt=/0/g,jt={0:s("January"),1:s("February"),2:s("March"),3:s("April"),4:s("May"),5:s("June"),6:s("July"),7:s("August"),8:s("September"),9:s("October"),10:s("November"),11:s("December")},Yt={0:s("Sunday"),1:s("Monday"),2:s("Tuesday"),3:s("Wednesday"),4:s("Thursday"),5:s("Friday"),6:s("Saturday")},Xt={};function Kt(e){let t=Xt[e];return void 0===t&&(t=function(e){if(""===e)throw new Error("A format cannot be empty");let t=0,i=[];for(;t<e.length;){let n;if("["===e.charAt(t)){if("$"!==e.charAt(t+1))throw new Error(`Currency formats have to be prefixed by a $: ${e}`);if(n=e.substring(t+1).indexOf("]")+t+2,0===n)throw new Error(`Invalid currency brackets format: ${e}`);const o=e.substring(t+2,n-1);if(o.includes("["))throw new Error(`Invalid currency format: ${e}`);i.push({type:"STRING",format:o})}else{const o=e.substring(t).indexOf("[");n=o>-1?o+t:e.length;const s=e.substring(t,n);s.match(Y)?i.push({type:"DATE",format:s}):i.push({type:"NUMBER",format:di(s)})}t=n}return i}(e),Xt[e]=t),t}function Qt(e,t){switch(typeof e){case"string":return e.includes('\\"')?e.replace(/\\"/g,'"'):e;case"boolean":return e?"TRUE":"FALSE";case"number":t||(t=ai(e));return function(e,t){if("DATE"===t[0].type)return oi(e,t[0].format);let i=e<0?"-":"";for(let n of t)switch(n.type){case"NUMBER":i+=Jt(Math.abs(e),n.format);break;case"STRING":i+=n.format}return i}(e,Kt(t));case"object":return"0"}}function Jt(e,t){t.isPercent&&(e*=100),e/=t.magnitude;let i=0;void 0!==t.decimalPart&&(i=t.decimalPart.length);const{integerDigits:n,decimalDigits:o}=ti(e,i);let s=function(e,t,i){var n;const o="0"===e?"":e;let s=o;const r=t.length-o.length;if(r>0){const e=(t.substring(0,r).match(Zt)||[]).length;s="0".repeat(e)+s}i&&(s=(null===(n=s.match(qt))||void 0===n?void 0:n.join(","))||s);return s}(n,t.integerPart,t.thousandsSeparator);return void 0!==t.decimalPart&&(s+="."+function(e,t){let i=e;if(t.length-e.length>0){const n=(t.substring(e.length,t.length+1).match(Zt)||[]).length;i+="0".repeat(n)}return i}(o||"",t.decimalPart)),t.isPercent&&(s+="%"),s}const ei=[];function ti(e,t=Gt){const i=e.toString();if(i.includes("e"))return function(e,t=Gt){let i=ei[t];i||(i=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),ei[t]=i);const[n,o]=i.format(e).split(".");return{integerDigits:n,decimalDigits:o}}(e,t);if(Number.isInteger(e))return{integerDigits:i,decimalDigits:void 0};const n=i.indexOf(".");let o=i.substring(0,n),s=i.substring(n+1);if(0===t)return Number(s[0])>=5&&(o=(Number(o)+1).toString()),{integerDigits:o,decimalDigits:void 0};if(s.length>t){const{integerDigits:e,decimalDigits:i}=function(e,t){var i;let n="0",o=e,s=e.slice(0,t);const r=t;if(Number(e[r])<5)return{integerDigits:n,decimalDigits:s};const a=(null===(i=s.match(ni))||void 0===i?void 0:i[0])||"",l=(Number(s)+1).toString(),c=s.slice(a.length),h=l.length>c.length;h&&!a?(n="1",o=void 0):o=h?a.slice(0,-1)+l:a+l;return{integerDigits:n,decimalDigits:o}}(s,t);s=i,"0"!==e&&(o=(Number(o)+Number(e)).toString())}return{integerDigits:o,decimalDigits:ii(s||"")}}function ii(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const ni=/^0+/;function oi(e,t){const i=Se(e),n=t.indexOf("h");let o="",s="";return n>0?(o=si(i,t.substring(0,n-1)),s=ri(i,t.substring(n))):0===n?s=ri(i,t):n<0&&(o=si(i,t)),o+(o&&s?" ":"")+s}function si(e,t){var i;const n=null===(i=t.match(/\/|-|\s/))||void 0===i?void 0:i[0];return(n?t.split(n):[t]).map((i=>{switch(i){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return Yt[e.getDay()].slice(0,3);case"dddd":return Yt[e.getDay()];case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return jt[e.getMonth()].slice(0,3);case"mmmm":return jt[e.getMonth()];case"mmmmm":return jt[e.getMonth()].slice(0,1);case"yy":const i=String(e.getFullYear()).replace("-","").padStart(2,"0");return i.slice(i.length-2);case"yyyy":return e.getFullYear();default:throw new Error(`invalid format: ${t}`)}})).join(n)}function ri(e,t){let i=t.split(/:|\s/);const n=e.getHours(),o="a"===i[i.length-1];let s=n,r="";return o&&(s=0===s?12:s>12?s-12:s,r=n>=12?" PM":" AM",i.pop()),i.map((i=>{switch(i){case"hhhh":return Math.floor((e.getTime()-le.getTime())/36e5).toString();case"hh":return s.toString().padStart(2,"0");case"mm":return e.getMinutes().toString().padStart(2,"0");case"ss":return e.getSeconds().toString().padStart(2,"0");default:throw new Error(`invalid format: ${t}`)}})).join(":")+r}function ai(e){let{decimalDigits:t}=ti(e,10);return t?"0."+"0".repeat(t.length):"0"}function li(e,t,i){const n=Kt(e||"#,##0"),o=[];for(let e=0;e<n.length;e++){const s=n[e];if("NUMBER"!==s.type){o.push(s);continue}o.push({...s,format:{...s.format,magnitude:t,decimalPart:void 0}}),o.push({type:"STRING",format:i});const r=n[e+1];"STRING"===(null==r?void 0:r.type)&&["k","m","b"].includes(r.format)&&e++}return gi(o)}function ci(e,t){var i;const n={...e},o=Math.sign(t),s=(null===(i=n.decimalPart)||void 0===i?void 0:i.length)||0,r=Math.min(Math.max(0,s+o),Gt);return n.decimalPart="0".repeat(r),""===n.decimalPart&&delete n.decimalPart,n}const hi=/,*?$/;function di(e){var t;if(function(e){return Boolean(e.replace(ui,""))}(e=e.trim()))throw new Error(`Invalid number format: ${e}`);const i=e.includes("%"),n=(null===(t=e.match(hi))||void 0===t?void 0:t[0])||"",o=n?1e3**n.length:1;let s=e.slice(0,e.length-(n.length||0));const r=s.includes(",");if(s.match(/\..*,/))throw new Error("A format can't contain ',' symbol in the decimal part");s=s.replace("%","").replace(",","");const a=s.match(/[\%|,]/);if(a)throw new Error(`A format can only contain a single '${a[0]}' symbol`);const[l,c]=s.split(".");if(c&&c.length>20)throw new Error("A format can't contain more than 20 decimal places");return void 0!==c?{integerPart:l,isPercent:i,thousandsSeparator:r,decimalPart:c,magnitude:o}:{integerPart:l,isPercent:i,thousandsSeparator:r,magnitude:o}}const ui=/[,#0.%]/g;function gi(e){let t="";for(let i of e){let e;switch(i.type){case"NUMBER":const t=i.format;e=t.integerPart,t.thousandsSeparator&&(e=e.slice(0,-3)+","+e.slice(-3)),void 0!==t.decimalPart&&(e+="."+t.decimalPart),t.isPercent&&(e+="%"),t.magnitude&&(e+=",".repeat(Math.log10(t.magnitude)/3));break;case"STRING":e=`[$${i.format}]`;break;case"DATE":e=i.format}t+=e}return t}const pi=/(^-?\d+(\.?\d*(e\d+)?)?|^-?\.\d+)(?!\w|!)/,mi="(\\s*(\\d+(,\\d{3,})*(\\.\\d*)?)|(\\.\\d+))(e(\\+|-)?\\d+)?(\\s*%)?",fi="(\\s*-)?",vi="(\\s*[\\$€])?",bi="^(("+[fi+vi+mi,fi+mi+vi,vi+fi+mi].join(")|(")+"))$",Si=new RegExp(bi,"i");function Ci(e){return!!e&&Si.test(e.trim())}const Ei=/[,\$€]+/g;function wi(e){e=e.replace(Ei,"");let t=Number(e);return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}function yi(e,t,i){const n=[...e].sort(((e,t)=>e-t));let o=(n.length+(i?-1:1))*t;if(i||o--,Number.isInteger(o))return n[o];const s=Math.ceil(o),r=Math.floor(o);return n[s]*(o-r)+n[r]*(s-o)}class xi{constructor(e,t){this.getSheetSize=t,this.prefixSheet=!1,this._zone=e.zone,this.parts=e.parts,this.prefixSheet=e.prefixSheet,this.invalidXc=e.invalidXc,this.sheetId=e.sheetId,this.invalidSheetName=e.invalidSheetName}static fromRange(e,t){return e instanceof xi?e:new xi(e,t.getSheetSize)}get unboundedZone(){return this._zone}get zone(){const{left:e,top:t,bottom:i,right:n}=this._zone;if(void 0!==n&&void 0!==i)return this._zone;if(void 0===i&&void 0!==n)return{right:n,top:t,left:e,bottom:this.getSheetSize(this.sheetId).height-1};if(void 0===n&&void 0!==i)return{bottom:i,left:e,top:t,right:this.getSheetSize(this.sheetId).width-1};throw new Error(s("Bad zone format"))}static getRangeParts(e,t){const i=e.split(":").map((e=>{const t=_t(e);return{colFixed:!t&&e.startsWith("$"),rowFixed:t?e.startsWith("$"):e.includes("$",1)}})),n=void 0===t.bottom,o=void 0===t.right;return n&&(i[0].rowFixed=i[0].rowFixed||i[1].rowFixed,i[1].rowFixed=i[0].rowFixed||i[1].rowFixed),o&&(i[0].colFixed=i[0].colFixed||i[1].colFixed,i[1].colFixed=i[0].colFixed||i[1].colFixed),i}get isFullCol(){return void 0===this._zone.bottom}get isFullRow(){return void 0===this._zone.right}get rangeData(){return{_zone:this._zone,_sheetId:this.sheetId}}orderZone(){if(void 0!==this._zone.right&&this._zone.right<this._zone.left){let e=this._zone.right;this._zone.right=this._zone.left,this._zone.left=e;let t=this.parts[1].colFixed;this.parts[1].colFixed=this.parts[0].colFixed,this.parts[0].colFixed=t}if(void 0!==this._zone.bottom&&this._zone.bottom<this._zone.top){let e=this._zone.bottom;this._zone.bottom=this._zone.top,this._zone.top=e;let t=this.parts[1].rowFixed;this.parts[1].rowFixed=this.parts[0].rowFixed,this.parts[0].rowFixed=t}}clone(e){return new xi({zone:(null==e?void 0:e.zone)?e.zone:{...this._zone},sheetId:(null==e?void 0:e.sheetId)?e.sheetId:this.sheetId,invalidSheetName:e&&"invalidSheetName"in e?e.invalidSheetName:this.invalidSheetName,invalidXc:e&&"invalidXc"in e?e.invalidXc:this.invalidXc,parts:(null==e?void 0:e.parts)?e.parts:this.parts.map((e=>({rowFixed:e.rowFixed,colFixed:e.colFixed}))),prefixSheet:(null==e?void 0:e.prefixSheet)?e.prefixSheet:this.prefixSheet},this.getSheetSize)}}function Ri(e,t,i){const n=i.sheetId===e?t:i.sheetId;return i.clone({sheetId:n})}function Ii(e,t,i){if(!i)return;const n=e.getRangeFromSheetXC(t,i);return n.invalidSheetName||n.invalidXc?void 0:n}function Ti(e){const t=[];for(let i=0;i<e;i++){const e={cells:{}};t.push(e)}return t}function Ai(e,t){return void 0!==e&&void 0!==t&&Oe(e.trim().toUpperCase())===Oe(t.trim().toUpperCase())}class Oi{constructor(){this.isFastIdStrategy=!1,this.fastIdStart=0}setIsFastStrategy(e){this.isFastIdStrategy=e}smallUuid(){return this.isFastIdStrategy?(this.fastIdStart++,String(this.fastIdStart)):window.crypto?"10000000-1000".replace(/[01]/g,(e=>{const t=Number(e);return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)})):"xxxxxxxx-xxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}uuidv4(){return this.isFastIdStrategy?(this.fastIdStart++,String(this.fastIdStart)):window.crypto?"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(e=>{const t=Number(e);return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/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 Ni(e){const t=function(e){const t=(e=e.split("!").pop()).replace(/\$/g,"").split(":").map((e=>e.trim()));let i,n,o,s,r=!1,a=!1,l=!1;const c=t[0],h=t[1]&&t[1];if(Mt(c))o=s=Pt(c),i=n=0,r=!0;else if(_t(c))i=n=parseInt(c,10)-1,o=s=0,a=!0;else{const e=Ut(c);o=s=e.col,i=n=e.row,l=!0}if(2===t.length)if(Mt(h))s=Pt(h),r=!0;else if(_t(h))n=parseInt(h,10)-1,a=!0;else{const e=Ut(h);s=e.col,n=e.row,i=r?n:i,o=a?s:o,l=!0}if(r&&a)throw new Error("Wrong zone xc. The zone cannot be at the same time a full column and a full row");const d={top:i,left:o,bottom:r?void 0:n,right:a?void 0:s};return l=l&&(a||r),l&&(d.hasHeader=l),d}(e);return function(e){if(void 0!==e.right&&e.right<e.left){const t=e.left;e.left=e.right,e.right=t}if(void 0!==e.bottom&&e.bottom<e.top){const t=e.top;e.top=e.bottom,e.bottom=t}}(t),t}function Mi(e){const t=Ni(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function _i(e){const{bottom:t,top:i,left:n,right:o}=e;return!(void 0!==t&&isNaN(t)||isNaN(i)||isNaN(n)||void 0!==o&&isNaN(o))&&((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 Fi(e){const{top:t,bottom:i,left:n,right:o}=e,r="hasHeader"in e&&e.hasHeader,a=t===i&&n===o;if(void 0===i&&void 0!==o)return 0!==t||r?`${Vt(n,t)}:${Lt(o)}`:`${Lt(n)}:${Lt(o)}`;if(void 0===o&&void 0!==i)return 0!==n||r?`${Vt(n,t)}:${i+1}`:`${t+1}:${i+1}`;if(void 0!==i&&void 0!==o)return a?Vt(n,t):`${Vt(n,t)}:${Vt(o,i)}`;throw new Error(s("Bad zone format"))}function Di(e,t,i,n,o){const s="left"===t?"columns":"rows",r="before"===n?i-1:i,a=e["left"===t?"right":"bottom"];return e[t]<=r&&a&&a>r?Yi(e,s,"RESIZE",o):r<e[t]?Yi(e,s,"MOVE",o):{...e}}function ki(e,t,i,n,o){const s="left"===t?"columns":"rows",r="before"===n?i-1:i,a="left"===t?"right":"bottom";return e[t]<=r&&e[a]>r?Yi(e,s,"RESIZE",o):r<e[t]?Yi(e,s,"MOVE",o):{...e}}function $i(e,t,i){const n="left"===t?"right":"bottom";let o=e[t],s=e[n];for(let r of i.sort(((e,t)=>t-e)))e[t]>r&&(o--,s--),e[t]<r&&e[n]>=r&&s--;return{...e,[t]:o,[n]:s}}function Li(e,t,i){const n="left"===t?"right":"bottom";let o=e[t],s=e[n];const r=e[n];for(let n of i.sort(((e,t)=>t-e)))e[t]>n&&(o--,void 0!==s&&s--),void 0!==r&&void 0!==s&&e[t]<=n&&r>=n&&s--;if(!(void 0!==s&&o>s))return{...e,[t]:o,[n]:s}}function Pi(...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 Ui(e,t){if(zi(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 Vi(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function zi(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function Bi(e,t,i){const{left:n,right:o,top:s,bottom:r}=i;return e>=n&&e<=o&&t>=s&&t<=r}function Hi(e,t){return Vi(Pi(t,e),t)}function Wi(e,t){const i=e.map(Ni),n=t.map(Mi),o=Math.max(...i.concat(n).map((e=>e.bottom||0))),s=Math.max(...i.concat(n).map((e=>e.right||0))),r=i.map((e=>({...e,bottom:void 0===e.bottom?o+1:e.bottom,right:void 0===e.right?s+1:e.right}))),a=n.map((e=>({...e,bottom:void 0===e.bottom?o+1:e.bottom,right:void 0===e.right?s+1:e.right}))),l=function(e,t){const i=new Set(t.map((({col:e,row:t})=>`${e}-${t}`)));return e.filter((({col:e,row:t})=>!i.has(`${e}-${t}`)))}(r.map(ji).flat(),a.map(ji).flat()),c=function(e){if(0===e.length)return[];const[t,...i]=[...e].sort(((e,t)=>e.row-t.row)).sort(((e,t)=>e.col-t.col)),n=[];let o=Qi(t);for(const{col:e,row:t}of i)if(!Bi(e,t,o))if(e===o.left&&t===o.bottom+1){const e=o.bottom+1;o={...o,bottom:e}}else n.push(o),o=Qi({col:e,row:t});return[...n,o]}(l);return function(e){if(0===e.length)return[];if(e.some((e=>e.left!==e.right)))throw new Error("only columns can be merged");const t=[],i=Gi(e),n=(e,t)=>e.top===t.top&&e.bottom===t.bottom&&e.right+1===t.left;for(;i.length;){const e=i.reduce(((e,t)=>n(e,t)?Pi(e,t):e),i.shift());t.push(e)}return Gi(t)}(c).map((e=>({...e,bottom:e.bottom===o+1?void 0:e.bottom,right:e.right===s+1?void 0:e.right}))).map(Fi)}function Gi(e){const t=[...e].sort(((e,t)=>t.right-e.right)).sort(((e,t)=>t.bottom-e.bottom)).sort(((e,t)=>e.top-t.top)).sort(((e,t)=>e.left-t.left)).reverse(),i=[];for(;0!==t.length;){const e=t.shift();t.some((t=>Hi(e,t)))||i.push(e)}return i.reverse()}function qi(e){return{height:e.bottom-e.top+1,width:e.right-e.left+1}}function Zi(e){const{width:t,height:i}=qi(e);return 1===t||1===i}function ji(e){const t=[],[i,n]=[e.right,e.left].sort(((e,t)=>e-t)),[o,s]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of $e(i,n+1))for(const i of $e(o,s+1))t.push({col:e,row:i});return t}function Yi(e,t,i,n){const o="both"===t?n[0]:"columns"===t?n:0,s="both"===t?n[1]:"rows"===t?n:0,r="hasHeader"in e&&e.hasHeader;let a;a=!function(e){return void 0===e.bottom}(e)||r?!(Ji(e)&&!r)||"columns"!==t:"rows"!==t;const l={...e};return a&&"MOVE"===i&&(l.left+=o,l.top+=s),void 0!==l.right&&(l.right+=o),void 0!==l.bottom&&(l.bottom+=s),l}function Xi(e,t){let i,n;const{left:o,right:s,top:r,bottom:a}=e,{left:l,right:c,top:h,bottom:d}=t;return i=l!=o?l:c!=s?c:l,n=h!=r?h:d!=a?d:h,{col:i,row:n}}function Ki(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 Qi(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function Ji(e){return void 0===e.right}function en(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function tn(...e){return e.length<2||1===Wi(e.map(Fi),[]).length}class nn{constructor(){this.content={}}add(e,t){return this.content[e]=t,this}get(e){const t=this.content[e];if(!t&&!(e in this.content))throw new Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}}const on=new nn,sn=new nn;class rn extends t.Component{constructor(){super(...arguments),this.canvas=t.useRef("graphContainer")}get background(){return this.chartRuntime.background}get canvasStyle(){return`background-color: ${this.background}`}get chartRuntime(){const e=this.env.model.getters.getChartRuntime(this.props.figure.id);if(!("chartJsConfig"in e))throw new Error("Unsupported chart runtime");return e}setup(){t.onMounted((()=>{const e=this.chartRuntime;this.createChart(e.chartJsConfig)}));let e=this.chartRuntime;t.onPatched((()=>{const t=this.chartRuntime;ot(e,t)||(this.updateChartJs(t),e=t)}))}createChart(e){const t=this.canvas.el.getContext("2d");this.chart=new window.Chart(t,e)}updateChartJs(e){var t,i,n,o;const s=e.chartJsConfig;s.data&&s.data.datasets?(this.chart.data=s.data,(null===(t=s.options)||void 0===t?void 0:t.title)&&(this.chart.config.options.title=s.options.title),s.options&&"valueLabel"in s.options&&(null===(i=s.options)||void 0===i?void 0:i.valueLabel)&&(this.chart.config.options.valueLabel=s.options.valueLabel)):this.chart.data.datasets=void 0,this.chart.config.options.legend=null===(n=s.options)||void 0===n?void 0:n.legend,this.chart.config.options.scales=null===(o=s.options)||void 0===o?void 0:o.scales,this.chart.update({duration:0})}}rn.template="o-spreadsheet-ChartJsComponent",sn.add("line",rn),sn.add("bar",rn),sn.add("pie",rn),sn.add("gauge",rn);const an=new nn;var ln;an.add("INCREMENT_MODIFIER",{apply:(e,t)=>{var i;e.current+=e.increment;const n=e.current.toString(),o=Qt(e.current,null===(i=t.cell)||void 0===i?void 0:i.format);return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:n},tooltip:n?{props:{content:o}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,i)=>{var n,o;const s=(null===(n=t.cell)||void 0===n?void 0:n.content)||"";return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:s},tooltip:s?{props:{content:null===(o=t.cell)||void 0===o?void 0:o.formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,i,n)=>{e.current+=e.increment;let o=0,s=0;switch(n){case"up":o=0,s=-e.current;break;case"down":o=0,s=e.current;break;case"left":o=-e.current,s=0;break;case"right":o=e.current,s=0}if(!t.cell||!t.cell.isFormula())return{cellData:{}};const r=t.sheetId,a=i.createAdaptedRanges(t.cell.dependencies,o,s,r),l=i.buildFormulaContent(r,t.cell,a);return{cellData:{border:t.border,style:t.cell.style,format:t.cell.format,content:l},tooltip:l?{props:{content:l}}:void 0}}}),function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(ln||(ln={}));const cn=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),hn=new Set([...cn,"DUPLICATE_SHEET","EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT"]),dn=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"]),un=new Set(["UPDATE_CELL","UPDATE_CELL_POSITION","CLEAR_CELL","DELETE_CONTENT","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","RESIZE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","UNHIDE_COLUMNS_ROWS","SET_GRID_LINES_VISIBILITY","UNFREEZE_COLUMNS","UNFREEZE_ROWS","FREEZE_COLUMNS","FREEZE_ROWS","UNFREEZE_COLUMNS_ROWS","ADD_MERGE","REMOVE_MERGE","CREATE_SHEET","DELETE_SHEET","DUPLICATE_SHEET","MOVE_SHEET","RENAME_SHEET","HIDE_SHEET","SHOW_SHEET","MOVE_RANGES","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT","CREATE_FIGURE","DELETE_FIGURE","UPDATE_FIGURE","SET_FORMATTING","CLEAR_FORMATTING","SET_BORDER","CREATE_CHART","UPDATE_CHART","CREATE_FILTER_TABLE","REMOVE_FILTER_TABLE"]);function gn(e){return un.has(e.type)}class pn{constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return mn}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}const mn=new pn;var fn,vn,bn;e.CommandResult=void 0,(fn=e.CommandResult||(e.CommandResult={}))[fn.Success=0]="Success",fn[fn.CancelledForUnknownReason=1]="CancelledForUnknownReason",fn[fn.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",fn[fn.MergeIsDestructive=3]="MergeIsDestructive",fn[fn.CellIsMerged=4]="CellIsMerged",fn[fn.InvalidTarget=5]="InvalidTarget",fn[fn.EmptyUndoStack=6]="EmptyUndoStack",fn[fn.EmptyRedoStack=7]="EmptyRedoStack",fn[fn.NotEnoughElements=8]="NotEnoughElements",fn[fn.NotEnoughSheets=9]="NotEnoughSheets",fn[fn.MissingSheetName=10]="MissingSheetName",fn[fn.DuplicatedSheetName=11]="DuplicatedSheetName",fn[fn.DuplicatedSheetId=12]="DuplicatedSheetId",fn[fn.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",fn[fn.WrongSheetMove=14]="WrongSheetMove",fn[fn.WrongSheetPosition=15]="WrongSheetPosition",fn[fn.InvalidAnchorZone=16]="InvalidAnchorZone",fn[fn.SelectionOutOfBound=17]="SelectionOutOfBound",fn[fn.TargetOutOfSheet=18]="TargetOutOfSheet",fn[fn.WrongCutSelection=19]="WrongCutSelection",fn[fn.WrongPasteSelection=20]="WrongPasteSelection",fn[fn.WrongPasteOption=21]="WrongPasteOption",fn[fn.WrongFigurePasteOption=22]="WrongFigurePasteOption",fn[fn.EmptyClipboard=23]="EmptyClipboard",fn[fn.EmptyRange=24]="EmptyRange",fn[fn.InvalidRange=25]="InvalidRange",fn[fn.InvalidZones=26]="InvalidZones",fn[fn.InvalidSheetId=27]="InvalidSheetId",fn[fn.InvalidCellId=28]="InvalidCellId",fn[fn.InputAlreadyFocused=29]="InputAlreadyFocused",fn[fn.MaximumRangesReached=30]="MaximumRangesReached",fn[fn.InvalidInputId=31]="InvalidInputId",fn[fn.InvalidChartDefinition=32]="InvalidChartDefinition",fn[fn.InvalidDataSet=33]="InvalidDataSet",fn[fn.InvalidLabelRange=34]="InvalidLabelRange",fn[fn.InvalidScorecardKeyValue=35]="InvalidScorecardKeyValue",fn[fn.InvalidScorecardBaseline=36]="InvalidScorecardBaseline",fn[fn.InvalidGaugeDataRange=37]="InvalidGaugeDataRange",fn[fn.EmptyGaugeRangeMin=38]="EmptyGaugeRangeMin",fn[fn.GaugeRangeMinNaN=39]="GaugeRangeMinNaN",fn[fn.EmptyGaugeRangeMax=40]="EmptyGaugeRangeMax",fn[fn.GaugeRangeMaxNaN=41]="GaugeRangeMaxNaN",fn[fn.GaugeRangeMinBiggerThanRangeMax=42]="GaugeRangeMinBiggerThanRangeMax",fn[fn.GaugeLowerInflectionPointNaN=43]="GaugeLowerInflectionPointNaN",fn[fn.GaugeUpperInflectionPointNaN=44]="GaugeUpperInflectionPointNaN",fn[fn.GaugeLowerBiggerThanUpper=45]="GaugeLowerBiggerThanUpper",fn[fn.InvalidAutofillSelection=46]="InvalidAutofillSelection",fn[fn.WrongComposerSelection=47]="WrongComposerSelection",fn[fn.MinBiggerThanMax=48]="MinBiggerThanMax",fn[fn.LowerBiggerThanUpper=49]="LowerBiggerThanUpper",fn[fn.MidBiggerThanMax=50]="MidBiggerThanMax",fn[fn.MinBiggerThanMid=51]="MinBiggerThanMid",fn[fn.FirstArgMissing=52]="FirstArgMissing",fn[fn.SecondArgMissing=53]="SecondArgMissing",fn[fn.MinNaN=54]="MinNaN",fn[fn.MidNaN=55]="MidNaN",fn[fn.MaxNaN=56]="MaxNaN",fn[fn.ValueUpperInflectionNaN=57]="ValueUpperInflectionNaN",fn[fn.ValueLowerInflectionNaN=58]="ValueLowerInflectionNaN",fn[fn.MinInvalidFormula=59]="MinInvalidFormula",fn[fn.MidInvalidFormula=60]="MidInvalidFormula",fn[fn.MaxInvalidFormula=61]="MaxInvalidFormula",fn[fn.ValueUpperInvalidFormula=62]="ValueUpperInvalidFormula",fn[fn.ValueLowerInvalidFormula=63]="ValueLowerInvalidFormula",fn[fn.InvalidSortZone=64]="InvalidSortZone",fn[fn.WaitingSessionConfirmation=65]="WaitingSessionConfirmation",fn[fn.MergeOverlap=66]="MergeOverlap",fn[fn.TooManyHiddenElements=67]="TooManyHiddenElements",fn[fn.Readonly=68]="Readonly",fn[fn.InvalidViewportSize=69]="InvalidViewportSize",fn[fn.InvalidScrollingDirection=70]="InvalidScrollingDirection",fn[fn.FigureDoesNotExist=71]="FigureDoesNotExist",fn[fn.InvalidConditionalFormatId=72]="InvalidConditionalFormatId",fn[fn.InvalidCellPopover=73]="InvalidCellPopover",fn[fn.EmptyTarget=74]="EmptyTarget",fn[fn.InvalidFreezeQuantity=75]="InvalidFreezeQuantity",fn[fn.FrozenPaneOverlap=76]="FrozenPaneOverlap",fn[fn.ValuesNotChanged=77]="ValuesNotChanged",fn[fn.InvalidFilterZone=78]="InvalidFilterZone",fn[fn.FilterOverlap=79]="FilterOverlap",fn[fn.FilterNotFound=80]="FilterNotFound",fn[fn.MergeInFilter=81]="MergeInFilter",fn[fn.NonContinuousTargets=82]="NonContinuousTargets",fn[fn.DuplicatedFigureId=83]="DuplicatedFigureId",fn[fn.InvalidSelectionStep=84]="InvalidSelectionStep",fn[fn.DuplicatedChartId=85]="DuplicatedChartId",fn[fn.ChartDoesNotExist=86]="ChartDoesNotExist",fn[fn.InvalidHeaderIndex=87]="InvalidHeaderIndex",fn[fn.InvalidQuantity=88]="InvalidQuantity",fn[fn.NoChanges=89]="NoChanges",function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(vn||(vn={})),function(e){e[e.Background=0]="Background",e[e.Highlights=1]="Highlights",e[e.Clipboard=2]="Clipboard",e[e.Search=3]="Search",e[e.Chart=4]="Chart",e[e.Selection=5]="Selection",e[e.Autofill=6]="Autofill",e[e.Headers=7]="Headers"}(bn||(bn={}));const Sn=new nn;Sn.add("simple_value_copy",{condition:(e,t)=>{var i;return 1===t.length&&!e.isFormula()&&!(null===(i=e.format)||void 0===i?void 0:i.match(Y))},generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("copy_text",{condition:e=>!e.isFormula()&&e.evaluated.type===ln.text,generateRule:()=>({type:"COPY_MODIFIER"}),sequence:20}).add("update_formula",{condition:e=>e.isFormula(),generateRule:(e,t)=>({type:"FORMULA_MODIFIER",increment:t.length,current:0}),sequence:30}).add("increment_number",{condition:e=>e.evaluated.type===ln.number,generateRule:(e,t,i)=>{const n=function(e,t){let i=[],n=!1;for(let o of t)if(o===e&&(n=!0),(null==o?void 0:o.evaluated.type)===ln.number)i.push(o.evaluated.value);else{if(n)return i;i=[]}return i}(e,t);let o=1;return 1===n.length&&["up","left"].includes(i)?o=-1:2==n.length?o=2*(n[1]-n[0]):n.length>2&&(o=function(e){const t=[];let i=e[0];for(let n=1;n<e.length;n++){const o=e[n];t.push(o-i),i=o}return t.reduce(((e,t)=>e+t),0)/t.length}(n)*n.length),{type:"INCREMENT_MODIFIER",increment:o,current:e.evaluated.type===ln.number?e.evaluated.value:0}},sequence:40});const Cn={};let En=0;function wn(e,...t){const i="__sheet__"+En++;return function(e,t){const i=document.createElement("style");i.textContent=function(e){const t=e.split(/(\{|\}|;)/).map((e=>e.trim())),i=[],n=[];let o=[];function s(e,t){const n=[];for(const o of i[e]){let r=t&&t+" "+o||o;r.includes("&")&&(r=o.replace(/&/g,t||"")),e<i.length-1&&(r=s(e+1,r)),n.push(r)}return n.join(", ")}function r(){o.length&&(n.push(s(0)+" {"),n.push(...o),n.push("}"),o=[])}for(;t.length;){let e=t.shift();"}"===e?(r(),i.pop()):("{"===t[0]&&(r(),i.push(e.split(/\s*,\s*/)),t.shift()),";"===t[0]&&o.push(" "+e+";"))}return n.join("\n")}(t),Cn[e]=i}(i,String.raw(e,...t)),function(e){const t=Cn[e];t.setAttribute("component",e),document.head.appendChild(t)}(i),i}function yn({strikethrough:e,underline:t}){return e||t?`${e?"line-through":""} ${t?"underline":""}`:"none"}function xn(e){return"\n"+Object.entries(e).map((([e,t])=>`${e}: ${t};`)).join("\n")+"\n"}wn`
1
+ !function(e,t){"use strict";let i=e=>e;function n(e,...t){if(1===t.length&&"object"==typeof t[0]){const i=t[0];e=e.replace(/\%\(?([^\)]+)\)s/g,((e,t)=>i[t]))}else t.length>0&&(e=e.replace(/\%s/g,(()=>t.shift())));return e}const o=function(e,...t){return n(i(e),...t)},s=function(e,...t){return new r(e,t)};class r extends String{constructor(e,t){super(e),this.values=t}valueOf(){const e=super.valueOf();return n(i(e),...this.values)}toString(){return this.valueOf()}}var a,l;!function(e){e.NotAvailable="#N/A",e.InvalidReference="#REF",e.BadExpression="#BAD_EXPR",e.CircularDependency="#CYCLE",e.UnknownFunction="#NAME?",e.GenericError="#ERROR"}(a||(a={})),function(e){e[e.silent=0]="silent",e[e.error=1]="error"}(l||(l={}));class c extends Error{constructor(e,t,i=l.error){super(t),this.errorType=e,this.logLevel=i}}class h extends c{constructor(e){super(a.BadExpression,e)}}class d extends c{constructor(){super(a.CircularDependency,s("Circular reference"))}}class u extends c{constructor(){super(a.InvalidReference,s("Invalid reference"))}}class g extends c{constructor(){super(a.NotAvailable,s("Data not available"),l.silent)}}class p extends c{constructor(e){super(a.UnknownFunction,s('Unknown function: "%s"',e))}}const m=.5,f="#f5f5f5",v="#F8F9FA",b="#E8EAED",S="#595959",C="#666666",E="#3266ca",w="#FFFFFF",y="#CACACA",x=11982760,R="#01666b",I="#188038",T="#E6F4EA",A="#CEEAD6",N=["#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"],O=26,M=48,_=96,F=23,D=15,k=18,$=14,L=4,P=4,U=3,V=P,z=17,B=250,H=1,W="400",G=10,q="'Roboto', arial",Z=["thin","#000"],j=["thin",I],Y=/[ymdhs:]/,X=a.InvalidReference,K="START_REVISION",Q=20,J=.4,ee=["'","*","?","/","\\","[","]"],te=/'|\*|\?|\/|\\|\[|\]/,ie="|",ne=s("Invalid expression");var oe;!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.ColorPicker=25]="ColorPicker",e[e.IconPicker=25]="IconPicker",e[e.TopBarComposer=30]="TopBarComposer",e[e.Popover=35]="Popover",e[e.ChartAnchor=1e3]="ChartAnchor"}(oe||(oe={}));const se=[{pt:7.5,px:10},{pt:8,px:11},{pt:9,px:12},{pt:10,px:13},{pt:10.5,px:14},{pt:11,px:15},{pt:12,px:16},{pt:14,px:18.7},{pt:15,px:20},{pt:16,px:21.3},{pt:18,px:24},{pt:22,px:29.3},{pt:24,px:32},{pt:26,px:34.7},{pt:36,px:48}],re={};for(let e of se)re[e.pt]=e.px;class ae{constructor(e,t,i,n=0,o=0,s=0){this.jsDate=new Date(Date.UTC(e,t,i,n,o,s,0))}static fromTimestamp(e){const t=new Date(e);return new ae(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds())}static now(){const e=new Date;return new ae(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds())}toString(){return this.jsDate.toString()}getTime(){return this.jsDate.getTime()}getFullYear(){return this.jsDate.getUTCFullYear()}getMonth(){return this.jsDate.getUTCMonth()}getDate(){return this.jsDate.getUTCDate()}getDay(){return this.jsDate.getUTCDay()}getHours(){return this.jsDate.getUTCHours()}getMinutes(){return this.jsDate.getUTCMinutes()}getSeconds(){return this.jsDate.getUTCSeconds()}setFullYear(e){this.jsDate.setFullYear(e)}setDate(e){this.jsDate.setUTCDate(e)}setHours(e){this.jsDate.setUTCHours(e)}setMinutes(e){this.jsDate.setUTCMinutes(e)}setSeconds(e){this.jsDate.setUTCSeconds(e)}}const le=new ae(1899,11,30),ce=864e5,he=2e3,de=ae.now().getFullYear(),ue=ae.fromTimestamp(0).getTime()-le.getTime(),ge=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,pe=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,me=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/,fe={};function ve(e){if(fe[e])return fe[e];const t=function(e){let t;e=e.trim();const i=e.match(me);if(i){if(t=function(e){if(e=e.trim(),me.test(e)){const t=/AM/i.test(e),i=/PM/i.test(e),n=(t||i?e.substring(0,e.length-2).trim():e).split(/:/),o=n.length>=2,s=3===n.length;let r=Number(n[0]),a=o?Number(n[1]):0,l=s?Number(n[2]):0,c=s?"hh:mm:ss":"hh:mm";if(t||i)c+=" a";else if(!o)return null;r>=12&&t?r-=12:r<12&&i&&(r+=12),a+=Math.floor(l/60),l%=60,r+=Math.floor(a/60),a%=60,r>=24&&(c="hhhh:mm:ss");return{value:r/24+a/1440+l/86400,format:c,jsDate:new ae(1899,11,30,r,a,l)}}return null}(i[0]),null===t)return null;e=e.replace(i[0],"").trim()}let n;const o=e.match(ge),s=e.match(pe);if(o||s){let t;if(o?(t=o[0],n=be(t,"mdy")):(t=s[0],n=be(t,"ymd")),null===n)return null;e=e.replace(t,"").trim()}if(""!==e||!n&&!t)return null;if(n&&t)return{value:n.value+t.value,format:n.format+" "+("hhhh:mm:ss"===t.format?"hh:mm:ss":t.format),jsDate:new ae(n.jsDate.getFullYear()+t.jsDate.getFullYear()-1899,n.jsDate.getMonth()+t.jsDate.getMonth()-11,n.jsDate.getDate()+t.jsDate.getDate()-30,n.jsDate.getHours()+t.jsDate.getHours(),n.jsDate.getMinutes()+t.jsDate.getMinutes(),n.jsDate.getSeconds()+t.jsDate.getSeconds())};return n||t}(e);return fe[e]=t,t}function be(e,t){const i="mdy"===t;if(i||"ymd"===t){const t=e.split(/\/|-|\s/),n=i?0:1,o=i?1:2,s=i?2:0,r=Number(t[n]),a=Number(t[o]),l=2===t[n].length&&r<10||2===t[o].length&&a<10,c=t[s]?function(e){const t=Number(e);switch(e.length){case 1:return he+t;case 2:return he+(he+t>de+10?-100:0)+t;case 3:case 4:return t}return 0}(t[s]):de,h=new ae(c,r-1,a),d=e.match(/\/|-|\s/)[0];if(h.getMonth()!==r-1||h.getDate()!==a)return null;const u=h.getTime()-le.getTime();let g=l?`mm${d}dd`:`m${d}d`;return t[s]&&(g=i?g+d+"yyyy":"yyyy"+d+g),{value:Math.round(u/ce),format:g,jsDate:h}}return null}function Se(e){const t=Math.trunc(e);let i=ae.fromTimestamp(t*ce-ue),n=e-t;n=n<0?1+n:n;const o=Math.round(24*n),s=Math.round(24*(n-o/24)*60),r=Math.round(24*(n-o/24-s/24/60)*60*60);return i.setHours(o),i.setMinutes(s),i.setSeconds(r),i}function Ce(e){const t=e.getTime()-le.getTime();return Math.round(t/ce)}function Ee(e){return new ae(e.getFullYear(),e.getMonth()+1,0).getDate()}function we(e){return Ee(e)===e.getDate()}function ye(e,t,i){const n=e.getFullYear(),o=e.getMonth(),s=e.getDate(),r=new ae(n,o+t,1);return i&&s===Ee(e)||s>Ee(r)?r.setDate(Ee(r)):r.setDate(s),r}function xe(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function Re(e,t,i){if(e===t)return 0;if(e>t){const i=t;t=e,e=i}const n=Se(e),o=Se(t);let s=n.getDate(),r=o.getDate();const a=n.getMonth(),l=o.getMonth(),c=n.getFullYear(),h=o.getFullYear();let d=0,u=0;switch(i){case 0:31===s&&(s=30),30===s&&31===r&&(r=30),1===a&&s===(xe(c)?29:28)&&(s=30,1===l&&r===(xe(h)?29:28)&&(r=30)),d=c+(30*a+s)/360,u=h+(30*l+r)/360;break;case 1:let i=365;const n=c===h;if(!n&&!(c+1===h)||!n&&a<l||!n&&a===l&&s<r){let e=0,t=0;for(let i=c;i<=h;i++)e++,t+=xe(i)?366:365;i=t/e}else n?xe(c)&&(i=366):(xe(c)&&a<2&&(i=366),xe(h)&&(l>1||1===l&&29===r)&&(i=366));d=e/i,u=t/i;break;case 2:d=e/360,u=t/360;break;case 3:d=e/365,u=t/365;break;case 4:31===s&&(s=30),31===r&&(r=30),d=c+(30*a+s)/360,u=h+(30*l+r)/360}return u-d}function Ie(e){return'"'===e[0]&&(e=e.slice(1)),'"'===e[e.length-1]&&"\\"!==e[e.length-2]?e.slice(0,e.length-1):e}function Te(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ae(e){const t=Array.isArray(e)?[]:{};switch(typeof e){case"object":if(null===e)return e;if(function(e){return"clone"in e&&e.clone instanceof Function}(e))return e.clone();if(!(function(e){return"object"==typeof e&&(null==e?void 0:e.constructor)===Object}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");for(const i in e)t[i]=Ae(e[i]);return t;case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function Ne(e){return e.startsWith("'")&&(e=e.slice(1,-1).replace(/''/g,"'")),e}function Oe(e){var t;return(null===(t=e.match(/\w/g))||void 0===t?void 0:t.length)!==e.length&&(e=`'${e}'`),e}function Me(e,t,i){return e<t?t:e>i?i:e}function _e(e,t,i){const n=De(i);if(Fe[n]||(Fe[n]={}),void 0===Fe[n][t]){e.save(),e.font=n;const i=e.measureText(t).width;e.restore(),Fe[n][t]=i}return Fe[n][t]}const Fe={};function De(e){return`${e.italic?"italic ":""}${e.bold?"bold":W} ${ke(e)}px ${q}`}function ke(e){const t=e.fontSize||G;if(!re[t])throw new Error("Size of the font is not supported");return re[t]}function $e(e,t,i=1){if(t<=e&&i>0)return[];if(0===i)throw new Error("range() step must not be zero");const n=Math.ceil(Math.abs((t-e)/i)),o=Array(n);for(let t=0;t<n;t++)o[t]=e+t*i;return o}function Le(e){return e.reduce(((e,t,i,n)=>{if(1===Math.abs(t-n[i-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*Pe(e,t){t.next();for(const i of e){const e=t.next();yield{...i,next:e.done?void 0:e.value}}}function Ue(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}function Ve(e){return null!==ve(e)}const ze=/^\[(.+)\]\((.+)\)$/,Be=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function He(e){return ze.test(e)}function We(e,t){return`[${e}](${t})`}function Ge(e){const t=e.match(ze)||[],i=t[1],n=t[2];if(!i||!n)throw new Error(`Could not parse markdown link ${e}.`);return{label:i,url:n}}const qe="o-spreadsheet://";function Ze(e){if(!He(e))return!1;const{url:t}=Ge(e);return t.startsWith(qe)}function je(e){return`${qe}${e}`}function Ye(e){if(e.startsWith(qe))return e.substr(qe.length);throw new Error(`${e} is not a valid sheet link`)}function Xe(e){return void 0!==e}function Ke(e){return void 0!==e&&""!==e}function Qe(e){return void 0===e||Object.values(e).every((e=>"object"==typeof e?Qe(e):!e))}function Je(e,t){for(let[i,n]of Object.entries(t))if(ot(n,e))return parseInt(i,10);const i=Object.keys(t),n=0===i.length?0:lt(i.map((e=>parseInt(e,10))));return t[n+1]=e,n+1}function et(e){let t="";for(let i=0,n=e.length;i<n;i++)t+=e[i];return t}function tt(e){let t,i=!1;const n=()=>(i||(t=e instanceof Function?e():e,i=!0),t);return n.map=e=>tt((()=>e(n()))),n}function it(e,t){let i=e.slice(t).find((e=>e));return i||(i=e.slice(0,t).reverse().find((e=>e))),i||""}function nt(e,t){return"after"===e?t+1:t}function ot(e,t){if(e===t)return!0;if(e&&!t||t&&!e)return!1;if(typeof e!=typeof t)return!1;if("object"!=typeof e)return!1;const i=new Set;Object.keys(e).forEach((e=>i.add(e))),Object.keys(t).forEach((e=>i.add(e)));for(let n of i){if(typeof e[n]!=typeof e[n])return!1;if("object"==typeof e[n]){if(!ot(e[n],t[n]))return!1}else if(e[n]!==t[n])return!1}return!0}function st(e,t){if(e.length<t.length)return!1;const i=new Set(e);return t.every((e=>i.has(e)))}function rt(e){const t={...e};return Object.keys(t).forEach((e=>!t[e]&&delete t[e])),t}function at(e){return e?e.toLowerCase():""}function lt(e){let t=e.length;if(t<1e5)return Math.max(...e);let i=-1/0;for(;t--;)i=e[t]>i?e[t]:i;return i}function ct(e){let t=e.length;if(t<1e5)return Math.min(...e);let i=1/0;for(;t--;)i=e[t]<i?e[t]:i;return i}const ht=/rgba?\(|\s+|\)/gi,dt=/^#([A-F\d]{2}){3,4}$/g,ut=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function gt(e){return mt(e.toString(16).padStart(6,"0"))}let pt=0;function mt(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(ht,"").split(",");let i=255;if(3!==t.length&&4!==t.length)throw new Error("invalid color");if(4===t.length){const e=parseFloat(t.pop()||"1");i=Math.round(255*(e||1))}const n=t.map((e=>parseInt(e,10)));255!==i&&n.push(i);return"#"+et(n.map((e=>e.toString(16).padStart(2,"0")))).toUpperCase()}(e):(t=e.replace("#","").toUpperCase(),3!==t.length&&4!==t.length||(t=t.split("").reduce(((e,t)=>e+t+t),"")),t=`#${t}`),!t.match(dt))throw new Error(`invalid color input: ${e}`);return t}function ft(e){try{return mt(e),!0}catch(e){return!1}}const vt=e=>e>=0&&e<=255;function bt(e,t,i,n=1){if(!vt(e)||!vt(t)||!vt(i)||n<0||n>1)throw new Error(`Invalid RGBA values ${[e,t,i,n]}`);return{a:n,b:i,g:t,r:e}}function St(e){let{r:t,g:i,b:n}=Et(e);t/=255,i/=255,n/=255;const o=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return.2126*o(t)+.7152*o(i)+.0722*o(n)}function Ct(e){let t=e.r.toString(16),i=e.g.toString(16),n=e.b.toString(16),o=Math.round(255*e.a).toString(16);return 1==t.length&&(t="0"+t),1==i.length&&(i="0"+i),1==n.length&&(n="0"+n),1==o.length&&(o="0"+o),"ff"===o&&(o=""),("#"+t+i+n+o).toUpperCase()}function Et(e){let t,i,n,o;if(7===(e=mt(e)).length)t=parseInt(e[1]+e[2],16),i=parseInt(e[3]+e[4],16),n=parseInt(e[5]+e[6],16),o=255;else{if(9!==e.length)throw new Error("Invalid color");t=parseInt(e[1]+e[2],16),i=parseInt(e[3]+e[4],16),n=parseInt(e[5]+e[6],16),o=parseInt(e[7]+e[8],16)}return o=+(o/255).toFixed(3),{a:o,r:t,g:i,b:n}}function wt(e){(e={...e}).s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,i=t*(1-Math.abs(e.h/60%2-1)),n=e.l-t/2,o=0,s=0,r=0;return 0<=e.h&&e.h<60?(o=t,s=i,r=0):60<=e.h&&e.h<120?(o=i,s=t,r=0):120<=e.h&&e.h<180?(o=0,s=t,r=i):180<=e.h&&e.h<240?(o=0,s=i,r=t):240<=e.h&&e.h<300?(o=i,s=0,r=t):300<=e.h&&e.h<360&&(o=t,s=0,r=i),o=Math.round(255*(o+n)),s=Math.round(255*(s+n)),r=Math.round(255*(r+n)),{a:e.a,r:o,g:s,b:r}}function yt(e){const t=e.r/255,i=e.g/255,n=e.b/255;let o=Math.min(t,i,n),s=Math.max(t,i,n),r=s-o,a=0,l=0,c=0;return a=0==r?0:s==t?(i-n)/r%6:s==i?(n-t)/r+2:(t-i)/r+4,a=Math.round(60*a),a<0&&(a+=360),c=(s+o)/2,l=0==r?0:r/(1-Math.abs(2*c-1)),l=+(100*l).toFixed(1),c=+(100*c).toFixed(1),{a:e.a,h:a,s:l,l:c}}const xt=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),Rt=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),It=new RegExp(/^\$?([A-Z]{1,3})+$/,"i"),Tt=new RegExp(/^\$?([0-9]{1,7})+$/,"i"),At=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),Nt=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),Ot=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[xt.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 Mt(e){return At.test(e)}function _t(e){return Nt.test(e)}function Ft(e){return It.test(e)}function Dt(e){return Tt.test(e)}function kt(e){return Rt.test(e)}function $t(e){const t=e.split("!"),i=t.pop();return{sheetName:Ne(t.join("!"))||void 0,xc:i}}function Lt(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Lt(Math.floor(e/26)-1)+Lt(e%26)}function Pt(e){let t=0;const i=e.length;for(let n=0;n<i;n++){t+=(e.charCodeAt(n)-65+(n<i-1?1:0))*26**(i-n-1)}return t}function Ut(e){const t=(e=e.toUpperCase().trim()).match(xt);if(null!==t){const[i,n,o]=t;if(i===e){return{col:Pt(n),row:parseInt(o,10)-1}}}throw new Error(`Invalid cell description: ${e}`)}function Vt(e,t,i={colFixed:!1,rowFixed:!1}){return(i.colFixed?"$":"")+Lt(e)+(i.rowFixed?"$":"")+String(t+1)}const zt=140,Bt=20,Ht=.035;function Wt(e){return Bt+(zt-Bt)*Math.exp(-Ht*(e-1))}const Gt=20,qt=/(\d+?)(?=(\d{3})+(?!\d)|$)/g,Zt=/0/g,jt={0:s("January"),1:s("February"),2:s("March"),3:s("April"),4:s("May"),5:s("June"),6:s("July"),7:s("August"),8:s("September"),9:s("October"),10:s("November"),11:s("December")},Yt={0:s("Sunday"),1:s("Monday"),2:s("Tuesday"),3:s("Wednesday"),4:s("Thursday"),5:s("Friday"),6:s("Saturday")},Xt={};function Kt(e){let t=Xt[e];return void 0===t&&(t=function(e){if(""===e)throw new Error("A format cannot be empty");let t=0,i=[];for(;t<e.length;){let n;if("["===e.charAt(t)){if("$"!==e.charAt(t+1))throw new Error(`Currency formats have to be prefixed by a $: ${e}`);if(n=e.substring(t+1).indexOf("]")+t+2,0===n)throw new Error(`Invalid currency brackets format: ${e}`);const o=e.substring(t+2,n-1);if(o.includes("["))throw new Error(`Invalid currency format: ${e}`);i.push({type:"STRING",format:o})}else{const o=e.substring(t).indexOf("[");n=o>-1?o+t:e.length;const s=e.substring(t,n);s.match(Y)?i.push({type:"DATE",format:s}):i.push({type:"NUMBER",format:di(s)})}t=n}return i}(e),Xt[e]=t),t}function Qt(e,t){switch(typeof e){case"string":return e.includes('\\"')?e.replace(/\\"/g,'"'):e;case"boolean":return e?"TRUE":"FALSE";case"number":t||(t=ai(e));return function(e,t){if("DATE"===t[0].type)return oi(e,t[0].format);let i=e<0?"-":"";for(let n of t)switch(n.type){case"NUMBER":i+=Jt(Math.abs(e),n.format);break;case"STRING":i+=n.format}return i}(e,Kt(t));case"object":return"0"}}function Jt(e,t){t.isPercent&&(e*=100),e/=t.magnitude;let i=0;void 0!==t.decimalPart&&(i=t.decimalPart.length);const{integerDigits:n,decimalDigits:o}=ti(e,i);let s=function(e,t,i){var n;const o="0"===e?"":e;let s=o;const r=t.length-o.length;if(r>0){const e=(t.substring(0,r).match(Zt)||[]).length;s="0".repeat(e)+s}i&&(s=(null===(n=s.match(qt))||void 0===n?void 0:n.join(","))||s);return s}(n,t.integerPart,t.thousandsSeparator);return void 0!==t.decimalPart&&(s+="."+function(e,t){let i=e;if(t.length-e.length>0){const n=(t.substring(e.length,t.length+1).match(Zt)||[]).length;i+="0".repeat(n)}return i}(o||"",t.decimalPart)),t.isPercent&&(s+="%"),s}const ei=[];function ti(e,t=Gt){const i=e.toString();if(i.includes("e"))return function(e,t=Gt){let i=ei[t];i||(i=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),ei[t]=i);const[n,o]=i.format(e).split(".");return{integerDigits:n,decimalDigits:o}}(e,t);if(Number.isInteger(e))return{integerDigits:i,decimalDigits:void 0};const n=i.indexOf(".");let o=i.substring(0,n),s=i.substring(n+1);if(0===t)return Number(s[0])>=5&&(o=(Number(o)+1).toString()),{integerDigits:o,decimalDigits:void 0};if(s.length>t){const{integerDigits:e,decimalDigits:i}=function(e,t){var i;let n="0",o=e,s=e.slice(0,t);const r=t;if(Number(e[r])<5)return{integerDigits:n,decimalDigits:s};const a=(null===(i=s.match(ni))||void 0===i?void 0:i[0])||"",l=(Number(s)+1).toString(),c=s.slice(a.length),h=l.length>c.length;h&&!a?(n="1",o=void 0):o=h?a.slice(0,-1)+l:a+l;return{integerDigits:n,decimalDigits:o}}(s,t);s=i,"0"!==e&&(o=(Number(o)+Number(e)).toString())}return{integerDigits:o,decimalDigits:ii(s||"")}}function ii(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const ni=/^0+/;function oi(e,t){const i=Se(e),n=t.indexOf("h");let o="",s="";return n>0?(o=si(i,t.substring(0,n-1)),s=ri(i,t.substring(n))):0===n?s=ri(i,t):n<0&&(o=si(i,t)),o+(o&&s?" ":"")+s}function si(e,t){var i;const n=null===(i=t.match(/\/|-|\s/))||void 0===i?void 0:i[0];return(n?t.split(n):[t]).map((i=>{switch(i){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return Yt[e.getDay()].slice(0,3);case"dddd":return Yt[e.getDay()];case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return jt[e.getMonth()].slice(0,3);case"mmmm":return jt[e.getMonth()];case"mmmmm":return jt[e.getMonth()].slice(0,1);case"yy":const i=String(e.getFullYear()).replace("-","").padStart(2,"0");return i.slice(i.length-2);case"yyyy":return e.getFullYear();default:throw new Error(`invalid format: ${t}`)}})).join(n)}function ri(e,t){let i=t.split(/:|\s/);const n=e.getHours(),o="a"===i[i.length-1];let s=n,r="";return o&&(s=0===s?12:s>12?s-12:s,r=n>=12?" PM":" AM",i.pop()),i.map((i=>{switch(i){case"hhhh":return Math.floor((e.getTime()-le.getTime())/36e5).toString();case"hh":return s.toString().padStart(2,"0");case"mm":return e.getMinutes().toString().padStart(2,"0");case"ss":return e.getSeconds().toString().padStart(2,"0");default:throw new Error(`invalid format: ${t}`)}})).join(":")+r}function ai(e){let{decimalDigits:t}=ti(e,10);return t?"0."+"0".repeat(t.length):"0"}function li(e,t,i){const n=Kt(e||"#,##0"),o=[];for(let e=0;e<n.length;e++){const s=n[e];if("NUMBER"!==s.type){o.push(s);continue}o.push({...s,format:{...s.format,magnitude:t,decimalPart:void 0}}),o.push({type:"STRING",format:i});const r=n[e+1];"STRING"===(null==r?void 0:r.type)&&["k","m","b"].includes(r.format)&&e++}return gi(o)}function ci(e,t){var i;const n={...e},o=Math.sign(t),s=(null===(i=n.decimalPart)||void 0===i?void 0:i.length)||0,r=Math.min(Math.max(0,s+o),Gt);return n.decimalPart="0".repeat(r),""===n.decimalPart&&delete n.decimalPart,n}const hi=/,*?$/;function di(e){var t;if(function(e){return Boolean(e.replace(ui,""))}(e=e.trim()))throw new Error(`Invalid number format: ${e}`);const i=e.includes("%"),n=(null===(t=e.match(hi))||void 0===t?void 0:t[0])||"",o=n?1e3**n.length:1;let s=e.slice(0,e.length-(n.length||0));const r=s.includes(",");if(s.match(/\..*,/))throw new Error("A format can't contain ',' symbol in the decimal part");s=s.replace("%","").replace(",","");const a=s.match(/[\%|,]/);if(a)throw new Error(`A format can only contain a single '${a[0]}' symbol`);const[l,c]=s.split(".");if(c&&c.length>20)throw new Error("A format can't contain more than 20 decimal places");return void 0!==c?{integerPart:l,isPercent:i,thousandsSeparator:r,decimalPart:c,magnitude:o}:{integerPart:l,isPercent:i,thousandsSeparator:r,magnitude:o}}const ui=/[,#0.%]/g;function gi(e){let t="";for(let i of e){let e;switch(i.type){case"NUMBER":const t=i.format;e=t.integerPart,t.thousandsSeparator&&(e=e.slice(0,-3)+","+e.slice(-3)),void 0!==t.decimalPart&&(e+="."+t.decimalPart),t.isPercent&&(e+="%"),t.magnitude&&(e+=",".repeat(Math.log10(t.magnitude)/3));break;case"STRING":e=`[$${i.format}]`;break;case"DATE":e=i.format}t+=e}return t}const pi=/(^-?\d+(\.?\d*(e\d+)?)?|^-?\.\d+)(?!\w|!)/,mi="(\\s*(\\d+(,\\d{3,})*(\\.\\d*)?)|(\\.\\d+))(e(\\+|-)?\\d+)?(\\s*%)?",fi="(\\s*-)?",vi="(\\s*[\\$€])?",bi="^(("+[fi+vi+mi,fi+mi+vi,vi+fi+mi].join(")|(")+"))$",Si=new RegExp(bi,"i");function Ci(e){return!!e&&Si.test(e.trim())}const Ei=/[,\$€]+/g;function wi(e){e=e.replace(Ei,"");let t=Number(e);return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}function yi(e,t,i){const n=[...e].sort(((e,t)=>e-t));let o=(n.length+(i?-1:1))*t;if(i||o--,Number.isInteger(o))return n[o];const s=Math.ceil(o),r=Math.floor(o);return n[s]*(o-r)+n[r]*(s-o)}class xi{constructor(e,t){this.getSheetSize=t,this.prefixSheet=!1,this._zone=e.zone,this.parts=e.parts,this.prefixSheet=e.prefixSheet,this.invalidXc=e.invalidXc,this.sheetId=e.sheetId,this.invalidSheetName=e.invalidSheetName}static fromRange(e,t){return e instanceof xi?e:new xi(e,t.getSheetSize)}get unboundedZone(){return this._zone}get zone(){const{left:e,top:t,bottom:i,right:n}=this._zone;if(void 0!==n&&void 0!==i)return this._zone;if(void 0===i&&void 0!==n)return{right:n,top:t,left:e,bottom:this.getSheetSize(this.sheetId).height-1};if(void 0===n&&void 0!==i)return{bottom:i,left:e,top:t,right:this.getSheetSize(this.sheetId).width-1};throw new Error(s("Bad zone format"))}static getRangeParts(e,t){const i=e.split(":").map((e=>{const t=_t(e);return{colFixed:!t&&e.startsWith("$"),rowFixed:t?e.startsWith("$"):e.includes("$",1)}})),n=void 0===t.bottom,o=void 0===t.right;return n&&(i[0].rowFixed=i[0].rowFixed||i[1].rowFixed,i[1].rowFixed=i[0].rowFixed||i[1].rowFixed),o&&(i[0].colFixed=i[0].colFixed||i[1].colFixed,i[1].colFixed=i[0].colFixed||i[1].colFixed),i}get isFullCol(){return void 0===this._zone.bottom}get isFullRow(){return void 0===this._zone.right}get rangeData(){return{_zone:this._zone,_sheetId:this.sheetId}}orderZone(){if(void 0!==this._zone.right&&this._zone.right<this._zone.left){let e=this._zone.right;this._zone.right=this._zone.left,this._zone.left=e;let t=this.parts[1].colFixed;this.parts[1].colFixed=this.parts[0].colFixed,this.parts[0].colFixed=t}if(void 0!==this._zone.bottom&&this._zone.bottom<this._zone.top){let e=this._zone.bottom;this._zone.bottom=this._zone.top,this._zone.top=e;let t=this.parts[1].rowFixed;this.parts[1].rowFixed=this.parts[0].rowFixed,this.parts[0].rowFixed=t}}clone(e){return new xi({zone:(null==e?void 0:e.zone)?e.zone:{...this._zone},sheetId:(null==e?void 0:e.sheetId)?e.sheetId:this.sheetId,invalidSheetName:e&&"invalidSheetName"in e?e.invalidSheetName:this.invalidSheetName,invalidXc:e&&"invalidXc"in e?e.invalidXc:this.invalidXc,parts:(null==e?void 0:e.parts)?e.parts:this.parts.map((e=>({rowFixed:e.rowFixed,colFixed:e.colFixed}))),prefixSheet:(null==e?void 0:e.prefixSheet)?e.prefixSheet:this.prefixSheet},this.getSheetSize)}}function Ri(e,t,i){const n=i.sheetId===e?t:i.sheetId;return i.clone({sheetId:n})}function Ii(e,t,i){if(!i)return;const n=e.getRangeFromSheetXC(t,i);return n.invalidSheetName||n.invalidXc?void 0:n}function Ti(e){const t=[];for(let i=0;i<e;i++){const e={cells:{}};t.push(e)}return t}function Ai(e,t){return void 0!==e&&void 0!==t&&Ne(e.trim().toUpperCase())===Ne(t.trim().toUpperCase())}function Ni(e,t="Sheet"){let i=1,n=`${t}${i}`;for(;e.includes(n);)n=`${t}${i}`,i++;return n}function Oi(e,t){let i=1;const n=s("Copy of %s",e);let o=n.toString();for(;t.includes(o);)o=`${n} (${i})`,i++;return o}class Mi{constructor(){this.isFastIdStrategy=!1,this.fastIdStart=0}setIsFastStrategy(e){this.isFastIdStrategy=e}smallUuid(){return this.isFastIdStrategy?(this.fastIdStart++,String(this.fastIdStart)):window.crypto?"10000000-1000".replace(/[01]/g,(e=>{const t=Number(e);return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)})):"xxxxxxxx-xxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}uuidv4(){return this.isFastIdStrategy?(this.fastIdStart++,String(this.fastIdStart)):window.crypto?"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(e=>{const t=Number(e);return(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/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 _i(e){const t=function(e){const t=(e=e.split("!").pop()).replace(/\$/g,"").split(":").map((e=>e.trim()));let i,n,o,s,r=!1,a=!1,l=!1;const c=t[0],h=t[1]&&t[1];if(Mt(c))o=s=Pt(c),i=n=0,r=!0;else if(_t(c))i=n=parseInt(c,10)-1,o=s=0,a=!0;else{const e=Ut(c);o=s=e.col,i=n=e.row,l=!0}if(2===t.length)if(Mt(h))s=Pt(h),r=!0;else if(_t(h))n=parseInt(h,10)-1,a=!0;else{const e=Ut(h);s=e.col,n=e.row,i=r?n:i,o=a?s:o,l=!0}if(r&&a)throw new Error("Wrong zone xc. The zone cannot be at the same time a full column and a full row");const d={top:i,left:o,bottom:r?void 0:n,right:a?void 0:s};return l=l&&(a||r),l&&(d.hasHeader=l),d}(e);return function(e){if(void 0!==e.right&&e.right<e.left){const t=e.left;e.left=e.right,e.right=t}if(void 0!==e.bottom&&e.bottom<e.top){const t=e.top;e.top=e.bottom,e.bottom=t}}(t),t}function Fi(e){const t=_i(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function Di(e){const{bottom:t,top:i,left:n,right:o}=e;return!(void 0!==t&&isNaN(t)||isNaN(i)||isNaN(n)||void 0!==o&&isNaN(o))&&((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 ki(e){const{top:t,bottom:i,left:n,right:o}=e,r="hasHeader"in e&&e.hasHeader,a=t===i&&n===o;if(void 0===i&&void 0!==o)return 0!==t||r?`${Vt(n,t)}:${Lt(o)}`:`${Lt(n)}:${Lt(o)}`;if(void 0===o&&void 0!==i)return 0!==n||r?`${Vt(n,t)}:${i+1}`:`${t+1}:${i+1}`;if(void 0!==i&&void 0!==o)return a?Vt(n,t):`${Vt(n,t)}:${Vt(o,i)}`;throw new Error(s("Bad zone format"))}function $i(e,t,i,n,o){const s="left"===t?"columns":"rows",r="before"===n?i-1:i,a=e["left"===t?"right":"bottom"];return e[t]<=r&&a&&a>r?Ki(e,s,"RESIZE",o):r<e[t]?Ki(e,s,"MOVE",o):{...e}}function Li(e,t,i,n,o){const s="left"===t?"columns":"rows",r="before"===n?i-1:i,a="left"===t?"right":"bottom";return e[t]<=r&&e[a]>r?Ki(e,s,"RESIZE",o):r<e[t]?Ki(e,s,"MOVE",o):{...e}}function Pi(e,t,i){const n="left"===t?"right":"bottom";let o=e[t],s=e[n];for(let r of i.sort(((e,t)=>t-e)))e[t]>r&&(o--,s--),e[t]<r&&e[n]>=r&&s--;return{...e,[t]:o,[n]:s}}function Ui(e,t,i){const n="left"===t?"right":"bottom";let o=e[t],s=e[n];const r=e[n];for(let n of i.sort(((e,t)=>t-e)))e[t]>n&&(o--,void 0!==s&&s--),void 0!==r&&void 0!==s&&e[t]<=n&&r>=n&&s--;if(!(void 0!==s&&o>s))return{...e,[t]:o,[n]:s}}function Vi(...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 zi(e,t){if(Hi(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 Bi(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function Hi(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function Wi(e,t,i){const{left:n,right:o,top:s,bottom:r}=i;return e>=n&&e<=o&&t>=s&&t<=r}function Gi(e,t){return Bi(Vi(t,e),t)}function qi(e,t){const i=e.map(_i),n=t.map(Fi),o=Math.max(...i.concat(n).map((e=>e.bottom||0))),s=Math.max(...i.concat(n).map((e=>e.right||0))),r=i.map((e=>({...e,bottom:void 0===e.bottom?o+1:e.bottom,right:void 0===e.right?s+1:e.right}))),a=n.map((e=>({...e,bottom:void 0===e.bottom?o+1:e.bottom,right:void 0===e.right?s+1:e.right}))),l=function(e,t){const i=new Set(t.map((({col:e,row:t})=>`${e}-${t}`)));return e.filter((({col:e,row:t})=>!i.has(`${e}-${t}`)))}(r.map(Xi).flat(),a.map(Xi).flat()),c=function(e){if(0===e.length)return[];const[t,...i]=[...e].sort(((e,t)=>e.row-t.row)).sort(((e,t)=>e.col-t.col)),n=[];let o=en(t);for(const{col:e,row:t}of i)if(!Wi(e,t,o))if(e===o.left&&t===o.bottom+1){const e=o.bottom+1;o={...o,bottom:e}}else n.push(o),o=en({col:e,row:t});return[...n,o]}(l);return function(e){if(0===e.length)return[];if(e.some((e=>e.left!==e.right)))throw new Error("only columns can be merged");const t=[],i=Zi(e),n=(e,t)=>e.top===t.top&&e.bottom===t.bottom&&e.right+1===t.left;for(;i.length;){const e=i.reduce(((e,t)=>n(e,t)?Vi(e,t):e),i.shift());t.push(e)}return Zi(t)}(c).map((e=>({...e,bottom:e.bottom===o+1?void 0:e.bottom,right:e.right===s+1?void 0:e.right}))).map(ki)}function Zi(e){const t=[...e].sort(((e,t)=>t.right-e.right)).sort(((e,t)=>t.bottom-e.bottom)).sort(((e,t)=>e.top-t.top)).sort(((e,t)=>e.left-t.left)).reverse(),i=[];for(;0!==t.length;){const e=t.shift();t.some((t=>Gi(e,t)))||i.push(e)}return i.reverse()}function ji(e){return{height:e.bottom-e.top+1,width:e.right-e.left+1}}function Yi(e){const{width:t,height:i}=ji(e);return 1===t||1===i}function Xi(e){const t=[],[i,n]=[e.right,e.left].sort(((e,t)=>e-t)),[o,s]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of $e(i,n+1))for(const i of $e(o,s+1))t.push({col:e,row:i});return t}function Ki(e,t,i,n){const o="both"===t?n[0]:"columns"===t?n:0,s="both"===t?n[1]:"rows"===t?n:0,r="hasHeader"in e&&e.hasHeader;let a;a=!function(e){return void 0===e.bottom}(e)||r?!(tn(e)&&!r)||"columns"!==t:"rows"!==t;const l={...e};return a&&"MOVE"===i&&(l.left+=o,l.top+=s),void 0!==l.right&&(l.right+=o),void 0!==l.bottom&&(l.bottom+=s),l}function Qi(e,t){let i,n;const{left:o,right:s,top:r,bottom:a}=e,{left:l,right:c,top:h,bottom:d}=t;return i=l!=o?l:c!=s?c:l,n=h!=r?h:d!=a?d:h,{col:i,row:n}}function Ji(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 en(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function tn(e){return void 0===e.right}function nn(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function on(...e){return e.length<2||1===qi(e.map(ki),[]).length}class sn{constructor(){this.content={}}add(e,t){return this.content[e]=t,this}get(e){const t=this.content[e];if(!t&&!(e in this.content))throw new Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}}const rn=new sn,an=new sn;class ln extends t.Component{constructor(){super(...arguments),this.canvas=t.useRef("graphContainer")}get background(){return this.chartRuntime.background}get canvasStyle(){return`background-color: ${this.background}`}get chartRuntime(){const e=this.env.model.getters.getChartRuntime(this.props.figure.id);if(!("chartJsConfig"in e))throw new Error("Unsupported chart runtime");return e}setup(){t.onMounted((()=>{const e=this.chartRuntime;this.createChart(e.chartJsConfig)}));let e=this.chartRuntime;t.onPatched((()=>{const t=this.chartRuntime;ot(e,t)||(this.updateChartJs(t),e=t)}))}createChart(e){const t=this.canvas.el.getContext("2d");this.chart=new window.Chart(t,e)}updateChartJs(e){var t,i,n,o;const s=e.chartJsConfig;s.data&&s.data.datasets?(this.chart.data=s.data,(null===(t=s.options)||void 0===t?void 0:t.title)&&(this.chart.config.options.title=s.options.title),s.options&&"valueLabel"in s.options&&(null===(i=s.options)||void 0===i?void 0:i.valueLabel)&&(this.chart.config.options.valueLabel=s.options.valueLabel)):this.chart.data.datasets=void 0,this.chart.config.options.legend=null===(n=s.options)||void 0===n?void 0:n.legend,this.chart.config.options.scales=null===(o=s.options)||void 0===o?void 0:o.scales,this.chart.update({duration:0})}}ln.template="o-spreadsheet-ChartJsComponent",an.add("line",ln),an.add("bar",ln),an.add("pie",ln),an.add("gauge",ln);const cn=new sn;var hn;cn.add("INCREMENT_MODIFIER",{apply:(e,t)=>{var i;e.current+=e.increment;const n=e.current.toString(),o=Qt(e.current,null===(i=t.cell)||void 0===i?void 0:i.format);return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:n},tooltip:n?{props:{content:o}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,i)=>{var n,o;const s=(null===(n=t.cell)||void 0===n?void 0:n.content)||"";return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:s},tooltip:s?{props:{content:null===(o=t.cell)||void 0===o?void 0:o.formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,i,n)=>{e.current+=e.increment;let o=0,s=0;switch(n){case"up":o=0,s=-e.current;break;case"down":o=0,s=e.current;break;case"left":o=-e.current,s=0;break;case"right":o=e.current,s=0}if(!t.cell||!t.cell.isFormula())return{cellData:{}};const r=t.sheetId,a=i.createAdaptedRanges(t.cell.dependencies,o,s,r),l=i.buildFormulaContent(r,t.cell,a);return{cellData:{border:t.border,style:t.cell.style,format:t.cell.format,content:l},tooltip:l?{props:{content:l}}:void 0}}}),function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(hn||(hn={}));const dn=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),un=new Set([...dn,"DUPLICATE_SHEET","EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT"]),gn=new Set(["START","ACTIVATE_SHEET","COPY","PREPARE_SELECTION_INPUT_EXPANSION","STOP_SELECTION_INPUT","RESIZE_SHEETVIEW","SET_VIEWPORT_OFFSET","SELECT_SEARCH_NEXT_MATCH","SELECT_SEARCH_PREVIOUS_MATCH","UPDATE_SEARCH","CLEAR_SEARCH","EVALUATE_CELLS","SET_CURRENT_CONTENT","SET_FORMULA_VISIBILITY","OPEN_CELL_POPOVER","CLOSE_CELL_POPOVER","UPDATE_FILTER"]),pn=new Set(["UPDATE_CELL","UPDATE_CELL_POSITION","CLEAR_CELL","DELETE_CONTENT","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","RESIZE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","UNHIDE_COLUMNS_ROWS","SET_GRID_LINES_VISIBILITY","UNFREEZE_COLUMNS","UNFREEZE_ROWS","FREEZE_COLUMNS","FREEZE_ROWS","UNFREEZE_COLUMNS_ROWS","ADD_MERGE","REMOVE_MERGE","CREATE_SHEET","DELETE_SHEET","DUPLICATE_SHEET","MOVE_SHEET","RENAME_SHEET","HIDE_SHEET","SHOW_SHEET","MOVE_RANGES","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT","CREATE_FIGURE","DELETE_FIGURE","UPDATE_FIGURE","SET_FORMATTING","CLEAR_FORMATTING","SET_BORDER","CREATE_CHART","UPDATE_CHART","CREATE_FILTER_TABLE","REMOVE_FILTER_TABLE"]);function mn(e){return pn.has(e.type)}class fn{constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return vn}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}const vn=new fn;var bn,Sn,Cn;e.CommandResult=void 0,(bn=e.CommandResult||(e.CommandResult={}))[bn.Success=0]="Success",bn[bn.CancelledForUnknownReason=1]="CancelledForUnknownReason",bn[bn.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",bn[bn.MergeIsDestructive=3]="MergeIsDestructive",bn[bn.CellIsMerged=4]="CellIsMerged",bn[bn.InvalidTarget=5]="InvalidTarget",bn[bn.EmptyUndoStack=6]="EmptyUndoStack",bn[bn.EmptyRedoStack=7]="EmptyRedoStack",bn[bn.NotEnoughElements=8]="NotEnoughElements",bn[bn.NotEnoughSheets=9]="NotEnoughSheets",bn[bn.MissingSheetName=10]="MissingSheetName",bn[bn.DuplicatedSheetName=11]="DuplicatedSheetName",bn[bn.DuplicatedSheetId=12]="DuplicatedSheetId",bn[bn.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",bn[bn.WrongSheetMove=14]="WrongSheetMove",bn[bn.WrongSheetPosition=15]="WrongSheetPosition",bn[bn.InvalidAnchorZone=16]="InvalidAnchorZone",bn[bn.SelectionOutOfBound=17]="SelectionOutOfBound",bn[bn.TargetOutOfSheet=18]="TargetOutOfSheet",bn[bn.WrongCutSelection=19]="WrongCutSelection",bn[bn.WrongPasteSelection=20]="WrongPasteSelection",bn[bn.WrongPasteOption=21]="WrongPasteOption",bn[bn.WrongFigurePasteOption=22]="WrongFigurePasteOption",bn[bn.EmptyClipboard=23]="EmptyClipboard",bn[bn.EmptyRange=24]="EmptyRange",bn[bn.InvalidRange=25]="InvalidRange",bn[bn.InvalidZones=26]="InvalidZones",bn[bn.InvalidSheetId=27]="InvalidSheetId",bn[bn.InvalidCellId=28]="InvalidCellId",bn[bn.InputAlreadyFocused=29]="InputAlreadyFocused",bn[bn.MaximumRangesReached=30]="MaximumRangesReached",bn[bn.InvalidInputId=31]="InvalidInputId",bn[bn.InvalidChartDefinition=32]="InvalidChartDefinition",bn[bn.InvalidDataSet=33]="InvalidDataSet",bn[bn.InvalidLabelRange=34]="InvalidLabelRange",bn[bn.InvalidScorecardKeyValue=35]="InvalidScorecardKeyValue",bn[bn.InvalidScorecardBaseline=36]="InvalidScorecardBaseline",bn[bn.InvalidGaugeDataRange=37]="InvalidGaugeDataRange",bn[bn.EmptyGaugeRangeMin=38]="EmptyGaugeRangeMin",bn[bn.GaugeRangeMinNaN=39]="GaugeRangeMinNaN",bn[bn.EmptyGaugeRangeMax=40]="EmptyGaugeRangeMax",bn[bn.GaugeRangeMaxNaN=41]="GaugeRangeMaxNaN",bn[bn.GaugeRangeMinBiggerThanRangeMax=42]="GaugeRangeMinBiggerThanRangeMax",bn[bn.GaugeLowerInflectionPointNaN=43]="GaugeLowerInflectionPointNaN",bn[bn.GaugeUpperInflectionPointNaN=44]="GaugeUpperInflectionPointNaN",bn[bn.GaugeLowerBiggerThanUpper=45]="GaugeLowerBiggerThanUpper",bn[bn.InvalidAutofillSelection=46]="InvalidAutofillSelection",bn[bn.WrongComposerSelection=47]="WrongComposerSelection",bn[bn.MinBiggerThanMax=48]="MinBiggerThanMax",bn[bn.LowerBiggerThanUpper=49]="LowerBiggerThanUpper",bn[bn.MidBiggerThanMax=50]="MidBiggerThanMax",bn[bn.MinBiggerThanMid=51]="MinBiggerThanMid",bn[bn.FirstArgMissing=52]="FirstArgMissing",bn[bn.SecondArgMissing=53]="SecondArgMissing",bn[bn.MinNaN=54]="MinNaN",bn[bn.MidNaN=55]="MidNaN",bn[bn.MaxNaN=56]="MaxNaN",bn[bn.ValueUpperInflectionNaN=57]="ValueUpperInflectionNaN",bn[bn.ValueLowerInflectionNaN=58]="ValueLowerInflectionNaN",bn[bn.MinInvalidFormula=59]="MinInvalidFormula",bn[bn.MidInvalidFormula=60]="MidInvalidFormula",bn[bn.MaxInvalidFormula=61]="MaxInvalidFormula",bn[bn.ValueUpperInvalidFormula=62]="ValueUpperInvalidFormula",bn[bn.ValueLowerInvalidFormula=63]="ValueLowerInvalidFormula",bn[bn.InvalidSortZone=64]="InvalidSortZone",bn[bn.WaitingSessionConfirmation=65]="WaitingSessionConfirmation",bn[bn.MergeOverlap=66]="MergeOverlap",bn[bn.TooManyHiddenElements=67]="TooManyHiddenElements",bn[bn.Readonly=68]="Readonly",bn[bn.InvalidViewportSize=69]="InvalidViewportSize",bn[bn.InvalidScrollingDirection=70]="InvalidScrollingDirection",bn[bn.FigureDoesNotExist=71]="FigureDoesNotExist",bn[bn.InvalidConditionalFormatId=72]="InvalidConditionalFormatId",bn[bn.InvalidCellPopover=73]="InvalidCellPopover",bn[bn.EmptyTarget=74]="EmptyTarget",bn[bn.InvalidFreezeQuantity=75]="InvalidFreezeQuantity",bn[bn.FrozenPaneOverlap=76]="FrozenPaneOverlap",bn[bn.ValuesNotChanged=77]="ValuesNotChanged",bn[bn.InvalidFilterZone=78]="InvalidFilterZone",bn[bn.FilterOverlap=79]="FilterOverlap",bn[bn.FilterNotFound=80]="FilterNotFound",bn[bn.MergeInFilter=81]="MergeInFilter",bn[bn.NonContinuousTargets=82]="NonContinuousTargets",bn[bn.DuplicatedFigureId=83]="DuplicatedFigureId",bn[bn.InvalidSelectionStep=84]="InvalidSelectionStep",bn[bn.DuplicatedChartId=85]="DuplicatedChartId",bn[bn.ChartDoesNotExist=86]="ChartDoesNotExist",bn[bn.InvalidHeaderIndex=87]="InvalidHeaderIndex",bn[bn.InvalidQuantity=88]="InvalidQuantity",bn[bn.NoChanges=89]="NoChanges",function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(Sn||(Sn={})),function(e){e[e.Background=0]="Background",e[e.Highlights=1]="Highlights",e[e.Clipboard=2]="Clipboard",e[e.Search=3]="Search",e[e.Chart=4]="Chart",e[e.Selection=5]="Selection",e[e.Autofill=6]="Autofill",e[e.Headers=7]="Headers"}(Cn||(Cn={}));const En=new sn;En.add("simple_value_copy",{condition:(e,t)=>{var i;return 1===t.length&&!e.isFormula()&&!(null===(i=e.format)||void 0===i?void 0:i.match(Y))},generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("copy_text",{condition:e=>!e.isFormula()&&e.evaluated.type===hn.text,generateRule:()=>({type:"COPY_MODIFIER"}),sequence:20}).add("update_formula",{condition:e=>e.isFormula(),generateRule:(e,t)=>({type:"FORMULA_MODIFIER",increment:t.length,current:0}),sequence:30}).add("increment_number",{condition:e=>e.evaluated.type===hn.number,generateRule:(e,t,i)=>{const n=function(e,t){let i=[],n=!1;for(let o of t)if(o===e&&(n=!0),(null==o?void 0:o.evaluated.type)===hn.number)i.push(o.evaluated.value);else{if(n)return i;i=[]}return i}(e,t);let o=1;return 1===n.length&&["up","left"].includes(i)?o=-1:2==n.length?o=2*(n[1]-n[0]):n.length>2&&(o=function(e){const t=[];let i=e[0];for(let n=1;n<e.length;n++){const o=e[n];t.push(o-i),i=o}return t.reduce(((e,t)=>e+t),0)/t.length}(n)*n.length),{type:"INCREMENT_MODIFIER",increment:o,current:e.evaluated.type===hn.number?e.evaluated.value:0}},sequence:40});const wn={};let yn=0;function xn(e,...t){const i="__sheet__"+yn++;return function(e,t){const i=document.createElement("style");i.textContent=function(e){const t=e.split(/(\{|\}|;)/).map((e=>e.trim())),i=[],n=[];let o=[];function s(e,t){const n=[];for(const o of i[e]){let r=t&&t+" "+o||o;r.includes("&")&&(r=o.replace(/&/g,t||"")),e<i.length-1&&(r=s(e+1,r)),n.push(r)}return n.join(", ")}function r(){o.length&&(n.push(s(0)+" {"),n.push(...o),n.push("}"),o=[])}for(;t.length;){let e=t.shift();"}"===e?(r(),i.pop()):("{"===t[0]&&(r(),i.push(e.split(/\s*,\s*/)),t.shift()),";"===t[0]&&o.push(" "+e+";"))}return n.join("\n")}(t),wn[e]=i}(i,String.raw(e,...t)),function(e){const t=wn[e];t.setAttribute("component",e),document.head.appendChild(t)}(i),i}function Rn({strikethrough:e,underline:t}){return e||t?`${e?"line-through":""} ${t?"underline":""}`:"none"}function In(e){return"\n"+Object.entries(e).map((([e,t])=>`${e}: ${t};`)).join("\n")+"\n"}xn`
2
2
  .o-error-tooltip {
3
3
  font-size: 13px;
4
4
  background-color: white;
@@ -6,7 +6,7 @@
6
6
  padding: 10px;
7
7
  overflow-wrap: break-word;
8
8
  }
9
- `;class Rn extends t.Component{}Rn.size={width:180,height:40},Rn.template="o-spreadsheet-ErrorToolTip",Rn.components={};const In={onHover:(e,t)=>{const i=t.getCell(t.getActiveSheetId(),e.col,e.row);return(null==i?void 0:i.evaluated.type)===ln.error&&i.evaluated.error.logLevel>l.silent?{isOpen:!0,props:{text:i.evaluated.error.message},Component:Rn,cellCorner:"TopRight"}:{isOpen:!1}}};class Tn extends t.Component{constructor(){super(...arguments),this.itemRef=t.useRef("menuValueItem")}setup(){t.onWillPatch((()=>{this.props.scrolledTo&&this.scrollListToSelectedValue()}))}scrollListToSelectedValue(){var e,t;this.itemRef.el&&(null===(t=(e=this.itemRef.el).scrollIntoView)||void 0===t||t.call(e,{block:"bottom"===this.props.scrolledTo?"end":"start"}))}}Tn.template="o-spreadsheet-FilterMenuValueItem";const An=wn`
9
+ `;class Tn extends t.Component{}Tn.size={width:180,height:40},Tn.template="o-spreadsheet-ErrorToolTip",Tn.components={};const An={onHover:(e,t)=>{const i=t.getCell(t.getActiveSheetId(),e.col,e.row);return(null==i?void 0:i.evaluated.type)===hn.error&&i.evaluated.error.logLevel>l.silent?{isOpen:!0,props:{text:i.evaluated.error.message},Component:Tn,cellCorner:"TopRight"}:{isOpen:!1}}};class Nn extends t.Component{constructor(){super(...arguments),this.itemRef=t.useRef("menuValueItem")}setup(){t.onWillPatch((()=>{this.props.scrolledTo&&this.scrollListToSelectedValue()}))}scrollListToSelectedValue(){var e,t;this.itemRef.el&&(null===(t=(e=this.itemRef.el).scrollIntoView)||void 0===t||t.call(e,{block:"bottom"===this.props.scrolledTo?"end":"start"}))}}Nn.template="o-spreadsheet-FilterMenuValueItem";const On=xn`
10
10
  .o-filter-menu {
11
11
  box-sizing: border-box;
12
12
  padding: 8px 16px;
@@ -108,7 +108,7 @@
108
108
  }
109
109
  }
110
110
  }
111
- `;class On extends t.Component{constructor(){super(...arguments),this.state=t.useState({values:[],textFilter:"",selectedValue:void 0}),this.searchBar=t.useRef("filterMenuSearchBar")}setup(){t.onWillUpdateProps((e=>{ot(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(),i=this.env.model.getters.getFilter(t,e.col,e.row);if(!i)return[];const n=(i.filteredZone?ji(i.filteredZone):[]).filter((({row:e})=>!this.env.model.getters.isRowHidden(t,e))).map((({col:e,row:i})=>{var n;return null===(n=this.env.model.getters.getCell(t,e,i))||void 0===n?void 0:n.formattedValue})),o=this.env.model.getters.getFilterValues(t,e.col,e.row),s=[...n,...o],r=o.map(at);return[...new Set(s.map(at))].sort(((e,t)=>e.localeCompare(t,void 0,{numeric:!0,sensitivity:"base"}))).map((e=>({checked:-1===r.findIndex((t=>t===e)),string:s.find((t=>at(t)===e))||""})))}checkValue(e){var t;this.state.selectedValue=e.string,e.checked=!e.checked,null===(t=this.searchBar.el)||void 0===t||t.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(e,t.col,t.row)}get displayedValues(){return this.state.textFilter?function(e,t,i){const n=[];return t.forEach((t=>{const o=function(e,t){e=e.toLocaleLowerCase();let i=0,n=0,o=(t=t.toLocaleLowerCase()).length,s=0;for(let r=0;r<o;r++)t[r]===e[s]?(s++,n+=100+n-r/200):n=0,i+=n;return s===e.length?i:0}(e,i(t));o>0&&n.push({score:o,elem:t})})),n.sort(((e,t)=>t.score-e.score)),n.map((e=>e.elem))}(this.state.textFilter,this.state.values,(e=>e.string)):this.state.values}confirm(){var e,t;const i=this.props.filterPosition;this.env.model.dispatch("UPDATE_FILTER",{...i,sheetId:this.env.model.getters.getActiveSheetId(),values:this.state.values.filter((e=>!e.checked)).map((e=>e.string))}),null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}cancel(){var e,t;null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}onKeyDown(e){const t=this.displayedValues;if(0===t.length)return;let i;if(void 0!==this.state.selectedValue){const e=t.findIndex((e=>e.string===this.state.selectedValue));i=-1===e?void 0:e}switch(e.key){case"ArrowDown":i=void 0===i?0:Math.min(i+1,t.length-1),e.preventDefault();break;case"ArrowUp":i=void 0===i?t.length-1:Math.max(i-1,0),e.preventDefault();break;case"Enter":void 0!==i&&this.checkValue(t[i]),e.preventDefault()}this.state.selectedValue=void 0!==i?t[i].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){var t,i;const n=this.props.filterPosition,o=this.filterTable;if(!n||!o||!o.contentZone)return;const s=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("SORT_CELLS",{sheetId:s,col:n.col,row:o.contentZone.top,zone:o.contentZone,sortDirection:e,sortOptions:{emptyCellAsZero:!0,sortHeaders:!0}}),null===(i=(t=this.props).onClosed)||void 0===i||i.call(t)}}On.size={width:B,height:295},On.template="o-spreadsheet-FilterMenu",On.style=An,On.components={FilterMenuValueItem:Tn};const Nn={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:On,cellCorner:"BottomLeft"})};function Mn(e,t){const i=[];for(const n of e.children)"function"==typeof n?i.push(...n(t)):i.push(n);return i.sort(((e,t)=>e.sequence-t.sequence))}function _n(e,t){return"function"==typeof e.name?e.name(t):e.name}const Fn=/Mac/i,Dn=["Shift","Control","Alt","Meta"];function kn(e,t){return!!t.target&&e.contains(t.target)}function $n(){const e=document.querySelector(".o-grid-overlay");if(e){const{top:t,left:i}=null==e?void 0:e.getBoundingClientRect();return{top:t,left:i}}throw new Error("Can't find spreadsheet position")}const Ln=/^[a-zA-Z]$/;function Pn(){return Boolean(Fn.test(navigator.userAgent))}function Un(e){return Pn()?e.metaKey:e.ctrlKey}function Vn(){const e=t.useState({x:0,y:0,width:0,height:0});let i=document.querySelector(".o-spreadsheet");function n(){if(i||(i=document.querySelector(".o-spreadsheet")),i){const{top:t,left:n,width:o,height:s}=i.getBoundingClientRect();e.x=n,e.y=t,e.width=o,e.height=s}}return n(),t.onMounted(n),t.onPatched(n),e}function zn(e){const i=t.useState({x:0,y:0});function n(){const t=e.el;if(null===t)return;const{top:n,left:o}=t.getBoundingClientRect();o===i.x&&n===i.y||(i.x=o,i.y=n)}return t.onMounted(n),t.onPatched(n),i}class Bn extends t.Component{constructor(){super(...arguments),this.spreadsheetRect=Vn()}get maxHeight(){return Math.max(0,this.viewportDimension.height-36-D)}get style(){const e="left:"+(this.horizontalPosition()-this.spreadsheetRect.x),t="top:"+(this.verticalPosition()-this.spreadsheetRect.y),i=this.maxHeight,n=`max-height:${i}`,o=0!==i?"box-shadow: 1px 2px 5px 2px rgb(51 51 51 / 15%);":"";return`\n position: absolute;\n z-index: ${this.props.zIndex};\n ${t}px;\n ${e}px;\n ${n}px;\n width:${this.props.childWidth}px;\n overflow-y: auto;\n overflow-x: hidden;\n ${o}\n `}get viewportDimension(){return this.env.model.getters.getSheetViewDimensionWithHeaders()}get shouldRenderRight(){const{x:e}=this.props.position;return e+this.props.childWidth<this.viewportDimension.width}get shouldRenderBottom(){const{y:e}=this.props.position;return e+Math.min(this.props.childHeight,this.maxHeight)<this.viewportDimension.height+(this.env.isDashboard()?0:63)}horizontalPosition(){const{x:e}=this.props.position;return this.shouldRenderRight?e:e-this.props.childWidth-this.props.flipHorizontalOffset}verticalPosition(){const{y:e}=this.props.position;return this.shouldRenderBottom?e:Math.max(e-this.props.childHeight+this.props.flipVerticalOffset,this.props.marginTop)}}Bn.template="o-spreadsheet-Popover",Bn.defaultProps={flipHorizontalOffset:0,flipVerticalOffset:0,verticalOffset:0,marginTop:0,onMouseWheel:()=>{},zIndex:oe.Popover},wn`
111
+ `;class Mn extends t.Component{constructor(){super(...arguments),this.state=t.useState({values:[],textFilter:"",selectedValue:void 0}),this.searchBar=t.useRef("filterMenuSearchBar")}setup(){t.onWillUpdateProps((e=>{ot(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(),i=this.env.model.getters.getFilter(t,e.col,e.row);if(!i)return[];const n=(i.filteredZone?Xi(i.filteredZone):[]).filter((({row:e})=>!this.env.model.getters.isRowHidden(t,e))).map((({col:e,row:i})=>{var n;return null===(n=this.env.model.getters.getCell(t,e,i))||void 0===n?void 0:n.formattedValue})),o=this.env.model.getters.getFilterValues(t,e.col,e.row),s=[...n,...o],r=o.map(at);return[...new Set(s.map(at))].sort(((e,t)=>e.localeCompare(t,void 0,{numeric:!0,sensitivity:"base"}))).map((e=>({checked:-1===r.findIndex((t=>t===e)),string:s.find((t=>at(t)===e))||""})))}checkValue(e){var t;this.state.selectedValue=e.string,e.checked=!e.checked,null===(t=this.searchBar.el)||void 0===t||t.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(e,t.col,t.row)}get displayedValues(){return this.state.textFilter?function(e,t,i){const n=[];return t.forEach((t=>{const o=function(e,t){e=e.toLocaleLowerCase();let i=0,n=0,o=(t=t.toLocaleLowerCase()).length,s=0;for(let r=0;r<o;r++)t[r]===e[s]?(s++,n+=100+n-r/200):n=0,i+=n;return s===e.length?i:0}(e,i(t));o>0&&n.push({score:o,elem:t})})),n.sort(((e,t)=>t.score-e.score)),n.map((e=>e.elem))}(this.state.textFilter,this.state.values,(e=>e.string)):this.state.values}confirm(){var e,t;const i=this.props.filterPosition;this.env.model.dispatch("UPDATE_FILTER",{...i,sheetId:this.env.model.getters.getActiveSheetId(),values:this.state.values.filter((e=>!e.checked)).map((e=>e.string))}),null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}cancel(){var e,t;null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}onKeyDown(e){const t=this.displayedValues;if(0===t.length)return;let i;if(void 0!==this.state.selectedValue){const e=t.findIndex((e=>e.string===this.state.selectedValue));i=-1===e?void 0:e}switch(e.key){case"ArrowDown":i=void 0===i?0:Math.min(i+1,t.length-1),e.preventDefault();break;case"ArrowUp":i=void 0===i?t.length-1:Math.max(i-1,0),e.preventDefault();break;case"Enter":void 0!==i&&this.checkValue(t[i]),e.preventDefault()}this.state.selectedValue=void 0!==i?t[i].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){var t,i;const n=this.props.filterPosition,o=this.filterTable;if(!n||!o||!o.contentZone)return;const s=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("SORT_CELLS",{sheetId:s,col:n.col,row:o.contentZone.top,zone:o.contentZone,sortDirection:e,sortOptions:{emptyCellAsZero:!0,sortHeaders:!0}}),null===(i=(t=this.props).onClosed)||void 0===i||i.call(t)}}Mn.size={width:B,height:295},Mn.template="o-spreadsheet-FilterMenu",Mn.style=On,Mn.components={FilterMenuValueItem:Nn};const _n={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:Mn,cellCorner:"BottomLeft"})};function Fn(e,t){const i=[];for(const n of e.children)"function"==typeof n?i.push(...n(t)):i.push(n);return i.sort(((e,t)=>e.sequence-t.sequence))}function Dn(e,t){return"function"==typeof e.name?e.name(t):e.name}const kn=/Mac/i,$n=["Shift","Control","Alt","Meta"];function Ln(e,t){return!!t.target&&e.contains(t.target)}function Pn(){const e=document.querySelector(".o-grid-overlay");if(e){const{top:t,left:i}=null==e?void 0:e.getBoundingClientRect();return{top:t,left:i}}throw new Error("Can't find spreadsheet position")}const Un=/^[a-zA-Z]$/;function Vn(){return Boolean(kn.test(navigator.userAgent))}function zn(e){return Vn()?e.metaKey:e.ctrlKey}function Bn(){const e=t.useState({x:0,y:0,width:0,height:0});let i=document.querySelector(".o-spreadsheet");function n(){if(i||(i=document.querySelector(".o-spreadsheet")),i){const{top:t,left:n,width:o,height:s}=i.getBoundingClientRect();e.x=n,e.y=t,e.width=o,e.height=s}}return n(),t.onMounted(n),t.onPatched(n),e}function Hn(e){const i=t.useState({x:0,y:0});function n(){const t=e.el;if(null===t)return;const{top:n,left:o}=t.getBoundingClientRect();o===i.x&&n===i.y||(i.x=o,i.y=n)}return t.onMounted(n),t.onPatched(n),i}class Wn extends t.Component{constructor(){super(...arguments),this.spreadsheetRect=Bn()}get maxHeight(){return Math.max(0,this.viewportDimension.height-36-D)}get style(){const e="left:"+(this.horizontalPosition()-this.spreadsheetRect.x),t="top:"+(this.verticalPosition()-this.spreadsheetRect.y),i=this.maxHeight,n=`max-height:${i}`,o=0!==i?"box-shadow: 1px 2px 5px 2px rgb(51 51 51 / 15%);":"";return`\n position: absolute;\n z-index: ${this.props.zIndex};\n ${t}px;\n ${e}px;\n ${n}px;\n width:${this.props.childWidth}px;\n overflow-y: auto;\n overflow-x: hidden;\n ${o}\n `}get viewportDimension(){return this.env.model.getters.getSheetViewDimensionWithHeaders()}get shouldRenderRight(){const{x:e}=this.props.position;return e+this.props.childWidth<this.viewportDimension.width}get shouldRenderBottom(){const{y:e}=this.props.position;return e+Math.min(this.props.childHeight,this.maxHeight)<this.viewportDimension.height+(this.env.isDashboard()?0:63)}horizontalPosition(){const{x:e}=this.props.position;return this.shouldRenderRight?e:e-this.props.childWidth-this.props.flipHorizontalOffset}verticalPosition(){const{y:e}=this.props.position;return this.shouldRenderBottom?e:Math.max(e-this.props.childHeight+this.props.flipVerticalOffset,this.props.marginTop)}}Wn.template="o-spreadsheet-Popover",Wn.defaultProps={flipHorizontalOffset:0,flipVerticalOffset:0,verticalOffset:0,marginTop:0,onMouseWheel:()=>{},zIndex:oe.Popover},xn`
112
112
  .o-menu {
113
113
  background-color: white;
114
114
  padding: 5px 0px;
@@ -155,7 +155,7 @@
155
155
  }
156
156
  }
157
157
  }
158
- `;class Hn extends t.Component{constructor(){super(...arguments),this.MENU_WIDTH=B,this.subMenu=t.useState({isOpen:!1,position:null,scrollOffset:0,menuItems:[]}),this.menuRef=t.useRef("menu"),this.position=zn(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 visibleMenuItems(){return this.props.menuItems.filter((e=>e.isVisible(this.env)))}get subMenuPosition(){const e=Object.assign({},this.subMenu.position);return e.y-=this.subMenu.scrollOffset||0,e}get menuHeight(){return this.menuComponentHeight(this.visibleMenuItems)}get subMenuHeight(){return this.menuComponentHeight(this.subMenu.menuItems)}get popover(){const e=1===this.props.depth;let t=6;return this.env.isDashboard()||(t+=89),{marginTop:t,flipHorizontalOffset:B*(this.props.depth-1),flipVerticalOffset:e?0:28}}getColor(e){return e.textColor?`color: ${e.textColor}`:void 0}async activateMenu(e){var t,i;const n=await e.action(this.env);this.close(),null===(i=(t=this.props).onMenuClicked)||void 0===i||i.call(t,{detail:n})}close(){this.closeSubMenu(),this.props.onClose()}subMenuVerticalPosition(e){const t=this.visibleMenuItems.slice(0,e);return this.menuComponentHeight(t)+this.position.y}onExternalClick(e){this.menuRef.el&&Array.from(document.querySelectorAll(".o-spreadsheet .o-menu")).some((t=>kn(t,e)))||(e.closedMenuId=this.props.menuId,this.close())}menuComponentHeight(e){const t=e.filter((e=>e.separator));return 28*e.length+11*t.length}getName(e){return _n(e,this.env)}getDescription(e){return(t=e).description?t.description:"";var t}isRoot(e){return!e.action}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){const i=this.subMenuVerticalPosition(t);this.subMenu.position={x:this.position.x+B,y:i-(this.subMenu.scrollOffset||0)},this.subMenu.menuItems=Mn(e,this.env).filter((e=>!e.isVisible||e.isVisible(this.env))),this.subMenu.isOpen=!0,this.subMenu.parentMenu=e}isParentMenu(e,t){var i;return(null===(i=e.parentMenu)||void 0===i?void 0:i.id)===t.id}closeSubMenu(){this.subMenu.isOpen=!1,this.subMenu.parentMenu=void 0}onClickMenu(e,t){this.isEnabled(e)&&(this.isRoot(e)?this.openSubMenu(e,t):this.activateMenu(e))}onMouseOver(e,t){e.isEnabled(this.env)&&(this.isRoot(e)?this.openSubMenu(e,t):this.closeSubMenu())}}Hn.template="o-spreadsheet-Menu",Hn.components={Menu:Hn,Popover:Bn},Hn.defaultProps={depth:1};wn`
158
+ `;class Gn extends t.Component{constructor(){super(...arguments),this.MENU_WIDTH=B,this.subMenu=t.useState({isOpen:!1,position:null,scrollOffset:0,menuItems:[]}),this.menuRef=t.useRef("menu"),this.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 visibleMenuItems(){return this.props.menuItems.filter((e=>e.isVisible(this.env)))}get subMenuPosition(){const e=Object.assign({},this.subMenu.position);return e.y-=this.subMenu.scrollOffset||0,e}get menuHeight(){return this.menuComponentHeight(this.visibleMenuItems)}get subMenuHeight(){return this.menuComponentHeight(this.subMenu.menuItems)}get popover(){const e=1===this.props.depth;let t=6;return this.env.isDashboard()||(t+=89),{marginTop:t,flipHorizontalOffset:B*(this.props.depth-1),flipVerticalOffset:e?0:28}}getColor(e){return e.textColor?`color: ${e.textColor}`:void 0}async activateMenu(e){var t,i;const n=await e.action(this.env);this.close(),null===(i=(t=this.props).onMenuClicked)||void 0===i||i.call(t,{detail:n})}close(){this.closeSubMenu(),this.props.onClose()}subMenuVerticalPosition(e){const t=this.visibleMenuItems.slice(0,e);return this.menuComponentHeight(t)+this.position.y}onExternalClick(e){this.menuRef.el&&Array.from(document.querySelectorAll(".o-spreadsheet .o-menu")).some((t=>Ln(t,e)))||(e.closedMenuId=this.props.menuId,this.close())}menuComponentHeight(e){const t=e.filter((e=>e.separator));return 28*e.length+11*t.length}getName(e){return Dn(e,this.env)}getDescription(e){return(t=e).description?t.description:"";var t}isRoot(e){return!e.action}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){const i=this.subMenuVerticalPosition(t);this.subMenu.position={x:this.position.x+B,y:i-(this.subMenu.scrollOffset||0)},this.subMenu.menuItems=Fn(e,this.env).filter((e=>!e.isVisible||e.isVisible(this.env))),this.subMenu.isOpen=!0,this.subMenu.parentMenu=e}isParentMenu(e,t){var i;return(null===(i=e.parentMenu)||void 0===i?void 0:i.id)===t.id}closeSubMenu(){this.subMenu.isOpen=!1,this.subMenu.parentMenu=void 0}onClickMenu(e,t){this.isEnabled(e)&&(this.isRoot(e)?this.openSubMenu(e,t):this.activateMenu(e))}onMouseOver(e,t){e.isEnabled(this.env)&&(this.isRoot(e)?this.openSubMenu(e,t):this.closeSubMenu())}}Gn.template="o-spreadsheet-Menu",Gn.components={Menu:Gn,Popover:Wn},Gn.defaultProps={depth:1};xn`
159
159
  .o-link-tool {
160
160
  font-size: 13px;
161
161
  background-color: white;
@@ -199,7 +199,7 @@
199
199
  cursor: pointer;
200
200
  color: #000;
201
201
  }
202
- `;class Wn extends t.Component{get cell(){const{col:e,row:t}=this.props.cellPosition,i=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getCell(i,e,t);if(null==n?void 0:n.isLink())return n;throw new Error(`LinkDisplay Component can only be used with link cells. ${Vt(e,t)} is not a link.`)}openLink(){this.cell.action(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:i}=this.props.cellPosition,n=this.cell.style,o=(null==n?void 0:n.textColor)===R||null==n?void 0:n.textColor;this.env.model.dispatch("UPDATE_CELL",{col:t,row:i,sheetId:e,content:this.cell.link.label,style:{...n,textColor:o,underline:void 0}})}}Wn.components={Menu:Hn},Wn.template="o-spreadsheet-LinkDisplay",Wn.size={width:220,height:43};const Gn={onHover:(e,t)=>{const i=t.getActiveSheetId(),n=t.getCell(i,e.col,e.row);return!t.isDashboard()&&(null==n?void 0:n.isLink())&&t.isVisibleInViewport(i,e.col,e.row)?{isOpen:!0,Component:Wn,props:{cellPosition:e},cellCorner:"BottomLeft"}:{isOpen:!1}}},qn=e=>({isVisible:()=>!0,isEnabled:()=>!0,isReadonlyAllowed:!1,description:"",action:!1,children:[],separator:!1,icon:!1,id:e});function Zn(e,t){return Object.assign({},qn(e),t)}function jn(e){return"function"!=typeof e}class Yn extends nn{add(e,t){return this.content[e]=Zn(e,t),this}addChild(e,t,i){const n=t.splice(0,1)[0];let o=this.content[n];if(!o)throw new Error(`Path ${n+":"+t.join(":")} not found`);for(let e of t)if(o=o.children.filter(jn).find((t=>t.id===e)),!o)throw new Error(`Path ${n+":"+t.join(":")} not found`);return"function"!=typeof i?o.children.push(Zn(e,i)):o.children.push(i),this}getAll(){return super.getAll().sort(((e,t)=>e.sequence-t.sequence))}}const Xn=new Yn;Xn.add("sheet",{name:s("Link sheet"),sequence:10}).addChild("sheet_list",["sheet"],(e=>e.model.getters.getSheetIds().map((t=>e.model.getters.getSheet(t))).map(((e,t)=>Zn(e.id,{name:e.name,sequence:t,action:()=>({link:{label:e.name,url:je(e.id)},urlRepresentation:e.name,isUrlEditable:!1})})))));wn`
202
+ `;class qn extends t.Component{get cell(){const{col:e,row:t}=this.props.cellPosition,i=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getCell(i,e,t);if(null==n?void 0:n.isLink())return n;throw new Error(`LinkDisplay Component can only be used with link cells. ${Vt(e,t)} is not a link.`)}openLink(){this.cell.action(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:i}=this.props.cellPosition,n=this.cell.style,o=(null==n?void 0:n.textColor)===R||null==n?void 0:n.textColor;this.env.model.dispatch("UPDATE_CELL",{col:t,row:i,sheetId:e,content:this.cell.link.label,style:{...n,textColor:o,underline:void 0}})}}qn.components={Menu:Gn},qn.template="o-spreadsheet-LinkDisplay",qn.size={width:220,height:43};const Zn={onHover:(e,t)=>{const i=t.getActiveSheetId(),n=t.getCell(i,e.col,e.row);return!t.isDashboard()&&(null==n?void 0:n.isLink())&&t.isVisibleInViewport(i,e.col,e.row)?{isOpen:!0,Component:qn,props:{cellPosition:e},cellCorner:"BottomLeft"}:{isOpen:!1}}},jn=e=>({isVisible:()=>!0,isEnabled:()=>!0,isReadonlyAllowed:!1,description:"",action:!1,children:[],separator:!1,icon:!1,id:e});function Yn(e,t){return Object.assign({},jn(e),t)}function Xn(e){return"function"!=typeof e}class Kn extends sn{add(e,t){return this.content[e]=Yn(e,t),this}addChild(e,t,i){const n=t.splice(0,1)[0];let o=this.content[n];if(!o)throw new Error(`Path ${n+":"+t.join(":")} not found`);for(let e of t)if(o=o.children.filter(Xn).find((t=>t.id===e)),!o)throw new Error(`Path ${n+":"+t.join(":")} not found`);return"function"!=typeof i?o.children.push(Yn(e,i)):o.children.push(i),this}getAll(){return super.getAll().sort(((e,t)=>e.sequence-t.sequence))}}const Qn=new Kn;Qn.add("sheet",{name:s("Link sheet"),sequence:10}).addChild("sheet_list",["sheet"],(e=>e.model.getters.getSheetIds().map((t=>e.model.getters.getSheet(t))).map(((e,t)=>Yn(e.id,{name:e.name,sequence:t,action:()=>({link:{label:e.name,url:je(e.id)},urlRepresentation:e.name,isUrlEditable:!1})})))));xn`
203
203
  .o-link-editor {
204
204
  font-size: 13px;
205
205
  background-color: white;
@@ -269,7 +269,7 @@
269
269
  }
270
270
  }
271
271
  }
272
- `;class Kn extends t.Component{constructor(){super(...arguments),this.menuItems=Xn.getAll(),this.state=t.useState(this.defaultState),this.menu=t.useState({isOpen:!1}),this.linkEditorRef=t.useRef("linkEditor"),this.position=zn(this.linkEditorRef),this.urlInput=t.useRef("urlInput")}setup(){t.onMounted((()=>{var e;return null===(e=this.urlInput.el)||void 0===e?void 0:e.focus()}))}get defaultState(){const{col:e,row:t}=this.props.cellPosition,i=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getCell(i,e,t);return(null==n?void 0:n.isLink())?{link:{url:n.link.url,label:n.formattedValue},urlRepresentation:n.urlRepresentation,isUrlEditable:n.isUrlEditable}:{link:{url:"",label:(null==n?void 0:n.formattedValue)||""},isUrlEditable:!0,urlRepresentation:""}}get menuPosition(){return{x:this.position.x+320-12-2,y:this.position.y+100}}onSpecialLink(e){const{detail:t}=e;this.state.link.url=t.link.url,this.state.link.label=t.link.label,this.state.isUrlEditable=t.isUrlEditable,this.state.urlRepresentation=t.urlRepresentation}openMenu(){this.menu.isOpen=!0}removeLink(){this.state.link.url="",this.state.urlRepresentation="",this.state.isUrlEditable=!0}save(){var e,t;const{col:i,row:n}=this.props.cellPosition,o=this.state.link.label||this.state.link.url;this.env.model.dispatch("UPDATE_CELL",{col:i,row:n,sheetId:this.env.model.getters.getActiveSheetId(),content:We(o,this.state.link.url)}),null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}cancel(){var e,t;null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}onKeyDown(e){switch(e.key){case"Enter":this.state.link.url&&this.save(),e.preventDefault();break;case"Escape":this.cancel()}}}Kn.template="o-spreadsheet-LinkEditor",Kn.size={width:340,height:180},Kn.components={Menu:Hn};const Qn={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:Kn,cellCorner:"BottomLeft"})},Jn=new nn;Jn.add("ErrorToolTip",In).add("LinkCell",Gn).add("LinkEditor",Qn).add("FilterMenu",Nn);const eo=new nn,to=new nn,io=new nn,no=(new nn).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let i=e.base;"after"===e.position&&i++;for(let n=0;n<e.quantity;n++)t.push(n+i);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],i=[...e.elements].sort(((e,t)=>e-t));for(let n of Le(i)){const i=0===n[0]?0:n[0]-1,o=0===n[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:n.length,base:i,sheetId:e.sheetId,position:o})}return t})).add("ADD_MERGE",(function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]})).add("REMOVE_MERGE",(function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]})).add("CREATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId}]})).add("DELETE_SHEET",(function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1}]})).add("DUPLICATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo}]})).add("CREATE_FIGURE",(function(e){return[{type:"DELETE_FIGURE",id:e.figure.id,sheetId:e.sheetId}]})).add("CREATE_CHART",(function(e){return[{type:"DELETE_FIGURE",id:e.id,sheetId:e.sheetId}]})).add("HIDE_COLUMNS_ROWS",(function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("UNHIDE_COLUMNS_ROWS",(function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}));for(const e of un.values())no.contains(e)||no.add(e,oo);function oo(e){return[e]}const so=[ln.number,ln.error,ln.text,ln.boolean];function ro(e,t){return{index:t,type:e?e.evaluated.type:ln.empty,value:e?e.evaluated.value:""}}function ao(e,t,i,n,o){let r=pn.Success,a=n.right>n.left;if(e.model.getters.doesIntersectMerge(t,n)){let i;a=!1;for(let o=n.top;o<=n.bottom;o++){i=[];for(let s=n.left;s<=n.right;s++){let n=e.model.getters.getMerge(t,s,o);n&&!i.includes(n.id.toString())&&i.push(n.id.toString())}if(i.length>=2){a=!0;break}}}const{col:l,row:c}=i;if(a)r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:n,sortDirection:o});else{const i=e.model.getters.getContiguousZone(t,n);Vi(i,n)?r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:n,sortDirection:o}):e.askConfirmation(s("We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?"),(()=>{n=i,r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:n,sortDirection:o})}),(()=>{r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:n,sortDirection:o})}))}if(r.isCancelledBecause(64)){const{col:t,row:o}=i;e.model.selection.selectZone({cell:{col:t,row:o},zone:n}),e.raiseError(s("Cannot sort. To sort, select only cells or only merges that have the same size."))}}function lo(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause(19)&&e.raiseError(s("This operation is not allowed with multiple selections."))}const co={filterOverlap:s("You cannot create overlapping filters."),nonContinuousTargets:s("A filter can only be created on a continuous selection."),mergeInFilter:s("You can't create a filter over a range that contains a merge.")};function ho(e,t,i){const n=e.model.dispatch("CREATE_FILTER_TABLE",{target:i,sheetId:t});n.isCancelledBecause(79)?e.raiseError(co.filterOverlap):n.isCancelledBecause(81)?e.raiseError(co.mergeInFilter):n.isCancelledBecause(82)&&e.raiseError(co.nonContinuousTargets)}const uo={wrongPasteSelection:s("This operation is not allowed with multiple selections."),willRemoveExistingMerge:s("This operation is not possible due to a merge. Please remove the merges first than try again."),wrongFigurePasteOption:s("Cannot do a special paste of a figure."),frozenPaneOverlap:s("Cannot paste merged cells over a frozen pane.")};function go(e,t){t.isSuccessful||(t.reasons.includes(20)?e.raiseError(uo.wrongPasteSelection):t.reasons.includes(2)?e.raiseError(uo.willRemoveExistingMerge):t.reasons.includes(22)?e.raiseError(uo.wrongFigurePasteOption):t.reasons.includes(76)&&e.raiseError(uo.frozenPaneOverlap))}function po(e,t,i){const n=e.model.dispatch("PASTE",{target:t,pasteOption:i});go(e,n)}function mo(e,t,i){const n=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,text:i});go(e,n)}function fo(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 vo(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 bo(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function So(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}async function Co(e){try{return await e.clipboard.readText()}catch(e){return console.warn("The OS clipboard could not be read."),void console.error(e)}}const Eo=async e=>{e.model.dispatch("COPY"),await e.clipboard.writeText(e.model.getters.getClipboardContent())},wo=async e=>{lo(e),await e.clipboard.writeText(e.model.getters.getClipboardContent())},yo=async e=>{const t=e.model.getters.getClipboardContent(),i=await Co(e),n=e.model.getters.getSelectedZones();i&&i!==t?mo(e,n,i):po(e,n)},xo=async e=>{const t=e.model.getters.getClipboardContent(),i=await Co(e),n=e.model.getters.getSelectedZones();i&&i!==t?e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:n,text:i}):e.model.dispatch("PASTE",{target:e.model.getters.getSelectedZones(),pasteOption:"onlyValue"})},Ro=e=>po(e,e.model.getters.getSelectedZones(),"onlyFormat"),Io=e=>!e.model.getters.isCutOperation(),To=e=>{if(e.model.getters.getSelectedZones().length>1)return s("Delete rows");let t,i;const n=e.model.getters.getActiveRows();if(0!==n.size)t=ct([...n]),i=lt([...n]);else{const n=e.model.getters.getSelectedZones()[0];t=n.top,i=n.bottom}return t===i?s("Delete row %s",(t+1).toString()):s("Delete rows %s - %s",(t+1).toString(),(i+1).toString())},Ao=e=>{let t=[...e.model.getters.getActiveRows()];if(!t.length){const i=e.model.getters.getSelectedZones()[0];for(let e=i.top;e<=i.bottom;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},Oo=(e,t)=>{const i=t.model.getters.getActiveSheetId(),n=t.model.getters.getElementsFromSelection(e),o=t.model.getters.checkElementsIncludeAllVisibleHeaders(i,e,n),s=t.model.getters.checkElementsIncludeAllNonFrozenHeaders(i,e,n);return!o&&!s},No=e=>{if(e.model.getters.getSelectedZones().length>1)return s("Delete columns");let t,i;const n=e.model.getters.getActiveCols();if(0!==n.size)t=ct([...n]),i=lt([...n]);else{const n=e.model.getters.getSelectedZones()[0];t=n.left,i=n.right}return t===i?s("Delete column %s",Lt(t)):s("Delete columns %s - %s",Lt(t),Lt(i))},Mo=e=>{let t=[...e.model.getters.getActiveCols()];if(!t.length){const i=e.model.getters.getSelectedZones()[0];for(let e=i.left;e<=i.right;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},_o=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});go(e,i)},Fo=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});go(e,i)},Do=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});go(e,i)},ko=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});go(e,i)},$o=e=>{const t=e.model.getters.getActiveRows();let i,n;if(t.size)i=ct([...t]),n=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.top,n=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",base:i,quantity:n,dimension:"ROW"})},Lo=e=>{const t=e.model.getters.getActiveRows();let i,n;if(t.size)i=lt([...t]),n=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.bottom,n=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",base:i,quantity:n,dimension:"ROW"})},Po=e=>{const t=e.model.getters.getActiveCols();let i,n;if(t.size)i=ct([...t]),n=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.left,n=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",dimension:"COL",base:i,quantity:n})},Uo=e=>{const t=e.model.getters.getActiveCols();let i,n;if(t.size)i=lt([...t]),n=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.right,n=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",dimension:"COL",base:i,quantity:n})},Vo=e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},zo=e=>{let{col:t,row:i}=e.model.getters.getPosition();e.model.dispatch("OPEN_CELL_POPOVER",{col:t,row:i,popoverType:"LinkEditor"})},Bo=e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,i)},Ho=e=>{const{anchor:t,zones:i}=e.model.getters.getSelection(),n=e.model.getters.getActiveSheetId();ao(e,n,t.cell,i[0],"ascending")},Wo=e=>{const{anchor:t,zones:i}=e.model.getters.getSelection(),n=e.model.getters.getActiveSheetId();ao(e,n,t.cell,i[0],"descending")},Go=e=>1===e.model.getters.getSelectedZones().length,qo=new Yn;qo.add("cut",{name:s("Cut"),description:"Ctrl+X",sequence:10,action:wo}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Eo}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:yo}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Io}).addChild("paste_value_only",["paste_special"],{name:s("Paste values only"),sequence:10,action:xo}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:Ro}).add("add_row_before",{name:e=>{const t=vo(e);return 1===t?s("Insert row"):s("Insert %s rows",t.toString())},sequence:70,action:$o,isVisible:Go}).add("add_column_before",{name:e=>{const t=fo(e);return 1===t?s("Insert column"):s("Insert %s columns",t.toString())},sequence:90,action:Po,isVisible:Go}).add("insert_cell",{name:s("Insert cells"),sequence:100,isVisible:Go,separator:!0}).addChild("insert_cell_down",["insert_cell"],{name:s("Shift down"),sequence:10,action:_o}).addChild("insert_cell_right",["insert_cell"],{name:s("Shift right"),sequence:20,action:Fo}).add("delete_row",{name:To,sequence:110,action:Ao,isVisible:Go}).add("delete_column",{name:No,sequence:120,action:Mo,isVisible:Go}).add("delete_cell",{name:s("Delete cells"),sequence:130,isVisible:Go}).addChild("delete_cell_up",["delete_cell"],{name:s("Shift up"),sequence:10,action:Do}).addChild("delete_cell_down",["delete_cell"],{name:s("Shift left"),sequence:20,action:ko}).add("insert_link",{name:e=>{const t=e.model.getters.getActiveSheetId(),{col:i,row:n}=e.model.getters.getPosition(),o=e.model.getters.getCell(t,i,n);return o&&o.isLink()?s("Edit link"):s("Insert link")},separator:!0,sequence:150,action:zo});const Zo=new Yn;Zo.add("cut",{name:s("Cut"),description:"Ctrl+X",sequence:10,action:wo}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Eo}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:yo}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Io}).addChild("paste_value_only",["paste_special"],{name:s("Paste value only"),sequence:10,action:xo}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:Ro}).add("sort_columns",{name:e=>e.model.getters.getActiveCols().size>1?s("Sort columns"):s("Sort column"),sequence:50,isVisible:Go,separator:!0}).addChild("sort_ascending",["sort_columns"],{name:s("Ascending (A ⟶ Z)"),sequence:10,action:Ho}).addChild("sort_descending",["sort_columns"],{name:s("Descending (Z ⟶ A)"),sequence:20,action:Wo}).add("add_column_before",{name:e=>{const t=fo(e);return 1===t?s("Insert column left"):s("Insert %s columns left",t.toString())},sequence:70,action:Po}).add("add_column_after",{name:e=>{const t=fo(e);return 1===t?s("Insert column right"):s("Insert %s columns right",t.toString())},sequence:80,action:Uo}).add("delete_column",{name:No,sequence:90,action:Mo,isVisible:e=>Oo("COL",e)}).add("clear_column",{name:e=>{if(e.model.getters.getSelectedZones().length>1)return s("Clear columns");let t,i;const n=e.model.getters.getActiveCols();if(0!==n.size)t=ct([...n]),i=lt([...n]);else{const n=e.model.getters.getSelectedZones()[0];t=n.left,i=n.right}return t===i?s("Clear column %s",Lt(t)):s("Clear columns %s - %s",Lt(t),Lt(i))},sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId(),i=[...e.model.getters.getActiveCols()].map((i=>e.model.getters.getColsZone(t,i,i)));e.model.dispatch("DELETE_CONTENT",{target:i,sheetId:e.model.getters.getActiveSheetId()})}}).add("hide_columns",{name:e=>{const t=e.model.getters.getElementsFromSelection("COL");let i=t[0],n=t[t.length-1];return 1===t.length?s("Hide column %s",Lt(i).toString()):n-i+1===t.length?s("Hide columns %s - %s",Lt(i).toString(),Lt(n).toString()):s("Hide columns")},sequence:85,action:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getElementsFromSelection("COL");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"COL",i)},separator:!0}).add("unhide_columns",{name:s("Unhide columns"),sequence:86,action:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("COL").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:s("Conditional formatting"),sequence:110,action:Vo});const jo=new Yn;function Yo(e,t,i){if(e.model.getters.isReadonly())return;const n=e.model.getters.getSheetName(t),o=s("Rename Sheet");e.editText(o,(i=>{if(null===i||i===n)return;const o=e.model.dispatch("RENAME_SHEET",{sheetId:t,name:i});o.isSuccessful||(o.reasons.includes(10)&&Yo(e,t,s("The sheet name cannot be empty.")),o.reasons.includes(11)&&Yo(e,t,s("A sheet with the name %s already exists. Please select another name.",i)),o.reasons.includes(13)&&Yo(e,t,s("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",ee.join(" "))))}),{placeholder:n,error:i})}jo.add("cut",{name:s("Cut"),sequence:10,description:"Ctrl+X",action:wo}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Eo}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:yo}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Io}).addChild("paste_value_only",["paste_special"],{name:s("Paste value only"),sequence:10,action:xo}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:Ro}).add("add_row_before",{name:e=>{const t=vo(e);return 1===t?s("Insert row above"):s("Insert %s rows above",t.toString())},sequence:50,action:$o}).add("add_row_after",{name:e=>{const t=vo(e);return 1===t?s("Insert row below"):s("Insert %s rows below",t.toString())},sequence:60,action:Lo}).add("delete_row",{name:To,sequence:70,action:Ao,isVisible:e=>Oo("ROW",e)}).add("clear_row",{name:e=>{if(e.model.getters.getSelectedZones().length>1)return s("Clear rows");let t,i;const n=e.model.getters.getActiveRows();if(0!==n.size)t=ct([...n]),i=lt([...n]);else{const n=e.model.getters.getSelectedZones()[0];t=n.top,i=n.bottom}return t===i?s("Clear row %s",(t+1).toString()):s("Clear rows %s - %s",(t+1).toString(),(i+1).toString())},sequence:80,action:e=>{const t=e.model.getters.getActiveSheetId(),i=[...e.model.getters.getActiveRows()].map((i=>e.model.getters.getRowsZone(t,i,i)));e.model.dispatch("DELETE_CONTENT",{target:i,sheetId:e.model.getters.getActiveSheetId()})}}).add("hide_rows",{name:e=>{const t=e.model.getters.getElementsFromSelection("ROW");let i=t[0],n=t[t.length-1];return 1===t.length?s("Hide row %s",(i+1).toString()):n-i+1===t.length?s("Hide rows %s - %s",(i+1).toString(),(n+1).toString()):s("Hide rows")},sequence:85,action:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getElementsFromSelection("ROW");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"ROW",i)},separator:!0}).add("unhide_rows",{name:s("Unhide rows"),sequence:86,action:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("ROW").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:s("Conditional formatting"),sequence:90,action:Vo});const Xo=new Yn;Xo.add("delete",{name:s("Delete"),sequence:10,isVisible:e=>e.model.getters.getVisibleSheetIds().length>1,action:e=>e.askConfirmation(s("Are you sure you want to delete this sheet ?"),(()=>{e.model.dispatch("DELETE_SHEET",{sheetId:e.model.getters.getActiveSheetId()})}))}).add("duplicate",{name:s("Duplicate"),sequence:20,action:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.uuidGenerator.smallUuid();e.model.dispatch("DUPLICATE_SHEET",{sheetId:t,sheetIdTo:i}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:i})}}).add("rename",{name:s("Rename"),sequence:30,action:e=>Yo(e,e.model.getters.getActiveSheetId())}).add("move_right",{name:s("Move right"),sequence:40,isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getVisibleSheetIds();return i.indexOf(t)!==i.length-1},action:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),direction:"right"})}).add("move_left",{name:s("Move left"),sequence:50,isVisible:e=>{const t=e.model.getters.getActiveSheetId();return e.model.getters.getVisibleSheetIds()[0]!==t},action:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),direction:"left"})}).add("hide_sheet",{name:s("Hide sheet"),sequence:60,isVisible:e=>1!==e.model.getters.getVisibleSheetIds().length,action:e=>e.model.dispatch("HIDE_SHEET",{sheetId:e.model.getters.getActiveSheetId()})});const Ko={Errors:{25:s("The range is invalid"),52:s("The argument is missing. Please provide a value"),53:s("The second argument is missing. Please provide a value"),54:s("The minpoint must be a number"),55:s("The midpoint must be a number"),56:s("The maxpoint must be a number"),57:s("The first value must be a number"),58:s("The second value must be a number"),48:s("Minimum must be smaller then Maximum"),51:s("Minimum must be smaller then Midpoint"),50:s("Midpoint must be smaller then Maximum"),49:s("Lower inflection point must be smaller than upper inflection point"),59:s("Invalid Minpoint formula"),61:s("Invalid Maxpoint formula"),60:s("Invalid Midpoint formula"),62:s("Invalid upper inflection point formula"),63:s("Invalid lower inflection point formula"),24:s("A range needs to be defined"),Unexpected:s("The rule is invalid for an unknown reason")},ColorScale:s("Color scale"),IconSet:s("Icon set")},Qo={IsEmpty:s("Is empty"),IsNotEmpty:s("Is not empty"),ContainsText:s("Contains"),NotContains:s("Does not contain"),BeginsWith:s("Starts with"),EndsWith:s("Ends with"),Equal:s("Is equal to"),NotEqual:s("Is not equal to"),GreaterThan:s("Is greater than"),GreaterThanOrEqual:s("Is greater than or equal to"),LessThan:s("Is less than"),LessThanOrEqual:s("Is less than or equal to"),Between:s("Is between"),NotBetween:s("Is not between")},Jo={Series:s("Series"),Errors:{Unexpected:s("The chart definition is invalid for an unknown reason"),33:s("The dataset is invalid"),34:s("Labels are invalid"),35:s("The key value is invalid"),36:s("The baseline value is invalid"),37:s("The data range is invalid"),38:s("A minimum range limit value is needed"),39:s("The minimum range limit value must be a number"),40:s("A maximum range limit value is needed"),41:s("The maximum range limit value must be a number"),42:s("Minimum range limit must be smaller than maximum range limit"),43:s("The lower inflection point value must be a number"),44:s("The upper inflection point value must be a number")}},es={Automatic:s("Automatic"),Number:s("Number"),Percent:s("Percent"),Currency:s("Currency"),CurrencyRounded:s("Currency rounded"),Date:s("Date"),Time:s("Time"),DateTime:s("Date time"),Duration:s("Duration"),CustomCurrency:s("Custom currency")},ts={Custom:s("Custom")},is=s("Merged cells are preventing this operation. Unmerge those cells and try again.");function ns(e,t,i){const n=e.model.getters.getActiveSheetId(),o="COL"===t?"FREEZE_COLUMNS":"FREEZE_ROWS";e.model.dispatch(o,{sheetId:n,quantity:i}).isCancelledBecause(66)&&e.raiseError(is)}const os=new Yn;os.add("file",{name:s("File"),sequence:10}).add("edit",{name:s("Edit"),sequence:20}).add("view",{name:s("View"),sequence:30}).add("insert",{name:s("Insert"),sequence:40}).add("format",{name:s("Format"),sequence:50}).add("data",{name:s("Data"),sequence:60}).addChild("save",["file"],{name:s("Save"),description:"Ctrl+S",sequence:10,action:()=>console.log("Not implemented")}).addChild("undo",["edit"],{name:s("Undo"),description:"Ctrl+Z",sequence:10,action:e=>e.model.dispatch("REQUEST_UNDO")}).addChild("redo",["edit"],{name:s("Redo"),description:"Ctrl+Y",sequence:20,action:e=>e.model.dispatch("REQUEST_REDO"),separator:!0}).addChild("copy",["edit"],{name:s("Copy"),description:"Ctrl+C",sequence:30,isReadonlyAllowed:!0,action:Eo}).addChild("cut",["edit"],{name:s("Cut"),description:"Ctrl+X",sequence:40,action:wo}).addChild("paste",["edit"],{name:s("Paste"),description:"Ctrl+V",sequence:50,action:yo}).addChild("paste_special",["edit"],{name:s("Paste special"),sequence:60,separator:!0,isVisible:Io}).addChild("paste_special_value",["edit","paste_special"],{name:s("Paste value only"),sequence:10,action:xo}).addChild("paste_special_format",["edit","paste_special"],{name:s("Paste format only"),sequence:20,action:Ro}).addChild("sort_range",["data"],{name:s("Sort range"),sequence:62,isVisible:Go,separator:!0}).addChild("sort_ascending",["data","sort_range"],{name:s("Ascending (A ⟶ Z)"),sequence:10,action:Ho}).addChild("sort_descending",["data","sort_range"],{name:s("Descending (Z ⟶ A)"),sequence:20,action:Wo}).addChild("find_and_replace",["edit"],{name:s("Find and replace"),description:"Ctrl+H",sequence:65,isReadonlyAllowed:!0,action:e=>{e.openSidePanel("FindAndReplace",{})},separator:!0}).addChild("edit_delete_cell_values",["edit"],{name:s("Delete values"),sequence:70,action:e=>e.model.dispatch("DELETE_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})}).addChild("edit_delete_row",["edit"],{name:To,sequence:80,action:Ao,isVisible:e=>Oo("ROW",e)}).addChild("edit_delete_column",["edit"],{name:No,sequence:90,action:Mo,isVisible:e=>Oo("COL",e)}).addChild("edit_delete_cell_shift_up",["edit"],{name:s("Delete cell and shift up"),sequence:93,action:Do}).addChild("edit_delete_cell_shift_left",["edit"],{name:s("Delete cell and shift left"),sequence:97,action:ko}).addChild("edit_unhide_columns",["edit"],{name:s("Unhide all columns"),sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"COL",elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0}).addChild("edit_unhide_rows",["edit"],{name:s("Unhide all rows"),sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"ROW",elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0}).addChild("insert_row_before",["insert"],{name:e=>{const t=vo(e);return 1===t?s("Row above"):s("%s Rows above",t.toString())},sequence:10,action:$o,isVisible:e=>0===e.model.getters.getActiveCols().size}).addChild("insert_row_after",["insert"],{name:e=>{const t=vo(e);return 1===t?s("Row below"):s("%s Rows below",t.toString())},sequence:20,action:Lo,isVisible:e=>0===e.model.getters.getActiveCols().size,separator:!0}).addChild("insert_column_before",["insert"],{name:e=>{const t=fo(e);return 1===t?s("Column left"):s("%s Columns left",t.toString())},sequence:30,action:Po,isVisible:e=>0===e.model.getters.getActiveRows().size}).addChild("insert_column_after",["insert"],{name:e=>{const t=fo(e);return 1===t?s("Column right"):s("%s Columns right",t.toString())},sequence:40,action:Uo,isVisible:e=>0===e.model.getters.getActiveRows().size,separator:!0}).addChild("insert_insert_cell_shift_down",["insert"],{name:s("Insert cells and shift down"),sequence:43,action:_o}).addChild("insert_insert_cell_shift_right",["insert"],{name:s("Insert cells and shift right"),sequence:47,action:Fo,separator:!0}).addChild("insert_chart",["insert"],{name:s("Chart"),sequence:50,action:e=>{const t=e.model.getters,i=t.getSelectedZone();let n=i;const o=e.model.uuidGenerator.smallUuid();let s;i.left!==i.right&&(n={...i,left:i.left+1});const r=[Fi(n)],a=t.getActiveSheetId(),l={width:536,height:335},{x:c,y:h}=t.getMainViewportCoordinates(),{scrollX:d,scrollY:u}=t.getActiveSheetScrollInfo(),{width:g,height:p}=t.getVisibleRect(t.getActiveMainViewport()),m={x:c+d+Math.max(0,(g-l.width)/2),y:h+u+Math.max(0,(p-l.height)/2)};let f="";const v=e.model.getters.getCellsInZone(a,{...n,bottom:n.top}),b=!!v.find((e=>e&&e.evaluated.type!==ln.number));if(b){const t=v.reduce(((t,i)=>{const n=i&&i.evaluated.type!==ln.error&&e.model.getters.getCellText(i);return n&&t.push(n),t}),[]),i=t.splice(-1)[0];f=t.join(", "),i&&(f+=(f?" "+e._t("and")+" ":"")+i)}i.left!==i.right&&(s=Fi({...i,right:i.left,top:b?i.top+1:i.top}));const S=n.right===n.left?"none":"top";e.model.dispatch("CREATE_CHART",{sheetId:a,id:o,position:m,size:l,definition:{title:f,dataSets:r,labelRange:s,type:"bar",stacked:!1,dataSetsHaveTitle:b,verticalAxisPosition:"left",legendPosition:S}}),e.model.dispatch("SELECT_FIGURE",{id:o}),e.openSidePanel("ChartPanel")}}).addChild("insert_link",["insert"],{name:s("Link"),separator:!0,sequence:60,action:zo}).addChild("insert_sheet",["insert"],{name:s("New sheet"),sequence:70,action:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSheetIds().indexOf(t)+1,n=e.model.uuidGenerator.smallUuid();e.model.dispatch("CREATE_SHEET",{sheetId:n,position:i}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:n})},separator:!0}).addChild("unfreeze_panes",["view"],{name:s("Unfreeze"),sequence:4,isVisible:e=>{const{xSplit:t,ySplit:i}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+i>0},action:e=>e.model.dispatch("UNFREEZE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId()})}).addChild("freeze_panes",["view"],{name:s("Freeze"),sequence:5,separator:!0}).addChild("unfreeze_rows",["view","freeze_panes"],{name:s("No rows"),action:e=>e.model.dispatch("UNFREEZE_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,sequence:5,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit}).addChild("freeze_first_row",["view","freeze_panes"],{name:s("1 row"),action:e=>ns(e,"ROW",1),isReadonlyAllowed:!0,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{name:s("2 rows"),action:e=>ns(e,"ROW",2),isReadonlyAllowed:!0,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{name:s("Up to current row"),action:e=>{const{bottom:t}=e.model.getters.getSelectedZone();ns(e,"ROW",t+1)},isReadonlyAllowed:!0,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{name:s("No columns"),action:e=>e.model.dispatch("UNFREEZE_COLUMNS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,sequence:25,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit}).addChild("freeze_first_col",["view","freeze_panes"],{name:s("1 column"),action:e=>ns(e,"COL",1),isReadonlyAllowed:!0,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{name:s("2 columns"),action:e=>ns(e,"COL",2),isReadonlyAllowed:!0,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{name:s("Up to current column"),action:e=>{const{right:t}=e.model.getters.getSelectedZone();ns(e,"COL",t+1)},isReadonlyAllowed:!0,sequence:40}).addChild("view_gridlines",["view"],{name:e=>e.model.getters.getGridLinesVisibility(e.model.getters.getActiveSheetId())?s("Hide gridlines"):s("Show gridlines"),action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},sequence:10}).addChild("view_formulas",["view"],{name:e=>e.model.getters.shouldShowFormulas()?s("Hide formulas"):s("Show formulas"),action:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,sequence:15}).addChild("format_number",["format"],{name:s("Numbers"),sequence:10,separator:!0}).addChild("format_number_automatic",["format","format_number"],{name:es.Automatic,sequence:10,separator:!0,action:e=>bo(e,"")}).addChild("format_number_number",["format","format_number"],{name:es.Number,description:"1,000.12",sequence:20,action:e=>bo(e,"#,##0.00")}).addChild("format_number_percent",["format","format_number"],{name:es.Percent,description:"10.12%",sequence:30,separator:!0,action:e=>bo(e,"0.00%")}).addChild("format_number_currency",["format","format_number"],{name:es.Currency,description:"$1,000.12",sequence:37,action:e=>bo(e,"[$$]#,##0.00")}).addChild("format_number_currency_rounded",["format","format_number"],{name:es.CurrencyRounded,description:"$1,000",sequence:38,action:e=>bo(e,"[$$]#,##0")}).addChild("format_custom_currency",["format","format_number"],{name:es.CustomCurrency,sequence:39,separator:!0,action:e=>{e.openSidePanel("CustomCurrency",{})}}).addChild("format_number_date",["format","format_number"],{name:es.Date,description:"9/26/2008",sequence:40,action:e=>bo(e,"m/d/yyyy")}).addChild("format_number_time",["format","format_number"],{name:es.Time,description:"10:43:00 PM",sequence:50,action:e=>bo(e,"hh:mm:ss a")}).addChild("format_number_date_time",["format","format_number"],{name:es.DateTime,description:"9/26/2008 22:43:00",sequence:60,action:e=>bo(e,"m/d/yyyy hh:mm:ss")}).addChild("format_number_duration",["format","format_number"],{name:es.Duration,description:"27:51:38",sequence:70,separator:!0,action:e=>bo(e,"hhhh:mm:ss")}).addChild("format_bold",["format"],{name:s("Bold"),sequence:20,description:"Ctrl+B",action:e=>So(e,{bold:!e.model.getters.getCurrentStyle().bold})}).addChild("format_italic",["format"],{name:s("Italic"),sequence:30,description:"Ctrl+I",action:e=>So(e,{italic:!e.model.getters.getCurrentStyle().italic})}).addChild("format_underline",["format"],{name:s("Underline"),description:"Ctrl+U",sequence:40,action:e=>So(e,{underline:!e.model.getters.getCurrentStyle().underline})}).addChild("format_strikethrough",["format"],{name:s("Strikethrough"),sequence:50,action:e=>So(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),separator:!0}).addChild("format_font_size",["format"],{name:s("Font size"),sequence:60}).addChild("format_wrapping",["format"],{name:s("Wrapping"),sequence:70,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{name:s("Overflow"),sequence:10,action:e=>So(e,{wrapping:"overflow"})}).addChild("format_wrapping_wrap",["format","format_wrapping"],{name:s("Wrap"),sequence:20,action:e=>So(e,{wrapping:"wrap"})}).addChild("format_wrapping_clip",["format","format_wrapping"],{name:s("Clip"),sequence:30,action:e=>So(e,{wrapping:"clip"})}).addChild("format_cf",["format"],{name:s("Conditional formatting"),sequence:80,action:Vo,separator:!0}).addChild("format_clearFormat",["format"],{name:s("Clear formatting"),sequence:90,action:e=>{e.model.dispatch("CLEAR_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},separator:!0}).addChild("add_data_filter",["data"],{name:s("Add Filter"),sequence:20,action:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSelection().zones;ho(e,t,i)},isVisible:e=>!Bo(e),isEnabled:e=>(e=>tn(...e.model.getters.getSelectedZones()))(e)}).addChild("remove_data_filter",["data"],{name:s("Remove Filter"),sequence:20,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:t,target:e.model.getters.getSelectedZones()})},isVisible:Bo});for(let e of se)os.addChild(`format_font_size_${e.pt}`,["format","format_font_size"],{name:e.pt.toString(),sequence:e.pt,action:t=>So(t,{fontSize:e.pt})});const ss=new class extends nn{addTransformation(e,t,i){for(let n of t)this.content[n]||(this.content[n]=new Map),this.content[n].set(e,i);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},rs=new Oi;wn`
272
+ `;class Jn extends t.Component{constructor(){super(...arguments),this.menuItems=Qn.getAll(),this.state=t.useState(this.defaultState),this.menu=t.useState({isOpen:!1}),this.linkEditorRef=t.useRef("linkEditor"),this.position=Hn(this.linkEditorRef),this.urlInput=t.useRef("urlInput")}setup(){t.onMounted((()=>{var e;return null===(e=this.urlInput.el)||void 0===e?void 0:e.focus()}))}get defaultState(){const{col:e,row:t}=this.props.cellPosition,i=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getCell(i,e,t);return(null==n?void 0:n.isLink())?{link:{url:n.link.url,label:n.formattedValue},urlRepresentation:n.urlRepresentation,isUrlEditable:n.isUrlEditable}:{link:{url:"",label:(null==n?void 0:n.formattedValue)||""},isUrlEditable:!0,urlRepresentation:""}}get menuPosition(){return{x:this.position.x+320-12-2,y:this.position.y+100}}onSpecialLink(e){const{detail:t}=e;this.state.link.url=t.link.url,this.state.link.label=t.link.label,this.state.isUrlEditable=t.isUrlEditable,this.state.urlRepresentation=t.urlRepresentation}openMenu(){this.menu.isOpen=!0}removeLink(){this.state.link.url="",this.state.urlRepresentation="",this.state.isUrlEditable=!0}save(){var e,t;const{col:i,row:n}=this.props.cellPosition,o=this.state.link.label||this.state.link.url;this.env.model.dispatch("UPDATE_CELL",{col:i,row:n,sheetId:this.env.model.getters.getActiveSheetId(),content:We(o,this.state.link.url)}),null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}cancel(){var e,t;null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}onKeyDown(e){switch(e.key){case"Enter":this.state.link.url&&this.save(),e.preventDefault();break;case"Escape":this.cancel()}}}Jn.template="o-spreadsheet-LinkEditor",Jn.size={width:340,height:180},Jn.components={Menu:Gn};const eo={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:Jn,cellCorner:"BottomLeft"})},to=new sn;to.add("ErrorToolTip",An).add("LinkCell",Zn).add("LinkEditor",eo).add("FilterMenu",_n);const io=new sn,no=new sn,oo=new sn,so=(new sn).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let i=e.base;"after"===e.position&&i++;for(let n=0;n<e.quantity;n++)t.push(n+i);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],i=[...e.elements].sort(((e,t)=>e-t));for(let n of Le(i)){const i=0===n[0]?0:n[0]-1,o=0===n[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:n.length,base:i,sheetId:e.sheetId,position:o})}return t})).add("ADD_MERGE",(function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]})).add("REMOVE_MERGE",(function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]})).add("CREATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId}]})).add("DELETE_SHEET",(function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1}]})).add("DUPLICATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo}]})).add("CREATE_FIGURE",(function(e){return[{type:"DELETE_FIGURE",id:e.figure.id,sheetId:e.sheetId}]})).add("CREATE_CHART",(function(e){return[{type:"DELETE_FIGURE",id:e.id,sheetId:e.sheetId}]})).add("HIDE_COLUMNS_ROWS",(function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("UNHIDE_COLUMNS_ROWS",(function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}));for(const e of pn.values())so.contains(e)||so.add(e,ro);function ro(e){return[e]}const ao=[hn.number,hn.error,hn.text,hn.boolean];function lo(e,t){return{index:t,type:e?e.evaluated.type:hn.empty,value:e?e.evaluated.value:""}}function co(e,t,i,n,o){let r=fn.Success,a=n.right>n.left;if(e.model.getters.doesIntersectMerge(t,n)){let i;a=!1;for(let o=n.top;o<=n.bottom;o++){i=[];for(let s=n.left;s<=n.right;s++){let n=e.model.getters.getMerge(t,s,o);n&&!i.includes(n.id.toString())&&i.push(n.id.toString())}if(i.length>=2){a=!0;break}}}const{col:l,row:c}=i;if(a)r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:n,sortDirection:o});else{const i=e.model.getters.getContiguousZone(t,n);Bi(i,n)?r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:n,sortDirection:o}):e.askConfirmation(s("We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?"),(()=>{n=i,r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:n,sortDirection:o})}),(()=>{r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:n,sortDirection:o})}))}if(r.isCancelledBecause(64)){const{col:t,row:o}=i;e.model.selection.selectZone({cell:{col:t,row:o},zone:n}),e.raiseError(s("Cannot sort. To sort, select only cells or only merges that have the same size."))}}function ho(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause(19)&&e.raiseError(s("This operation is not allowed with multiple selections."))}const uo={filterOverlap:s("You cannot create overlapping filters."),nonContinuousTargets:s("A filter can only be created on a continuous selection."),mergeInFilter:s("You can't create a filter over a range that contains a merge.")};function go(e,t,i){const n=e.model.dispatch("CREATE_FILTER_TABLE",{target:i,sheetId:t});n.isCancelledBecause(79)?e.raiseError(uo.filterOverlap):n.isCancelledBecause(81)?e.raiseError(uo.mergeInFilter):n.isCancelledBecause(82)&&e.raiseError(uo.nonContinuousTargets)}const po={wrongPasteSelection:s("This operation is not allowed with multiple selections."),willRemoveExistingMerge:s("This operation is not possible due to a merge. Please remove the merges first than try again."),wrongFigurePasteOption:s("Cannot do a special paste of a figure."),frozenPaneOverlap:s("Cannot paste merged cells over a frozen pane.")};function mo(e,t){t.isSuccessful||(t.reasons.includes(20)?e.raiseError(po.wrongPasteSelection):t.reasons.includes(2)?e.raiseError(po.willRemoveExistingMerge):t.reasons.includes(22)?e.raiseError(po.wrongFigurePasteOption):t.reasons.includes(76)&&e.raiseError(po.frozenPaneOverlap))}function fo(e,t,i){const n=e.model.dispatch("PASTE",{target:t,pasteOption:i});mo(e,n)}function vo(e,t,i){const n=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,text:i});mo(e,n)}function bo(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 So(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 Co(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function Eo(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}async function wo(e){try{return await e.clipboard.readText()}catch(e){return console.warn("The OS clipboard could not be read."),void console.error(e)}}const yo=async e=>{e.model.dispatch("COPY"),await e.clipboard.writeText(e.model.getters.getClipboardContent())},xo=async e=>{ho(e),await e.clipboard.writeText(e.model.getters.getClipboardContent())},Ro=async e=>{const t=e.model.getters.getClipboardContent(),i=await wo(e),n=e.model.getters.getSelectedZones();i&&i!==t?vo(e,n,i):fo(e,n)},Io=async e=>{const t=e.model.getters.getClipboardContent(),i=await wo(e),n=e.model.getters.getSelectedZones();i&&i!==t?e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:n,text:i}):e.model.dispatch("PASTE",{target:e.model.getters.getSelectedZones(),pasteOption:"onlyValue"})},To=e=>fo(e,e.model.getters.getSelectedZones(),"onlyFormat"),Ao=e=>!e.model.getters.isCutOperation(),No=e=>{if(e.model.getters.getSelectedZones().length>1)return s("Delete rows");let t,i;const n=e.model.getters.getActiveRows();if(0!==n.size)t=ct([...n]),i=lt([...n]);else{const n=e.model.getters.getSelectedZones()[0];t=n.top,i=n.bottom}return t===i?s("Delete row %s",(t+1).toString()):s("Delete rows %s - %s",(t+1).toString(),(i+1).toString())},Oo=e=>{let t=[...e.model.getters.getActiveRows()];if(!t.length){const i=e.model.getters.getSelectedZones()[0];for(let e=i.top;e<=i.bottom;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},Mo=(e,t)=>{const i=t.model.getters.getActiveSheetId(),n=t.model.getters.getElementsFromSelection(e),o=t.model.getters.checkElementsIncludeAllVisibleHeaders(i,e,n),s=t.model.getters.checkElementsIncludeAllNonFrozenHeaders(i,e,n);return!o&&!s},_o=e=>{if(e.model.getters.getSelectedZones().length>1)return s("Delete columns");let t,i;const n=e.model.getters.getActiveCols();if(0!==n.size)t=ct([...n]),i=lt([...n]);else{const n=e.model.getters.getSelectedZones()[0];t=n.left,i=n.right}return t===i?s("Delete column %s",Lt(t)):s("Delete columns %s - %s",Lt(t),Lt(i))},Fo=e=>{let t=[...e.model.getters.getActiveCols()];if(!t.length){const i=e.model.getters.getSelectedZones()[0];for(let e=i.left;e<=i.right;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},Do=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});mo(e,i)},ko=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});mo(e,i)},$o=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});mo(e,i)},Lo=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});mo(e,i)},Po=e=>{const t=e.model.getters.getActiveRows();let i,n;if(t.size)i=ct([...t]),n=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.top,n=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",base:i,quantity:n,dimension:"ROW"})},Uo=e=>{const t=e.model.getters.getActiveRows();let i,n;if(t.size)i=lt([...t]),n=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.bottom,n=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",base:i,quantity:n,dimension:"ROW"})},Vo=e=>{const t=e.model.getters.getActiveCols();let i,n;if(t.size)i=ct([...t]),n=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.left,n=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",dimension:"COL",base:i,quantity:n})},zo=e=>{const t=e.model.getters.getActiveCols();let i,n;if(t.size)i=lt([...t]),n=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.right,n=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",dimension:"COL",base:i,quantity:n})},Bo=e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},Ho=e=>{let{col:t,row:i}=e.model.getters.getPosition();e.model.dispatch("OPEN_CELL_POPOVER",{col:t,row:i,popoverType:"LinkEditor"})},Wo=e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,i)},Go=e=>{const{anchor:t,zones:i}=e.model.getters.getSelection(),n=e.model.getters.getActiveSheetId();co(e,n,t.cell,i[0],"ascending")},qo=e=>{const{anchor:t,zones:i}=e.model.getters.getSelection(),n=e.model.getters.getActiveSheetId();co(e,n,t.cell,i[0],"descending")},Zo=e=>1===e.model.getters.getSelectedZones().length,jo=new Kn;jo.add("cut",{name:s("Cut"),description:"Ctrl+X",sequence:10,action:xo}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:yo}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:Ro}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Ao}).addChild("paste_value_only",["paste_special"],{name:s("Paste values only"),sequence:10,action:Io}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:To}).add("add_row_before",{name:e=>{const t=So(e);return 1===t?s("Insert row"):s("Insert %s rows",t.toString())},sequence:70,action:Po,isVisible:Zo}).add("add_column_before",{name:e=>{const t=bo(e);return 1===t?s("Insert column"):s("Insert %s columns",t.toString())},sequence:90,action:Vo,isVisible:Zo}).add("insert_cell",{name:s("Insert cells"),sequence:100,isVisible:Zo,separator:!0}).addChild("insert_cell_down",["insert_cell"],{name:s("Shift down"),sequence:10,action:Do}).addChild("insert_cell_right",["insert_cell"],{name:s("Shift right"),sequence:20,action:ko}).add("delete_row",{name:No,sequence:110,action:Oo,isVisible:Zo}).add("delete_column",{name:_o,sequence:120,action:Fo,isVisible:Zo}).add("delete_cell",{name:s("Delete cells"),sequence:130,isVisible:Zo}).addChild("delete_cell_up",["delete_cell"],{name:s("Shift up"),sequence:10,action:$o}).addChild("delete_cell_down",["delete_cell"],{name:s("Shift left"),sequence:20,action:Lo}).add("insert_link",{name:e=>{const t=e.model.getters.getActiveSheetId(),{col:i,row:n}=e.model.getters.getPosition(),o=e.model.getters.getCell(t,i,n);return o&&o.isLink()?s("Edit link"):s("Insert link")},separator:!0,sequence:150,action:Ho});const Yo=new Kn;Yo.add("cut",{name:s("Cut"),description:"Ctrl+X",sequence:10,action:xo}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:yo}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:Ro}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Ao}).addChild("paste_value_only",["paste_special"],{name:s("Paste value only"),sequence:10,action:Io}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:To}).add("sort_columns",{name:e=>e.model.getters.getActiveCols().size>1?s("Sort columns"):s("Sort column"),sequence:50,isVisible:Zo,separator:!0}).addChild("sort_ascending",["sort_columns"],{name:s("Ascending (A ⟶ Z)"),sequence:10,action:Go}).addChild("sort_descending",["sort_columns"],{name:s("Descending (Z ⟶ A)"),sequence:20,action:qo}).add("add_column_before",{name:e=>{const t=bo(e);return 1===t?s("Insert column left"):s("Insert %s columns left",t.toString())},sequence:70,action:Vo}).add("add_column_after",{name:e=>{const t=bo(e);return 1===t?s("Insert column right"):s("Insert %s columns right",t.toString())},sequence:80,action:zo}).add("delete_column",{name:_o,sequence:90,action:Fo,isVisible:e=>Mo("COL",e)}).add("clear_column",{name:e=>{if(e.model.getters.getSelectedZones().length>1)return s("Clear columns");let t,i;const n=e.model.getters.getActiveCols();if(0!==n.size)t=ct([...n]),i=lt([...n]);else{const n=e.model.getters.getSelectedZones()[0];t=n.left,i=n.right}return t===i?s("Clear column %s",Lt(t)):s("Clear columns %s - %s",Lt(t),Lt(i))},sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId(),i=[...e.model.getters.getActiveCols()].map((i=>e.model.getters.getColsZone(t,i,i)));e.model.dispatch("DELETE_CONTENT",{target:i,sheetId:e.model.getters.getActiveSheetId()})}}).add("hide_columns",{name:e=>{const t=e.model.getters.getElementsFromSelection("COL");let i=t[0],n=t[t.length-1];return 1===t.length?s("Hide column %s",Lt(i).toString()):n-i+1===t.length?s("Hide columns %s - %s",Lt(i).toString(),Lt(n).toString()):s("Hide columns")},sequence:85,action:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getElementsFromSelection("COL");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"COL",i)},separator:!0}).add("unhide_columns",{name:s("Unhide columns"),sequence:86,action:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("COL").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:s("Conditional formatting"),sequence:110,action:Bo});const Xo=new Kn;function Ko(e,t,i){if(e.model.getters.isReadonly())return;const n=e.model.getters.getSheetName(t),o=s("Rename Sheet");e.editText(o,(i=>{if(null===i||i===n)return;const o=e.model.dispatch("RENAME_SHEET",{sheetId:t,name:i});o.isSuccessful||(o.reasons.includes(10)&&Ko(e,t,s("The sheet name cannot be empty.")),o.reasons.includes(11)&&Ko(e,t,s("A sheet with the name %s already exists. Please select another name.",i)),o.reasons.includes(13)&&Ko(e,t,s("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",ee.join(" "))))}),{placeholder:n,error:i})}Xo.add("cut",{name:s("Cut"),sequence:10,description:"Ctrl+X",action:xo}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:yo}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:Ro}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Ao}).addChild("paste_value_only",["paste_special"],{name:s("Paste value only"),sequence:10,action:Io}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:To}).add("add_row_before",{name:e=>{const t=So(e);return 1===t?s("Insert row above"):s("Insert %s rows above",t.toString())},sequence:50,action:Po}).add("add_row_after",{name:e=>{const t=So(e);return 1===t?s("Insert row below"):s("Insert %s rows below",t.toString())},sequence:60,action:Uo}).add("delete_row",{name:No,sequence:70,action:Oo,isVisible:e=>Mo("ROW",e)}).add("clear_row",{name:e=>{if(e.model.getters.getSelectedZones().length>1)return s("Clear rows");let t,i;const n=e.model.getters.getActiveRows();if(0!==n.size)t=ct([...n]),i=lt([...n]);else{const n=e.model.getters.getSelectedZones()[0];t=n.top,i=n.bottom}return t===i?s("Clear row %s",(t+1).toString()):s("Clear rows %s - %s",(t+1).toString(),(i+1).toString())},sequence:80,action:e=>{const t=e.model.getters.getActiveSheetId(),i=[...e.model.getters.getActiveRows()].map((i=>e.model.getters.getRowsZone(t,i,i)));e.model.dispatch("DELETE_CONTENT",{target:i,sheetId:e.model.getters.getActiveSheetId()})}}).add("hide_rows",{name:e=>{const t=e.model.getters.getElementsFromSelection("ROW");let i=t[0],n=t[t.length-1];return 1===t.length?s("Hide row %s",(i+1).toString()):n-i+1===t.length?s("Hide rows %s - %s",(i+1).toString(),(n+1).toString()):s("Hide rows")},sequence:85,action:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getElementsFromSelection("ROW");return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,"ROW",i)},separator:!0}).add("unhide_rows",{name:s("Unhide rows"),sequence:86,action:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("ROW").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:s("Conditional formatting"),sequence:90,action:Bo});const Qo=new Kn;Qo.add("delete",{name:s("Delete"),sequence:10,isVisible:e=>e.model.getters.getVisibleSheetIds().length>1,action:e=>e.askConfirmation(s("Are you sure you want to delete this sheet ?"),(()=>{e.model.dispatch("DELETE_SHEET",{sheetId:e.model.getters.getActiveSheetId()})}))}).add("duplicate",{name:s("Duplicate"),sequence:20,action:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSheetName(t),n=e.model.uuidGenerator.smallUuid(),o=e.model.getters.getDuplicateSheetName(i);e.model.dispatch("DUPLICATE_SHEET",{sheetId:t,sheetIdTo:n,sheetNameTo:o}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:n})}}).add("rename",{name:s("Rename"),sequence:30,action:e=>Ko(e,e.model.getters.getActiveSheetId())}).add("move_right",{name:s("Move right"),sequence:40,isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getVisibleSheetIds();return i.indexOf(t)!==i.length-1},action:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),direction:"right"})}).add("move_left",{name:s("Move left"),sequence:50,isVisible:e=>{const t=e.model.getters.getActiveSheetId();return e.model.getters.getVisibleSheetIds()[0]!==t},action:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),direction:"left"})}).add("hide_sheet",{name:s("Hide sheet"),sequence:60,isVisible:e=>1!==e.model.getters.getVisibleSheetIds().length,action:e=>e.model.dispatch("HIDE_SHEET",{sheetId:e.model.getters.getActiveSheetId()})});const Jo={Errors:{25:s("The range is invalid"),52:s("The argument is missing. Please provide a value"),53:s("The second argument is missing. Please provide a value"),54:s("The minpoint must be a number"),55:s("The midpoint must be a number"),56:s("The maxpoint must be a number"),57:s("The first value must be a number"),58:s("The second value must be a number"),48:s("Minimum must be smaller then Maximum"),51:s("Minimum must be smaller then Midpoint"),50:s("Midpoint must be smaller then Maximum"),49:s("Lower inflection point must be smaller than upper inflection point"),59:s("Invalid Minpoint formula"),61:s("Invalid Maxpoint formula"),60:s("Invalid Midpoint formula"),62:s("Invalid upper inflection point formula"),63:s("Invalid lower inflection point formula"),24:s("A range needs to be defined"),Unexpected:s("The rule is invalid for an unknown reason")},ColorScale:s("Color scale"),IconSet:s("Icon set")},es={IsEmpty:s("Is empty"),IsNotEmpty:s("Is not empty"),ContainsText:s("Contains"),NotContains:s("Does not contain"),BeginsWith:s("Starts with"),EndsWith:s("Ends with"),Equal:s("Is equal to"),NotEqual:s("Is not equal to"),GreaterThan:s("Is greater than"),GreaterThanOrEqual:s("Is greater than or equal to"),LessThan:s("Is less than"),LessThanOrEqual:s("Is less than or equal to"),Between:s("Is between"),NotBetween:s("Is not between")},ts={Series:s("Series"),Errors:{Unexpected:s("The chart definition is invalid for an unknown reason"),33:s("The dataset is invalid"),34:s("Labels are invalid"),35:s("The key value is invalid"),36:s("The baseline value is invalid"),37:s("The data range is invalid"),38:s("A minimum range limit value is needed"),39:s("The minimum range limit value must be a number"),40:s("A maximum range limit value is needed"),41:s("The maximum range limit value must be a number"),42:s("Minimum range limit must be smaller than maximum range limit"),43:s("The lower inflection point value must be a number"),44:s("The upper inflection point value must be a number")}},is={Automatic:s("Automatic"),Number:s("Number"),Percent:s("Percent"),Currency:s("Currency"),CurrencyRounded:s("Currency rounded"),Date:s("Date"),Time:s("Time"),DateTime:s("Date time"),Duration:s("Duration"),CustomCurrency:s("Custom currency")},ns={Custom:s("Custom")},os=s("Merged cells are preventing this operation. Unmerge those cells and try again.");function ss(e,t,i){const n=e.model.getters.getActiveSheetId(),o="COL"===t?"FREEZE_COLUMNS":"FREEZE_ROWS";e.model.dispatch(o,{sheetId:n,quantity:i}).isCancelledBecause(66)&&e.raiseError(os)}const rs=new Kn;rs.add("file",{name:s("File"),sequence:10}).add("edit",{name:s("Edit"),sequence:20}).add("view",{name:s("View"),sequence:30}).add("insert",{name:s("Insert"),sequence:40}).add("format",{name:s("Format"),sequence:50}).add("data",{name:s("Data"),sequence:60}).addChild("save",["file"],{name:s("Save"),description:"Ctrl+S",sequence:10,action:()=>console.log("Not implemented")}).addChild("undo",["edit"],{name:s("Undo"),description:"Ctrl+Z",sequence:10,action:e=>e.model.dispatch("REQUEST_UNDO")}).addChild("redo",["edit"],{name:s("Redo"),description:"Ctrl+Y",sequence:20,action:e=>e.model.dispatch("REQUEST_REDO"),separator:!0}).addChild("copy",["edit"],{name:s("Copy"),description:"Ctrl+C",sequence:30,isReadonlyAllowed:!0,action:yo}).addChild("cut",["edit"],{name:s("Cut"),description:"Ctrl+X",sequence:40,action:xo}).addChild("paste",["edit"],{name:s("Paste"),description:"Ctrl+V",sequence:50,action:Ro}).addChild("paste_special",["edit"],{name:s("Paste special"),sequence:60,separator:!0,isVisible:Ao}).addChild("paste_special_value",["edit","paste_special"],{name:s("Paste value only"),sequence:10,action:Io}).addChild("paste_special_format",["edit","paste_special"],{name:s("Paste format only"),sequence:20,action:To}).addChild("sort_range",["data"],{name:s("Sort range"),sequence:62,isVisible:Zo,separator:!0}).addChild("sort_ascending",["data","sort_range"],{name:s("Ascending (A ⟶ Z)"),sequence:10,action:Go}).addChild("sort_descending",["data","sort_range"],{name:s("Descending (Z ⟶ A)"),sequence:20,action:qo}).addChild("find_and_replace",["edit"],{name:s("Find and replace"),description:"Ctrl+H",sequence:65,isReadonlyAllowed:!0,action:e=>{e.openSidePanel("FindAndReplace",{})},separator:!0}).addChild("edit_delete_cell_values",["edit"],{name:s("Delete values"),sequence:70,action:e=>e.model.dispatch("DELETE_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})}).addChild("edit_delete_row",["edit"],{name:No,sequence:80,action:Oo,isVisible:e=>Mo("ROW",e)}).addChild("edit_delete_column",["edit"],{name:_o,sequence:90,action:Fo,isVisible:e=>Mo("COL",e)}).addChild("edit_delete_cell_shift_up",["edit"],{name:s("Delete cell and shift up"),sequence:93,action:$o}).addChild("edit_delete_cell_shift_left",["edit"],{name:s("Delete cell and shift left"),sequence:97,action:Lo}).addChild("edit_unhide_columns",["edit"],{name:s("Unhide all columns"),sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"COL",elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0}).addChild("edit_unhide_rows",["edit"],{name:s("Unhide all rows"),sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"ROW",elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0}).addChild("insert_row_before",["insert"],{name:e=>{const t=So(e);return 1===t?s("Row above"):s("%s Rows above",t.toString())},sequence:10,action:Po,isVisible:e=>0===e.model.getters.getActiveCols().size}).addChild("insert_row_after",["insert"],{name:e=>{const t=So(e);return 1===t?s("Row below"):s("%s Rows below",t.toString())},sequence:20,action:Uo,isVisible:e=>0===e.model.getters.getActiveCols().size,separator:!0}).addChild("insert_column_before",["insert"],{name:e=>{const t=bo(e);return 1===t?s("Column left"):s("%s Columns left",t.toString())},sequence:30,action:Vo,isVisible:e=>0===e.model.getters.getActiveRows().size}).addChild("insert_column_after",["insert"],{name:e=>{const t=bo(e);return 1===t?s("Column right"):s("%s Columns right",t.toString())},sequence:40,action:zo,isVisible:e=>0===e.model.getters.getActiveRows().size,separator:!0}).addChild("insert_insert_cell_shift_down",["insert"],{name:s("Insert cells and shift down"),sequence:43,action:Do}).addChild("insert_insert_cell_shift_right",["insert"],{name:s("Insert cells and shift right"),sequence:47,action:ko,separator:!0}).addChild("insert_chart",["insert"],{name:s("Chart"),sequence:50,action:e=>{const t=e.model.getters,i=t.getSelectedZone();let n=i;const o=e.model.uuidGenerator.smallUuid();let s;i.left!==i.right&&(n={...i,left:i.left+1});const r=[ki(n)],a=t.getActiveSheetId(),l={width:536,height:335},{x:c,y:h}=t.getMainViewportCoordinates(),{scrollX:d,scrollY:u}=t.getActiveSheetScrollInfo(),{width:g,height:p}=t.getVisibleRect(t.getActiveMainViewport()),m={x:c+d+Math.max(0,(g-l.width)/2),y:h+u+Math.max(0,(p-l.height)/2)};let f="";const v=e.model.getters.getCellsInZone(a,{...n,bottom:n.top}),b=!!v.find((e=>e&&e.evaluated.type!==hn.number));if(b){const t=v.reduce(((t,i)=>{const n=i&&i.evaluated.type!==hn.error&&e.model.getters.getCellText(i);return n&&t.push(n),t}),[]),i=t.splice(-1)[0];f=t.join(", "),i&&(f+=(f?" "+e._t("and")+" ":"")+i)}i.left!==i.right&&(s=ki({...i,right:i.left,top:b?i.top+1:i.top}));const S=n.right===n.left?"none":"top";e.model.dispatch("CREATE_CHART",{sheetId:a,id:o,position:m,size:l,definition:{title:f,dataSets:r,labelRange:s,type:"bar",stacked:!1,dataSetsHaveTitle:b,verticalAxisPosition:"left",legendPosition:S}}),e.model.dispatch("SELECT_FIGURE",{id:o}),e.openSidePanel("ChartPanel")}}).addChild("insert_link",["insert"],{name:s("Link"),separator:!0,sequence:60,action:Ho}).addChild("insert_sheet",["insert"],{name:s("New sheet"),sequence:70,action:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSheetIds().indexOf(t)+1,n=e.model.uuidGenerator.smallUuid();e.model.dispatch("CREATE_SHEET",{sheetId:n,position:i}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:n})},separator:!0}).addChild("unfreeze_panes",["view"],{name:s("Unfreeze"),sequence:4,isVisible:e=>{const{xSplit:t,ySplit:i}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+i>0},action:e=>e.model.dispatch("UNFREEZE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId()})}).addChild("freeze_panes",["view"],{name:s("Freeze"),sequence:5,separator:!0}).addChild("unfreeze_rows",["view","freeze_panes"],{name:s("No rows"),action:e=>e.model.dispatch("UNFREEZE_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,sequence:5,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit}).addChild("freeze_first_row",["view","freeze_panes"],{name:s("1 row"),action:e=>ss(e,"ROW",1),isReadonlyAllowed:!0,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{name:s("2 rows"),action:e=>ss(e,"ROW",2),isReadonlyAllowed:!0,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{name:s("Up to current row"),action:e=>{const{bottom:t}=e.model.getters.getSelectedZone();ss(e,"ROW",t+1)},isReadonlyAllowed:!0,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{name:s("No columns"),action:e=>e.model.dispatch("UNFREEZE_COLUMNS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,sequence:25,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit}).addChild("freeze_first_col",["view","freeze_panes"],{name:s("1 column"),action:e=>ss(e,"COL",1),isReadonlyAllowed:!0,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{name:s("2 columns"),action:e=>ss(e,"COL",2),isReadonlyAllowed:!0,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{name:s("Up to current column"),action:e=>{const{right:t}=e.model.getters.getSelectedZone();ss(e,"COL",t+1)},isReadonlyAllowed:!0,sequence:40}).addChild("view_gridlines",["view"],{name:e=>e.model.getters.getGridLinesVisibility(e.model.getters.getActiveSheetId())?s("Hide gridlines"):s("Show gridlines"),action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},sequence:10}).addChild("view_formulas",["view"],{name:e=>e.model.getters.shouldShowFormulas()?s("Hide formulas"):s("Show formulas"),action:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,sequence:15}).addChild("format_number",["format"],{name:s("Numbers"),sequence:10,separator:!0}).addChild("format_number_automatic",["format","format_number"],{name:is.Automatic,sequence:10,separator:!0,action:e=>Co(e,"")}).addChild("format_number_number",["format","format_number"],{name:is.Number,description:"1,000.12",sequence:20,action:e=>Co(e,"#,##0.00")}).addChild("format_number_percent",["format","format_number"],{name:is.Percent,description:"10.12%",sequence:30,separator:!0,action:e=>Co(e,"0.00%")}).addChild("format_number_currency",["format","format_number"],{name:is.Currency,description:"$1,000.12",sequence:37,action:e=>Co(e,"[$$]#,##0.00")}).addChild("format_number_currency_rounded",["format","format_number"],{name:is.CurrencyRounded,description:"$1,000",sequence:38,action:e=>Co(e,"[$$]#,##0")}).addChild("format_custom_currency",["format","format_number"],{name:is.CustomCurrency,sequence:39,separator:!0,action:e=>{e.openSidePanel("CustomCurrency",{})}}).addChild("format_number_date",["format","format_number"],{name:is.Date,description:"9/26/2008",sequence:40,action:e=>Co(e,"m/d/yyyy")}).addChild("format_number_time",["format","format_number"],{name:is.Time,description:"10:43:00 PM",sequence:50,action:e=>Co(e,"hh:mm:ss a")}).addChild("format_number_date_time",["format","format_number"],{name:is.DateTime,description:"9/26/2008 22:43:00",sequence:60,action:e=>Co(e,"m/d/yyyy hh:mm:ss")}).addChild("format_number_duration",["format","format_number"],{name:is.Duration,description:"27:51:38",sequence:70,separator:!0,action:e=>Co(e,"hhhh:mm:ss")}).addChild("format_bold",["format"],{name:s("Bold"),sequence:20,description:"Ctrl+B",action:e=>Eo(e,{bold:!e.model.getters.getCurrentStyle().bold})}).addChild("format_italic",["format"],{name:s("Italic"),sequence:30,description:"Ctrl+I",action:e=>Eo(e,{italic:!e.model.getters.getCurrentStyle().italic})}).addChild("format_underline",["format"],{name:s("Underline"),description:"Ctrl+U",sequence:40,action:e=>Eo(e,{underline:!e.model.getters.getCurrentStyle().underline})}).addChild("format_strikethrough",["format"],{name:s("Strikethrough"),sequence:50,action:e=>Eo(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),separator:!0}).addChild("format_font_size",["format"],{name:s("Font size"),sequence:60}).addChild("format_wrapping",["format"],{name:s("Wrapping"),sequence:70,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{name:s("Overflow"),sequence:10,action:e=>Eo(e,{wrapping:"overflow"})}).addChild("format_wrapping_wrap",["format","format_wrapping"],{name:s("Wrap"),sequence:20,action:e=>Eo(e,{wrapping:"wrap"})}).addChild("format_wrapping_clip",["format","format_wrapping"],{name:s("Clip"),sequence:30,action:e=>Eo(e,{wrapping:"clip"})}).addChild("format_cf",["format"],{name:s("Conditional formatting"),sequence:80,action:Bo,separator:!0}).addChild("format_clearFormat",["format"],{name:s("Clear formatting"),sequence:90,action:e=>{e.model.dispatch("CLEAR_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},separator:!0}).addChild("add_data_filter",["data"],{name:s("Add Filter"),sequence:20,action:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSelection().zones;go(e,t,i)},isVisible:e=>!Wo(e),isEnabled:e=>(e=>on(...e.model.getters.getSelectedZones()))(e)}).addChild("remove_data_filter",["data"],{name:s("Remove Filter"),sequence:20,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:t,target:e.model.getters.getSelectedZones()})},isVisible:Wo});for(let e of se)rs.addChild(`format_font_size_${e.pt}`,["format","format_font_size"],{name:e.pt.toString(),sequence:e.pt,action:t=>Eo(t,{fontSize:e.pt})});const as=new class extends sn{addTransformation(e,t,i){for(let n of t)this.content[n]||(this.content[n]=new Map),this.content[n].set(e,i);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},ls=new Mi;xn`
273
273
  .o-selection {
274
274
  .o-selection-input {
275
275
  display: flex;
@@ -319,7 +319,7 @@
319
319
  font-size: calc(100% + 4px);
320
320
  }
321
321
  }
322
- `;class as extends t.Component{constructor(){super(...arguments),this.id=rs.smallUuid(),this.previousRanges=this.props.ranges||[],this.originSheet=this.env.model.getters.getActiveSheetId(),this.state=t.useState({isMissing:!1})}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.toString(),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.onMounted((()=>this.enableNewSelectionInput())),t.onWillUnmount((async()=>this.disableNewSelectionInput())),t.onPatched((()=>this.checkChange()))}enableNewSelectionInput(){this.env.model.dispatch("ENABLE_NEW_SELECTION_INPUT",{id:this.id,initialRanges:this.props.ranges,hasSingleRange:this.props.hasSingleRange})}disableNewSelectionInput(){this.env.model.dispatch("DISABLE_SELECTION_INPUT",{id:this.id})}checkChange(){const e=this.env.model.getters.getSelectionInputValue(this.id);this.previousRanges.join()!==e.join()&&this.triggerChange()}getColor(e){return"color: "+(e.color||"#000")+";"}triggerChange(){var e,t;const i=this.env.model.getters.getSelectionInputValue(this.id);null===(t=(e=this.props).onSelectionChanged)||void 0===t||t.call(e,i),this.previousRanges=i}extractRanges(e){return this.props.hasSingleRange?e.split(",")[0]:e}focus(e){this.state.isMissing=!1,this.env.model.dispatch("FOCUS_RANGE",{id:this.id,rangeId:e})}addEmptyInput(){this.env.model.dispatch("ADD_EMPTY_RANGE",{id:this.id})}removeInput(e){var t,i;this.env.model.dispatch("REMOVE_RANGE",{id:this.id,rangeId:e}),this.triggerChange(),null===(i=(t=this.props).onSelectionConfirmed)||void 0===i||i.call(t)}onInputChanged(e,t){const i=t.target,n=this.extractRanges(i.value);this.env.model.dispatch("CHANGE_RANGE",{id:this.id,rangeId:e,value:n}),i.blur(),this.triggerChange()}confirm(){var e,t;this.env.model.dispatch("UNFOCUS_SELECTION_INPUT");const i=this.env.model.getters.getSelectionInputValue(this.id);this.props.required&&0===i.length&&(this.state.isMissing=!0);const n=this.env.model.getters.getActiveSheetId();this.originSheet!==n&&this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:n,sheetIdTo:this.originSheet}),null===(t=(e=this.props).onSelectionConfirmed)||void 0===t||t.call(e)}}as.template="o-spreadsheet-SelectionInput";class ls extends t.Component{constructor(){super(...arguments),this.state=t.useState({datasetDispatchResult:void 0,labelsDispatchResult:void 0}),this.dataSeriesRanges=[]}setup(){this.dataSeriesRanges=this.props.definition.dataSets,this.labelRange=this.props.definition.labelRange}get errorMessages(){var e,t;return[...(null===(e=this.state.datasetDispatchResult)||void 0===e?void 0:e.reasons)||[],...(null===(t=this.state.labelsDispatchResult)||void 0===t?void 0:t.reasons)||[]].map((e=>Jo.Errors[e]||Jo.Errors.Unexpected))}get isDatasetInvalid(){var e;return!!(null===(e=this.state.datasetDispatchResult)||void 0===e?void 0:e.isCancelledBecause(33))}get isLabelInvalid(){var e;return!!(null===(e=this.state.labelsDispatchResult)||void 0===e?void 0:e.isCancelledBecause(34))}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.figureId,{dataSetsHaveTitle:e.target.checked})}onDataSeriesRangesChanged(e){this.dataSeriesRanges=e}onDataSeriesConfirmed(){this.state.datasetDispatchResult=this.props.updateChart(this.props.figureId,{dataSets:this.dataSeriesRanges})}onLabelRangeChanged(e){this.labelRange=e[0]}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.figureId,{labelRange:this.labelRange})}}ls.template="o-spreadsheet-LineBarPieConfigPanel",ls.components={SelectionInput:as};class cs extends ls{onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e.target.checked})}}cs.template="o-spreadsheet-BarConfigPanel";class hs{constructor(e,t,i){this.title=e.title,this.sheetId=t,this.getters=i}static validateChartDefinition(e,t){throw new Error("This method should be implemented by sub class")}static transformDefinition(e,t){throw new Error("This method should be implemented by sub class")}static getDefinitionFromContextCreation(e){throw new Error("This method should be implemented by sub class")}}function ds(e){return 8===(e=mt(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}function us(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?Li(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?Di(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):e}function gs(e,t,i,n){let o=!1;const s=[];for(let n in i){let r=i[n];if(r.labelCell){const e=fs(r.labelCell,t);r.labelCell!==e&&(o=!0,r={...r,labelCell:e})}const a=fs(r.dataRange,t);void 0===a||e.getRangeString(a,a.sheetId)===X?(o=!0,r=void 0):a!==r.dataRange&&(o=!0,r={...r,dataRange:a}),s[n]=r}let r=n;const a=fs(r,t);a!==r&&(o=!0,r=a);return{isStale:o,dataSets:s.filter(Xe),labelRange:r}}function ps(e,t,i){return i.map((i=>({dataRange:Ri(e,t,i.dataRange),labelCell:i.labelCell?Ri(e,t,i.labelCell):void 0})))}function ms(e,t,i){return i?Ri(e,t,i):void 0}function fs(e,t){if(!e)return;const i=t(e);switch(i.changeType){case"NONE":return e;case"REMOVE":return;default:return i.range}}function vs(e,t,i,n){const o=[];for(const s of t){const t=e.getRangeFromSheetXC(i,s),{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 i={...r,left:t,right:t};o.push(bs(e,a,i,n?{top:i.top,bottom:i.top,left:i.left,right:i.left}:void 0))}}else o.push(bs(e,a,r,n?{top:r.top,bottom:r.top,left:r.left,right:r.left}:void 0))}return o}function bs(e,t,i,n){if(i.left!==i.right&&i.top!==i.bottom)throw new Error(`Zone should be a single column or row: ${Fi(i)}`);if(n){const o=Fi(i),s=Fi(n);return{labelCell:e.getRangeFromSheetXC(t,s),dataRange:e.getRangeFromSheetXC(t,o)}}return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,Fi(i))}}function Ss(e,t){var i;const n=null===(i=t.labelCell)||void 0===i?void 0:i.zone;let o=t.dataRange.zone;if(n){const{height:e,width:t}=qi(o);1===e?o={...o,left:o.left+1}:1===t&&(o={...o,top:o.top+1})}const s=t.dataRange.clone({zone:o});return{label:t.labelCell?e.getRangeString(t.labelCell,"forceSheetReference",!0):void 0,range:e.getRangeString(s,"forceSheetReference",!0)}}function Cs(e,t){let i;if(e.labelRange){const n=us(Ni(e.labelRange),t);i=n?Fi(n):void 0}const n=e.dataSets.map(Ni).map((e=>us(e,t))).filter(Xe).map(Fi);return{...e,labelRange:i,dataSets:n}}const Es=["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 ws{constructor(){this.graphColorIndex=0}next(){return Es[this.graphColorIndex++%Es.length]}}function ys(e){return e&&St(e)<.3?"#FFFFFF":"#000000"}function xs(e){if(e.dataSets){const t=void 0!==e.dataSets.find((e=>!Nt.test(e)));if(t)return 33;if(e.dataSets.map(Ni).some((e=>e.top!==e.bottom&&Ji(e))))return 33}return 0}function Rs(e){if(e.labelRange){if(!Nt.test(e.labelRange||""))return 34}return 0}function Is(e,t,i){const n=null==e?void 0:e.evaluated;if(e&&void 0!==n){if("text"===i||(null==t?void 0:t.type)!==ln.number||n.type!==ln.number)return e.formattedValue;{let e=t.value-n.value;if("percentage"===i&&0!==e&&(e=e/n.value*100),"percentage"!==i&&n.format)return Qt(e,n.format);const o=Math.abs(parseFloat(e.toFixed(2))).toLocaleString();return"percentage"===i?o+"%":o}}return""}function Ts(e,t,i,n,o){if("text"===t||(null==e?void 0:e.type)!==ln.number||(null==i?void 0:i.type)!==ln.number)return;const s=i.value-e.value;return s>0?n:s<0?o:void 0}function As(e,t,i){if("text"===i||(null==e?void 0:e.type)!==ln.number||(null==t?void 0:t.type)!==ln.number)return"neutral";const n=t.value-e.value;return n>0?"up":n<0?"down":"neutral"}function Os(e,t){if(t.dataRange){const i=t.labelCell?[Fi(t.labelCell.zone)]:[],n=Wi([Fi(t.dataRange.zone)],i)[0];if(void 0===n)return[];const o=e.getRangeFromSheetXC(t.dataRange.sheetId,n);return e.getRangeValues(o)}return[]}function Ns(e,t){const i=$e(0,Math.max(e.length,...t.map((e=>{var t;return(null===(t=e.data)||void 0===t?void 0:t.length)||0})))).filter((i=>{const n=e[i],o=t.map((e=>{var t;return null===(t=e.data)||void 0===t?void 0:t[i]}));return n||o.some((e=>0===e||Boolean(e)))}));return{labels:i.map((t=>e[t]||"")),dataSetsValues:t.map((e=>({...e,data:i.map((t=>e.data[t]))})))}}function Ms(e){return e?e.length>Q?e.substring(0,Q)+"…":e:""}function _s(e,t,i,n=!0){return{type:e.type,options:{responsive:!0,maintainAspectRatio:!1,layout:{padding:{left:20,right:20,top:e.title?10:25,bottom:10}},elements:{line:{fill:!1},point:{hitRadius:15}},animation:{duration:0},hover:{animationDuration:10},responsiveAnimationDuration:0,title:{display:!!e.title,fontSize:22,fontStyle:"normal",text:o(e.title),fontColor:i},legend:{onClick:void 0}},data:{labels:n?t.map(Ms):t,datasets:[]}}}function Fs(e,t,i){let n={values:[],formattedValues:[]};if(i)i.invalidXc||i.invalidSheetName||(n={formattedValues:e.getRangeFormattedValues(i),values:e.getRangeValues(i).map((e=>null!=e?String(e):""))});else if(1===t.length){const i=Os(e,t[0]).length;for(let e=0;e<i;e++)n.formattedValues.push(""),n.values.push("")}else if(t[0]){n={formattedValues:$e(0,Os(e,t[0]).length).map((e=>e.toString())),values:n.formattedValues}}return n}function Ds(e,t){const i=[];for(const[n,o]of Object.entries(t)){let t;if(o.labelCell){const i=o.labelCell,s=i?e.getCell(i.sheetId,i.zone.left,i.zone.top):void 0;t=s&&i?Ms(s.formattedValue):t=`${Jo.Series} ${parseInt(n)+1}`}else t=t=`${Jo.Series} ${parseInt(n)+1}`;let s=o.dataRange?Os(e,o):[];i.push({data:s,label:t})}return i}function ks(e){return 0===e?"origin":e-1}on.add("bar",{match:e=>"bar"===e,createChart:(e,t,i)=>new $s(e,t,i),getChartRuntime:function(e,t){let i=Fs(t,e.dataSets,e.labelRange).formattedValues,n=Ds(t,e.dataSets);({labels:i,dataSetsValues:n}=Ns(i,n));const o=function(e,t){var i;const n=ys(e.background),o=_s(e,t,n),s={labels:{fontColor:n}};!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?s.display=!1:s.position=e.legendPosition;o.options.legend={...null===(i=o.options)||void 0===i?void 0:i.legend,...s},o.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},o.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:n}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:n,beginAtZero:!0}}]},e.stacked&&(o.options.scales.xAxes[0].stacked=!0,o.options.scales.yAxes[0].stacked=!0);return o}(e,i),s=new ws;for(let{label:e,data:t}of n){const i=s.next(),n={label:e,data:t,borderColor:i,backgroundColor:i};o.data.datasets.push(n)}return{chartJsConfig:o,background:e.background||w}},validateChartDefinition:(e,t)=>$s.validateChartDefinition(e,t),transformDefinition:(e,t)=>$s.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>$s.getDefinitionFromContextCreation(e),name:s("Bar")});class $s extends hs{constructor(e,t,i){super(e,t,i),this.type="bar",this.dataSets=vs(i,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ii(i,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.stacked=e.stacked}static transformDefinition(e,t){return Cs(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,xs,Rs)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:!1,stacked:!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=ps(this.sheetId,e,this.dataSets),i=ms(this.sheetId,e,this.labelRange),n=this.getDefinitionWithSpecificDataSets(t,i,e);return new $s(n,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new $s(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,i){return{type:"bar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title,stacked:this.stacked}}getDefinitionForExcel(){const e=this.dataSets.map((e=>Ss(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),labelRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId,!0):void 0,backgroundColor:ds(this.background||w),fontColor:ds(ys(this.background)),dataSets:e}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:n}=gs(this.getters,e,this.dataSets,this.labelRange);if(!n)return this;const o=this.getDefinitionWithSpecificDataSets(t,i);return new $s(o,this.sheetId,this.getters)}}function Ls(e,t){const i=on.getAll().find((t=>t.match(e.type)));if(!i)throw new Error("Unknown chart type.");return i.transformDefinition(e,t)}function Ps(e){return e.dataRange&&!Nt.test(e.dataRange)?37:0}function Us(e,t){return t((t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):0),(t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):0))}function Vs(e){return e.sectionRule&&Number(e.sectionRule.rangeMin)>=Number(e.sectionRule.rangeMax)?42:0}function zs(e,t){if(""===e)switch(t){case"rangeMin":return 38;case"rangeMax":return 40}return 0}function Bs(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}on.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,i)=>new Hs(e,t,i),getChartRuntime:function(e,t){const i=function(e){const t=ys(e.background),i=_s(e,[],t);return i.options.hover=void 0,i.options.events=[],i.options.layout={padding:{left:30,right:30,top:e.title?10:25,bottom:25}},i.options.needle={radiusPercentage:2,widthPercentage:3.2,lengthPercentage:80,color:"#000000"},i.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},i}(e),n=e.sectionRule.colors,o=e.sectionRule.lowerInflectionPoint,s=e.sectionRule.upperInflectionPoint,r=Number(o.value),a=Number(s.value),l=Number(e.sectionRule.rangeMin),c=Number(e.sectionRule.rangeMax),h=c-l,d=[];if(""!==o.value){const e="number"===o.type?r:l+h*r/100;d.push({value:Me(e,l,c),color:n.lowerColor})}if(""!==s.value){const e="number"===s.type?a:l+h*a/100;d.push({value:Me(e,l,c),color:n.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(n.upperColor);const p=e.dataRange,m=h/30;let f=l-m,v=null,b=!1;if(void 0!==p){const e=t.getCell(p.sheetId,p.zone.left,p.zone.top);(null==e?void 0:e.evaluated.type)===ln.number&&(f=Me(null==e?void 0:e.evaluated.value,l-m,c+m),v=()=>t.getRangeFormattedValues(p)[0],b=!0)}return i.options.valueLabel.display=b,i.options.valueLabel.formatter=v,i.data.datasets.push({data:u,minValue:Number(e.sectionRule.rangeMin),value:f,backgroundColor:g}),{chartJsConfig:i,background:t.getStyleOfSingleCellChart(e.background,p).background}},validateChartDefinition:(e,t)=>Hs.validateChartDefinition(e,t),transformDefinition:(e,t)=>Hs.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Hs.getDefinitionFromContextCreation(e),name:s("Gauge")});class Hs extends hs{constructor(e,t,i){super(e,t,i),this.type="gauge",this.dataRange=Ii(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,Ps,e.chainValidations(Us(zs,e.batchValidations),Us(Bs,e.batchValidations),Vs),e.chainValidations((i=Bs,(0,e.batchValidations)((e=>e.sectionRule?i(e.sectionRule.lowerInflectionPoint.value,"lowerInflectionPointValue"):0),(e=>e.sectionRule?i(e.sectionRule.upperInflectionPoint.value,"upperInflectionPointValue"):0)))));var i}static transformDefinition(e,t){let i;return e.dataRange&&(i=us(Ni(e.dataRange),t)),{...e,dataRange:i?Fi(i):void 0}}static getDefinitionFromContextCreation(e){return{background:e.background,title:e.title||"",type:"gauge",dataRange:e.range?e.range[0]:void 0,sectionRule:{colors:{lowerColor:"#cc0000",middleColor:"#f1c232",upperColor:"#6aa84f"},rangeMin:"0",rangeMax:"100",lowerInflectionPoint:{type:"percentage",value:"15"},upperInflectionPoint:{type:"percentage",value:"40"}}}}copyForSheetId(e){const t=ms(this.sheetId,e,this.dataRange),i=this.getDefinitionWithSpecificRanges(t,e);return new Hs(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.dataRange,e);return new Hs(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=fs(this.dataRange,e);if(this.dataRange===t)return this;const i=this.getDefinitionWithSpecificRanges(t);return new Hs(i,this.sheetId,this.getters)}}const Ws={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},Gs={inSeconds:function(e){return Math.floor(e/Ws.second)},inMinutes:function(e){return Math.floor(e/Ws.minute)},inHours:function(e){return Math.floor(e/Ws.hour)},inDays:function(e){return Math.floor(e/Ws.day)},inMonths:function(e){return Math.floor(e/Ws.month)},inYears:function(e){return Math.floor(e/Ws.year)}},qs=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function Zs(e,t){const i=function(e){const t=(e=(e=e.replace(/y/g,"Y")).replace(/d/g,"D")).indexOf("h");e=t>=0?e.slice(0,t).replace(/m/g,"M")+e.slice(t):e.replace(/m/g,"M");e.includes("a")||(e=e.replace(/h/g,"H"));return e}(t),n=function(e,t){const i=e.map((e=>{var t;return null===(t=ve(e))||void 0===t?void 0:t.jsDate}));if(i.some((e=>void 0===e))||e.length<2)return;const n=i.map((e=>e.getTime())),o=lt(n)-ct(n),s=function(e){if(e.includes("s"))return"second";if(e.includes("m"))return"minute";if(e.includes("h")||e.includes("H"))return"hour";if(e.includes("D"))return"day";if(e.includes("M"))return"month";return"year"}(t);if(Ws.second>=Ws[s]&&Gs.inSeconds(o)<180)return"second";if(Ws.minute>=Ws[s]&&Gs.inMinutes(o)<180)return"minute";if(Ws.hour>=Ws[s]&&Gs.inHours(o)<96)return"hour";if(Ws.day>=Ws[s]&&Gs.inDays(o)<90)return"day";if(Ws.month>=Ws[s]&&Gs.inMonths(o)<36)return"month";return"year"}(e,i),o={};return n&&(o[n]=i),{parser:i,displayFormats:o,unit:n}}on.add("line",{match:e=>"line"===e,createChart:(e,t,i)=>new js(e,t,i),getChartRuntime:function(e,t){const i=function(e,t){if(function(e,t){return!e.labelsAsText&&Ys(e,t)}(e,t))return"time";if(function(e,t){return!e.labelsAsText&&Xs(e,t)}(e,t))return"linear";return"category"}(e,t),n=Fs(t,e.dataSets,e.labelRange);let o="linear"===i?n.values:n.formattedValues,s=Ds(t,e.dataSets);({labels:o,dataSetsValues:s}=Ns(o,s)),"time"===i&&({labels:o,dataSetsValues:s}=function(e,t){if(0===e.length||e.every((e=>!e)))return{labels:e,dataSetsValues:t};const i=[...e],n=Ae(t);for(let e=0;e<i.length;e++)if(!i[e]){i[e]=it(i,e);for(let t of n)t.data[e]=void 0}return{labels:i,dataSetsValues:n}}(o,s));const r=function(e,t,i){var n;const o=ys(e.background),s=_s(e,t,o,i),r={labels:{fontColor:o,generateLabels(e){const{data:t}=e,i=window.Chart.defaults.global.legend.labels.generateLabels(e);for(const[e,n]of i.entries())n.fillStyle=t.datasets[e].borderColor;return i}}};!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition;s.options.legend={...null===(n=s.options)||void 0===n?void 0:n.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:o}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:o,beginAtZero:!0}}]},e.stacked&&(s.options.scales.yAxes[0].stacked=!0);return s}(e,o,"category"===i),a=function(e,t){var i;if(t)return null===(i=e.getCell(t.sheetId,t.zone.left,t.zone.top))||void 0===i?void 0:i.evaluated.format}(t,e.labelRange);"time"===i?(r.options.scales.xAxes[0].type="time",r.options.scales.xAxes[0].time=Zs(o,a),r.options.scales.xAxes[0].ticks.maxTicksLimit=15):"linear"===i&&(r.options.scales.xAxes[0].type="linear",r.options.scales.xAxes[0].ticks.callback=e=>Qt(e,a));const l=new ws;for(let[t,{label:n,data:a}]of s.entries()){if(e.cumulative){let e=0;a=a.map((t=>isNaN(t)?t:(e+=parseFloat(t),e)))}["linear","time"].includes(i)&&(a=a.map(((e,t)=>({x:o[t]||void 0,y:e}))));const s=l.next();let c=Et(s);e.stacked&&(c.a=J);const h={label:n,data:a,lineTension:0,borderColor:s,backgroundColor:Ct(c),pointBackgroundColor:s,fill:!!e.stacked&&ks(t)};r.data.datasets.push(h)}return{chartJsConfig:r,background:e.background||w}},validateChartDefinition:(e,t)=>js.validateChartDefinition(e,t),transformDefinition:(e,t)=>js.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>js.getDefinitionFromContextCreation(e),name:s("Line")});class js extends hs{constructor(e,t,i){super(e,t,i),this.type="line",this.dataSets=vs(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ii(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.cumulative=e.cumulative}static validateChartDefinition(e,t){return e.checkValidations(t,xs,Rs)}static transformDefinition(e,t){return Cs(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,cumulative:!1}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,i){return{type:"line",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,stacked:this.stacked,cumulative:this.cumulative}}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:n}=gs(this.getters,e,this.dataSets,this.labelRange);if(!n)return this;const o=this.getDefinitionWithSpecificDataSets(t,i);return new js(o,this.sheetId,this.getters)}getDefinitionForExcel(){const e=this.dataSets.map((e=>Ss(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),labelRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId,!0):void 0,backgroundColor:ds(this.background||w),fontColor:ds(ys(this.background)),dataSets:e}}copyForSheetId(e){const t=ps(this.sheetId,e,this.dataSets),i=ms(this.sheetId,e,this.labelRange),n=this.getDefinitionWithSpecificDataSets(t,i,e);return new js(n,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new js(t,e,this.getters)}}function Ys(e,t){var i;if(!e.labelRange||!e.dataSets||!Xs(e,t))return!1;const n=null===(i=t.getCell(e.labelRange.sheetId,e.labelRange.zone.left,e.labelRange.zone.top))||void 0===i?void 0:i.evaluated.format;return Boolean(n&&qs.test(n))}function Xs(e,t){if(!e.labelRange||!e.dataSets)return!1;const i=t.getRangeValues(e.labelRange);return!i.some((e=>isNaN(Number(e))&&e))&&!i.every((e=>!e))}on.add("pie",{match:e=>"pie"===e,createChart:(e,t,i)=>new Ks(e,t,i),getChartRuntime:function(e,t){let i=Fs(t,e.dataSets,e.labelRange).formattedValues,n=Ds(t,e.dataSets);({labels:i,dataSetsValues:n}=Ns(i,n));const o=function(e,t){var i;const n=ys(e.background),o=_s(e,t,n),s={labels:{fontColor:n}};!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?s.display=!1:s.position=e.legendPosition;return o.options.legend={...null===(i=o.options)||void 0===i?void 0:i.legend,...s},o.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},o.options.tooltips={callbacks:{title:function(e,t){return t.datasets[e[0].datasetIndex].label}}},o}(e,i),s=new ws;for(let{label:t,data:i}of n){const r=Qs(s,n),a={label:t,data:i,borderColor:e.background||"#FFFFFF",backgroundColor:r};o.data.datasets.push(a)}return{chartJsConfig:o,background:e.background||w}},validateChartDefinition:(e,t)=>Ks.validateChartDefinition(e,t),transformDefinition:(e,t)=>Ks.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Ks.getDefinitionFromContextCreation(e),name:s("Pie")});class Ks extends hs{constructor(e,t,i){super(e,t,i),this.type="pie",this.dataSets=vs(i,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ii(i,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition}static transformDefinition(e,t){return Cs(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,xs,Rs)}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}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinitionWithSpecificDataSets(e,t,i){return{type:"pie",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title}}copyForSheetId(e){const t=ps(this.sheetId,e,this.dataSets),i=ms(this.sheetId,e,this.labelRange),n=this.getDefinitionWithSpecificDataSets(t,i,e);return new Ks(n,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Ks(t,e,this.getters)}getDefinitionForExcel(){const e=this.dataSets.map((e=>Ss(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),labelRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId,!0):void 0,backgroundColor:ds(this.background||w),fontColor:ds(ys(this.background)),verticalAxisPosition:"left",dataSets:e}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:n}=gs(this.getters,e,this.dataSets,this.labelRange);if(!n)return this;const o=this.getDefinitionWithSpecificDataSets(t,i);return new Ks(o,this.sheetId,this.getters)}}function Qs(e,t){const i=[],n=lt(t.map((e=>e.data.length)));for(let t=0;t<=n;t++)i.push(e.next());return i}function Js(e){return e.keyValue&&!Nt.test(e.keyValue)?35:0}function er(e){return e.baseline&&!Nt.test(e.baseline)?36:0}on.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,i)=>new tr(e,t,i),getChartRuntime:function(e,t){let i,n,s="",r="";if(e.keyValue){const n=e.keyValue.zone;i=t.getCell(e.keyValue.sheetId,n.left,n.top),s=(null==i?void 0:i.evaluated.value)?String(null==i?void 0:i.evaluated.value):"",r=(null==i?void 0:i.formattedValue)||""}if(e.baseline){const i=e.baseline.zone;n=t.getCell(e.baseline.sheetId,i.left,i.top)}const{background:a,fontColor:l}=t.getStyleOfSingleCellChart(e.background,e.keyValue);return{title:o(e.title),keyValue:r||s,baselineDisplay:Is(n,null==i?void 0:i.evaluated,e.baselineMode),baselineArrow:As(null==n?void 0:n.evaluated,null==i?void 0:i.evaluated,e.baselineMode),baselineColor:Ts(null==n?void 0:n.evaluated,e.baselineMode,null==i?void 0:i.evaluated,e.baselineColorUp,e.baselineColorDown),baselineDescr:e.baselineDescr?o(e.baselineDescr):"",fontColor:l,background:a,baselineStyle:"percentage"!==e.baselineMode?null==n?void 0:n.style:void 0,keyValueStyle:null==i?void 0:i.style}},validateChartDefinition:(e,t)=>tr.validateChartDefinition(e,t),transformDefinition:(e,t)=>tr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>tr.getDefinitionFromContextCreation(e),name:s("Scorecard")});class tr extends hs{constructor(e,t,i){super(e,t,i),this.type="scorecard",this.keyValue=Ii(i,t,e.keyValue),this.baseline=Ii(i,t,e.baseline),this.baselineMode=e.baselineMode,this.baselineDescr=e.baselineDescr,this.background=e.background,this.baselineColorUp=e.baselineColorUp,this.baselineColorDown=e.baselineColorDown}static validateChartDefinition(e,t){return e.checkValidations(t,Js,er)}static getDefinitionFromContextCreation(e){return{background:e.background,type:"scorecard",keyValue:e.range?e.range[0]:void 0,title:e.title||"",baselineMode:"difference",baselineColorUp:"#00A04A",baselineColorDown:"#DC6965",baseline:e.auxiliaryRange||""}}static transformDefinition(e,t){let i,n;return e.baseline&&(i=us(Ni(e.baseline),t)),e.keyValue&&(n=us(Ni(e.keyValue),t)),{...e,baseline:i?Fi(i):void 0,keyValue:n?Fi(n):void 0}}copyForSheetId(e){const t=ms(this.sheetId,e,this.baseline),i=ms(this.sheetId,e,this.keyValue),n=this.getDefinitionWithSpecificRanges(t,i,e);return new tr(n,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,e);return new tr(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue)}getContextCreation(){return{background:this.background,title:this.title,range:this.keyValue?[this.getters.getRangeString(this.keyValue,this.sheetId)]:void 0,auxiliaryRange:this.baseline?this.getters.getRangeString(this.baseline,this.sheetId):void 0}}getDefinitionWithSpecificRanges(e,t,i){return{baselineColorDown:this.baselineColorDown,baselineColorUp:this.baselineColorUp,baselineMode:this.baselineMode,title:this.title,type:"scorecard",background:this.background,baseline:e?this.getters.getRangeString(e,i||this.sheetId):void 0,baselineDescr:this.baselineDescr,keyValue:t?this.getters.getRangeString(t,i||this.sheetId):void 0}}getDefinitionForExcel(){}updateRanges(e){const t=fs(this.baseline,e),i=fs(this.keyValue,e);if(this.baseline===t&&this.keyValue===i)return this;const n=this.getDefinitionWithSpecificRanges(t,i);return new tr(n,this.sheetId,this.getters)}}const ir=218,nr=182;function or(e){return Ct(wt({h:360*e.offsetX/ir,s:100,l:100*e.offsetY/nr,a:1}))}wn`
322
+ `;class cs extends t.Component{constructor(){super(...arguments),this.id=ls.smallUuid(),this.previousRanges=this.props.ranges||[],this.originSheet=this.env.model.getters.getActiveSheetId(),this.state=t.useState({isMissing:!1})}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.toString(),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.onMounted((()=>this.enableNewSelectionInput())),t.onWillUnmount((async()=>this.disableNewSelectionInput())),t.onPatched((()=>this.checkChange()))}enableNewSelectionInput(){this.env.model.dispatch("ENABLE_NEW_SELECTION_INPUT",{id:this.id,initialRanges:this.props.ranges,hasSingleRange:this.props.hasSingleRange})}disableNewSelectionInput(){this.env.model.dispatch("DISABLE_SELECTION_INPUT",{id:this.id})}checkChange(){const e=this.env.model.getters.getSelectionInputValue(this.id);this.previousRanges.join()!==e.join()&&this.triggerChange()}getColor(e){return"color: "+(e.color||"#000")+";"}triggerChange(){var e,t;const i=this.env.model.getters.getSelectionInputValue(this.id);null===(t=(e=this.props).onSelectionChanged)||void 0===t||t.call(e,i),this.previousRanges=i}extractRanges(e){return this.props.hasSingleRange?e.split(",")[0]:e}focus(e){this.state.isMissing=!1,this.env.model.dispatch("FOCUS_RANGE",{id:this.id,rangeId:e})}addEmptyInput(){this.env.model.dispatch("ADD_EMPTY_RANGE",{id:this.id})}removeInput(e){var t,i;this.env.model.dispatch("REMOVE_RANGE",{id:this.id,rangeId:e}),this.triggerChange(),null===(i=(t=this.props).onSelectionConfirmed)||void 0===i||i.call(t)}onInputChanged(e,t){const i=t.target,n=this.extractRanges(i.value);this.env.model.dispatch("CHANGE_RANGE",{id:this.id,rangeId:e,value:n}),i.blur(),this.triggerChange()}confirm(){var e,t;this.env.model.dispatch("UNFOCUS_SELECTION_INPUT");const i=this.env.model.getters.getSelectionInputValue(this.id);this.props.required&&0===i.length&&(this.state.isMissing=!0);const n=this.env.model.getters.getActiveSheetId();this.originSheet!==n&&this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:n,sheetIdTo:this.originSheet}),null===(t=(e=this.props).onSelectionConfirmed)||void 0===t||t.call(e)}}cs.template="o-spreadsheet-SelectionInput";class hs extends t.Component{constructor(){super(...arguments),this.state=t.useState({datasetDispatchResult:void 0,labelsDispatchResult:void 0}),this.dataSeriesRanges=[]}setup(){this.dataSeriesRanges=this.props.definition.dataSets,this.labelRange=this.props.definition.labelRange}get errorMessages(){var e,t;return[...(null===(e=this.state.datasetDispatchResult)||void 0===e?void 0:e.reasons)||[],...(null===(t=this.state.labelsDispatchResult)||void 0===t?void 0:t.reasons)||[]].map((e=>ts.Errors[e]||ts.Errors.Unexpected))}get isDatasetInvalid(){var e;return!!(null===(e=this.state.datasetDispatchResult)||void 0===e?void 0:e.isCancelledBecause(33))}get isLabelInvalid(){var e;return!!(null===(e=this.state.labelsDispatchResult)||void 0===e?void 0:e.isCancelledBecause(34))}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.figureId,{dataSetsHaveTitle:e.target.checked})}onDataSeriesRangesChanged(e){this.dataSeriesRanges=e}onDataSeriesConfirmed(){this.state.datasetDispatchResult=this.props.updateChart(this.props.figureId,{dataSets:this.dataSeriesRanges})}onLabelRangeChanged(e){this.labelRange=e[0]}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.figureId,{labelRange:this.labelRange})}}hs.template="o-spreadsheet-LineBarPieConfigPanel",hs.components={SelectionInput:cs};class ds extends hs{onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e.target.checked})}}ds.template="o-spreadsheet-BarConfigPanel";class us{constructor(e,t,i){this.title=e.title,this.sheetId=t,this.getters=i}static validateChartDefinition(e,t){throw new Error("This method should be implemented by sub class")}static transformDefinition(e,t){throw new Error("This method should be implemented by sub class")}static getDefinitionFromContextCreation(e){throw new Error("This method should be implemented by sub class")}}function gs(e){return 8===(e=mt(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}function ps(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?Ui(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?$i(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):e}function ms(e,t,i,n){let o=!1;const s=[];for(let n in i){let r=i[n];if(r.labelCell){const e=bs(r.labelCell,t);r.labelCell!==e&&(o=!0,r={...r,labelCell:e})}const a=bs(r.dataRange,t);void 0===a||e.getRangeString(a,a.sheetId)===X?(o=!0,r=void 0):a!==r.dataRange&&(o=!0,r={...r,dataRange:a}),s[n]=r}let r=n;const a=bs(r,t);a!==r&&(o=!0,r=a);return{isStale:o,dataSets:s.filter(Xe),labelRange:r}}function fs(e,t,i){return i.map((i=>({dataRange:Ri(e,t,i.dataRange),labelCell:i.labelCell?Ri(e,t,i.labelCell):void 0})))}function vs(e,t,i){return i?Ri(e,t,i):void 0}function bs(e,t){if(!e)return;const i=t(e);switch(i.changeType){case"NONE":return e;case"REMOVE":return;default:return i.range}}function Ss(e,t,i,n){const o=[];for(const s of t){const t=e.getRangeFromSheetXC(i,s),{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 i={...r,left:t,right:t};o.push(Cs(e,a,i,n?{top:i.top,bottom:i.top,left:i.left,right:i.left}:void 0))}}else o.push(Cs(e,a,r,n?{top:r.top,bottom:r.top,left:r.left,right:r.left}:void 0))}return o}function Cs(e,t,i,n){if(i.left!==i.right&&i.top!==i.bottom)throw new Error(`Zone should be a single column or row: ${ki(i)}`);if(n){const o=ki(i),s=ki(n);return{labelCell:e.getRangeFromSheetXC(t,s),dataRange:e.getRangeFromSheetXC(t,o)}}return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,ki(i))}}function Es(e,t){var i;const n=null===(i=t.labelCell)||void 0===i?void 0:i.zone;let o=t.dataRange.zone;if(n){const{height:e,width:t}=ji(o);1===e?o={...o,left:o.left+1}:1===t&&(o={...o,top:o.top+1})}const s=t.dataRange.clone({zone:o});return{label:t.labelCell?e.getRangeString(t.labelCell,"forceSheetReference",!0):void 0,range:e.getRangeString(s,"forceSheetReference",!0)}}function ws(e,t){let i;if(e.labelRange){const n=ps(_i(e.labelRange),t);i=n?ki(n):void 0}const n=e.dataSets.map(_i).map((e=>ps(e,t))).filter(Xe).map(ki);return{...e,labelRange:i,dataSets:n}}const ys=["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 xs{constructor(){this.graphColorIndex=0}next(){return ys[this.graphColorIndex++%ys.length]}}function Rs(e){return e&&St(e)<.3?"#FFFFFF":"#000000"}function Is(e){if(e.dataSets){const t=void 0!==e.dataSets.find((e=>!Ot.test(e)));if(t)return 33;if(e.dataSets.map(_i).some((e=>e.top!==e.bottom&&tn(e))))return 33}return 0}function Ts(e){if(e.labelRange){if(!Ot.test(e.labelRange||""))return 34}return 0}function As(e,t,i){const n=null==e?void 0:e.evaluated;if(e&&void 0!==n){if("text"===i||(null==t?void 0:t.type)!==hn.number||n.type!==hn.number)return e.formattedValue;{let e=t.value-n.value;if("percentage"===i&&0!==e&&(e=e/n.value*100),"percentage"!==i&&n.format)return Qt(e,n.format);const o=Math.abs(parseFloat(e.toFixed(2))).toLocaleString();return"percentage"===i?o+"%":o}}return""}function Ns(e,t,i,n,o){if("text"===t||(null==e?void 0:e.type)!==hn.number||(null==i?void 0:i.type)!==hn.number)return;const s=i.value-e.value;return s>0?n:s<0?o:void 0}function Os(e,t,i){if("text"===i||(null==e?void 0:e.type)!==hn.number||(null==t?void 0:t.type)!==hn.number)return"neutral";const n=t.value-e.value;return n>0?"up":n<0?"down":"neutral"}function Ms(e,t){if(t.dataRange){const i=t.labelCell?[ki(t.labelCell.zone)]:[],n=qi([ki(t.dataRange.zone)],i)[0];if(void 0===n)return[];const o=e.getRangeFromSheetXC(t.dataRange.sheetId,n);return e.getRangeValues(o)}return[]}function _s(e,t){const i=$e(0,Math.max(e.length,...t.map((e=>{var t;return(null===(t=e.data)||void 0===t?void 0:t.length)||0})))).filter((i=>{const n=e[i],o=t.map((e=>{var t;return null===(t=e.data)||void 0===t?void 0:t[i]}));return n||o.some((e=>0===e||Boolean(e)))}));return{labels:i.map((t=>e[t]||"")),dataSetsValues:t.map((e=>({...e,data:i.map((t=>e.data[t]))})))}}function Fs(e){return e?e.length>Q?e.substring(0,Q)+"…":e:""}function Ds(e,t,i,n=!0){return{type:e.type,options:{responsive:!0,maintainAspectRatio:!1,layout:{padding:{left:20,right:20,top:e.title?10:25,bottom:10}},elements:{line:{fill:!1},point:{hitRadius:15}},animation:{duration:0},hover:{animationDuration:10},responsiveAnimationDuration:0,title:{display:!!e.title,fontSize:22,fontStyle:"normal",text:o(e.title),fontColor:i},legend:{onClick:void 0}},data:{labels:n?t.map(Fs):t,datasets:[]}}}function ks(e,t,i){let n={values:[],formattedValues:[]};if(i)i.invalidXc||i.invalidSheetName||(n={formattedValues:e.getRangeFormattedValues(i),values:e.getRangeValues(i).map((e=>null!=e?String(e):""))});else if(1===t.length){const i=Ms(e,t[0]).length;for(let e=0;e<i;e++)n.formattedValues.push(""),n.values.push("")}else if(t[0]){n={formattedValues:$e(0,Ms(e,t[0]).length).map((e=>e.toString())),values:n.formattedValues}}return n}function $s(e,t){const i=[];for(const[n,o]of Object.entries(t)){let t;if(o.labelCell){const i=o.labelCell,s=i?e.getCell(i.sheetId,i.zone.left,i.zone.top):void 0;t=s&&i?Fs(s.formattedValue):t=`${ts.Series} ${parseInt(n)+1}`}else t=t=`${ts.Series} ${parseInt(n)+1}`;let s=o.dataRange?Ms(e,o):[];i.push({data:s,label:t})}return i}function Ls(e){return 0===e?"origin":e-1}rn.add("bar",{match:e=>"bar"===e,createChart:(e,t,i)=>new Ps(e,t,i),getChartRuntime:function(e,t){let i=ks(t,e.dataSets,e.labelRange).formattedValues,n=$s(t,e.dataSets);({labels:i,dataSetsValues:n}=_s(i,n));const o=function(e,t){var i;const n=Rs(e.background),o=Ds(e,t,n),s={labels:{fontColor:n}};!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?s.display=!1:s.position=e.legendPosition;o.options.legend={...null===(i=o.options)||void 0===i?void 0:i.legend,...s},o.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},o.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:n}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:n,beginAtZero:!0}}]},e.stacked&&(o.options.scales.xAxes[0].stacked=!0,o.options.scales.yAxes[0].stacked=!0);return o}(e,i),s=new xs;for(let{label:e,data:t}of n){const i=s.next(),n={label:e,data:t,borderColor:i,backgroundColor:i};o.data.datasets.push(n)}return{chartJsConfig:o,background:e.background||w}},validateChartDefinition:(e,t)=>Ps.validateChartDefinition(e,t),transformDefinition:(e,t)=>Ps.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Ps.getDefinitionFromContextCreation(e),name:s("Bar")});class Ps extends us{constructor(e,t,i){super(e,t,i),this.type="bar",this.dataSets=Ss(i,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ii(i,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.stacked=e.stacked}static transformDefinition(e,t){return ws(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,Is,Ts)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:!1,stacked:!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=fs(this.sheetId,e,this.dataSets),i=vs(this.sheetId,e,this.labelRange),n=this.getDefinitionWithSpecificDataSets(t,i,e);return new Ps(n,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Ps(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,i){return{type:"bar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title,stacked:this.stacked}}getDefinitionForExcel(){const e=this.dataSets.map((e=>Es(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),labelRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId,!0):void 0,backgroundColor:gs(this.background||w),fontColor:gs(Rs(this.background)),dataSets:e}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:n}=ms(this.getters,e,this.dataSets,this.labelRange);if(!n)return this;const o=this.getDefinitionWithSpecificDataSets(t,i);return new Ps(o,this.sheetId,this.getters)}}function Us(e,t){const i=rn.getAll().find((t=>t.match(e.type)));if(!i)throw new Error("Unknown chart type.");return i.transformDefinition(e,t)}function Vs(e){return e.dataRange&&!Ot.test(e.dataRange)?37:0}function zs(e,t){return t((t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):0),(t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):0))}function Bs(e){return e.sectionRule&&Number(e.sectionRule.rangeMin)>=Number(e.sectionRule.rangeMax)?42:0}function Hs(e,t){if(""===e)switch(t){case"rangeMin":return 38;case"rangeMax":return 40}return 0}function Ws(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}rn.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,i)=>new Gs(e,t,i),getChartRuntime:function(e,t){const i=function(e){const t=Rs(e.background),i=Ds(e,[],t);return i.options.hover=void 0,i.options.events=[],i.options.layout={padding:{left:30,right:30,top:e.title?10:25,bottom:25}},i.options.needle={radiusPercentage:2,widthPercentage:3.2,lengthPercentage:80,color:"#000000"},i.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},i}(e),n=e.sectionRule.colors,o=e.sectionRule.lowerInflectionPoint,s=e.sectionRule.upperInflectionPoint,r=Number(o.value),a=Number(s.value),l=Number(e.sectionRule.rangeMin),c=Number(e.sectionRule.rangeMax),h=c-l,d=[];if(""!==o.value){const e="number"===o.type?r:l+h*r/100;d.push({value:Me(e,l,c),color:n.lowerColor})}if(""!==s.value){const e="number"===s.type?a:l+h*a/100;d.push({value:Me(e,l,c),color:n.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(n.upperColor);const p=e.dataRange,m=h/30;let f=l-m,v=null,b=!1;if(void 0!==p){const e=t.getCell(p.sheetId,p.zone.left,p.zone.top);(null==e?void 0:e.evaluated.type)===hn.number&&(f=Me(null==e?void 0:e.evaluated.value,l-m,c+m),v=()=>t.getRangeFormattedValues(p)[0],b=!0)}return i.options.valueLabel.display=b,i.options.valueLabel.formatter=v,i.data.datasets.push({data:u,minValue:Number(e.sectionRule.rangeMin),value:f,backgroundColor:g}),{chartJsConfig:i,background:t.getStyleOfSingleCellChart(e.background,p).background}},validateChartDefinition:(e,t)=>Gs.validateChartDefinition(e,t),transformDefinition:(e,t)=>Gs.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Gs.getDefinitionFromContextCreation(e),name:s("Gauge")});class Gs extends us{constructor(e,t,i){super(e,t,i),this.type="gauge",this.dataRange=Ii(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,Vs,e.chainValidations(zs(Hs,e.batchValidations),zs(Ws,e.batchValidations),Bs),e.chainValidations((i=Ws,(0,e.batchValidations)((e=>e.sectionRule?i(e.sectionRule.lowerInflectionPoint.value,"lowerInflectionPointValue"):0),(e=>e.sectionRule?i(e.sectionRule.upperInflectionPoint.value,"upperInflectionPointValue"):0)))));var i}static transformDefinition(e,t){let i;return e.dataRange&&(i=ps(_i(e.dataRange),t)),{...e,dataRange:i?ki(i):void 0}}static getDefinitionFromContextCreation(e){return{background:e.background,title:e.title||"",type:"gauge",dataRange:e.range?e.range[0]:void 0,sectionRule:{colors:{lowerColor:"#cc0000",middleColor:"#f1c232",upperColor:"#6aa84f"},rangeMin:"0",rangeMax:"100",lowerInflectionPoint:{type:"percentage",value:"15"},upperInflectionPoint:{type:"percentage",value:"40"}}}}copyForSheetId(e){const t=vs(this.sheetId,e,this.dataRange),i=this.getDefinitionWithSpecificRanges(t,e);return new Gs(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.dataRange,e);return new Gs(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=bs(this.dataRange,e);if(this.dataRange===t)return this;const i=this.getDefinitionWithSpecificRanges(t);return new Gs(i,this.sheetId,this.getters)}}const qs={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},Zs={inSeconds:function(e){return Math.floor(e/qs.second)},inMinutes:function(e){return Math.floor(e/qs.minute)},inHours:function(e){return Math.floor(e/qs.hour)},inDays:function(e){return Math.floor(e/qs.day)},inMonths:function(e){return Math.floor(e/qs.month)},inYears:function(e){return Math.floor(e/qs.year)}},js=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function Ys(e,t){const i=function(e){const t=(e=(e=e.replace(/y/g,"Y")).replace(/d/g,"D")).indexOf("h");e=t>=0?e.slice(0,t).replace(/m/g,"M")+e.slice(t):e.replace(/m/g,"M");e.includes("a")||(e=e.replace(/h/g,"H"));return e}(t),n=function(e,t){const i=e.map((e=>{var t;return null===(t=ve(e))||void 0===t?void 0:t.jsDate}));if(i.some((e=>void 0===e))||e.length<2)return;const n=i.map((e=>e.getTime())),o=lt(n)-ct(n),s=function(e){if(e.includes("s"))return"second";if(e.includes("m"))return"minute";if(e.includes("h")||e.includes("H"))return"hour";if(e.includes("D"))return"day";if(e.includes("M"))return"month";return"year"}(t);if(qs.second>=qs[s]&&Zs.inSeconds(o)<180)return"second";if(qs.minute>=qs[s]&&Zs.inMinutes(o)<180)return"minute";if(qs.hour>=qs[s]&&Zs.inHours(o)<96)return"hour";if(qs.day>=qs[s]&&Zs.inDays(o)<90)return"day";if(qs.month>=qs[s]&&Zs.inMonths(o)<36)return"month";return"year"}(e,i),o={};return n&&(o[n]=i),{parser:i,displayFormats:o,unit:n}}rn.add("line",{match:e=>"line"===e,createChart:(e,t,i)=>new Xs(e,t,i),getChartRuntime:function(e,t){const i=function(e,t){if(function(e,t){return!e.labelsAsText&&Ks(e,t)}(e,t))return"time";if(function(e,t){return!e.labelsAsText&&Qs(e,t)}(e,t))return"linear";return"category"}(e,t),n=ks(t,e.dataSets,e.labelRange);let o="linear"===i?n.values:n.formattedValues,s=$s(t,e.dataSets);({labels:o,dataSetsValues:s}=_s(o,s)),"time"===i&&({labels:o,dataSetsValues:s}=function(e,t){if(0===e.length||e.every((e=>!e)))return{labels:e,dataSetsValues:t};const i=[...e],n=Ae(t);for(let e=0;e<i.length;e++)if(!i[e]){i[e]=it(i,e);for(let t of n)t.data[e]=void 0}return{labels:i,dataSetsValues:n}}(o,s));const r=function(e,t,i){var n;const o=Rs(e.background),s=Ds(e,t,o,i),r={labels:{fontColor:o,generateLabels(e){const{data:t}=e,i=window.Chart.defaults.global.legend.labels.generateLabels(e);for(const[e,n]of i.entries())n.fillStyle=t.datasets[e].borderColor;return i}}};!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition;s.options.legend={...null===(n=s.options)||void 0===n?void 0:n.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:o}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:o,beginAtZero:!0}}]},e.stacked&&(s.options.scales.yAxes[0].stacked=!0);return s}(e,o,"category"===i),a=function(e,t){var i;if(t)return null===(i=e.getCell(t.sheetId,t.zone.left,t.zone.top))||void 0===i?void 0:i.evaluated.format}(t,e.labelRange);"time"===i?(r.options.scales.xAxes[0].type="time",r.options.scales.xAxes[0].time=Ys(o,a),r.options.scales.xAxes[0].ticks.maxTicksLimit=15):"linear"===i&&(r.options.scales.xAxes[0].type="linear",r.options.scales.xAxes[0].ticks.callback=e=>Qt(e,a));const l=new xs;for(let[t,{label:n,data:a}]of s.entries()){if(e.cumulative){let e=0;a=a.map((t=>isNaN(t)?t:(e+=parseFloat(t),e)))}["linear","time"].includes(i)&&(a=a.map(((e,t)=>({x:o[t]||void 0,y:e}))));const s=l.next();let c=Et(s);e.stacked&&(c.a=J);const h={label:n,data:a,lineTension:0,borderColor:s,backgroundColor:Ct(c),pointBackgroundColor:s,fill:!!e.stacked&&Ls(t)};r.data.datasets.push(h)}return{chartJsConfig:r,background:e.background||w}},validateChartDefinition:(e,t)=>Xs.validateChartDefinition(e,t),transformDefinition:(e,t)=>Xs.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Xs.getDefinitionFromContextCreation(e),name:s("Line")});class Xs extends us{constructor(e,t,i){super(e,t,i),this.type="line",this.dataSets=Ss(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ii(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.cumulative=e.cumulative}static validateChartDefinition(e,t){return e.checkValidations(t,Is,Ts)}static transformDefinition(e,t){return ws(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,cumulative:!1}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,i){return{type:"line",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,stacked:this.stacked,cumulative:this.cumulative}}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:n}=ms(this.getters,e,this.dataSets,this.labelRange);if(!n)return this;const o=this.getDefinitionWithSpecificDataSets(t,i);return new Xs(o,this.sheetId,this.getters)}getDefinitionForExcel(){const e=this.dataSets.map((e=>Es(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),labelRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId,!0):void 0,backgroundColor:gs(this.background||w),fontColor:gs(Rs(this.background)),dataSets:e}}copyForSheetId(e){const t=fs(this.sheetId,e,this.dataSets),i=vs(this.sheetId,e,this.labelRange),n=this.getDefinitionWithSpecificDataSets(t,i,e);return new Xs(n,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Xs(t,e,this.getters)}}function Ks(e,t){var i;if(!e.labelRange||!e.dataSets||!Qs(e,t))return!1;const n=null===(i=t.getCell(e.labelRange.sheetId,e.labelRange.zone.left,e.labelRange.zone.top))||void 0===i?void 0:i.evaluated.format;return Boolean(n&&js.test(n))}function Qs(e,t){if(!e.labelRange||!e.dataSets)return!1;const i=t.getRangeValues(e.labelRange);return!i.some((e=>isNaN(Number(e))&&e))&&!i.every((e=>!e))}rn.add("pie",{match:e=>"pie"===e,createChart:(e,t,i)=>new Js(e,t,i),getChartRuntime:function(e,t){let i=ks(t,e.dataSets,e.labelRange).formattedValues,n=$s(t,e.dataSets);({labels:i,dataSetsValues:n}=_s(i,n));const o=function(e,t){var i;const n=Rs(e.background),o=Ds(e,t,n),s={labels:{fontColor:n}};!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?s.display=!1:s.position=e.legendPosition;return o.options.legend={...null===(i=o.options)||void 0===i?void 0:i.legend,...s},o.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},o.options.tooltips={callbacks:{title:function(e,t){return t.datasets[e[0].datasetIndex].label}}},o}(e,i),s=new xs;for(let{label:t,data:i}of n){const r=er(s,n),a={label:t,data:i,borderColor:e.background||"#FFFFFF",backgroundColor:r};o.data.datasets.push(a)}return{chartJsConfig:o,background:e.background||w}},validateChartDefinition:(e,t)=>Js.validateChartDefinition(e,t),transformDefinition:(e,t)=>Js.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Js.getDefinitionFromContextCreation(e),name:s("Pie")});class Js extends us{constructor(e,t,i){super(e,t,i),this.type="pie",this.dataSets=Ss(i,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ii(i,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition}static transformDefinition(e,t){return ws(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,Is,Ts)}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}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinitionWithSpecificDataSets(e,t,i){return{type:"pie",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title}}copyForSheetId(e){const t=fs(this.sheetId,e,this.dataSets),i=vs(this.sheetId,e,this.labelRange),n=this.getDefinitionWithSpecificDataSets(t,i,e);return new Js(n,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Js(t,e,this.getters)}getDefinitionForExcel(){const e=this.dataSets.map((e=>Es(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),labelRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId,!0):void 0,backgroundColor:gs(this.background||w),fontColor:gs(Rs(this.background)),verticalAxisPosition:"left",dataSets:e}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:n}=ms(this.getters,e,this.dataSets,this.labelRange);if(!n)return this;const o=this.getDefinitionWithSpecificDataSets(t,i);return new Js(o,this.sheetId,this.getters)}}function er(e,t){const i=[],n=lt(t.map((e=>e.data.length)));for(let t=0;t<=n;t++)i.push(e.next());return i}function tr(e){return e.keyValue&&!Ot.test(e.keyValue)?35:0}function ir(e){return e.baseline&&!Ot.test(e.baseline)?36:0}rn.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,i)=>new nr(e,t,i),getChartRuntime:function(e,t){let i,n,s="",r="";if(e.keyValue){const n=e.keyValue.zone;i=t.getCell(e.keyValue.sheetId,n.left,n.top),s=(null==i?void 0:i.evaluated.value)?String(null==i?void 0:i.evaluated.value):"",r=(null==i?void 0:i.formattedValue)||""}if(e.baseline){const i=e.baseline.zone;n=t.getCell(e.baseline.sheetId,i.left,i.top)}const{background:a,fontColor:l}=t.getStyleOfSingleCellChart(e.background,e.keyValue);return{title:o(e.title),keyValue:r||s,baselineDisplay:As(n,null==i?void 0:i.evaluated,e.baselineMode),baselineArrow:Os(null==n?void 0:n.evaluated,null==i?void 0:i.evaluated,e.baselineMode),baselineColor:Ns(null==n?void 0:n.evaluated,e.baselineMode,null==i?void 0:i.evaluated,e.baselineColorUp,e.baselineColorDown),baselineDescr:e.baselineDescr?o(e.baselineDescr):"",fontColor:l,background:a,baselineStyle:"percentage"!==e.baselineMode?null==n?void 0:n.style:void 0,keyValueStyle:null==i?void 0:i.style}},validateChartDefinition:(e,t)=>nr.validateChartDefinition(e,t),transformDefinition:(e,t)=>nr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>nr.getDefinitionFromContextCreation(e),name:s("Scorecard")});class nr extends us{constructor(e,t,i){super(e,t,i),this.type="scorecard",this.keyValue=Ii(i,t,e.keyValue),this.baseline=Ii(i,t,e.baseline),this.baselineMode=e.baselineMode,this.baselineDescr=e.baselineDescr,this.background=e.background,this.baselineColorUp=e.baselineColorUp,this.baselineColorDown=e.baselineColorDown}static validateChartDefinition(e,t){return e.checkValidations(t,tr,ir)}static getDefinitionFromContextCreation(e){return{background:e.background,type:"scorecard",keyValue:e.range?e.range[0]:void 0,title:e.title||"",baselineMode:"difference",baselineColorUp:"#00A04A",baselineColorDown:"#DC6965",baseline:e.auxiliaryRange||""}}static transformDefinition(e,t){let i,n;return e.baseline&&(i=ps(_i(e.baseline),t)),e.keyValue&&(n=ps(_i(e.keyValue),t)),{...e,baseline:i?ki(i):void 0,keyValue:n?ki(n):void 0}}copyForSheetId(e){const t=vs(this.sheetId,e,this.baseline),i=vs(this.sheetId,e,this.keyValue),n=this.getDefinitionWithSpecificRanges(t,i,e);return new nr(n,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,e);return new nr(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue)}getContextCreation(){return{background:this.background,title:this.title,range:this.keyValue?[this.getters.getRangeString(this.keyValue,this.sheetId)]:void 0,auxiliaryRange:this.baseline?this.getters.getRangeString(this.baseline,this.sheetId):void 0}}getDefinitionWithSpecificRanges(e,t,i){return{baselineColorDown:this.baselineColorDown,baselineColorUp:this.baselineColorUp,baselineMode:this.baselineMode,title:this.title,type:"scorecard",background:this.background,baseline:e?this.getters.getRangeString(e,i||this.sheetId):void 0,baselineDescr:this.baselineDescr,keyValue:t?this.getters.getRangeString(t,i||this.sheetId):void 0}}getDefinitionForExcel(){}updateRanges(e){const t=bs(this.baseline,e),i=bs(this.keyValue,e);if(this.baseline===t&&this.keyValue===i)return this;const n=this.getDefinitionWithSpecificRanges(t,i);return new nr(n,this.sheetId,this.getters)}}const or=218,sr=182;function rr(e){return Ct(wt({h:360*e.offsetX/or,s:100,l:100*e.offsetY/sr,a:1}))}xn`
323
323
  .o-color-picker {
324
324
  position: absolute;
325
325
  top: calc(100% + 5px);
@@ -330,7 +330,7 @@
330
330
  line-height: 1.2;
331
331
  overflow-y: auto;
332
332
  overflow-x: hidden;
333
- width: ${ir+12}px;
333
+ width: ${or+12}px;
334
334
 
335
335
  .o-color-picker-section-name {
336
336
  margin: 0px ${1}px;
@@ -431,8 +431,8 @@
431
431
  hsl(1turn 100% 50%) 100%
432
432
  );
433
433
  border: ${1}px solid #c0c0c0;
434
- width: ${ir}px;
435
- height: ${nr}px;
434
+ width: ${or}px;
435
+ height: ${sr}px;
436
436
  &:hover {
437
437
  cursor: crosshair;
438
438
  }
@@ -468,7 +468,7 @@
468
468
  width: 30px;
469
469
  height: 30px;
470
470
  }
471
- `;class sr extends t.Component{constructor(){super(...arguments),this.COLORS=O,this.state=t.useState({showGradient:!1,currentColor:ft(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?xn({display:"none"}):xn({"max-height":`${this.props.maxHeight}px`})}onColorClick(e){e&&this.props.onColorPicked(mt(e))}getCheckMarkColor(){return ys(this.props.currentColor)}resetColor(){this.props.onColorPicked("")}setCustomColor(e){if(!ft(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=or(e)}hideMagnifier(e){this.state.style.display="none"}showMagnifier(e){this.state.style.display="block"}moveMagnifier(e){this.state.style.background=or(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:i,top:n}=this.state.style;return`display:${e};${"block"===e?`background-color:${t};left:${i};top:${n};`:""}`}isSameColor(e,t){return function(e,t){return ft(e)&&ft(t)&&mt(e)===mt(t)}(e,t)}}sr.template="o-spreadsheet-ColorPicker";class rr extends t.Component{constructor(){super(...arguments),this.state=t.useState({fillColorTool:!1})}onClick(e){this.state.fillColorTool=!1}setup(){t.useExternalListener(window,"click",this.onClick)}toggleColorPicker(){this.state.fillColorTool=!this.state.fillColorTool}updateBackgroundColor(e){this.props.updateChart(this.props.figureId,{background:e})}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}updateSelect(e,t){this.props.updateChart(this.props.figureId,{[e]:t.target.value})}}rr.template="o-spreadsheet-LineBarPieDesignPanel",rr.components={ColorPicker:sr};class ar extends rr{}ar.template="o-spreadsheet-BarChartDesignPanel";class lr extends t.Component{constructor(){super(...arguments),this.state=t.useState({dataRangeDispatchResult:void 0}),this.dataRange=this.props.definition.dataRange}get configurationErrorMessages(){var e;return[...(null===(e=this.state.dataRangeDispatchResult)||void 0===e?void 0:e.reasons)||[]].map((e=>Jo.Errors[e]||Jo.Errors.Unexpected))}get isDataRangeInvalid(){var e;return!!(null===(e=this.state.dataRangeDispatchResult)||void 0===e?void 0:e.isCancelledBecause(37))}onDataRangeChanged(e){this.dataRange=e[0]}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.figureId,{dataRange:this.dataRange})}}lr.template="o-spreadsheet-GaugeChartConfigPanel",lr.components={SelectionInput:as},wn`
471
+ `;class ar extends t.Component{constructor(){super(...arguments),this.COLORS=N,this.state=t.useState({showGradient:!1,currentColor:ft(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?In({display:"none"}):In({"max-height":`${this.props.maxHeight}px`})}onColorClick(e){e&&this.props.onColorPicked(mt(e))}getCheckMarkColor(){return Rs(this.props.currentColor)}resetColor(){this.props.onColorPicked("")}setCustomColor(e){if(!ft(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=rr(e)}hideMagnifier(e){this.state.style.display="none"}showMagnifier(e){this.state.style.display="block"}moveMagnifier(e){this.state.style.background=rr(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:i,top:n}=this.state.style;return`display:${e};${"block"===e?`background-color:${t};left:${i};top:${n};`:""}`}isSameColor(e,t){return function(e,t){return ft(e)&&ft(t)&&mt(e)===mt(t)}(e,t)}}ar.template="o-spreadsheet-ColorPicker";class lr extends t.Component{constructor(){super(...arguments),this.state=t.useState({fillColorTool:!1})}onClick(e){this.state.fillColorTool=!1}setup(){t.useExternalListener(window,"click",this.onClick)}toggleColorPicker(){this.state.fillColorTool=!this.state.fillColorTool}updateBackgroundColor(e){this.props.updateChart(this.props.figureId,{background:e})}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}updateSelect(e,t){this.props.updateChart(this.props.figureId,{[e]:t.target.value})}}lr.template="o-spreadsheet-LineBarPieDesignPanel",lr.components={ColorPicker:ar};class cr extends lr{}cr.template="o-spreadsheet-BarChartDesignPanel";class hr extends t.Component{constructor(){super(...arguments),this.state=t.useState({dataRangeDispatchResult:void 0}),this.dataRange=this.props.definition.dataRange}get configurationErrorMessages(){var e;return[...(null===(e=this.state.dataRangeDispatchResult)||void 0===e?void 0:e.reasons)||[]].map((e=>ts.Errors[e]||ts.Errors.Unexpected))}get isDataRangeInvalid(){var e;return!!(null===(e=this.state.dataRangeDispatchResult)||void 0===e?void 0:e.isCancelledBecause(37))}onDataRangeChanged(e){this.dataRange=e[0]}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.figureId,{dataRange:this.dataRange})}}hr.template="o-spreadsheet-GaugeChartConfigPanel",hr.components={SelectionInput:cs},xn`
472
472
  .o-gauge-color-set {
473
473
  .o-gauge-color-set-color-button {
474
474
  display: inline-block;
@@ -508,7 +508,7 @@
508
508
  box-sizing: border-box;
509
509
  }
510
510
  }
511
- `;class cr extends t.Component{constructor(){super(...arguments),this.state=t.useState({openedMenu:void 0,sectionRuleDispatchResult:void 0})}get designErrorMessages(){var e;return[...(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.reasons)||[]].map((e=>Jo.Errors[e]||Jo.Errors.Unexpected))}onClick(e){this.state.openedMenu=void 0}setup(){t.useExternalListener(window,"click",this.onClick)}updateBackgroundColor(e){this.state.openedMenu=void 0,this.props.updateChart(this.props.figureId,{background:e})}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}isRangeMinInvalid(){var e,t,i;return!!((null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(38))||(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(39))||(null===(i=this.state.sectionRuleDispatchResult)||void 0===i?void 0:i.isCancelledBecause(42)))}isRangeMaxInvalid(){var e,t,i;return!!((null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(40))||(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(41))||(null===(i=this.state.sectionRuleDispatchResult)||void 0===i?void 0:i.isCancelledBecause(42)))}get isLowerInflectionPointInvalid(){var e,t;return!(!(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(43))&&!(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(45)))}get isUpperInflectionPointInvalid(){var e,t;return!(!(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(44))&&!(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(45)))}updateInflectionPointValue(e,t){const i=Ae(this.props.definition.sectionRule);i[e].value=t.target.value,this.updateSectionRule(i)}updateInflectionPointType(e,t){const i=Ae(this.props.definition.sectionRule);i[e].type=t.target.value,this.updateSectionRule(i)}updateSectionColor(e,t){const i=Ae(this.props.definition.sectionRule);i.colors[e]=t,this.updateSectionRule(i),this.closeMenus()}updateRangeMin(e){let t=Ae(this.props.definition.sectionRule);t={...t,rangeMin:e.target.value},this.updateSectionRule(t)}updateRangeMax(e){let t=Ae(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}}cr.template="o-spreadsheet-GaugeChartDesignPanel",cr.components={ColorPicker:sr};class hr extends ls{get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.figureId);return!!(e&&e instanceof js)&&function(e,t){return Ys(e,t)||Xs(e,t)}(e,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})}onUpdateCumulative(e){this.props.updateChart(this.props.figureId,{cumulative:e.target.checked})}}hr.template="o-spreadsheet-LineConfigPanel";class dr extends rr{}dr.template="o-spreadsheet-LineChartDesignPanel";class ur extends t.Component{constructor(){super(...arguments),this.state=t.useState({keyValueDispatchResult:void 0,baselineDispatchResult:void 0}),this.keyValue=this.props.definition.keyValue,this.baseline=this.props.definition.baseline}get errorMessages(){var e,t;return[...(null===(e=this.state.keyValueDispatchResult)||void 0===e?void 0:e.reasons)||[],...(null===(t=this.state.baselineDispatchResult)||void 0===t?void 0:t.reasons)||[]].map((e=>Jo.Errors[e]||Jo.Errors.Unexpected))}get isKeyValueInvalid(){var e;return!!(null===(e=this.state.keyValueDispatchResult)||void 0===e?void 0:e.isCancelledBecause(35))}get isBaselineInvalid(){var e;return!!(null===(e=this.state.keyValueDispatchResult)||void 0===e?void 0:e.isCancelledBecause(36))}onKeyValueRangeChanged(e){this.keyValue=e[0]}updateKeyValueRange(){this.state.keyValueDispatchResult=this.props.updateChart(this.props.figureId,{keyValue:this.keyValue})}onBaselineRangeChanged(e){this.baseline=e[0]}updateBaselineRange(){this.state.baselineDispatchResult=this.props.updateChart(this.props.figureId,{baseline:this.baseline})}updateBaselineMode(e){this.props.updateChart(this.props.figureId,{baselineMode:e.target.value})}}ur.template="o-spreadsheet-ScorecardChartConfigPanel",ur.components={SelectionInput:as};class gr extends t.Component{constructor(){super(...arguments),this.state=t.useState({openedColorPicker:void 0})}onClick(e){this.state.openedColorPicker=void 0}setup(){t.useExternalListener(window,"click",this.onClick)}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}updateBaselineDescr(e){this.props.updateChart(this.props.figureId,{baselineDescr:e.target.value})}openColorPicker(e){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.state.openedColorPicker=void 0}}gr.template="o-spreadsheet-ScorecardChartDesignPanel",gr.components={ColorPicker:sr};const pr=new nn;pr.add("line",{configuration:hr,design:dr}).add("bar",{configuration:cs,design:ar}).add("pie",{configuration:ls,design:rr}).add("gauge",{configuration:lr,design:cr}).add("scorecard",{configuration:ur,design:gr}),wn`
511
+ `;class dr extends t.Component{constructor(){super(...arguments),this.state=t.useState({openedMenu:void 0,sectionRuleDispatchResult:void 0})}get designErrorMessages(){var e;return[...(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.reasons)||[]].map((e=>ts.Errors[e]||ts.Errors.Unexpected))}onClick(e){this.state.openedMenu=void 0}setup(){t.useExternalListener(window,"click",this.onClick)}updateBackgroundColor(e){this.state.openedMenu=void 0,this.props.updateChart(this.props.figureId,{background:e})}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}isRangeMinInvalid(){var e,t,i;return!!((null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(38))||(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(39))||(null===(i=this.state.sectionRuleDispatchResult)||void 0===i?void 0:i.isCancelledBecause(42)))}isRangeMaxInvalid(){var e,t,i;return!!((null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(40))||(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(41))||(null===(i=this.state.sectionRuleDispatchResult)||void 0===i?void 0:i.isCancelledBecause(42)))}get isLowerInflectionPointInvalid(){var e,t;return!(!(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(43))&&!(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(45)))}get isUpperInflectionPointInvalid(){var e,t;return!(!(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(44))&&!(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(45)))}updateInflectionPointValue(e,t){const i=Ae(this.props.definition.sectionRule);i[e].value=t.target.value,this.updateSectionRule(i)}updateInflectionPointType(e,t){const i=Ae(this.props.definition.sectionRule);i[e].type=t.target.value,this.updateSectionRule(i)}updateSectionColor(e,t){const i=Ae(this.props.definition.sectionRule);i.colors[e]=t,this.updateSectionRule(i),this.closeMenus()}updateRangeMin(e){let t=Ae(this.props.definition.sectionRule);t={...t,rangeMin:e.target.value},this.updateSectionRule(t)}updateRangeMax(e){let t=Ae(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}}dr.template="o-spreadsheet-GaugeChartDesignPanel",dr.components={ColorPicker:ar};class ur extends hs{get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.figureId);return!!(e&&e instanceof Xs)&&function(e,t){return Ks(e,t)||Qs(e,t)}(e,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})}onUpdateCumulative(e){this.props.updateChart(this.props.figureId,{cumulative:e.target.checked})}}ur.template="o-spreadsheet-LineConfigPanel";class gr extends lr{}gr.template="o-spreadsheet-LineChartDesignPanel";class pr extends t.Component{constructor(){super(...arguments),this.state=t.useState({keyValueDispatchResult:void 0,baselineDispatchResult:void 0}),this.keyValue=this.props.definition.keyValue,this.baseline=this.props.definition.baseline}get errorMessages(){var e,t;return[...(null===(e=this.state.keyValueDispatchResult)||void 0===e?void 0:e.reasons)||[],...(null===(t=this.state.baselineDispatchResult)||void 0===t?void 0:t.reasons)||[]].map((e=>ts.Errors[e]||ts.Errors.Unexpected))}get isKeyValueInvalid(){var e;return!!(null===(e=this.state.keyValueDispatchResult)||void 0===e?void 0:e.isCancelledBecause(35))}get isBaselineInvalid(){var e;return!!(null===(e=this.state.keyValueDispatchResult)||void 0===e?void 0:e.isCancelledBecause(36))}onKeyValueRangeChanged(e){this.keyValue=e[0]}updateKeyValueRange(){this.state.keyValueDispatchResult=this.props.updateChart(this.props.figureId,{keyValue:this.keyValue})}onBaselineRangeChanged(e){this.baseline=e[0]}updateBaselineRange(){this.state.baselineDispatchResult=this.props.updateChart(this.props.figureId,{baseline:this.baseline})}updateBaselineMode(e){this.props.updateChart(this.props.figureId,{baselineMode:e.target.value})}}pr.template="o-spreadsheet-ScorecardChartConfigPanel",pr.components={SelectionInput:cs};class mr extends t.Component{constructor(){super(...arguments),this.state=t.useState({openedColorPicker:void 0})}onClick(e){this.state.openedColorPicker=void 0}setup(){t.useExternalListener(window,"click",this.onClick)}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}updateBaselineDescr(e){this.props.updateChart(this.props.figureId,{baselineDescr:e.target.value})}openColorPicker(e){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.state.openedColorPicker=void 0}}mr.template="o-spreadsheet-ScorecardChartDesignPanel",mr.components={ColorPicker:ar};const fr=new sn;fr.add("line",{configuration:ur,design:gr}).add("bar",{configuration:ds,design:cr}).add("pie",{configuration:hs,design:lr}).add("gauge",{configuration:hr,design:dr}).add("scorecard",{configuration:pr,design:mr}),xn`
512
512
  .o-chart {
513
513
  .o-panel {
514
514
  display: flex;
@@ -538,7 +538,7 @@
538
538
  border-bottom: 4px solid;
539
539
  }
540
540
  }
541
- `;class mr extends t.Component{get figureId(){return this.state.figureId}setup(){const e=this.env.model.getters.getSelectedFigureId();if(!e)throw new Error(s("Cannot open the chart side panel while no chart are selected"));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()}))}updateChart(e,t){if(e!==this.figureId)return;const i={...this.getChartDefinition(),...t};return this.env.model.dispatch("UPDATE_CHART",{definition:i,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 i=function(e,t){return on.get(t).getChartDefinitionFromContextCreation(e)}(t,e);this.env.model.dispatch("UPDATE_CHART",{definition:i,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=pr.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 on.getKeys())e[t]=on.get(t).name;return e}()}activatePanel(e){this.state.panel=e}}mr.template="o-spreadsheet-ChartPanel";function fr(e){e=`<svg xmlns="http://www.w3.org/2000/svg" ${e.slice(4)}`;const t=new Image;return t.src="data:image/svg+xml; charset=utf8, "+encodeURIComponent(e),t}const vr={arrowGood:{template:"ARROW_UP",img:fr('<svg class="o-cf-icon arrow-up" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#00A04A" d="M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9L413 289.4c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z"></path></svg>')},arrowNeutral:{template:"ARROW_RIGHT",img:fr('<svg class="o-cf-icon arrow-right" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#F0AD4E" d="M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"></path></svg>')},arrowBad:{template:"ARROW_DOWN",img:fr('<svg class="o-cf-icon arrow-down" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#DC6965" d="M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z"></path></svg>')},smileyGood:{template:"SMILE",img:fr('<svg class="o-cf-icon smile" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#00A04A" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160 0c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm4 72.6c-20.8 25-51.5 39.4-84 39.4s-63.2-14.3-84-39.4c-8.5-10.2-23.7-11.5-33.8-3.1-10.2 8.5-11.5 23.6-3.1 33.8 30 36 74.1 56.6 120.9 56.6s90.9-20.6 120.9-56.6c8.5-10.2 7.1-25.3-3.1-33.8-10.1-8.4-25.3-7.1-33.8 3.1z"></path></svg>')},smileyNeutral:{template:"MEH",img:fr('<svg class="o-cf-icon meh" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#F0AD4E" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm8 144H160c-13.2 0-24 10.8-24 24s10.8 24 24 24h176c13.2 0 24-10.8 24-24s-10.8-24-24-24z"></path></svg>')},smileyBad:{template:"FROWN",img:fr('<svg class="o-cf-icon frown" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#DC6965" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm-80 128c-40.2 0-78 17.7-103.8 48.6-8.5 10.2-7.1 25.3 3.1 33.8 10.2 8.4 25.3 7.1 33.8-3.1 16.6-19.9 41-31.4 66.9-31.4s50.3 11.4 66.9 31.4c8.1 9.7 23.1 11.9 33.8 3.1 10.2-8.5 11.5-23.6 3.1-33.8C326 321.7 288.2 304 248 304z"></path></svg>')},dotGood:{template:"GREEN_DOT",img:fr('<svg class="o-cf-icon green-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#00A04A" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>')},dotNeutral:{template:"YELLOW_DOT",img:fr('<svg class="o-cf-icon yellow-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#F0AD4E" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>')},dotBad:{template:"RED_DOT",img:fr('<svg class="o-cf-icon red-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#DC6965" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>')}},br={arrows:{good:"arrowGood",neutral:"arrowNeutral",bad:"arrowBad"},smiley:{good:"smileyGood",neutral:"smileyNeutral",bad:"smileyBad"},dots:{good:"dotGood",neutral:"dotNeutral",bad:"dotBad"}};wn`
541
+ `;class vr extends t.Component{get figureId(){return this.state.figureId}setup(){const e=this.env.model.getters.getSelectedFigureId();if(!e)throw new Error(s("Cannot open the chart side panel while no chart are selected"));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()}))}updateChart(e,t){if(e!==this.figureId)return;const i={...this.getChartDefinition(),...t};return this.env.model.dispatch("UPDATE_CHART",{definition:i,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 i=function(e,t){return rn.get(t).getChartDefinitionFromContextCreation(e)}(t,e);this.env.model.dispatch("UPDATE_CHART",{definition:i,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=fr.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 rn.getKeys())e[t]=rn.get(t).name;return e}()}activatePanel(e){this.state.panel=e}}vr.template="o-spreadsheet-ChartPanel";function br(e){e=`<svg xmlns="http://www.w3.org/2000/svg" ${e.slice(4)}`;const t=new Image;return t.src="data:image/svg+xml; charset=utf8, "+encodeURIComponent(e),t}const Sr={arrowGood:{template:"ARROW_UP",img:br('<svg class="o-cf-icon arrow-up" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#00A04A" d="M34.9 289.5l-22.2-22.2c-9.4-9.4-9.4-24.6 0-33.9L207 39c9.4-9.4 24.6-9.4 33.9 0l194.3 194.3c9.4 9.4 9.4 24.6 0 33.9L413 289.4c-9.5 9.5-25 9.3-34.3-.4L264 168.6V456c0 13.3-10.7 24-24 24h-32c-13.3 0-24-10.7-24-24V168.6L69.2 289.1c-9.3 9.8-24.8 10-34.3.4z"></path></svg>')},arrowNeutral:{template:"ARROW_RIGHT",img:br('<svg class="o-cf-icon arrow-right" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#F0AD4E" d="M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"></path></svg>')},arrowBad:{template:"ARROW_DOWN",img:br('<svg class="o-cf-icon arrow-down" width="10" height="10" focusable="false" viewBox="0 0 448 512"><path fill="#DC6965" d="M413.1 222.5l22.2 22.2c9.4 9.4 9.4 24.6 0 33.9L241 473c-9.4 9.4-24.6 9.4-33.9 0L12.7 278.6c-9.4-9.4-9.4-24.6 0-33.9l22.2-22.2c9.5-9.5 25-9.3 34.3.4L184 343.4V56c0-13.3 10.7-24 24-24h32c13.3 0 24 10.7 24 24v287.4l114.8-120.5c9.3-9.8 24.8-10 34.3-.4z"></path></svg>')},smileyGood:{template:"SMILE",img:br('<svg class="o-cf-icon smile" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#00A04A" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160 0c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm4 72.6c-20.8 25-51.5 39.4-84 39.4s-63.2-14.3-84-39.4c-8.5-10.2-23.7-11.5-33.8-3.1-10.2 8.5-11.5 23.6-3.1 33.8 30 36 74.1 56.6 120.9 56.6s90.9-20.6 120.9-56.6c8.5-10.2 7.1-25.3-3.1-33.8-10.1-8.4-25.3-7.1-33.8 3.1z"></path></svg>')},smileyNeutral:{template:"MEH",img:br('<svg class="o-cf-icon meh" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#F0AD4E" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm8 144H160c-13.2 0-24 10.8-24 24s10.8 24 24 24h176c13.2 0 24-10.8 24-24s-10.8-24-24-24z"></path></svg>')},smileyBad:{template:"FROWN",img:br('<svg class="o-cf-icon frown" width="10" height="10" focusable="false" viewBox="0 0 496 512"><path fill="#DC6965" d="M248 8C111 8 0 119 0 256s111 248 248 248 248-111 248-248S385 8 248 8zm0 448c-110.3 0-200-89.7-200-200S137.7 56 248 56s200 89.7 200 200-89.7 200-200 200zm-80-216c17.7 0 32-14.3 32-32s-14.3-32-32-32-32 14.3-32 32 14.3 32 32 32zm160-64c-17.7 0-32 14.3-32 32s14.3 32 32 32 32-14.3 32-32-14.3-32-32-32zm-80 128c-40.2 0-78 17.7-103.8 48.6-8.5 10.2-7.1 25.3 3.1 33.8 10.2 8.4 25.3 7.1 33.8-3.1 16.6-19.9 41-31.4 66.9-31.4s50.3 11.4 66.9 31.4c8.1 9.7 23.1 11.9 33.8 3.1 10.2-8.5 11.5-23.6 3.1-33.8C326 321.7 288.2 304 248 304z"></path></svg>')},dotGood:{template:"GREEN_DOT",img:br('<svg class="o-cf-icon green-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#00A04A" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>')},dotNeutral:{template:"YELLOW_DOT",img:br('<svg class="o-cf-icon yellow-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#F0AD4E" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>')},dotBad:{template:"RED_DOT",img:br('<svg class="o-cf-icon red-dot" width="10" height="10" focusable="false" viewBox="0 0 512 512"><path fill="#DC6965" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"></path></svg>')}},Cr={arrows:{good:"arrowGood",neutral:"arrowNeutral",bad:"arrowBad"},smiley:{good:"smileyGood",neutral:"smileyNeutral",bad:"smileyBad"},dots:{good:"dotGood",neutral:"dotNeutral",bad:"dotBad"}};xn`
542
542
  .o-icon-picker {
543
543
  position: absolute;
544
544
  z-index: ${oe.IconPicker};
@@ -557,7 +557,7 @@
557
557
  outline: 1px solid gray;
558
558
  }
559
559
  }
560
- `;class Sr extends t.Component{constructor(){super(...arguments),this.icons=vr,this.iconSets=br}onIconClick(e){e&&this.props.onIconPicked(e)}}Sr.template="o-spreadsheet-IconPicker",wn`
560
+ `;class Er extends t.Component{constructor(){super(...arguments),this.icons=Sr,this.iconSets=Cr}onIconClick(e){e&&this.props.onIconPicked(e)}}Er.template="o-spreadsheet-IconPicker",xn`
561
561
  label {
562
562
  vertical-align: middle;
563
563
  }
@@ -824,13 +824,13 @@
824
824
  }
825
825
  }
826
826
  }
827
- `;class Cr extends t.Component{constructor(){super(...arguments),this.icons=vr,this.cellIsOperators=Qo,this.iconSets=br,this.getTextDecoration=yn,this.colorNumberString=gt}setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId(),this.state=t.useState({mode:"list",errors:[],rules:this.getDefaultRules()});const e=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(1===i.length){const e=this.conditionalFormats.find((e=>e.id===i[0]));e&&this.editConditionalFormat(e)}t.onWillUpdateProps((e=>{const t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(1===i.length){const e=this.conditionalFormats.find((e=>e.id===i[0]));e&&this.editConditionalFormat(e)}else this.switchToList()}})),t.useExternalListener(window,"click",this.closeMenus)}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId())}get isRangeValid(){return this.state.errors.includes(24)}errorMessage(e){return Ko.Errors[e]||Ko.Errors.Unexpected}switchToList(){this.state.mode="list",this.state.currentCF=void 0,this.state.currentCFType=void 0,this.state.errors=[],this.state.rules=this.getDefaultRules()}getStyle(e){if("CellIsRule"===e.type){return`font-weight:${e.style.bold?"bold":"normal"};\n text-decoration:${yn(e.style)};\n font-style:${e.style.italic?"italic":"normal"};\n color:${e.style.textColor||"none"};\n background-color:${e.style.fillColor||"none"};`}if("ColorScaleRule"===e.type){const t=gt(e.minimum.color),i=e.midpoint?gt(e.midpoint.color):null,n=gt(e.maximum.color),o="background-image: linear-gradient(to right, ";return i?o+t+", "+i+", "+n+")":o+t+", "+n+")"}return""}getDescription(e){switch(e.rule.type){case"CellIsRule":const t=Qo[e.rule.operator];return 1===e.rule.values.length?`${t} ${e.rule.values[0]}`:2===e.rule.values.length?o("%s %s and %s",t,e.rule.values[0],e.rule.values[1]):t;case"ColorScaleRule":return Ko.ColorScale;case"IconSetRule":return Ko.IconSet;default:return""}}saveConditionalFormat(){if(this.state.currentCF){if(this.state.currentCF.ranges.some((e=>!e.match(Nt))))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.smallUuid()},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.smallUuid(),ranges:this.env.model.getters.getSelectedZones().map((e=>this.env.model.getters.zoneToXC(this.env.model.getters.getActiveSheetId(),e)))}}deleteConditionalFormat(e){this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:e.id,sheetId:this.env.model.getters.getActiveSheetId()})}editConditionalFormat(e){if("reorder"!==this.state.mode)switch(this.state.mode="edit",this.state.currentCF=e,this.state.currentCFType=e.rule.type,e.rule.type){case"CellIsRule":this.state.rules.cellIs=e.rule;break;case"ColorScaleRule":this.state.rules.colorScale=e.rule;break;case"IconSetRule":this.state.rules.iconSet=e.rule}}reorderConditionalFormats(){this.state.mode="reorder"}reorderRule(e,t){this.env.model.dispatch("MOVE_CONDITIONAL_FORMAT",{cfId:e.id,direction:t,sheetId:this.env.model.getters.getActiveSheetId()})}changeRuleType(e){this.state.currentCFType!==e&&this.state.rules&&(this.state.errors=[],this.state.currentCFType=e)}onRangesChanged(e){this.state.currentCF&&(this.state.currentCF.ranges=e)}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(52))}get isValue2Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(53))}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.closeMenus()}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.closeMenus()}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes(59)||this.state.errors.includes(51)||this.state.errors.includes(48)||this.state.errors.includes(54);case"midpoint":return this.state.errors.includes(60)||this.state.errors.includes(55)||this.state.errors.includes(50);case"maximum":return this.state.errors.includes(61)||this.state.errors.includes(56);default:return!1}}setColorScaleColor(e,t){if(!ft(t))return;const i=this.state.rules.colorScale[e];i&&(i.color=Number.parseInt(t.substr(1),16)),this.closeMenus()}getPreviewGradient(){var e;const t=this.state.rules.colorScale,i=gt(t.minimum.color),n=gt((null===(e=t.midpoint)||void 0===e?void 0:e.color)||x),o=gt(t.maximum.color),s="background-image: linear-gradient(to right, ";return void 0===t.midpoint?s+i+", "+o+")":s+i+", "+n+", "+o+")"}getThresholdColor(e){return gt(e?e.color:x)}onMidpointChange(e){const t=e.target.value,i=this.state.rules.colorScale;i.midpoint="none"===t?void 0:{color:x,value:"",...i.midpoint,type:t}}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes(58)||this.state.errors.includes(63)||this.state.errors.includes(49);case"upperInflectionPoint":return this.state.errors.includes(57)||this.state.errors.includes(62)||this.state.errors.includes(49);default:return!0}}reverseIcons(){const e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t}setIconSet(e){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad}setIcon(e,t){this.state.rules.iconSet.icons[e]=t}}Cr.template="o-spreadsheet-ConditionalFormattingPanel",Cr.components={SelectionInput:as,IconPicker:Sr,ColorPicker:sr},wn`
827
+ `;class wr extends t.Component{constructor(){super(...arguments),this.icons=Sr,this.cellIsOperators=es,this.iconSets=Cr,this.getTextDecoration=Rn,this.colorNumberString=gt}setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId(),this.state=t.useState({mode:"list",errors:[],rules:this.getDefaultRules()});const e=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(1===i.length){const e=this.conditionalFormats.find((e=>e.id===i[0]));e&&this.editConditionalFormat(e)}t.onWillUpdateProps((e=>{const t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(1===i.length){const e=this.conditionalFormats.find((e=>e.id===i[0]));e&&this.editConditionalFormat(e)}else this.switchToList()}})),t.useExternalListener(window,"click",this.closeMenus)}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId())}get isRangeValid(){return this.state.errors.includes(24)}errorMessage(e){return Jo.Errors[e]||Jo.Errors.Unexpected}switchToList(){this.state.mode="list",this.state.currentCF=void 0,this.state.currentCFType=void 0,this.state.errors=[],this.state.rules=this.getDefaultRules()}getStyle(e){if("CellIsRule"===e.type){return`font-weight:${e.style.bold?"bold":"normal"};\n text-decoration:${Rn(e.style)};\n font-style:${e.style.italic?"italic":"normal"};\n color:${e.style.textColor||"none"};\n background-color:${e.style.fillColor||"none"};`}if("ColorScaleRule"===e.type){const t=gt(e.minimum.color),i=e.midpoint?gt(e.midpoint.color):null,n=gt(e.maximum.color),o="background-image: linear-gradient(to right, ";return i?o+t+", "+i+", "+n+")":o+t+", "+n+")"}return""}getDescription(e){switch(e.rule.type){case"CellIsRule":const t=es[e.rule.operator];return 1===e.rule.values.length?`${t} ${e.rule.values[0]}`:2===e.rule.values.length?o("%s %s and %s",t,e.rule.values[0],e.rule.values[1]):t;case"ColorScaleRule":return Jo.ColorScale;case"IconSetRule":return Jo.IconSet;default:return""}}saveConditionalFormat(){if(this.state.currentCF){if(this.state.currentCF.ranges.some((e=>!e.match(Ot))))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.smallUuid()},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.smallUuid(),ranges:this.env.model.getters.getSelectedZones().map((e=>this.env.model.getters.zoneToXC(this.env.model.getters.getActiveSheetId(),e)))}}deleteConditionalFormat(e){this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:e.id,sheetId:this.env.model.getters.getActiveSheetId()})}editConditionalFormat(e){if("reorder"!==this.state.mode)switch(this.state.mode="edit",this.state.currentCF=e,this.state.currentCFType=e.rule.type,e.rule.type){case"CellIsRule":this.state.rules.cellIs=e.rule;break;case"ColorScaleRule":this.state.rules.colorScale=e.rule;break;case"IconSetRule":this.state.rules.iconSet=e.rule}}reorderConditionalFormats(){this.state.mode="reorder"}reorderRule(e,t){this.env.model.dispatch("MOVE_CONDITIONAL_FORMAT",{cfId:e.id,direction:t,sheetId:this.env.model.getters.getActiveSheetId()})}changeRuleType(e){this.state.currentCFType!==e&&this.state.rules&&(this.state.errors=[],this.state.currentCFType=e)}onRangesChanged(e){this.state.currentCF&&(this.state.currentCF.ranges=e)}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(52))}get isValue2Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(53))}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.closeMenus()}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.closeMenus()}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes(59)||this.state.errors.includes(51)||this.state.errors.includes(48)||this.state.errors.includes(54);case"midpoint":return this.state.errors.includes(60)||this.state.errors.includes(55)||this.state.errors.includes(50);case"maximum":return this.state.errors.includes(61)||this.state.errors.includes(56);default:return!1}}setColorScaleColor(e,t){if(!ft(t))return;const i=this.state.rules.colorScale[e];i&&(i.color=Number.parseInt(t.substr(1),16)),this.closeMenus()}getPreviewGradient(){var e;const t=this.state.rules.colorScale,i=gt(t.minimum.color),n=gt((null===(e=t.midpoint)||void 0===e?void 0:e.color)||x),o=gt(t.maximum.color),s="background-image: linear-gradient(to right, ";return void 0===t.midpoint?s+i+", "+o+")":s+i+", "+n+", "+o+")"}getThresholdColor(e){return gt(e?e.color:x)}onMidpointChange(e){const t=e.target.value,i=this.state.rules.colorScale;i.midpoint="none"===t?void 0:{color:x,value:"",...i.midpoint,type:t}}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes(58)||this.state.errors.includes(63)||this.state.errors.includes(49);case"upperInflectionPoint":return this.state.errors.includes(57)||this.state.errors.includes(62)||this.state.errors.includes(49);default:return!0}}reverseIcons(){const e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t}setIconSet(e){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad}setIcon(e,t){this.state.rules.iconSet.icons[e]=t}}wr.template="o-spreadsheet-ConditionalFormattingPanel",wr.components={SelectionInput:cs,IconPicker:Er,ColorPicker:ar},xn`
828
828
  .o-custom-currency {
829
829
  .o-format-proposals {
830
830
  color: black;
831
831
  }
832
832
  }
833
- `;class Er extends t.Component{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),i=e.position,n="before"===e.position?"after":"before",o=this.state.currencySymbol.trim()?this.state.currencySymbol:"",s=this.state.currencyCode.trim()?this.state.currencyCode:"";return s||o?[...this.createFormatProposals(t,o,s,i),...this.createFormatProposals(t,o,s,n)]:[]}get isSameFormat(){const e=this.formatProposals[this.state.selectedFormatIndex];return!!e&&e.format===this.getCommonFormat()}async updateAvailableCurrencies(){var e,t;if(0===to.getAll().length){(await(null===(t=(e=this.env).loadCurrencies)||void 0===t?void 0:t.call(e))||[]).forEach(((e,t)=>{to.add(t.toString(),e)}))}const i={name:this.env._t(ts.Custom),code:"",symbol:"",decimalPlaces:2,position:"after"};this.availableCurrencies=[i,...to.getAll()]}updateSelectCurrency(e){const t=e.target;this.state.selectedCurrencyIndex=parseInt(t.value,10);const i=this.availableCurrencies[this.state.selectedCurrencyIndex];this.state.currencyCode=i.code,this.state.currencySymbol=i.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"}],i=e?"."+"0".repeat(e):"";return i&&t.push({format:"#,##0"+i,example:"1,000"+i}),t}createFormatProposals(e,t,i,n){let o=[];if(t)for(let i of e)o.push(this.createFormatProposal(n,i.example,i.format,t));if(i)for(let s of e){const e=("after"===n?" ":"")+i+" "+t;o.push(this.createFormatProposal(n,s.example,s.format,e))}return o}createFormatProposal(e,t,i,n){const o="[$"+n+"]";return{example:"before"===e?n+t:t+n,format:"before"===e?o+i:i+o}}getCommonFormat(){var e;const t=this.env.model.getters.getSelectedZones(),i=this.env.model.getters.getActiveSheetId(),n=t.map((e=>this.env.model.getters.getCellsInZone(i,e))).flat(),o=null===(e=n[0])||void 0===e?void 0:e.format;return n.every((e=>(null==e?void 0:e.format)===o))?o:void 0}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:"")}}Er.template="o-spreadsheet-CustomCurrencyPanel",wn`
833
+ `;class yr extends t.Component{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),i=e.position,n="before"===e.position?"after":"before",o=this.state.currencySymbol.trim()?this.state.currencySymbol:"",s=this.state.currencyCode.trim()?this.state.currencyCode:"";return s||o?[...this.createFormatProposals(t,o,s,i),...this.createFormatProposals(t,o,s,n)]:[]}get isSameFormat(){const e=this.formatProposals[this.state.selectedFormatIndex];return!!e&&e.format===this.getCommonFormat()}async updateAvailableCurrencies(){var e,t;if(0===no.getAll().length){(await(null===(t=(e=this.env).loadCurrencies)||void 0===t?void 0:t.call(e))||[]).forEach(((e,t)=>{no.add(t.toString(),e)}))}const i={name:this.env._t(ns.Custom),code:"",symbol:"",decimalPlaces:2,position:"after"};this.availableCurrencies=[i,...no.getAll()]}updateSelectCurrency(e){const t=e.target;this.state.selectedCurrencyIndex=parseInt(t.value,10);const i=this.availableCurrencies[this.state.selectedCurrencyIndex];this.state.currencyCode=i.code,this.state.currencySymbol=i.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"}],i=e?"."+"0".repeat(e):"";return i&&t.push({format:"#,##0"+i,example:"1,000"+i}),t}createFormatProposals(e,t,i,n){let o=[];if(t)for(let i of e)o.push(this.createFormatProposal(n,i.example,i.format,t));if(i)for(let s of e){const e=("after"===n?" ":"")+i+" "+t;o.push(this.createFormatProposal(n,s.example,s.format,e))}return o}createFormatProposal(e,t,i,n){const o="[$"+n+"]";return{example:"before"===e?n+t:t+n,format:"before"===e?o+i:i+o}}getCommonFormat(){var e;const t=this.env.model.getters.getSelectedZones(),i=this.env.model.getters.getActiveSheetId(),n=t.map((e=>this.env.model.getters.getCellsInZone(i,e))).flat(),o=null===(e=n[0])||void 0===e?void 0:e.format;return n.every((e=>(null==e?void 0:e.format)===o))?o:void 0}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:"")}}yr.template="o-spreadsheet-CustomCurrencyPanel",xn`
834
834
  .o-find-and-replace {
835
835
  .o-far-item {
836
836
  display: block;
@@ -863,7 +863,7 @@
863
863
  }
864
864
  }
865
865
  }
866
- `;class wr extends t.Component{constructor(){super(...arguments),this.state=t.useState(this.initialState()),this.showFormulaState=!1,this.findAndReplaceRef=t.useRef("findAndReplace")}get hasSearchResult(){return null!==this.env.model.getters.getCurrentSelectedMatchIndex()}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(),this.onSelectNextCell())}onKeydownReplace(e){"Enter"===e.key&&(e.preventDefault(),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}}}}wr.template="o-spreadsheet-FindAndReplacePanel";const yr=new nn;yr.add("ConditionalFormatting",{title:s("Conditional formatting"),Body:Cr}),yr.add("ChartPanel",{title:s("Chart"),Body:mr}),yr.add("FindAndReplace",{title:s("Find and Replace"),Body:wr}),yr.add("CustomCurrency",{title:s("Custom currency format"),Body:Er});const xr=new class extends nn{constructor(){super(...arguments),this.mapping={},this.uuidGenerator=new Oi}add(e,t){const i={...t,id:this.uuidGenerator.smallUuid()};return super.add(e,i)}},Rr=1.2;wn`
866
+ `;class xr extends t.Component{constructor(){super(...arguments),this.state=t.useState(this.initialState()),this.showFormulaState=!1,this.findAndReplaceRef=t.useRef("findAndReplace")}get hasSearchResult(){return null!==this.env.model.getters.getCurrentSelectedMatchIndex()}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(),this.onSelectNextCell())}onKeydownReplace(e){"Enter"===e.key&&(e.preventDefault(),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}}}}xr.template="o-spreadsheet-FindAndReplacePanel";const Rr=new sn;Rr.add("ConditionalFormatting",{title:s("Conditional formatting"),Body:wr}),Rr.add("ChartPanel",{title:s("Chart"),Body:vr}),Rr.add("FindAndReplace",{title:s("Find and Replace"),Body:xr}),Rr.add("CustomCurrency",{title:s("Custom currency format"),Body:yr});const Ir=new class extends sn{constructor(){super(...arguments),this.mapping={},this.uuidGenerator=new Mi}add(e,t){const i={...t,id:this.uuidGenerator.smallUuid()};return super.add(e,i)}},Tr=1.2;xn`
867
867
  div.o-scorecard {
868
868
  font-family: ${q};
869
869
  user-select: none;
@@ -882,15 +882,15 @@
882
882
 
883
883
  .o-title-text {
884
884
  text-align: left;
885
- height: ${Rr+"em"};
886
- line-height: ${Rr+"em"};
885
+ height: ${Tr+"em"};
886
+ line-height: ${Tr+"em"};
887
887
  overflow: hidden;
888
888
  white-space: nowrap;
889
889
  }
890
890
 
891
891
  .o-key-text {
892
- line-height: ${Rr+"em"};
893
- height: ${Rr+"em"};
892
+ line-height: ${Tr+"em"};
893
+ height: ${Tr+"em"};
894
894
  overflow: hidden;
895
895
  white-space: nowrap;
896
896
  }
@@ -905,8 +905,8 @@
905
905
  }
906
906
 
907
907
  .o-baseline-text {
908
- line-height: ${Rr+"em"};
909
- height: ${Rr+"em"};
908
+ line-height: ${Tr+"em"};
909
+ height: ${Tr+"em"};
910
910
  overflow: hidden;
911
911
  white-space: nowrap;
912
912
 
@@ -915,7 +915,7 @@
915
915
  }
916
916
  }
917
917
  }
918
- `;class Ir extends t.Component{constructor(){super(...arguments),this.ctx=document.createElement("canvas").getContext("2d")}get runtime(){return this.env.model.getters.getChartRuntime(this.props.figure.id)}get title(){return this.runtime.title}get keyValue(){return this.runtime.keyValue}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){const e=this.runtime.baselineDescr||"";return this.baseline&&e?" "+e:e}get baselineArrowDirection(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get primaryFontColor(){return this.runtime.fontColor}get secondaryFontColor(){return St(this.backgroundColor)>.3?"#525252":"#C8C8C8"}get figure(){return this.props.figure}get chartStyle(){return`\n padding:${this.chartPadding}px;\n background:${this.backgroundColor};\n `}get chartContentStyle(){return`\n height:${this.getDrawableHeight()}px;\n `}get chartPadding(){return.02*this.props.figure.width}getTextStyles(){var e,t,i;const n=.96*this.props.figure.width,o=this.getWidestElement(),s=o.getElementMaxFontSize(this.getDrawableHeight(),this);let r=function(e,t,i,n=.25){let o=1;if(i(o)>e)return o;if(i(t)<e)return t;let s=(o+t)/2,r=i(s),a=0;for(;Math.abs(r-e)>n&&a<20;)r>=e?t=(o+t)/2:o=(o+t)/2,s=(o+t)/2,r=i(s),a++;return s}(n,s,(e=>o.getElementWidth(e,this.ctx,this)))/s;const a=(new Ar).getElementMaxFontSize(this.getDrawableHeight(),this)*r,l=(new Tr).getElementMaxFontSize(this.getDrawableHeight(),this)*r;return{titleStyle:this.getTextStyle({fontSize:18,color:this.secondaryFontColor}),keyStyle:this.getTextStyle({fontSize:a,cellStyle:null===(e=this.runtime)||void 0===e?void 0:e.keyValueStyle,color:this.primaryFontColor}),baselineStyle:this.getTextStyle({fontSize:l}),baselineValueStyle:this.getTextStyle({fontSize:l,cellStyle:null===(t=this.runtime)||void 0===t?void 0:t.baselineStyle,color:(null===(i=this.runtime)||void 0===i?void 0:i.baselineColor)||this.secondaryFontColor}),baselineDescrStyle:this.getTextStyle({fontSize:.9*l,color:this.secondaryFontColor})}}getTextStyle(e){const t=function(e){const t={};if(!e)return t;if(e.bold&&(t["font-weight"]="bold"),e.italic&&(t["font-style"]="italic"),e.strikethrough||e.underline){let i=e.strikethrough?"line-through":"";i=e.underline?i+" underline":i,t["text-decoration"]=i}return e.textColor&&(t.color=e.textColor),t}(e.cellStyle);return t["font-size"]=`${e.fontSize}px`,t.display="inline-block",!t.color&&e.color&&(t.color=e.color),xn(t)}getDrawableHeight(){const e=2*this.chartPadding;let t=this.props.figure.height-e;return t-=this.title?18*Rr:0,t}getWidestElement(){const e=new Tr,t=new Ar;return e.getElementWidth(.35,this.ctx,this)>t.getElementWidth(.65,this.ctx,this)?e:t}}Ir.template="o-spreadsheet-ScorecardChart";class Tr{getElementWidth(e,t,i){if(!i.runtime)return 0;const n=i.baseline,o="neutral"!==i.baselineArrowDirection?"A "+n:n;t.font=`${e}px ${q}`;let s=t.measureText(o).width;return t.font=`${.9*e}px ${q}`,s+=t.measureText(i.baselineDescr).width,s}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.35*e:0)/Rr}}class Ar{getElementWidth(e,t,i){if(!i.runtime)return 0;const n=i.keyValue||"";return t.font=`${e}px ${q}`,t.measureText(n).width}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.65*e:e)/Rr}}sn.add("scorecard",Ir),wn`
918
+ `;class Ar extends t.Component{constructor(){super(...arguments),this.ctx=document.createElement("canvas").getContext("2d")}get runtime(){return this.env.model.getters.getChartRuntime(this.props.figure.id)}get title(){return this.runtime.title}get keyValue(){return this.runtime.keyValue}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){const e=this.runtime.baselineDescr||"";return this.baseline&&e?" "+e:e}get baselineArrowDirection(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get primaryFontColor(){return this.runtime.fontColor}get secondaryFontColor(){return St(this.backgroundColor)>.3?"#525252":"#C8C8C8"}get figure(){return this.props.figure}get chartStyle(){return`\n padding:${this.chartPadding}px;\n background:${this.backgroundColor};\n `}get chartContentStyle(){return`\n height:${this.getDrawableHeight()}px;\n `}get chartPadding(){return.02*this.props.figure.width}getTextStyles(){var e,t,i;const n=.96*this.props.figure.width,o=this.getWidestElement(),s=o.getElementMaxFontSize(this.getDrawableHeight(),this);let r=function(e,t,i,n=.25){let o=1;if(i(o)>e)return o;if(i(t)<e)return t;let s=(o+t)/2,r=i(s),a=0;for(;Math.abs(r-e)>n&&a<20;)r>=e?t=(o+t)/2:o=(o+t)/2,s=(o+t)/2,r=i(s),a++;return s}(n,s,(e=>o.getElementWidth(e,this.ctx,this)))/s;const a=(new Or).getElementMaxFontSize(this.getDrawableHeight(),this)*r,l=(new Nr).getElementMaxFontSize(this.getDrawableHeight(),this)*r;return{titleStyle:this.getTextStyle({fontSize:18,color:this.secondaryFontColor}),keyStyle:this.getTextStyle({fontSize:a,cellStyle:null===(e=this.runtime)||void 0===e?void 0:e.keyValueStyle,color:this.primaryFontColor}),baselineStyle:this.getTextStyle({fontSize:l}),baselineValueStyle:this.getTextStyle({fontSize:l,cellStyle:null===(t=this.runtime)||void 0===t?void 0:t.baselineStyle,color:(null===(i=this.runtime)||void 0===i?void 0:i.baselineColor)||this.secondaryFontColor}),baselineDescrStyle:this.getTextStyle({fontSize:.9*l,color:this.secondaryFontColor})}}getTextStyle(e){const t=function(e){const t={};if(!e)return t;if(e.bold&&(t["font-weight"]="bold"),e.italic&&(t["font-style"]="italic"),e.strikethrough||e.underline){let i=e.strikethrough?"line-through":"";i=e.underline?i+" underline":i,t["text-decoration"]=i}return e.textColor&&(t.color=e.textColor),t}(e.cellStyle);return t["font-size"]=`${e.fontSize}px`,t.display="inline-block",!t.color&&e.color&&(t.color=e.color),In(t)}getDrawableHeight(){const e=2*this.chartPadding;let t=this.props.figure.height-e;return t-=this.title?18*Tr:0,t}getWidestElement(){const e=new Nr,t=new Or;return e.getElementWidth(.35,this.ctx,this)>t.getElementWidth(.65,this.ctx,this)?e:t}}Ar.template="o-spreadsheet-ScorecardChart";class Nr{getElementWidth(e,t,i){if(!i.runtime)return 0;const n=i.baseline,o="neutral"!==i.baselineArrowDirection?"A "+n:n;t.font=`${e}px ${q}`;let s=t.measureText(o).width;return t.font=`${.9*e}px ${q}`,s+=t.measureText(i.baselineDescr).width,s}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.35*e:0)/Tr}}class Or{getElementWidth(e,t,i){if(!i.runtime)return 0;const n=i.keyValue||"";return t.font=`${e}px ${q}`,t.measureText(n).width}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.65*e:e)/Tr}}an.add("scorecard",Ar),xn`
919
919
  .o-chart-container {
920
920
  width: 100%;
921
921
  height: 100%;
@@ -940,7 +940,7 @@
940
940
  }
941
941
  }
942
942
  }
943
- `;class Or extends t.Component{constructor(){super(...arguments),this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.chartContainerRef=t.useRef("chartContainer"),this.menuButtonRef=t.useRef("menuButton"),this.menuButtonPosition=zn(this.menuButtonRef),this.position=zn(this.chartContainerRef)}getMenuItemRegistry(){const e=new Yn;return e.add("edit",{name:s("Edit"),sequence:1,action:()=>{this.env.model.dispatch("SELECT_FIGURE",{id:this.props.figure.id}),this.env.openSidePanel("ChartPanel")}}),e.add("copy",{name:s("Copy"),sequence:2,action:async()=>{this.env.model.dispatch("SELECT_FIGURE",{id:this.props.figure.id}),this.env.model.dispatch("COPY"),await this.env.clipboard.writeText(this.env.model.getters.getClipboardContent())}}),e.add("cut",{name:s("Cut"),sequence:3,action:async()=>{this.env.model.dispatch("SELECT_FIGURE",{id:this.props.figure.id}),this.env.model.dispatch("CUT"),await this.env.clipboard.writeText(this.env.model.getters.getClipboardContent())}}),e.add("delete",{name:s("Delete"),sequence:10,action:()=>{this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:this.props.figure.id}),this.props.sidePanelIsOpen&&this.env.toggleSidePanel("ChartPanel"),this.props.onFigureDeleted()}}),e}get chartType(){return this.env.model.getters.getChartType(this.props.figure.id)}onContextMenu(e){const t={x:this.position.x+e.offsetX,y:this.position.y+e.offsetY};this.openContextMenu(t)}showMenu(){const e={x:this.menuButtonPosition.x-B,y:this.menuButtonPosition.y};this.openContextMenu(e)}openContextMenu(e){const t=this.getMenuItemRegistry();this.menuState.isOpen=!0,this.menuState.menuItems=t.getAll(),this.menuState.position=e}get chartComponent(){const e=this.chartType,t=sn.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}function Nr(e,t,i=(()=>{})){const n=()=>{window.removeEventListener("mousedown",i),window.removeEventListener("mouseup",o),window.removeEventListener("dragstart",s),window.removeEventListener("mousemove",e),window.removeEventListener("wheel",e)},o=e=>{t(e),n()};function s(e){e.preventDefault()}return window.addEventListener("mousedown",i),window.addEventListener("mouseup",o),window.addEventListener("dragstart",s),window.addEventListener("mousemove",e),window.addEventListener("wheel",e),n}function Mr(e,t,i,n=!1){let o,s,r,a,l,c=null;const h=e.model.getters,d=h.getActiveSheetId(),u=$n();let g,p;const m=i=>{if(o=i,c)return;const{x:r,y:f}=h.getMainViewportCoordinates();let{top:v,left:b,bottom:S,right:C}=h.getActiveMainViewport(),{scrollX:E,scrollY:w}=h.getActiveSheetDOMScrollInfo();const{xSplit:y,ySplit:x}=h.getPaneDivisions(d);let R=!1,I=zt;const T=o.clientX-u.left;if(g=h.getColIndex(T),"vertical"!==n){const t=s.clientX-u.left,i=h.getEdgeScrollCol(T,t,a);if(i.canEdgeScroll){let t;switch(R=!0,I=Math.min(I,i.delay),i.direction){case"reset":g=y,t=y;break;case 1:g=C,t=b+1;break;case-1:for(g=b-1;e.model.getters.isColHidden(d,g);)g--;t=g}E=h.getColDimensions(d,t).start-r}}const A=o.clientY-u.top;if(p=h.getRowIndex(A),"horizontal"!==n){const t=s.clientY-u.top,i=h.getEdgeScrollRow(A,t,l);if(i.canEdgeScroll){let t;switch(R=!0,I=Math.min(I,i.delay),i.direction){case"reset":p=x,t=x;break;case 1:p=S,t=v+i.direction;break;case-1:for(p=v-1;e.model.getters.isRowHidden(d,p);)p--;t=p}w=e.model.getters.getRowDimensions(d,t).start-f}}R||(-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,o),R&&(e.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:E,offsetY:w}),c=setTimeout((()=>{c=null,m(o)}),Math.round(I))),s=o};Nr(m,(()=>{clearTimeout(c),i()}),(e=>{s=e,r=e,a=r.clientX-u.left,l=r.clientY-u.top}))}Or.template="o-spreadsheet-ChartFigure",Or.components={Menu:Hn},wn`
943
+ `;class Mr extends t.Component{constructor(){super(...arguments),this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.chartContainerRef=t.useRef("chartContainer"),this.menuButtonRef=t.useRef("menuButton"),this.menuButtonPosition=Hn(this.menuButtonRef),this.position=Hn(this.chartContainerRef)}getMenuItemRegistry(){const e=new Kn;return e.add("edit",{name:s("Edit"),sequence:1,action:()=>{this.env.model.dispatch("SELECT_FIGURE",{id:this.props.figure.id}),this.env.openSidePanel("ChartPanel")}}),e.add("copy",{name:s("Copy"),sequence:2,action:async()=>{this.env.model.dispatch("SELECT_FIGURE",{id:this.props.figure.id}),this.env.model.dispatch("COPY"),await this.env.clipboard.writeText(this.env.model.getters.getClipboardContent())}}),e.add("cut",{name:s("Cut"),sequence:3,action:async()=>{this.env.model.dispatch("SELECT_FIGURE",{id:this.props.figure.id}),this.env.model.dispatch("CUT"),await this.env.clipboard.writeText(this.env.model.getters.getClipboardContent())}}),e.add("delete",{name:s("Delete"),sequence:10,action:()=>{this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:this.props.figure.id}),this.props.sidePanelIsOpen&&this.env.toggleSidePanel("ChartPanel"),this.props.onFigureDeleted()}}),e}get chartType(){return this.env.model.getters.getChartType(this.props.figure.id)}onContextMenu(e){const t={x:this.position.x+e.offsetX,y:this.position.y+e.offsetY};this.openContextMenu(t)}showMenu(){const e={x:this.menuButtonPosition.x-B,y:this.menuButtonPosition.y};this.openContextMenu(e)}openContextMenu(e){const t=this.getMenuItemRegistry();this.menuState.isOpen=!0,this.menuState.menuItems=t.getAll(),this.menuState.position=e}get chartComponent(){const e=this.chartType,t=an.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}function _r(e,t,i=(()=>{})){const n=()=>{window.removeEventListener("mousedown",i),window.removeEventListener("mouseup",o),window.removeEventListener("dragstart",s),window.removeEventListener("mousemove",e),window.removeEventListener("wheel",e)},o=e=>{t(e),n()};function s(e){e.preventDefault()}return window.addEventListener("mousedown",i),window.addEventListener("mouseup",o),window.addEventListener("dragstart",s),window.addEventListener("mousemove",e),window.addEventListener("wheel",e),n}function Fr(e,t,i,n=!1){let o,s,r,a,l,c=null;const h=e.model.getters,d=h.getActiveSheetId(),u=Pn();let g,p;const m=i=>{if(o=i,c)return;const{x:r,y:f}=h.getMainViewportCoordinates();let{top:v,left:b,bottom:S,right:C}=h.getActiveMainViewport(),{scrollX:E,scrollY:w}=h.getActiveSheetDOMScrollInfo();const{xSplit:y,ySplit:x}=h.getPaneDivisions(d);let R=!1,I=zt;const T=o.clientX-u.left;if(g=h.getColIndex(T),"vertical"!==n){const t=s.clientX-u.left,i=h.getEdgeScrollCol(T,t,a);if(i.canEdgeScroll){let t;switch(R=!0,I=Math.min(I,i.delay),i.direction){case"reset":g=y,t=y;break;case 1:g=C,t=b+1;break;case-1:for(g=b-1;e.model.getters.isColHidden(d,g);)g--;t=g}E=h.getColDimensions(d,t).start-r}}const A=o.clientY-u.top;if(p=h.getRowIndex(A),"horizontal"!==n){const t=s.clientY-u.top,i=h.getEdgeScrollRow(A,t,l);if(i.canEdgeScroll){let t;switch(R=!0,I=Math.min(I,i.delay),i.direction){case"reset":p=x,t=x;break;case 1:p=S,t=v+i.direction;break;case-1:for(p=v-1;e.model.getters.isRowHidden(d,p);)p--;t=p}w=e.model.getters.getRowDimensions(d,t).start-f}}R||(-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,o),R&&(e.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:E,offsetY:w}),c=setTimeout((()=>{c=null,m(o)}),Math.round(I))),s=o};_r(m,(()=>{clearTimeout(c),i()}),(e=>{s=e,r=e,a=r.clientX-u.left,l=r.clientY-u.top}))}Mr.template="o-spreadsheet-ChartFigure",Mr.components={Menu:Gn},xn`
944
944
  .o-autofill {
945
945
  height: 6px;
946
946
  width: 6px;
@@ -968,9 +968,9 @@
968
968
  white-space: nowrap;
969
969
  }
970
970
  }
971
- `;class _r extends t.Component{constructor(){super(...arguments),this.state=t.useState({position:{left:0,top:0},handler:!1})}get style(){const{left:e,top:t}=this.props.position;return`top:${t}px;left:${e}px`}get styleHandler(){let e=this.state.handler?this.state.position:{left:0,top:0};return`top:${e.top}px;left:${e.left}px;`}get styleNextvalue(){let e=this.state.handler?this.state.position:{left:0,top:0};return`top:${e.top+5}px;left:${e.left+15}px;`}getTooltip(){const e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=Fr),e}onMouseDown(e){this.state.handler=!0,this.state.position={left:0,top:0};const{scrollY:t,scrollX:i}=this.env.model.getters.getActiveSheetScrollInfo(),n=e.clientX+i,o=e.clientY+t;let s,r;Nr((e=>{const t=$n(),{scrollY:i,scrollX:a}=this.env.model.getters.getActiveSheetScrollInfo();this.state.position={left:e.clientX-n+a,top:e.clientY-o+i};const l=this.env.model.getters.getColIndex(e.clientX-t.left),c=this.env.model.getters.getRowIndex(e.clientY-t.top);if(s!==l||r!==c){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getNumberCols(e),i=this.env.model.getters.getNumberRows(e);s=-1===l?s:Me(l,0,t),r=-1===c?r:Me(c,0,i),void 0!==s&&void 0!==r&&this.env.model.dispatch("AUTOFILL_SELECT",{col:s,row:r})}}),(()=>{this.state.handler=!1,this.env.model.dispatch("AUTOFILL")}))}onDblClick(){this.env.model.dispatch("AUTOFILL_AUTO")}}_r.template="o-spreadsheet-Autofill";class Fr extends t.Component{}Fr.template=t.xml`
971
+ `;class Dr extends t.Component{constructor(){super(...arguments),this.state=t.useState({position:{left:0,top:0},handler:!1})}get style(){const{left:e,top:t}=this.props.position;return`top:${t}px;left:${e}px`}get styleHandler(){let e=this.state.handler?this.state.position:{left:0,top:0};return`top:${e.top}px;left:${e.left}px;`}get styleNextvalue(){let e=this.state.handler?this.state.position:{left:0,top:0};return`top:${e.top+5}px;left:${e.left+15}px;`}getTooltip(){const e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=kr),e}onMouseDown(e){this.state.handler=!0,this.state.position={left:0,top:0};const{scrollY:t,scrollX:i}=this.env.model.getters.getActiveSheetScrollInfo(),n=e.clientX+i,o=e.clientY+t;let s,r;_r((e=>{const t=Pn(),{scrollY:i,scrollX:a}=this.env.model.getters.getActiveSheetScrollInfo();this.state.position={left:e.clientX-n+a,top:e.clientY-o+i};const l=this.env.model.getters.getColIndex(e.clientX-t.left),c=this.env.model.getters.getRowIndex(e.clientY-t.top);if(s!==l||r!==c){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getNumberCols(e),i=this.env.model.getters.getNumberRows(e);s=-1===l?s:Me(l,0,t),r=-1===c?r:Me(c,0,i),void 0!==s&&void 0!==r&&this.env.model.dispatch("AUTOFILL_SELECT",{col:s,row:r})}}),(()=>{this.state.handler=!1,this.env.model.dispatch("AUTOFILL")}))}onDblClick(){this.env.model.dispatch("AUTOFILL_AUTO")}}Dr.template="o-spreadsheet-Autofill";class kr extends t.Component{}kr.template=t.xml`
972
972
  <div t-esc="props.content"/>
973
- `,wn`
973
+ `,xn`
974
974
  .o-client-tag {
975
975
  position: absolute;
976
976
  border-top-left-radius: 4px;
@@ -980,7 +980,7 @@
980
980
  opacity: 0;
981
981
  pointer-events: none;
982
982
  }
983
- `;class Dr extends t.Component{get tagStyle(){const{col:e,row:t,color:i}=this.props,{height:n}=this.env.model.getters.getSheetViewDimensionWithHeaders(),{x:o,y:s}=this.env.model.getters.getVisibleRect({left:e,top:t,right:e,bottom:t});return`bottom: ${n-s+15}px;left: ${o-1}px;border: 1px solid ${i};background-color: ${i};${this.props.active?"opacity:1 !important":""}`}}Dr.template="o-spreadsheet-ClientTag";const kr=/(.*?)\((.*?)\)(.*)/,$r=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function Lr(e){let t=e.split("\n");const i=[];for(let e of t)e=e.trim(),e&&i.push(Pr(e));return i}function Pr(e){let t,i=e.match(kr),n=i[1].trim(),o=[],s=!1,r=!1,a=!1;for(let e of i[2].split(",")){const i=e.trim().toUpperCase();let n=$r.find((e=>i===e));n?o.push(n):"RANGE<ANY>"===i?o.push("RANGE"):"OPTIONAL"===i?s=!0:"REPEATING"===i?r=!0:"LAZY"===i?a=!0:i.startsWith("DEFAULT=")&&(t=e.trim().slice(8))}const l={name:n,description:i[3].trim(),type:o};return s&&(l.optional=!0),r&&(l.repeating=!0),a&&(l.lazy=!0),void 0!==t&&(l.default=!0,l.defaultValue=t),l}function Ur(e){let t=0,i=0,n=0;for(let o of e.args)t++,o.optional||o.repeating||o.default||i++,o.repeating&&n++;const o=e;return o.minArgRequired=i,o.maxArgPossible=n?1/0:t,o.nbrArgRepeating=n,o.getArgToFocus=function(e,t){if(!t)return e=>e;if(1===t)return t=>Math.min(t,e);const i=e-t;return e=>{if(e<=i)return e;return i+((e-i)%t||t)}}(t,n),o}const Vr=["number","string","boolean","undefined"];function zr(e,t){if(!e())throw new Error(t)}const Br=e=>s("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function Hr(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(Ci(e)||""===e)return wi(e);const t=ve(e);if(t)return t.value;throw new Error(Br(e));default:return 0}}function Wr(e){if(""===e)throw new Error(Br(e));return Hr(e)}function Gr(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}const qr=function(e){const t=new Map,i=e.name?e.name+" (memoized)":"memoized";return{[i]:(...i)=>(t.has(i[0])||t.set(i[0],e(...i)),t.get(i[0]))}[i]}((function(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"")}));function Zr(e){return"string"==typeof e?qr(e):e}const jr=e=>s("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function Yr(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(jr(e))}return!1;case"number":return!!e;default:return!1}}function Xr(e){return Se(Hr(e))}function Kr(e,t,i){for(let n of e)if(Array.isArray(n)){const e=n.length,i=n[0].length;for(let o=0;o<i;o++)for(let i=0;i<e;i++)t(n[i][o])}else i(n)}function Qr(e,t){Kr(e,t,t)}function Jr(e,t){Kr(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(Wr(e))}))}function ea(e,t,i,n){let o=n;for(let n of e)if(Array.isArray(n)){const e=n.length,i=n[0].length;for(let s=0;s<i;s++)for(let i=0;i<e;i++)o=t(o,n[i][s])}else o=i(o,n);return o}function ta(e,t,i){return ea(e,t,t,i)}function ia(e,t,i){return ea(e,((e,i)=>"number"==typeof i?t(e,i):e),((e,i)=>t(e,Wr(i))),i)}function na(e,t,i){return ea(e,((e,i)=>null!=i?t(e,"number"==typeof i?i:"boolean"==typeof i?Hr(i):0):e),((e,i)=>t(e,Hr(i))),i)}function oa(e,t){return function(e,t,i){for(let n of e)if(Array.isArray(n)){const e=n.length,i=n[0].length;for(let o=0;o<i;o++)for(let i=0;i<e;i++)if(!t(n[i][o]))return}else if(!i(n))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error(jr(e));return Yr(e)}(e))))}function sa(e,t){let i,n,o=e.substring(0,2);"<="===o||">="===o||"<>"===o?(i=o,n=e.substring(2)):(o=e.substring(0,1),"<"===o||">"===o||"="===o?(i=o,n=e.substring(1)):(i="=",n=e)),Ci(n)||Ve(n)?n=Hr(n):"TRUE"!==n&&"FALSE"!==n||(n=Yr(n));const s={operator:i,operand:n};return"string"==typeof n&&(t&&(n+="*"),s.regexp=function(e){if("*"===e)return/.+/;let t="",i="";for(let n of e)"?"===n&&"~"!==i?t+=".":"*"===n&&"~"!==i?t+=".*":("*"!==n&&"?"!==n||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(n)&&(t+="\\"),t+=n),i=n;return new RegExp("^"+t+"$","i")}(n)),s}function ra(e="",t){const{operator:i,operand:n}=t;if(void 0===n)return!1;if("number"==typeof n&&"="===i)return"string"==typeof e&&(Ci(e)||Ve(e))?Hr(e)===n:e===n;if("<>"===i||"="===i){let o;return o=typeof e==typeof n&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===n),"="===i?o:!o}if(typeof e==typeof n)switch(i){case"<":return e<n;case">":return e>n;case"<=":return e<=n;case">=":return e>=n}return!1}function aa(e,t,i=!1){const n=e.length;if(n%2==1)throw new Error(s("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const o=e[0].length,r=e[0][0].length;let a=[];for(let t=0;t<n-1;t+=2){const n=e[t];if(!Array.isArray(n)||n.length!==o||n[0].length!==r)throw new Error(s("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=Gr(e[t+1]);a.push(sa(l,i))}for(let i=0;i<o;i++)for(let o=0;o<r;o++){let s=!0;for(let t=0;t<n-1;t+=2){if(s=ra(e[t][i][o],a[t/2]),!s)break}s&&t(i,o)}}function la(e,t){return Zr(e[0][t])}function ca(e,t){return Zr(e[t][0])}function ha(e,t,i,n,o,s){if(null==t)return-1;const r=typeof t;let a,l,c,h,d,u,g=0,p=o-1;const m="desc"===n?t=>s(e,o-t-1):t=>s(e,t);for(;p-g>=0;){for(c=Math.floor((g+p)/2),h=c,d=m(h),u=typeof d;g<h&&r!==u;)h--,d=m(h),u=typeof d;u===r&&void 0!==d?("strict"===i&&d===t?(a=d,l=h):"nextSmaller"===i&&d<=t?(void 0===a||a<d||a===d&&l<h)&&(a=d,l=h):"nextGreater"===i&&d>=t&&(void 0===a||a>d||a===d&&l<h)&&(a=d,l=h),d>t||"strict"===i&&d===t?p=h-1:g=c+1):g=c+1}return void 0===l?-1:"desc"===n?o-l-1:l}function da(e,t,i,n,o,s=!1){if(null==t)return-1;const r=s?(e,t)=>o(e,n-t-1):o;let a,l=-1;for(let o=0;o<n;o++){const c=r(e,o);if(c===t)return s?n-o-1:o;"nextSmaller"===i?(!a&&ua(t,c)>=0||ua(t,c)>=0&&ua(c,a)>0)&&(a=c,l=o):"nextGreater"===i&&(!a&&ua(t,c)<=0||ua(t,c)<=0&&ua(c,a)<0)&&(a=c,l=o)}return s?n-l-1:l}function ua(e,t){let i=Vr.indexOf(typeof e)-Vr.indexOf(typeof t);return 0===i&&("string"==typeof e&&"string"==typeof t?i=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?i=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(i=Number(e)-Number(t))),i}const ga={description:s("Apply a large number format"),args:Lr(`\n value (number) ${s("The number.")}\n unit (string, optional) ${s("The formatting unit. Use 'k', 'm', or 'b' to force the unit")}\n `),returns:["NUMBER"],computeFormat:(e,t)=>{const i=Math.abs(Hr(e.value)),n=e.format;if(void 0!==t){switch(null==t?void 0:t.value){case"k":return li(n,1e3,"k");case"m":return li(n,1e6,"m");case"b":return li(n,1e9,"b");default:throw new Error(s("The formatting unit should be 'k', 'm' or 'b'."))}}return i<1e5?li(n,0,""):i<1e8?li(n,1e3,"k"):i<1e11?li(n,1e6,"m"):li(n,1e9,"b")},compute:function(e){return Hr(e)}};var pa=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:ga});const ma={description:s("Absolute value of a number."),args:Lr(`\n value (number) ${s("The number of which to return the absolute value.")}\n `),returns:["NUMBER"],compute:function(e){return Math.abs(Hr(e))},isExported:!0},fa={description:s("Inverse cosine of a value, in radians."),args:Lr(`\n value (number) ${s("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=Hr(e);return zr((()=>Math.abs(t)<=1),s("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},va={description:s("Inverse hyperbolic cosine of a number."),args:Lr(`\n value (number) ${s("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.")}\n `),returns:["NUMBER"],compute:function(e){const t=Hr(e);return zr((()=>t>=1),s("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},ba={description:s("Inverse cotangent of a value."),args:Lr(`\n value (number) ${s("The value for which to calculate the inverse cotangent.")}\n `),returns:["NUMBER"],compute:function(e){const t=Hr(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Sa={description:s("Inverse hyperbolic cotangent of a value."),args:Lr(`\n value (number) ${s("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=Hr(e);return zr((()=>Math.abs(t)>1),s("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},Ca={description:s("Inverse sine of a value, in radians."),args:Lr(`\n value (number) ${s("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=Hr(e);return zr((()=>Math.abs(t)<=1),s("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},Ea={description:s("Inverse hyperbolic sine of a number."),args:Lr(`\n value (number) ${s("The value for which to calculate the inverse hyperbolic sine.")}\n `),returns:["NUMBER"],compute:function(e){return Math.asinh(Hr(e))},isExported:!0},wa={description:s("Inverse tangent of a value, in radians."),args:Lr(`\n value (number) ${s("The value for which to calculate the inverse tangent.")}\n `),returns:["NUMBER"],compute:function(e){return Math.atan(Hr(e))},isExported:!0},ya={description:s("Angle from the X axis to a point (x,y), in radians."),args:Lr(`\n x (number) ${s("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")}\n y (number) ${s("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")}\n `),returns:["NUMBER"],compute:function(e,t){const i=Hr(e),n=Hr(t);return zr((()=>0!==i||0!==n),s("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(n,i)},isExported:!0},xa={description:s("Inverse hyperbolic tangent of a number."),args:Lr(`\n value (number) ${s("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=Hr(e);return zr((()=>Math.abs(t)<1),s("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},Ra={description:s("Rounds number up to nearest multiple of factor."),args:Lr(`\n value (number) ${s("The value to round up to the nearest integer multiple of factor.")}\n factor (number, default=1) ${s("The number to whose multiples value will be rounded.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){const i=Hr(e),n=Hr(t);return zr((()=>n>=0||i<=0),s("The factor (%s) must be positive when the value (%s) is positive.",n.toString(),i.toString())),n?Math.ceil(i/n)*n:0},isExported:!0},Ia={description:s("Rounds number up to nearest multiple of factor."),args:Lr(`\n number (number) ${s("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${s("The number to whose multiples number will be rounded. The sign of significance will be ignored.")}\n mode (number, default=0) ${s("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1,i=0){let n=Hr(t);if(0===n)return 0;const o=Hr(e);if(n=Math.abs(n),o>=0)return Math.ceil(o/n)*n;return 0===Hr(i)?-Math.floor(Math.abs(o)/n)*n:-Math.ceil(Math.abs(o)/n)*n},isExported:!0},Ta={description:s("Rounds number up to nearest multiple of factor."),args:Lr(`\n number (number) ${s("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${s("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){return Ia.compute(e,t,0)},isExported:!0},Aa={description:s("Cosine of an angle provided in radians."),args:Lr(`\n angle (number) ${s("The angle to find the cosine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cos(Hr(e))},isExported:!0},Oa={description:s("Hyperbolic cosine of any real number."),args:Lr(`\n value (number) ${s("Any real value to calculate the hyperbolic cosine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cosh(Hr(e))},isExported:!0},Na={description:s("Cotangent of an angle provided in radians."),args:Lr(`\n angle (number) ${s("The angle to find the cotangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=Hr(e);return zr((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},Ma={description:s("Hyperbolic cotangent of any real number."),args:Lr(`\n value (number) ${s("Any real value to calculate the hyperbolic cotangent of.")}\n `),returns:["NUMBER"],compute:function(e){const t=Hr(e);return zr((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},_a={description:s("Number of empty values."),args:Lr(`\n value1 (any, range) ${s("The first value or range in which to count the number of blanks.")}\n value2 (any, range, repeating) ${s("Additional values or ranges in which to count the number of blanks.")}\n `),returns:["NUMBER"],compute:function(...e){return ta(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},Fa={description:s("A conditional count across a range."),args:Lr(`\n range (range) ${s("The range that is tested against criterion.")}\n criterion (string) ${s("The pattern or test to apply to range.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;return aa(e,((e,i)=>{t+=1})),t},isExported:!0},Da={description:s("Count values depending on multiple criteria."),args:Lr(`\n criteria_range1 (range) ${s("The range to check against criterion1.")}\n criterion1 (string) ${s("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${s("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${s("Additional criteria to check.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;return aa(e,((e,i)=>{t+=1})),t},isExported:!0};function ka(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const $a={description:s("Counts number of unique values in a range."),args:Lr(`\n value1 (any, range) ${s("The first value or range to consider for uniqueness.")}\n value2 (any, range, repeating) ${s("Additional values or ranges to consider for uniqueness.")}\n `),returns:["NUMBER"],compute:function(...e){return ta(e,((e,t)=>ka(t)?e.add(t):e),new Set).size}},La={description:s("Counts number of unique values in a range, filtered by a set of criteria."),args:Lr(`\n range (range) ${s("The range of cells from which the number of unique values will be counted.")}\n criteria_range1 (range) ${s("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${s("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${s("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let i=new Set;return aa(t,((t,n)=>{const o=e[t][n];ka(o)&&i.add(o)})),i.size}},Pa={description:s("Cosecant of an angle provided in radians."),args:Lr(`\n angle (number) ${s("The angle to find the cosecant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=Hr(e);return zr((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},Ua={description:s("Hyperbolic cosecant of any real number."),args:Lr(`\n value (number) ${s("Any real value to calculate the hyperbolic cosecant of.")}\n `),returns:["NUMBER"],compute:function(e){const t=Hr(e);return zr((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},Va={description:s("Converts from another base to decimal."),args:Lr(`\n value (string) ${s("The number to convert.")},\n base (number) ${s("The base to convert the value from.")},\n `),returns:["NUMBER"],compute:function(e,t){let i=Hr(t);i=Math.floor(i),zr((()=>2<=i&&i<=36),s("The base (%s) must be between 2 and 36 inclusive.",i.toString()));const n=Gr(e);if(""===n)return 0;zr((()=>!!n.match(/^-?[a-z0-9]+$/i)),s("The value (%s) must be a valid base %s representation.",n,i.toString()));const o=parseInt(n,i);return zr((()=>!isNaN(o)),s("The value (%s) must be a valid base %s representation.",n,i.toString())),o},isExported:!0},za={description:s("Converts an angle value in radians to degrees."),args:Lr(`\n angle (number) ${s("The angle to convert from radians to degrees.")}\n `),returns:["NUMBER"],compute:function(e){return 180*Hr(e)/Math.PI},isExported:!0},Ba={description:s("Euler's number, e (~2.718) raised to a power."),args:Lr(`\n value (number) ${s("The exponent to raise e.")}\n `),returns:["NUMBER"],compute:function(e){return Math.exp(Hr(e))},isExported:!0},Ha={description:s("Rounds number down to nearest multiple of factor."),args:Lr(`\n value (number) ${s("The value to round down to the nearest integer multiple of factor.")}\n factor (number, default=1) ${s("The number to whose multiples value will be rounded.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){const i=Hr(e),n=Hr(t);return zr((()=>n>=0||i<=0),s("The factor (%s) must be positive when the value (%s) is positive.",n.toString(),i.toString())),n?Math.floor(i/n)*n:0},isExported:!0},Wa={description:s("Rounds number down to nearest multiple of factor."),args:Lr(`\n number (number) ${s("The value to round down to the nearest integer multiple of significance.")}\n significance (number, default=1) ${s("The number to whose multiples number will be rounded. The sign of significance will be ignored.")}\n mode (number, default=0) ${s("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1,i=0){let n=Hr(t);if(0===n)return 0;const o=Hr(e);if(n=Math.abs(n),o>=0)return Math.floor(o/n)*n;return 0===Hr(i)?-Math.ceil(Math.abs(o)/n)*n:-Math.floor(Math.abs(o)/n)*n},isExported:!0},Ga={description:s("Rounds number down to nearest multiple of factor."),args:Lr(`\n number (number) ${s("The value to round down to the nearest integer multiple of significance.")}\n significance (number, default=1) ${s("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){return Wa.compute(e,t,0)},isExported:!0},qa={description:s("Whether the provided value is even."),args:Lr(`\n value (number) ${s("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=Wr(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},Za={description:s("Rounds number up to nearest multiple of factor."),args:Lr(`\n number (number) ${s("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${s("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){return Ia.compute(e,t,0)},isExported:!0},ja={description:s("Whether the provided value is even."),args:Lr(`\n value (number) ${s("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=Wr(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},Ya={description:s("The logarithm of a number, base e (euler's number)."),args:Lr(`\n value (number) ${s("The value for which to calculate the logarithm, base e.")}\n `),returns:["NUMBER"],compute:function(e){const t=Hr(e);return zr((()=>t>0),s("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},Xa={description:s("The logarithm of a number, for a given base."),args:Lr(`\n value (number) ${s("The value for which to calculate the logarithm, base e.")}\n base (number, default=10) ${s("The base of the logarithm.")}\n `),returns:["NUMBER"],compute:function(e,t=10){const i=Hr(e),n=Hr(t);return zr((()=>i>0),s("The value (%s) must be strictly positive.",i.toString())),zr((()=>n>0),s("The base (%s) must be strictly positive.",n.toString())),zr((()=>1!==n),s("The base must be different from 1.")),Math.log10(i)/Math.log10(n)},isExported:!0},Ka={description:s("Modulo (remainder) operator."),args:Lr(`\n dividend (number) ${s("The number to be divided to find the remainder.")}\n divisor (number) ${s("The number to divide by.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){const i=Hr(t);zr((()=>0!==i),s("The divisor must be different from 0."));const n=Hr(e)%i;return n>0&&i<0||n<0&&i>0?n+i:n},isExported:!0},Qa={description:s("Rounds a number up to the nearest odd integer."),args:Lr(`\n value (number) ${s("The value to round to the next greatest odd number.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){const t=Hr(e);let i=Math.ceil(Math.abs(t));return i=1&i?i:i+1,t<0?-i:i},isExported:!0},Ja={description:s("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},el={description:s("A number raised to a power."),args:Lr(`\n base (number) ${s("The number to raise to the exponent power.")}\n exponent (number) ${s("The exponent to raise base to.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){const i=Hr(e),n=Hr(t);return zr((()=>i>=0||Number.isInteger(n)),s("The exponent (%s) must be an integer when the base is negative.",n.toString())),Math.pow(i,n)},isExported:!0},tl={description:s("Result of multiplying a series of numbers together."),args:Lr(`\n factor1 (number, range<number>) ${s("The first number or range to calculate for the product.")}\n factor2 (number, range<number>, repeating) ${s("More numbers or ranges to calculate for the product.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0,i=1;for(let n of e)if(Array.isArray(n))for(let e of n)for(let n of e)"number"==typeof n&&(i*=n,t+=1);else null!=n&&(i*=Wr(n),t+=1);return 0===t?0:i},isExported:!0},il={description:s("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},nl={description:s("Random integer between two values, inclusive."),args:Lr(`\n low (number) ${s("The low end of the random range.")}\n high (number) ${s("The high end of the random range.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){let i=Hr(e);Number.isInteger(i)||(i=Math.ceil(i));let n=Hr(t);return Number.isInteger(n)||(n=Math.floor(n)),zr((()=>i<=n),s("The high (%s) must be greater than or equal to the low (%s).",n.toString(),i.toString())),i+Math.ceil((n-i+1)*Math.random())-1},isExported:!0},ol={description:s("Rounds a number according to standard rules."),args:Lr(`\n value (number) ${s("The value to round to places number of places.")}\n places (number, default=0) ${s("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Hr(e);let n=Hr(t);const o=Math.abs(i);let s;return 0===n?s=Math.round(o):(Number.isInteger(n)||(n=Math.trunc(n)),s=Math.round(o*Math.pow(10,n))/Math.pow(10,n)),i>=0?s:-s},isExported:!0},sl={description:s("Rounds down a number."),args:Lr(`\n value (number) ${s("The value to round to places number of places, always rounding down.")}\n places (number, default=0) ${s("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Hr(e);let n=Hr(t);const o=Math.abs(i);let s;return 0===n?s=Math.floor(o):(Number.isInteger(n)||(n=Math.trunc(n)),s=Math.floor(o*Math.pow(10,n))/Math.pow(10,n)),i>=0?s:-s},isExported:!0},rl={description:s("Rounds up a number."),args:Lr(`\n value (number) ${s("The value to round to places number of places, always rounding up.")}\n places (number, default=0) ${s("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Hr(e);let n=Hr(t);const o=Math.abs(i);let s;return 0===n?s=Math.ceil(o):(Number.isInteger(n)||(n=Math.trunc(n)),s=Math.ceil(o*Math.pow(10,n))/Math.pow(10,n)),i>=0?s:-s},isExported:!0},al={description:s("Secant of an angle provided in radians."),args:Lr(`\n angle (number) ${s("The angle to find the secant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cos(Hr(e))},isExported:!0},ll={description:s("Hyperbolic secant of any real number."),args:Lr(`\n value (number) ${s("Any real value to calculate the hyperbolic secant of.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cosh(Hr(e))},isExported:!0},cl={description:s("Sine of an angle provided in radians."),args:Lr(`\n angle (number) ${s("The angle to find the sine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sin(Hr(e))},isExported:!0},hl={description:s("Hyperbolic sine of any real number."),args:Lr(`\n value (number) ${s("Any real value to calculate the hyperbolic sine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sinh(Hr(e))},isExported:!0},dl={description:s("Positive square root of a positive number."),args:Lr(`\n value (number) ${s("The number for which to calculate the positive square root.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){const t=Hr(e);return zr((()=>t>=0),s("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},ul={description:s("Sum of a series of numbers and/or cells."),args:Lr(`\n value1 (number, range<number>) ${s("The first number or range to add together.")}\n value2 (number, range<number>, repeating) ${s("Additional numbers or ranges to add to value1.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){return ia(e,((e,t)=>e+t),0)},isExported:!0},gl={description:s("A conditional sum across a range."),args:Lr(`\n criteria_range (range) ${s("The range which is tested against criterion.")}\n criterion (string) ${s("The pattern or test to apply to range.")}\n sum_range (range, default=criteria_range) ${s("The range to be summed, if different from range.")}\n `),returns:["NUMBER"],compute:function(e,t,i){void 0===i&&(i=e);let n=0;return aa([e,t],((e,t)=>{const o=i[e][t];"number"==typeof o&&(n+=o)})),n},isExported:!0},pl={description:s("Sums a range depending on multiple criteria."),args:Lr(`\n sum_range (range) ${s("The range to sum.")}\n criteria_range1 (range) ${s("The range to check against criterion1.")}\n criterion1 (string) ${s("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${s("Additional ranges to check.")}\n criterion2 (string, repeating) ${s("Additional criteria to check.")}\n `),returns:["NUMBER"],compute:function(e,...t){let i=0;return aa(t,((t,n)=>{const o=e[t][n];"number"==typeof o&&(i+=o)})),i},isExported:!0},ml={description:s("Tangent of an angle provided in radians."),args:Lr(`\n angle (number) ${s("The angle to find the tangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tan(Hr(e))},isExported:!0},fl={description:s("Hyperbolic tangent of any real number."),args:Lr(`\n value (number) ${s("Any real value to calculate the hyperbolic tangent of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tanh(Hr(e))},isExported:!0},vl={description:s("Truncates a number."),args:Lr(`\n value (number) ${s("The value to be truncated.")}\n places (number, default=0) ${s("The number of significant digits to the right of the decimal point to retain.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Hr(e);let n=Hr(t);return 0===n?Math.trunc(i):(Number.isInteger(n)||(n=Math.trunc(n)),Math.trunc(i*Math.pow(10,n))/Math.pow(10,n))},isExported:!0};var bl=Object.freeze({__proto__:null,ABS:ma,ACOS:fa,ACOSH:va,ACOT:ba,ACOTH:Sa,ASIN:Ca,ASINH:Ea,ATAN:wa,ATAN2:ya,ATANH:xa,CEILING:Ra,CEILING_MATH:Ia,CEILING_PRECISE:Ta,COS:Aa,COSH:Oa,COT:Na,COTH:Ma,COUNTBLANK:_a,COUNTIF:Fa,COUNTIFS:Da,COUNTUNIQUE:$a,COUNTUNIQUEIFS:La,CSC:Pa,CSCH:Ua,DECIMAL:Va,DEGREES:za,EXP:Ba,FLOOR:Ha,FLOOR_MATH:Wa,FLOOR_PRECISE:Ga,ISEVEN:qa,ISO_CEILING:Za,ISODD:ja,LN:Ya,LOG:Xa,MOD:Ka,ODD:Qa,PI:Ja,POWER:el,PRODUCT:tl,RAND:il,RANDBETWEEN:nl,ROUND:ol,ROUNDDOWN:sl,ROUNDUP:rl,SEC:al,SECH:ll,SIN:cl,SINH:hl,SQRT:dl,SUM:ul,SUMIF:gl,SUMIFS:pl,TAN:ml,TANH:fl,TRUNC:vl});function Sl(e,t,i){let n=[],o=[],r=0,a=0;Qr([e],(e=>{n.push(e),r+=1})),Qr([t],(e=>{o.push(e),a+=1})),zr((()=>r===a),s("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",r.toString(),a.toString()));let l=0,c=0,h=0;for(let e=0;e<r;e++){const t=n[e],i=o[e];"number"==typeof t&&"number"==typeof i&&(l+=1,c+=t,h+=i)}zr((()=>0!==l&&(!i||1!==l)),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const d=c/l,u=h/l;let g=0;for(let e=0;e<r;e++){const t=n[e],i=o[e];"number"==typeof t&&"number"==typeof i&&(g+=(t-d)*(i-u))}return g/(l-(i?1:0))}function Cl(e,t,i){let n=0,o=0;const r=i?na:ia;o=r(e,((e,t)=>(n+=1,e+t)),0),zr((()=>0!==n&&(!t||1!==n)),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const a=o/n;return r(e,((e,t)=>e+Math.pow(t-a,2)),0)/(n-(t?1:0))}function El(e,t,i){const n=Hr(t);zr((()=>i?0<=n&&n<=1:0<n&&n<1),s("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let o,r=[],a=0;return Qr(e,(e=>{"number"==typeof e&&(o=ha(r,e,"nextSmaller","asc",r.length,((e,t)=>e[t])),r.splice(o+1,0,e),a++)})),zr((()=>0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),i||zr((()=>1/(a+1)<=n&&n<=a/(a+1)),s("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),yi(r,n,i)}const wl={description:s("Average magnitude of deviations from mean."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;const i=ia(e,((e,i)=>(t+=1,e+i)),0);zr((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const n=i/t;return ia(e,((e,t)=>e+Math.abs(n-t)),0)/t},isExported:!0},yl={description:s("Numerical average value in a dataset, ignoring text."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range to consider when calculating the average value.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to consider when calculating the average value.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0;const i=ia(e,((e,i)=>(t+=1,e+i)),0);return zr((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/t},isExported:!0},xl=s("[[FUNCTION_NAME]] has mismatched range sizes."),Rl=s("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),Il={description:s("Weighted average."),args:Lr(`\n values (number, range<number>) ${s("Values to average.")}\n weights (number, range<number>) ${s("Weights for each corresponding value.")}\n additional_values (number, range<number>, repeating) ${s("Additional values to average.")}\n additional_weights (number, range<number>, repeating) ${s("Additional weights.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t,i,n=0,o=0;zr((()=>e.length%2==0),s("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let r=0;r<e.length-1;r+=2)if(t=e[r],i=e[r+1],Array.isArray(t)){zr((()=>Array.isArray(i)),xl);let e=t.length,r=t[0].length;zr((()=>e===i.length&&r===i[0].length),xl);for(let a=0;a<e;a++)for(let e=0;e<r;e++){let r=t[a][e],l=i[a][e],c="number"==typeof r,h="number"==typeof l;zr((()=>c===h),s("[[FUNCTION_NAME]] expects number values.")),h&&(zr((()=>l>=0),Rl),n+=r*l,o+=l)}}else i=Hr(i),t=Hr(t),zr((()=>i>=0),Rl),n+=t*i,o+=i;return zr((()=>0!==o),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),n/o}},Tl={description:s("Numerical average value in a dataset."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range to consider when calculating the average value.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to consider when calculating the average value.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0;const i=na(e,((e,i)=>(t+=1,e+i)),0);return zr((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/t},isExported:!0},Al={description:s("Average of values depending on criteria."),args:Lr(`\n criteria_range (range) ${s("The range to check against criterion.")}\n criterion (string) ${s("The pattern or test to apply to criteria_range.")}\n average_range (range, default=criteria_range) ${s("The range to average. If not included, criteria_range is used for the average instead.")}\n `),returns:["NUMBER"],compute:function(e,t,i){null==i&&(i=e);let n=0,o=0;return aa([e,t],((t,s)=>{const r=(i||e)[t][s];"number"==typeof r&&(n+=1,o+=r)})),zr((()=>0!==n),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/n},isExported:!0},Ol={description:s("Average of values depending on multiple criteria."),args:Lr(`\n average_range (range) ${s("The range to average.")}\n criteria_range1 (range) ${s("The range to check against criterion1.")}\n criterion1 (string) ${s("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${s("Additional criteria_range and criterion to check.")}\n criterion2 (string, repeating) ${s("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let i=0,n=0;return aa(t,((t,o)=>{const s=e[t][o];"number"==typeof s&&(i+=1,n+=s)})),zr((()=>0!==i),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),n/i},isExported:!0},Nl={description:s("The number of numeric values in dataset."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range to consider when counting.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to consider when counting.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;for(let i of e)if(Array.isArray(i))for(let e of i)for(let i of e)"number"==typeof i&&(t+=1);else("string"!=typeof i||Ci(i)||ve(i))&&(t+=1);return t},isExported:!0},Ml={description:s("The number of values in a dataset."),args:Lr(`\n value1 (any, range) ${s("The first value or range to consider when counting.")}\n value2 (any, range, repeating) ${s("Additional values or ranges to consider when counting.")}\n `),returns:["NUMBER"],compute:function(...e){return ta(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},_l={description:s("The covariance of a dataset."),args:Lr(`\n data_y (any, range) ${s("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${s("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return Sl(e,t,!1)},isExported:!0},Fl={description:s("The covariance of a dataset."),args:Lr(`\n data_y (any, range) ${s("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${s("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return Sl(e,t,!1)},isExported:!0},Dl={description:s("The sample covariance of a dataset."),args:Lr(`\n data_y (any, range) ${s("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${s("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return Sl(e,t,!0)},isExported:!0},kl={description:s("Nth largest element from a data set."),args:Lr(`\n data (any, range) ${s("Array or range containing the dataset to consider.")}\n n (number) ${s("The rank from largest to smallest of the element to return.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){const i=Math.trunc(Hr(t));let n,o=[],r=0;Qr([e],(e=>{"number"==typeof e&&(n=ha(o,e,"nextSmaller","asc",o.length,((e,t)=>e[t])),o.splice(n+1,0,e),r++,r>i&&(o.shift(),r--))}));const a=o.shift();return zr((()=>void 0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),zr((()=>r>=i),s("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",i.toString())),a},isExported:!0},$l={description:s("Maximum value in a numeric dataset."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range to consider when calculating the maximum value.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to consider when calculating the maximum value.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=ia(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},Ll={description:s("Maximum numeric value in a dataset."),args:Lr(`\n value1 (any, range) ${s("The first value or range to consider when calculating the maximum value.")}\n value2 (any, range, repeating) ${s("Additional values or ranges to consider when calculating the maximum value.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=na(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},Pl={description:s("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:Lr(`\n range (range) ${s("The range of cells from which the maximum will be determined.")}\n criteria_range1 (range) ${s("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${s("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${s("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let i=-1/0;return aa(t,((t,n)=>{const o=e[t][n];"number"==typeof o&&(i=i<o?o:i)})),i===-1/0?0:i},isExported:!0},Ul={description:s("Median value in a numeric dataset."),args:Lr(`\n value1 (any, range) ${s("The first value or range to consider when calculating the median value.")}\n value2 (any, range, repeating) ${s("Additional values or ranges to consider when calculating the median value.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=[];return Jr(e,(e=>{t.push(e)})),El(t,.5,!0)},isExported:!0},Vl={description:s("Minimum value in a numeric dataset."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range to consider when calculating the minimum value.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to consider when calculating the minimum value.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=ia(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},zl={description:s("Minimum numeric value in a dataset."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range to consider when calculating the minimum value.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to consider when calculating the minimum value.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=na(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},Bl={description:s("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:Lr(`\n range (range) ${s("The range of cells from which the minimum will be determined.")}\n criteria_range1 (range) ${s("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${s("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${s("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let i=1/0;return aa(t,((t,n)=>{const o=e[t][n];"number"==typeof o&&(i=i>o?o:i)})),i===1/0?0:i},isExported:!0},Hl={description:s("Value at a given percentile of a dataset."),args:Lr(`\n data (any, range) ${s("The array or range containing the dataset to consider.")}\n percentile (number) ${s("The percentile whose value within data will be calculated and returned.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return Gl.compute(e,t)},isExported:!0},Wl={description:s("Value at a given percentile of a dataset exclusive of 0 and 1."),args:Lr(`\n data (any, range) ${s("The array or range containing the dataset to consider.")}\n percentile (number) ${s("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return El([e],t,!1)},isExported:!0},Gl={description:s("Value at a given percentile of a dataset."),args:Lr(`\n data (any, range) ${s("The array or range containing the dataset to consider.")}\n percentile (number) ${s("The percentile whose value within data will be calculated and returned.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return El([e],t,!0)},isExported:!0},ql={description:s("Value nearest to a specific quartile of a dataset."),args:Lr(`\n data (any, range) ${s("The array or range containing the dataset to consider.")}\n quartile_number (number) ${s("Which quartile value to return.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return jl.compute(e,t)},isExported:!0},Zl={description:s("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:Lr(`\n data (any, range) ${s("The array or range containing the dataset to consider.")}\n quartile_number (number) ${s("Which quartile value, exclusive of 0 and 4, to return.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return El([e],.25*Math.trunc(Hr(t)),!1)},isExported:!0},jl={description:s("Value nearest to a specific quartile of a dataset."),args:Lr(`\n data (any, range) ${s("The array or range containing the dataset to consider.")}\n quartile_number (number) ${s("Which quartile value to return.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return El([e],.25*Math.trunc(Hr(t)),!0)},isExported:!0},Yl={description:s("Nth smallest element in a data set."),args:Lr(`\n data (any, range) ${s("The array or range containing the dataset to consider.")}\n n (number) ${s("The rank from smallest to largest of the element to return.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){const i=Math.trunc(Hr(t));let n,o=[],r=0;Qr([e],(e=>{"number"==typeof e&&(n=ha(o,e,"nextSmaller","asc",o.length,((e,t)=>e[t])),o.splice(n+1,0,e),r++,r>i&&(o.pop(),r--))}));const a=o.pop();return zr((()=>void 0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),zr((()=>r>=i),s("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",i.toString())),a},isExported:!0},Xl={description:s("Standard deviation."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(ic.compute(...e))},isExported:!0},Kl={description:s("Standard deviation of entire population."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(nc.compute(...e))},isExported:!0},Ql={description:s("Standard deviation."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(oc.compute(...e))},isExported:!0},Jl={description:s("Standard deviation of sample (text as 0)."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(sc.compute(...e))},isExported:!0},ec={description:s("Standard deviation of entire population."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(rc.compute(...e))},isExported:!0},tc={description:s("Standard deviation of entire population (text as 0)."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(ac.compute(...e))},isExported:!0},ic={description:s("Variance."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Cl(e,!0,!1)},isExported:!0},nc={description:s("Variance of entire population."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Cl(e,!1,!1)},isExported:!0},oc={description:s("Variance."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Cl(e,!0,!1)},isExported:!0},sc={description:s("Variance of sample (text as 0)."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Cl(e,!0,!0)},isExported:!0},rc={description:s("Variance of entire population."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Cl(e,!1,!1)},isExported:!0},ac={description:s("Variance of entire population (text as 0)."),args:Lr(`\n value1 (number, range<number>) ${s("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Cl(e,!1,!0)},isExported:!0};var lc=Object.freeze({__proto__:null,AVEDEV:wl,AVERAGE:yl,AVERAGE_WEIGHTED:Il,AVERAGEA:Tl,AVERAGEIF:Al,AVERAGEIFS:Ol,COUNT:Nl,COUNTA:Ml,COVAR:_l,COVARIANCE_P:Fl,COVARIANCE_S:Dl,LARGE:kl,MAX:$l,MAXA:Ll,MAXIFS:Pl,MEDIAN:Ul,MIN:Vl,MINA:zl,MINIFS:Bl,PERCENTILE:Hl,PERCENTILE_EXC:Wl,PERCENTILE_INC:Gl,QUARTILE:ql,QUARTILE_EXC:Zl,QUARTILE_INC:jl,SMALL:Yl,STDEV:Xl,STDEV_P:Kl,STDEV_S:Ql,STDEVA:Jl,STDEVP:ec,STDEVPA:tc,VAR:ic,VAR_P:nc,VAR_S:oc,VARA:sc,VARP:rc,VARPA:ac});function cc(e,t,i){var n;const o=new Map,r=e.length;for(let t=r-1;t>=0;t--)o.set(Gr(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(s("The field must be a number or a string"));let a;if("number"==typeof t){if(a=Math.trunc(t)-1,a<0||r-1<a)throw new Error(s("The field (%s) must be one of %s or must be a number between 1 and %s inclusive.",t.toString(),r.toString()))}else{const e=Gr(t).toUpperCase();if(a=null!==(n=o.get(e))&&void 0!==n?n:-1,-1===a)throw new Error(s("The field (%s) must be one of %s.",Gr(t),[...o.keys()].toString()))}const l=i[0].length;if(l<2)throw new Error(s("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const h=e[0].length;for(let t=1;t<l;t++){let n=[],s=!0;for(let r=0;r<i.length;r++){const a=Gr(i[r][0]).toUpperCase(),l=o.get(a),c=i[r][t];if(void 0!==c){if(void 0===l){s=!1;break}n.push([e[l].slice(1,h)]),n.push(c)}}if(s){if(!(n.length>0)){c=new Set(Array(h-1).keys());break}aa(n,((e,t)=>{c.add(t)}),!0)}}const d=e[a];return[...c].map((e=>d[e+1]))}const hc=Lr(`\n database (range) ${s("The array or range containing the data to consider, structured in such a way that the first row contains the labels for each column's values.")}\n field (any) ${s("Indicates which column in database contains the values to be extracted and operated on.")}\n criteria (range) ${s("An array or range containing zero or more criteria to filter the database values by before operating.")}\n`),dc={description:s("Average of a set of values from a table-like range."),args:hc,returns:["NUMBER"],compute:function(e,t,i){const n=cc(e,t,i);return yl.compute([n])},isExported:!0},uc={description:s("Counts values from a table-like range."),args:hc,returns:["NUMBER"],compute:function(e,t,i){const n=cc(e,t,i);return Nl.compute([n])},isExported:!0},gc={description:s("Counts values and text from a table-like range."),args:hc,returns:["NUMBER"],compute:function(e,t,i){const n=cc(e,t,i);return Ml.compute([n])},isExported:!0},pc={description:s("Single value from a table-like range."),args:hc,returns:["NUMBER"],compute:function(e,t,i){const n=cc(e,t,i);return zr((()=>1===n.length),s("More than one match found in DGET evaluation.")),n[0]},isExported:!0},mc={description:s("Maximum of values from a table-like range."),args:hc,returns:["NUMBER"],compute:function(e,t,i){const n=cc(e,t,i);return $l.compute([n])},isExported:!0},fc={description:s("Minimum of values from a table-like range."),args:hc,returns:["NUMBER"],compute:function(e,t,i){const n=cc(e,t,i);return Vl.compute([n])},isExported:!0},vc={description:s("Product of values from a table-like range."),args:hc,returns:["NUMBER"],compute:function(e,t,i){const n=cc(e,t,i);return tl.compute([n])},isExported:!0},bc={description:s("Standard deviation of population sample from table."),args:hc,returns:["NUMBER"],compute:function(e,t,i){const n=cc(e,t,i);return Xl.compute([n])},isExported:!0},Sc={description:s("Standard deviation of entire population from table."),args:hc,returns:["NUMBER"],compute:function(e,t,i){const n=cc(e,t,i);return ec.compute([n])},isExported:!0},Cc={description:s("Sum of values from a table-like range."),args:hc,returns:["NUMBER"],compute:function(e,t,i){const n=cc(e,t,i);return ul.compute([n])},isExported:!0},Ec={description:s("Variance of population sample from table-like range."),args:hc,returns:["NUMBER"],compute:function(e,t,i){const n=cc(e,t,i);return ic.compute([n])},isExported:!0},wc={description:s("Variance of a population from a table-like range."),args:hc,returns:["NUMBER"],compute:function(e,t,i){const n=cc(e,t,i);return rc.compute([n])},isExported:!0};var yc=Object.freeze({__proto__:null,DAVERAGE:dc,DCOUNT:uc,DCOUNTA:gc,DGET:pc,DMAX:mc,DMIN:fc,DPRODUCT:vc,DSTDEV:bc,DSTDEVP:Sc,DSUM:Cc,DVAR:Ec,DVARP:wc});const xc={description:s("Converts year/month/day into a date."),args:Lr(`\n year (number) ${s("The year component of the date.")}\n month (number) ${s("The month component of the date.")}\n day (number) ${s("The day component of the date.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i){let n=Math.trunc(Hr(e));const o=Math.trunc(Hr(t)),r=Math.trunc(Hr(i));zr((()=>0<=n&&n<=9999),s("The year (%s) must be between 0 and 9999 inclusive.",n.toString())),n<1900&&(n+=1900);const a=Ce(new ae(n,o-1,r));return zr((()=>a>=0),s("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),a},isExported:!0},Rc={description:s("Converts a date string to a date value."),args:Lr(`\n date_string (string) ${s("The string representing the date.")}\n `),returns:["NUMBER"],compute:function(e){const t=Gr(e),i=ve(t);return zr((()=>null!==i),s("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(i.value)},isExported:!0},Ic={description:s("Day of the month that a specific date falls on."),args:Lr(`\n date (string) ${s("The date from which to extract the day.")}\n `),returns:["NUMBER"],compute:function(e){return Xr(e).getDate()},isExported:!0},Tc={description:s("Number of days between two dates."),args:Lr(`\n end_date (date) ${s("The end of the date range.")}\n start_date (date) ${s("The start of the date range.")}\n `),returns:["NUMBER"],compute:function(e,t){const i=Xr(e),n=Xr(t),o=i.getTime()-n.getTime();return Math.round(o/ce)},isExported:!0},Ac={description:s("Number of days between two dates on a 360-day year (months of 30 days)."),args:Lr(`\n start_date (date) ${s("The start date to consider in the calculation.")}\n end_date (date) ${s("The end date to consider in the calculation.")}\n method (number, default=0) ${s("An indicator of what day count method to use. (0) US NASD method (1) European method")}\n `),returns:["NUMBER"],compute:function(e,t,i=0){const n=Hr(e),o=Hr(t),s=Yr(i)?4:0,r=jc.compute(e,t,s);return Math.sign(o-n)*Math.round(360*r)},isExported:!0},Oc={description:s("Date a number of months before/after another date."),args:Lr(`\n start_date (date) ${s("The date from which to calculate the result.")}\n months (number) ${s("The number of months before (negative) or after (positive) 'start_date' to calculate.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){return Ce(ye(Xr(e),Math.trunc(Hr(t)),!1))},isExported:!0},Nc={description:s("Last day of a month before or after a date."),args:Lr(`\n start_date (date) ${s("The date from which to calculate the result.")}\n months (number) ${s("The number of months before (negative) or after (positive) 'start_date' to consider.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){const i=Xr(e),n=Math.trunc(Hr(t)),o=i.getFullYear(),s=i.getMonth();return Ce(new ae(o,s+n+1,0))},isExported:!0},Mc={description:s("Hour component of a specific time."),args:Lr(`\n time (date) ${s("The time from which to calculate the hour component.")}\n `),returns:["NUMBER"],compute:function(e){return Xr(e).getHours()},isExported:!0},_c={description:s("ISO week number of the year."),args:Lr(`\n date (date) ${s("The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n `),returns:["NUMBER"],compute:function(e){const t=Xr(e),i=t.getFullYear();let n=1;for(;4!==new ae(i,0,n).getDay();)n+=1;const o=new ae(i,0,n-3);let s=31;for(;4!==new ae(i,11,s).getDay();)s-=1;const r=new ae(i,11,s+3);let a,l;switch(a=o.getTime()<=t.getTime()?t.getTime()<=r.getTime()?0:1:-1,a){case 0:l=o;break;case 1:l=new ae(i,11,s+3+1);break;case-1:let e=1;for(;4!==new ae(i-1,0,e).getDay();)e+=1;l=new ae(i-1,0,e-3)}const c=(t.getTime()-l.getTime())/ce;return Math.floor(c/7)+1},isExported:!0},Fc={description:s("Minute component of a specific time."),args:Lr(`\n time (date) ${s("The time from which to calculate the minute component.")}\n `),returns:["NUMBER"],compute:function(e){return Xr(e).getMinutes()},isExported:!0},Dc={description:s("Month of the year a specific date falls in"),args:Lr(`\n date (date) ${s("The date from which to extract the month.")}\n `),returns:["NUMBER"],compute:function(e){return Xr(e).getMonth()+1},isExported:!0},kc={description:s("Net working days between two provided days."),args:Lr(`\n start_date (date) ${s("The start date of the period from which to calculate the number of net working days.")}\n end_date (date) ${s("The end date of the period from which to calculate the number of net working days.")}\n holidays (date, range<date>, optional) ${s("A range or array constant containing the date serial numbers to consider holidays.")}\n `),returns:["NUMBER"],compute:function(e,t,i){return Lc.compute(e,t,1,i)},isExported:!0};function $c(e){if("string"==typeof e){zr((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),s('When weekend is a string (%s) it must be composed of "0" or "1".',e));let t=[];for(let i=0;i<7;i++)"1"===e[i]&&t.push((i+1)%7);return t}if("number"==typeof e)return zr((()=>1<=e&&e<=7||11<=e&&e<=17),s("The weekend (%s) must be a string or a number in the range 1-7 or 11-17.",e.toString())),e<=7?[e-2==-1?6:e-2,e-1]:[e-11];throw Error(s("The weekend must be a number or a string."))}const Lc={description:s("Net working days between two dates (specifying weekends)."),args:Lr(`\n start_date (date) ${s("The start date of the period from which to calculate the number of net working days.")}\n end_date (date) ${s("The end date of the period from which to calculate the number of net working days.")}\n weekend (any, default=1) ${s("A number or string representing which days of the week are considered weekends.")}\n holidays (date, range<date>, optional) ${s("A range or array constant containing the dates to consider as holidays.")}\n `),returns:["NUMBER"],compute:function(e,t,i=1,n){const o=Xr(e),s=Xr(t),r=$c(i);let a=new Set;void 0!==n&&Qr([n],(e=>{const t=Xr(e);a.add(t.getTime())}));const l=o.getTime()>s.getTime(),c=ae.fromTimestamp((l?o:s).getTime());let h=ae.fromTimestamp((l?s:o).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},Pc={description:s("Current date and time as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy hh:mm:ss",compute:function(){let e=ae.now();const t=e.getTime()-le.getTime(),i=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/ce)+i},isExported:!0},Uc={description:s("Minute component of a specific time."),args:Lr(`\n time (date) ${s("The time from which to calculate the second component.")}\n `),returns:["NUMBER"],compute:function(e){return Xr(e).getSeconds()},isExported:!0},Vc={description:s("Converts hour/minute/second into a time."),args:Lr(`\n hour (number) ${s("The hour component of the time.")}\n minute (number) ${s("The minute component of the time.")}\n second (number) ${s("The second component of the time.")}\n `),returns:["DATE"],computeFormat:()=>"hh:mm:ss a",compute:function(e,t,i){let n=Math.trunc(Hr(e)),o=Math.trunc(Hr(t)),r=Math.trunc(Hr(i));return o+=Math.floor(r/60),r=r%60+(r<0?60:0),n+=Math.floor(o/60),o=o%60+(o<0?60:0),n%=24,zr((()=>n>=0),s("The function [[FUNCTION_NAME]] result cannot be negative")),n/24+o/1440+r/86400},isExported:!0},zc={description:s("Converts a time string into its serial number representation."),args:Lr(`\n time_string (string) ${s("The string that holds the time representation.")}\n `),returns:["NUMBER"],compute:function(e){const t=Gr(e),i=ve(t);zr((()=>null!==i),s("The time_string (%s) cannot be parsed to date/time.",t));const n=i.value-Math.trunc(i.value);return n<0?1+n:n},isExported:!0},Bc={description:s("Current date as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(){const e=ae.now();return Ce(new ae(e.getFullYear(),e.getMonth(),e.getDate()))},isExported:!0},Hc={description:s("Day of the week of the date provided (as number)."),args:Lr(`\n date (date) ${s("The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n type (number, default=1) ${s("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.")}\n `),returns:["NUMBER"],compute:function(e,t=1){const i=Xr(e),n=Math.round(Hr(t)),o=i.getDay();return zr((()=>[1,2,3].includes(n)),s("The type (%s) must be 1, 2 or 3.",n.toString())),1===n?o+1:2===n?0===o?7:o:0===o?6:o-1},isExported:!0},Wc={description:s("Week number of the year."),args:Lr(`\n date (date) ${s("The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n type (number, default=1) ${s("A number representing the day that a week starts on. Sunday = 1.")}\n `),returns:["NUMBER"],compute:function(e,t=1){const i=Xr(e),n=Math.round(Hr(t));if(zr((()=>1===n||2===n||11<=n&&n<=17||21===n),s("The type (%s) is out of range.",n.toString())),21===n)return _c.compute(e);let o;o=1===n||2===n?n-1:n-10==7?0:n-10;const r=i.getFullYear();let a=1,l=new ae(r,0,a);for(;l.getDay()!==o;)a+=1,l=new ae(r,0,a);const c=(i.getTime()-l.getTime())/ce;return c<0?1:Math.floor(c/7)+(1===a?1:2)},isExported:!0},Gc={description:s("Date after a number of workdays."),args:Lr(`\n start_date (date) ${s("The date from which to begin counting.")}\n num_days (number) ${s("The number of working days to advance from start_date. If negative, counts backwards.")}\n holidays (date, range<date>, optional) ${s("A range or array constant containing the dates to consider holidays.")}\n `),returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i){return qc.compute(e,t,1,i)},isExported:!0},qc={description:s("Date after a number of workdays (specifying weekends)."),args:Lr(`\n start_date (date) ${s("The date from which to begin counting.")}\n num_days (number) ${s("The number of working days to advance from start_date. If negative, counts backwards.")}\n weekend (any, default=1) ${s("A number or string representing which days of the week are considered weekends.")}\n holidays (date, range<date>, optional) ${s("A range or array constant containing the dates to consider holidays.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i=1,n){let o=Xr(e),r=Math.trunc(Hr(t));"string"==typeof i&&zr((()=>"1111111"!==i),s("The weekend (%s) must be different from '1111111'.",i));const a=$c(i);let l=new Set;void 0!==n&&Qr([n],(e=>{const t=Xr(e);l.add(t.getTime())}));let c=ae.fromTimestamp(o.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-le.getTime();return Math.round(g/ce)},isExported:!0},Zc={description:s("Year specified by a given date."),args:Lr(`\n date (date) ${s("The date from which to extract the year.")}\n `),returns:["NUMBER"],compute:function(e){return Xr(e).getFullYear()},isExported:!0},jc={description:s("Exact number of years between two dates."),args:Lr(`\n start_date (date) ${s("The start date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n end_date (date) ${s("The end date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n day_count_convention (number, default=0) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i=0){let n=Math.trunc(Hr(e)),o=Math.trunc(Hr(t));const r=Math.trunc(Hr(i));return zr((()=>n>=0),s("The start_date (%s) must be positive or null.",n.toString())),zr((()=>o>=0),s("The end_date (%s) must be positive or null.",o.toString())),zr((()=>0<=r&&r<=4),s("The day_count_convention (%s) must be between 0 and 4 inclusive.",r.toString())),Re(n,o,r)}},Yc={description:s("First day of the month preceding a date."),args:Lr(`\n date (date) ${s("The date from which to calculate the result.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Xr(e),i=t.getFullYear(),n=t.getMonth();return Ce(new ae(i,n,1))}},Xc={description:s("Last day of the month following a date."),args:Lr(`\n date (date) ${s("The date from which to calculate the result.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){return Nc.compute(e,0)}},Kc={description:s("Quarter of the year a specific date falls in"),args:Lr(`\n date (date) ${s("The date from which to extract the quarter.")}\n `),returns:["NUMBER"],compute:function(e){return Math.ceil((Xr(e).getMonth()+1)/3)}},Qc={description:s("First day of the quarter of the year a specific date falls in."),args:Lr(`\n date (date) ${s("The date from which to calculate the start of quarter.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Kc.compute(e),i=Zc.compute(e);return Ce(new ae(i,3*(t-1),1))}},Jc={description:s("Last day of the quarter of the year a specific date falls in."),args:Lr(`\n date (date) ${s("The date from which to calculate the end of quarter.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Kc.compute(e),i=Zc.compute(e);return Ce(new ae(i,3*t,0))}},eh={description:s("First day of the year a specific date falls in."),args:Lr(`\n date (date) ${s("The date from which to calculate the start of the year.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Zc.compute(e);return Ce(new ae(t,0,1))}},th={description:s("Last day of the year a specific date falls in."),args:Lr(`\n date (date) ${s("The date from which to calculate the end of the year.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Zc.compute(e);return Ce(new ae(t+1,0,0))}};var ih=Object.freeze({__proto__:null,DATE:xc,DATEVALUE:Rc,DAY:Ic,DAYS:Tc,DAYS360:Ac,EDATE:Oc,EOMONTH:Nc,HOUR:Mc,ISOWEEKNUM:_c,MINUTE:Fc,MONTH:Dc,NETWORKDAYS:kc,NETWORKDAYS_INTL:Lc,NOW:Pc,SECOND:Uc,TIME:Vc,TIMEVALUE:zc,TODAY:Bc,WEEKDAY:Hc,WEEKNUM:Wc,WORKDAY:Gc,WORKDAY_INTL:qc,YEAR:Zc,YEARFRAC:jc,MONTH_START:Yc,MONTH_END:Xc,QUARTER:Kc,QUARTER_START:Qc,QUARTER_END:Jc,YEAR_START:eh,YEAR_END:th});const nh={description:s("Compare two numeric values, returning 1 if they're equal."),args:Lr(`\n number1 (number) ${s("The first number to compare.")}\n number2 (number, default=0) ${s("The second number to compare.")}\n `),returns:["NUMBER"],compute:function(e,t=0){return Hr(e)===Hr(t)?1:0},isExported:!0};var oh=Object.freeze({__proto__:null,DELTA:nh});function sh(e,t){zr((()=>e<t),s("The maturity (%s) must be strictly greater than the settlement (%s).",t.toString(),e.toString()))}function rh(e,t){zr((()=>t<e),s("The settlement date (%s) must be strictly greater than the issue date (%s).",e.toString(),t.toString()))}function ah(e){zr((()=>[1,2,4].includes(e)),s("The frequency (%s) must be one of %s",e.toString(),[1,2,4].toString()))}function lh(e){zr((()=>0<=e&&e<=4),s("The day_count_convention (%s) must be between 0 and 4 inclusive.",e.toString()))}function ch(e){zr((()=>e>0),s("The redemption (%s) must be strictly positive.",e.toString()))}function hh(e){zr((()=>e>0),s("The price (%s) must be strictly positive.",e.toString()))}function dh(e){zr((()=>e>0),s("The number_of_periods (%s) must be greater than 0.",e.toString()))}function uh(e){zr((()=>e>0),s("The rate (%s) must be strictly positive.",e.toString()))}function gh(e){zr((()=>e>0),s("The life (%s) must be strictly positive.",e.toString()))}function ph(e){zr((()=>e>=0),s("The cost (%s) must be positive or null.",e.toString()))}function mh(e){zr((()=>e>0),s("The period (%s) must be strictly positive.",e.toString()))}function fh(e){zr((()=>e>=0),s("The salvage (%s) must be positive or null.",e.toString()))}function vh(e){zr((()=>e>0),s("The present value (%s) must be strictly positive.",e.toString()))}function bh(e,t){zr((()=>e<=t),s("The period (%s) must be less than or equal life (%.",e.toString(),t.toString()))}function Sh(e){zr((()=>e>0),s("The investment (%s) must be strictly positive.",e.toString()))}function Ch(e){zr((()=>e>0),s("The discount (%s) must be strictly positive.",e.toString()))}function Eh(e){zr((()=>e<1),s("The discount (%s) must be smaller than 1.",e.toString()))}function wh(e){zr((()=>e>0),s("The depreciation factor (%s) must be strictly positive.",e.toString()))}function yh(e,t){const i=Xr(e),n=Xr(t),o=Xr(e);o.setFullYear(i.getFullYear()+1),zr((()=>n.getTime()<=o.getTime()),s("The settlement date (%s) must at most one year after the maturity date (%s).",e.toString(),t.toString()))}function xh(e,t,i){dh(i),zr((()=>e>0),s("The first_period (%s) must be strictly positive.",e.toString())),zr((()=>t>0),s("The last_period (%s) must be strictly positive.",t.toString())),zr((()=>e<=t),s("The first_period (%s) must be smaller or equal to the last_period (%s).",e.toString(),t.toString())),zr((()=>t<=i),s("The last_period (%s) must be smaller or equal to the number_of_periods (%s).",e.toString(),i.toString()))}function Rh(e){zr((()=>e>-1),s("The rate_guess (%s) must be strictly greater than -1.",e.toString()))}function Ih(e,t){zr((()=>e.length===t.length&&e[0].length===t[0].length),s("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."))}function Th(e){zr((()=>e.every((t=>t>=e[0]))),s("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e[0].toString()))}const Ah=Lr(`\nsettlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\nmaturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\nfrequency (number) ${s("The number of interest or coupon payments per year (1, 2, or 4).")}\nday_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n`);function Oh(e,t,i,n,o=1e-10,r){let a,l,c,h,d=i,u=!1,g=0;do{c=e(d),isNaN(c)?(zr((()=>g<n&&void 0!==r),s("Function [[FUNCTION_NAME]] didn't find any result.")),g++,d=r(h),h=d):(a=d-c/t(d),l=Math.abs(a-d),d=a,u=l<o||Math.abs(c)<o,zr((()=>g<n),s("Function [[FUNCTION_NAME]] didn't find any result.")),g++)}while(!u);return d}const Nh={description:s("Accrued interest of security paying at maturity."),args:Lr(`\n issue (date) ${s("The date the security was initially issued.")}\n maturity (date) ${s("The maturity date of the security.")}\n rate (number) ${s("The annualized rate of interest.")}\n redemption (number) ${s("The redemption amount per 100 face value, or par.")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o=0){o=o||0;const s=Math.trunc(Hr(e)),r=Math.trunc(Hr(t)),a=Hr(n),l=Hr(i),c=Math.trunc(Hr(o));rh(r,s),lh(c),ch(a),uh(l);return a*l*jc.compute(s,r,o)},isExported:!0},Mh={description:s("Depreciation for an accounting period."),args:Lr(`\n cost (number) ${s("The initial cost of the asset.")}\n purchase_date (date) ${s("The date the asset was purchased.")}\n first_period_end (date) ${s("The date the first period ended.")}\n salvage (number) ${s("The value of the asset at the end of depreciation.")}\n period (number) ${s("The single period within life for which to calculate depreciation.")}\n rate (number) ${s("The deprecation rate.")}\n day_count_convention (number, optional) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,r,a=0){a=a||0;const l=Hr(e),c=Math.trunc(Hr(t)),h=Math.trunc(Hr(i)),d=Hr(n),u=Hr(o),g=Hr(r),p=Math.trunc(Hr(a));!function(e){zr((()=>e>0),s("The cost (%s) must be strictly positive.",e.toString()))}(l),fh(d),function(e,t){zr((()=>e<=t),s("The salvage (%s) must be smaller or equal than the cost (%s).",e.toString(),t.toString()))}(d,l),function(e){zr((()=>e>=0),s("The period (%s) must be positive or null.",e.toString()))}(u),uh(g),lh(p),zr((()=>c<=h),s("The purchase_date (%s) must be before the first_period_end (%s).",c.toString(),h.toString()));const m=u<1&&u>0?1:Math.trunc(u),f=l*g,v=jc.compute(c,h,p),b=c===h?f:f*v,S=l-b-f*m;return S>=d?0===m?b:f:d-S<f?f-(d-S):0},isExported:!0},_h={description:s("Days in coupon period containing settlement date."),args:Ah,returns:["NUMBER"],compute:function(e,t,i,n=0){n=n||0;const o=Math.trunc(Hr(e)),s=Math.trunc(Hr(t)),r=Math.trunc(Hr(i)),a=Math.trunc(Hr(n));if(sh(o,s),ah(r),lh(a),1===a){const o=Lh.compute(e,t,i,n);return kh.compute(e,t,i,n)-o}return(3===a?365:360)/r},isExported:!0},Fh={description:s("Days from settlement until next coupon."),args:Ah,returns:["NUMBER"],compute:function(e,t,i,n=0){n=n||0;const o=Math.trunc(Hr(e)),s=Math.trunc(Hr(t)),r=Math.trunc(Hr(i)),a=Math.trunc(Hr(n));sh(o,s),ah(r),lh(a);const l=Lh.compute(o,s,i,n);if([1,2,3].includes(a))return o-l;if(4===a){const e=Re(l,o,a);return Math.round(360*e)}const c=Xr(o),h=Xr(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&&we(h)&&we(c)&&(f=30),31!==f||30!==m&&31!==m||(f=30),2===g&&we(h)&&(m=30),31===m&&(m=30),360*(u-d)+30*(p-g)+(f-m)},isExported:!0},Dh={description:s("Days from settlement until next coupon."),args:Ah,returns:["NUMBER"],compute:function(e,t,i,n=0){n=n||0;const o=Math.trunc(Hr(e)),s=Math.trunc(Hr(t)),r=Math.trunc(Hr(i)),a=Math.trunc(Hr(n));sh(o,s),ah(r),lh(a);const l=kh.compute(o,s,i,n);if([1,2,3].includes(a))return l-o;if(4===a){const e=Re(o,l,a);return Math.round(360*e)}const c=Fh.compute(e,t,i,a);return _h.compute(e,t,i,a)-c},isExported:!0},kh={description:s("Next coupon date after the settlement date."),args:Ah,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i,n=0){n=n||0;const o=Math.trunc(Hr(e)),s=Math.trunc(Hr(t)),r=Math.trunc(Hr(i)),a=Math.trunc(Hr(n));sh(o,s),ah(r),lh(a);const l=12/r,c=$h.compute(e,t,i,n);return Ce(ye(Xr(s),-(c-1)*l,!0))},isExported:!0},$h={description:s("Number of coupons between settlement and maturity."),args:Ah,returns:["NUMBER"],compute:function(e,t,i,n=0){n=n||0;const o=Math.trunc(Hr(e)),s=Math.trunc(Hr(t)),r=Math.trunc(Hr(i)),a=Math.trunc(Hr(n));sh(o,s),ah(r),lh(a);let l=1,c=s;const h=12/r;for(;c>o;)c=Ce(ye(Xr(c),-h,!1)),l++;return l-1},isExported:!0},Lh={description:s("Last coupon date prior to or on the settlement date."),args:Ah,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i,n=0){n=n||0;const o=Math.trunc(Hr(e)),s=Math.trunc(Hr(t)),r=Math.trunc(Hr(i)),a=Math.trunc(Hr(n));sh(o,s),ah(r),lh(a);const l=12/r,c=$h.compute(e,t,i,n);return Ce(ye(Xr(s),-c*l,!0))},isExported:!0},Ph={description:s("Cumulative interest paid over a set of periods."),args:Lr(`\n rate (number) ${s("The interest rate.")}\n number_of_periods (number) ${s("The number of payments to be made.")}\n present_value (number) ${s("The current value of the annuity.")}\n first_period (number) ${s("The number of the payment period to begin the cumulative calculation.")}\n last_period (number) ${s("The number of the payment period to end the cumulative calculation.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,s=0){const r=Hr(n),a=Hr(o),l=Hr(e),c=Hr(i),h=Hr(t);xh(r,a,h),uh(l),vh(c);let d=0;for(let t=r;t<=a;t++){d+=Xh.compute(e,t,h,i,0,s)}return d},isExported:!0},Uh={description:s("Cumulative principal paid over a set of periods."),args:Lr(`\n rate (number) ${s("The interest rate.")}\n number_of_periods (number) ${s("The number of payments to be made.")}\n present_value (number) ${s("The current value of the annuity.")}\n first_period (number) ${s("The number of the payment period to begin the cumulative calculation.")}\n last_period (number) ${s("The number of the payment period to end the cumulative calculation.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,s=0){const r=Hr(n),a=Hr(o),l=Hr(e),c=Hr(i),h=Hr(t);xh(r,a,h),uh(l),vh(c);let d=0;for(let t=r;t<=a;t++){d+=rd.compute(e,t,h,i,0,s)}return d},isExported:!0},Vh={description:s("Depreciation via declining balance method."),args:Lr(`\n cost (number) ${s("The initial cost of the asset.")}\n salvage (number) ${s("The value of the asset at the end of depreciation.")}\n life (number) ${s("The number of periods over which the asset is depreciated.")}\n period (number) ${s("The single period within life for which to calculate depreciation.")}\n month (number, optional) ${s("The number of months in the first year of depreciation.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,n,...o){const r=Hr(e),a=Hr(t),l=Hr(i),c=Math.trunc(Hr(n)),h=o.length?Math.trunc(Hr(o[0])):12,d=l+(12===h?0:1);ph(r),fh(a),mh(c),gh(l),zr((()=>1<=h&&h<=12),s("The month (%s) must be between 1 and 12 inclusive.",h.toString())),zr((()=>c<=d),s("The period (%s) must be less than or equal to %s.",c.toString(),d.toString()));const u=h/12;let g=1-Math.pow(a/r,1/l);g=Math.round(1e3*g)/1e3;let p=r,m=r*(1-g*u);for(let e=1;e<c;e++)p=m,m=p*(1-g),e===l&&(m=p*(1-g*(1-u)));return p-m},isExported:!0},zh={description:s("Depreciation via double-declining balance method."),args:Lr(`\n cost (number) ${s("The initial cost of the asset.")}\n salvage (number) ${s("The value of the asset at the end of depreciation.")}\n life (number) ${s("The number of periods over which the asset is depreciated.")}\n period (number) ${s("The single period within life for which to calculate depreciation.")}\n factor (number, default=2) ${s("The factor by which depreciation decreases.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,n,o=2){o=o||0;const s=Hr(e),r=Hr(t),a=Hr(i),l=Hr(n),c=Hr(o);if(ph(s),fh(r),mh(l),gh(a),bh(l,a),wh(c),0===s||r>=s)return 0;const h=c/a;if(h>1)return 1===n?s-r:0;if(l<=1)return s*h;const d=s*Math.pow(1-h,l-1),u=s*Math.pow(1-h,l),g=u<r?d-r:d-u;return Math.max(g,0)},isExported:!0},Bh={description:s("Discount rate of a security based on price."),args:Lr(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n price (number) ${s("The price at which the security is bought per 100 face value.")}\n redemption (number) ${s("The redemption amount per 100 face value, or par.")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o=0){o=o||0;const s=Math.trunc(Hr(e)),r=Math.trunc(Hr(t)),a=Hr(i),l=Hr(n),c=Math.trunc(Hr(o));sh(s,r),lh(c),hh(a),ch(l);return(l-a)/l/jc.compute(s,r,c)},isExported:!0},Hh={description:s("Convert a decimal fraction to decimal value."),args:Lr(`\n fractional_price (number) ${s("The price quotation given using fractional decimal conventions.")}\n unit (number) ${s("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.")}\n `),returns:["NUMBER"],compute:function(e,t){const i=Hr(e),n=Math.trunc(Hr(t));zr((()=>n>0),s("The unit (%s) must be strictly positive.",n.toString()));const o=Math.trunc(i);return o+(i-o)*(10**Math.ceil(Math.log10(n))/n)},isExported:!0},Wh={description:s("Convert a decimal value to decimal fraction."),args:Lr(`\n decimal_price (number) ${s("The price quotation given as a decimal value.")}\n unit (number) ${s("The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.")}\n `),returns:["NUMBER"],compute:function(e,t){const i=Hr(e),n=Math.trunc(Hr(t));zr((()=>n>0),s("The unit (%s) must be strictly positive.",n.toString()));const o=Math.trunc(i);return o+(i-o)*(n/10**Math.ceil(Math.log10(n)))},isExported:!0},Gh={description:s("Number of periods for an investment to reach a value."),args:Lr(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${s("The annualized rate of interest.")}\n yield (number) ${s("The expected annual yield of the security.")}\n frequency (number) ${s("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,r=0){r=r||0;const a=Math.trunc(Hr(e)),l=Math.trunc(Hr(t)),c=Hr(i),h=Hr(n),d=Math.trunc(Hr(o)),u=Math.trunc(Hr(r));sh(a,l),ah(d),lh(u),zr((()=>c>=0),s("The rate (%s) must be positive or null.",c.toString())),zr((()=>h>=0),s("The yield (%s) must be positive or null.",h.toString()));const g=jc.compute(a,l,u),p=g-Math.trunc(g)||1/d,m=Math.ceil(g*d),f=c/d,v=h/d;let b=0,S=0;for(let e=1;e<=m;e++){const t=(f+(e===m?1:0))/(1+v)**e;S+=(p+(e-1)/d)*t,b+=t}return 0===b?0:S/b},isExported:!0},qh={description:s("Annual effective interest rate."),args:Lr(`\n nominal_rate (number) ${s("The nominal interest rate per year.")}\n periods_per_year (number) ${s("The number of compounding periods per year.")}\n `),returns:["NUMBER"],compute:function(e,t){const i=Hr(e),n=Math.trunc(Hr(t));return zr((()=>i>0),s("The nominal rate (%s) must be strictly greater than 0.",i.toString())),zr((()=>n>0),s("The number of periods by year (%s) must strictly greater than 0.",n.toString())),Math.pow(1+i/n,n)-1},isExported:!0},Zh={description:s("Future value of an annuity investment."),args:Lr(`\n rate (number) ${s("The interest rate.")}\n number_of_periods (number) ${s("The number of payments to be made.")}\n payment_amount (number) ${s("The amount per period to be paid.")}\n present_value (number, default=0) ${s("The current value of the annuity.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,n=0,o=0){n=n||0,o=o||0;const s=Hr(e),r=Hr(t),a=Hr(i),l=Hr(n),c=Yr(o)?1:0;return s?-l*(1+s)**r-a*(1+s*c)*((1+s)**r-1)/s:-(l+a*r)},isExported:!0},jh={description:s("Future value of principal from series of rates."),args:Lr(`\n principal (number) ${s("The amount of initial capital or value to compound against.")}\n rate_schedule (number, range<number>) ${s("A series of interest rates to compound against the principal.")}\n `),returns:["NUMBER"],compute:function(e,t){return ta([t],((e,t)=>e*(1+Hr(t))),Hr(e))},isExported:!0},Yh={description:s("Calculates effective interest rate."),args:Lr(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n investment (number) ${s("The amount invested in the security.")}\n redemption (number) ${s("The amount to be received at maturity.")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o=0){const s=Math.trunc(Hr(e)),r=Math.trunc(Hr(t)),a=Hr(n),l=Hr(i);sh(s,r),Sh(l),ch(a);return(a-l)/l/jc.compute(s,r,o)},isExported:!0},Xh={description:s("Payment on the principal of an investment."),args:Lr(`\n rate (number) ${s("The annualized rate of interest.")}\n period (number) ${s("The amortization period, in terms of number of periods.")}\n number_of_periods (number) ${s("The number of payments to be made.")}\n present_value (number) ${s("The current value of the annuity.")}\n future_value (number, default=0) ${s("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,n,o=0,s=0){return sd.compute(e,i,n,o,s)-rd.compute(e,t,i,n,o,s)},isExported:!0},Kh={description:s("Internal rate of return given periodic cashflows."),args:Lr(`\n cashflow_amounts (number, range<number>) ${s("An array or range containing the income or payments associated with the investment.")}\n rate_guess (number, default=0.1) ${s("An estimate for what the internal rate of return will be.")}\n `),returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t=.1){const i=Hr(t);Rh(i);let n=!1,o=!1,r=[];Jr([e],(e=>{e>0&&(n=!0),e<0&&(o=!0),r.push(e)})),zr((()=>n&&o),s("The cashflow_amounts must include negative and positive values."));const a=r.shift();return Oh((function(e){return function(e,t,i){const n=i.length;let o=0;return i.reduce(((t,i)=>(o++,t+i*e**(n-o))),t*e**n)}(e,a,r)}),(function(e){return function(e,t,i){const n=i.length;let o=0;return i.reduce(((t,i)=>(o++,t+i*(n-o)*e**(n-o-1))),t*n*e**(n-1))}(e,a,r)}),i+1,20,1e-5)-1},isExported:!0},Qh={description:s("Returns the interest paid at a particular period of an investment."),args:Lr(`\n rate (number) ${s("The interest rate.")}\n period (number) ${s("The period for which you want to view the interest payment.")}\n number_of_periods (number) ${s("The number of payments to be made.")}\n present_value (number) ${s("The current value of the annuity.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n){const o=Hr(e),r=Hr(t),a=Hr(i),l=Hr(n);zr((()=>0!==a),s("The number of periods must be different than 0.",a.toString()));return-1*(l-l*(r/a))*o},isExported:!0},Jh={description:s("Modified Macaulay duration."),args:Lr(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${s("The annualized rate of interest.")}\n yield (number) ${s("The expected annual yield of the security.")}\n frequency (number) ${s("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,s=0){return Gh.compute(e,t,i,n,o,s)/(1+Hr(n)/Math.trunc(Hr(o)))},isExported:!0},ed={description:s("Modified internal rate of return."),args:Lr(`\n cashflow_amounts (range<number>) ${s("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")}\n financing_rate (number) ${s("The interest rate paid on funds invested.")}\n reinvestment_return_rate (number) ${s("The return (as a percentage) earned on reinvestment of income received from the investment.")}\n `),returns:["NUMBER"],compute:function(e,t,i){const n=Hr(t),o=Hr(i),r=(a=e,a.length?a[0].map(((e,t)=>a.map((e=>e[t])))):a).flat().filter(Xe).map(Hr);var a;const l=r.length;let c=0,h=0;for(const e of $e(0,l)){const t=r[e];t>=0?c+=t*(o+1)**(l-e-1):h+=t/(n+1)**e}zr((()=>0!==h&&0!==c),s("There must be both positive and negative values in cashflow_amounts."));return(-c/h)**(1/(l-1))-1},isExported:!0},td={description:s("Annual nominal interest rate."),args:Lr(`\n effective_rate (number) ${s("The effective interest rate per year.")}\n periods_per_year (number) ${s("The number of compounding periods per year.")}\n `),returns:["NUMBER"],compute:function(e,t){const i=Hr(e),n=Math.trunc(Hr(t));return zr((()=>i>0),s("The effective rate (%s) must must strictly greater than 0.",i.toString())),zr((()=>n>0),s("The number of periods by year (%s) must strictly greater than 0.",n.toString())),(Math.pow(i+1,1/n)-1)*n},isExported:!0},id={description:s("Number of payment periods for an investment."),args:Lr(`\n rate (number) ${s("The interest rate.")}\n payment_amount (number) ${s("The amount of each payment made.")}\n present_value (number) ${s("The current value of the annuity.")}\n future_value (number, default=0) ${s("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n=0,o=0){n=n||0,o=o||0;const s=Hr(e),r=Hr(t),a=Hr(i),l=Hr(n),c=Yr(o)?1:0;if(0===s)return-(l+a)/r;const h=r*(1+s*c)/s;return Math.log((h-l)/(a+h))/Math.log(1+s)},isExported:!0};const nd={description:s("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:Lr(`\n discount (number) ${s("The discount rate of the investment over one period.")}\n cashflow1 (number, range<number>) ${s("The first future cash flow.")}\n cashflow2 (number, range<number>, repeating) ${s("Additional future cash flows.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,...t){const i=Hr(e);return zr((()=>-1!==i),s("The discount (%s) must be different from -1.",i.toString())),function(e,t,i){let n=0;return ia(i,((t,i)=>(n++,t+i/(1+e)**n)),t)}(i,0,t)},isExported:!0},od={description:s("Computes the number of periods needed for an investment to reach a value."),args:Lr(`\n rate (number) ${s("The rate at which the investment grows each period.")}\n present_value (number) ${s("The investment's current value.")}\n future_value (number) ${s("The investment's desired future value.")}\n `),returns:["NUMBER"],compute:function(e,t,i){const n=Hr(e),o=Hr(t),r=Hr(i);return uh(n),zr((()=>o>0),s("The present_value (%s) must be strictly positive.",o.toString())),zr((()=>r>0),s("The future_value (%s) must be strictly positive.",r.toString())),(Math.log(r)-Math.log(o))/Math.log(1+n)},isExported:!0},sd={description:s("Periodic payment for an annuity investment."),args:Lr(`\n rate (number) ${s("The annualized rate of interest.")}\n number_of_periods (number) ${s("The number of payments to be made.")}\n present_value (number) ${s("The current value of the annuity.")}\n future_value (number, default=0) ${s("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,n=0,o=0){n=n||0,o=o||0;const s=Hr(t),r=Hr(e),a=Yr(o)?1:0;let l=Hr(n),c=Hr(i);if(dh(s),0===r)return-(l+c)/s;let h=-(c*(1+r)**s+l);return h=h*r/((1+r*a)*((1+r)**s-1)),h},isExported:!0},rd={description:s("Payment on the principal of an investment."),args:Lr(`\n rate (number) ${s("The annualized rate of interest.")}\n period (number) ${s("The amortization period, in terms of number of periods.")}\n number_of_periods (number) ${s("The number of payments to be made.")}\n present_value (number) ${s("The current value of the annuity.")}\n future_value (number, default=0) ${s("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,n,o=0,r=0){o=o||0,r=r||0;const a=Hr(i),l=Hr(e),c=Hr(t),h=Yr(r)?1:0,d=Hr(o),u=Hr(n);dh(a),zr((()=>c>0&&c<=a),s("The period must be between 1 and number_of_periods",a.toString()));const g=sd.compute(l,a,u,d,r);if(1===h&&1===c)return g;return g+-Zh.compute(l,0===h?c-1:c-2,g,u+g*h,0)*l},isExported:!0},ad={description:s("Present value of an annuity investment."),args:Lr(`\n rate (number) ${s("The interest rate.")}\n number_of_periods (number) ${s("The number of payments to be made.")}\n payment_amount (number) ${s("The amount per period to be paid.")}\n future_value (number, default=0) ${s("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,n=0,o=0){n=n||0,o=o||0;const s=Hr(e),r=Hr(t),a=Hr(i),l=Hr(n),c=Yr(o)?1:0;return s?-(a*(1+s*c)*((1+s)**r-1)/s+l)/(1+s)**r:-(l+a*r)},isExported:!0},ld={description:s("Price of a security paying periodic interest."),args:Lr(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${s("The annualized rate of interest.")}\n yield (number) ${s("The expected annual yield of the security.")}\n redemption (number) ${s("The redemption amount per 100 face value, or par.")}\n frequency (number) ${s("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,r,a=0){a=a||0;const l=Math.trunc(Hr(e)),c=Math.trunc(Hr(t)),h=Hr(i),d=Hr(n),u=Hr(o),g=Math.trunc(Hr(r)),p=Math.trunc(Hr(a));sh(l,c),ah(g),lh(p),zr((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),zr((()=>d>=0),s("The yield (%s) must be positive or null.",d.toString())),ch(u);const m=jc.compute(l,c,p)*g,f=Math.ceil(m),v=m-Math.floor(m)||1,b=1+d/g,S=100*h/g;if(1===f)return(S+u)/(v*d/g+1)-S*(1-v);let C=0;for(let e=1;e<=f;e++)C+=S/b**(e-1+v);return u/b**(f-1+v)+C-S*(1-v)},isExported:!0},cd={description:s("Price of a discount security."),args:Lr(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n discount (number) ${s("The discount rate of the security at time of purchase.")}\n redemption (number) ${s("The redemption amount per 100 face value, or par.")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o=0){o=o||0;const s=Math.trunc(Hr(e)),r=Math.trunc(Hr(t)),a=Hr(i),l=Hr(n),c=Math.trunc(Hr(o));sh(s,r),lh(c),Ch(a),ch(l);return l-a*l*jc.compute(s,r,c)},isExported:!0},hd={description:s("Calculates the price of a security paying interest at maturity, based on expected yield."),args:Lr(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n issue (date) ${s("The date the security was initially issued.")}\n rate (number) ${s("The annualized rate of interest.")}\n yield (number) ${s("The expected annual yield of the security.")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,r=0){r=r||0;const a=Math.trunc(Hr(e)),l=Math.trunc(Hr(t)),c=Math.trunc(Hr(i)),h=Hr(n),d=Hr(o),u=Math.trunc(Hr(r));rh(a,c),sh(a,l),lh(u),zr((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),zr((()=>d>=0),s("The yield (%s) must be positive or null.",d.toString()));const g=jc.compute(a,l,u),p=jc.compute(a,c,u);return(100+jc.compute(c,l,u)*h*100)/(1+g*d)-p*h*100},isExported:!0},dd=.1,ud={description:s("Interest rate of an annuity investment."),args:Lr(`\n number_of_periods (number) ${s("The number of payments to be made.")}\n payment_per_period (number) ${s("The amount per period to be paid.")}\n present_value (number) ${s("The current value of the annuity.")}\n future_value (number, default=0) ${s("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n rate_guess (number, default=0.1) ${s("An estimate for what the interest rate will be.")}\n `),returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t,i,n=0,o=0,r=.1){n=n||0,o=o||0,r=r||dd;const a=Hr(e),l=Hr(t),c=Yr(o)?1:0,h=Hr(r);let d=Hr(n),u=Hr(i);dh(a),zr((()=>[l,u,d].some((e=>e>0))&&[l,u,d].some((e=>e<0))),s("There must be both positive and negative values in [payment_amount, present_value, future_value].",a.toString())),Rh(h),d-=l*c,u+=l*c;return Oh((e=>{const t=Math.pow(1+e,a);return d+u*t+l*((t-1)/e)}),(e=>{const t=Math.pow(1+e,a-1),i=Math.pow(1+e,a);return u*a*t+l*(a*t/e-(i-1)/e/e)}),h,40,1e-5)},isExported:!0},gd={description:s("Amount received at maturity for a security."),args:Lr(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n investment (number) ${s("The amount invested (irrespective of face value of each security).")}\n discount (number) ${s("The discount rate of the security invested in.")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o=0){o=o||0;const s=Math.trunc(Hr(e)),r=Math.trunc(Hr(t)),a=Hr(i),l=Hr(n),c=Math.trunc(Hr(o));sh(s,r),lh(c),Sh(a),Ch(l);return a/(1-l*jc.compute(s,r,c))},isExported:!0},pd={description:s("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:Lr(`\n number_of_periods (number) ${s("The number of periods.")}\n present_value (number) ${s("The present value of the investment.")}\n future_value (number) ${s("The future value of the investment.")}\n `),returns:["NUMBER"],compute:function(e,t,i){const n=Hr(e),o=Hr(t),s=Hr(i);return dh(n),(s/o)**(1/n)-1},isExported:!0},md={description:s("Depreciation of an asset using the straight-line method."),args:Lr(`\n cost (number) ${s("The initial cost of the asset.")}\n salvage (number) ${s("The value of the asset at the end of depreciation.")}\n life (number) ${s("The number of periods over which the asset is depreciated.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i){return(Hr(e)-Hr(t))/Hr(i)},isExported:!0},fd={description:s("Depreciation via sum of years digit method."),args:Lr(`\n cost (number) ${s("The initial cost of the asset.")}\n salvage (number) ${s("The value of the asset at the end of depreciation.")}\n life (number) ${s("The number of periods over which the asset is depreciated.")}\n period (number) ${s("The single period within life for which to calculate depreciation.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,n){const o=Hr(e),s=Hr(t),r=Hr(i),a=Hr(n);mh(a),gh(r),bh(a,r);return(r-a+1)/(r*(r+1)/2)*(o-s)},isExported:!0},vd={description:s("Price of a US Treasury bill."),args:Lr(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n discount (number) ${s("The discount rate of the bill at time of purchase.")}\n `),returns:["NUMBER"],compute:function(e,t,i){const n=Math.trunc(Hr(e)),o=Math.trunc(Hr(t)),s=Hr(i);sh(n,o),yh(n,o),Ch(s),Eh(s);return 100*(1-s*jc.compute(n,o,2))},isExported:!0},bd={description:s("Equivalent rate of return for a US Treasury bill."),args:Lr(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n discount (number) ${s("The discount rate of the bill at time of purchase.")}\n `),returns:["NUMBER"],compute:function(e,t,i){const n=Math.trunc(Hr(e)),o=Math.trunc(Hr(t)),s=Hr(i);sh(n,o),yh(n,o),Ch(s),Eh(s);const r=Tc.compute(o,n);if(r<=182)return 365*s/(360-s*r);const a=vd.compute(n,o,s)/100,l=r/(366===r?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},Sd={description:s("The yield of a US Treasury bill based on price."),args:Lr(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n price (number) ${s("The price at which the security is bought per 100 face value.")}\n `),returns:["NUMBER"],compute:function(e,t,i){const n=Math.trunc(Hr(e)),o=Math.trunc(Hr(t)),s=Hr(i);sh(n,o),yh(n,o),hh(s);return(100-s)/s*(1/jc.compute(n,o,2))},isExported:!0},Cd={description:s("Variable declining balance. WARNING : does not handle decimal periods."),args:Lr(`\n cost (number) ${s("The initial cost of the asset.")}\n salvage (number) ${s("The value of the asset at the end of depreciation.")}\n life (number) ${s("The number of periods over which the asset is depreciated.")}\n start (number) ${s("Starting period to calculate depreciation.")}\n end (number) ${s("Ending period to calculate depreciation.")}\n factor (number, default=2) ${s("The number of months in the first year of depreciation.")}\n no_switch (number, default=false) ${s("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,r=2,a=false){r=r||0;const l=Hr(e),c=Hr(t),h=Hr(i),d=Math.trunc(Hr(n)),u=Math.trunc(Hr(o)),g=Hr(r),p=Yr(a);if(ph(l),fh(c),function(e,t,i){gh(i),zr((()=>e>=0),s("The start_period (%s) must be greater or equal than 0.",e.toString())),zr((()=>t>=0),s("The end_period (%s) must be greater or equal than 0.",t.toString())),zr((()=>e<=t),s("The start_period (%s) must be smaller or equal to the end_period (%s).",e.toString(),t.toString())),zr((()=>t<=i),s("The end_period (%s) must be smaller or equal to the life (%s).",e.toString(),i.toString()))}(d,u,h),wh(g),0===l)return 0;if(c>=l)return d<1?l-c:0;const m=g/h;if(m>=1)return d<1?l-c:0;let f=l,v=0,b=0,S=!1;for(let e=0;e<u;e++){if(!S||p){const t=f*m,i=(f-c)/(h-e);!p&&i>t?(S=!0,v=i):v=t}const t=Math.max(f-v,c);e>=d&&(b+=f-t),f=t}return b},isExported:!0},Ed={description:s("Internal rate of return given non-periodic cash flows."),args:Lr(`\n cashflow_amounts (range<number>) ${s("An range containing the income or payments associated with the investment.")}\n cashflow_dates (range<number>) ${s("An range with dates corresponding to the cash flows in cashflow_amounts.")}\n rate_guess (number, default=0.1) ${s("An estimate for what the internal rate of return will be.")}\n `),returns:["NUMBER"],compute:function(e,t,i=.1){const n=Hr(i=i||0),o=e.flat().map(Hr),r=t.flat().map(Hr);var a;Ih(e,t),a=o,zr((()=>a.some((e=>e>0))&&a.some((e=>e<0))),s("There must be both positive and negative values in cashflow_amounts.")),Th(r),Rh(n);const l=new Map;for(const e of $e(0,r.length)){const t=r[e];l.has(t)?l.set(t,l.get(t)+o[e]):l.set(t,o[e])}const c=Array.from(l.keys()),h=c.map((e=>l.get(e)));return Oh((e=>{let t=h[0];for(const i of $e(1,h.length)){const n=(c[0]-c[i])/365;t+=h[i]*(1+e)**n}return t}),(e=>{let t=0;for(const i of $e(1,h.length)){const n=(c[0]-c[i])/365;t+=n*h[i]*(1+e)**(n-1)}return t}),n,40,1e-5,(e=>e?e/10-.9:-.9))},isExported:!0},wd={description:s("Net present value given to non-periodic cash flows.."),args:Lr(`\n discount (number) ${s("The discount rate of the investment over one period.")}\n cashflow_amounts (number, range<number>) ${s("An range containing the income or payments associated with the investment.")}\n cashflow_dates (number, range<number>) ${s("An range with dates corresponding to the cash flows in cashflow_amounts.")}\n `),returns:["NUMBER"],compute:function(e,t,i){const n=Hr(e),o=Array.isArray(t)?t.flat().map(Wr):[Wr(t)],r=Array.isArray(i)?i.flat().map(Wr):[Wr(i)];if(Array.isArray(i)&&Array.isArray(t)?Ih(t,i):zr((()=>o.length===r.length),s("There must be the same number of values in cashflow_amounts and cashflow_dates.")),Th(r),uh(n),1===o.length)return o[0];const a=new Map;for(const e of $e(0,r.length)){const t=r[e];a.has(t)?a.set(t,a.get(t)+o[e]):a.set(t,o[e])}const l=Array.from(a.keys()),c=l.map((e=>a.get(e)));let h=c[0];for(const e of $e(1,c.length)){const t=(l[0]-l[e])/365;h+=c[e]*(1+n)**t}return h},isExported:!0},yd={description:s("Annual yield of a security paying periodic interest."),args:Lr(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${s("The annualized rate of interest.")}\n price (number) ${s("The price at which the security is bought per 100 face value.")}\n redemption (number) ${s("The redemption amount per 100 face value, or par.")}\n frequency (number) ${s("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,r,a=0){a=a||0;const l=Math.trunc(Hr(e)),c=Math.trunc(Hr(t)),h=Hr(i),d=Hr(n),u=Hr(o),g=Math.trunc(Hr(r)),p=Math.trunc(Hr(a));sh(l,c),ah(g),lh(p),zr((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),hh(d),ch(u);const m=jc.compute(l,c,p)*g,f=Math.ceil(m),v=m-Math.floor(m)||1,b=100*h/g;if(1===f){const e=d+b*(1-v);return(u+b-e)*g*(1/v)/e}const S=Oh((function(e){return function(e,t,i,n,o,s){let r=s-(e+o*(1-t))*n**(i-1+t);for(let e=1;e<=i;e++)r+=o*n**(e-1);return r}(d,v,f,e,b,u)}),(function(e){return function(e,t,i,n,o){let s=-(e+o*(1-t))*(i-1+t)*n**(i-2+t);for(let e=1;e<=i;e++)s+=o*(e-1)*n**(e-2);return s}(d,v,f,e,b)}),1+(h+1)/g,100,1e-5);return(S-1)*g},isExported:!0},xd={description:s("Annual yield of a discount security."),args:Lr(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n price (number) ${s("The price at which the security is bought per 100 face value.")}\n redemption (number) ${s("The redemption amount per 100 face value, or par.")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o=0){o=o||0;const s=Math.trunc(Hr(e)),r=Math.trunc(Hr(t)),a=Hr(i),l=Hr(n),c=Math.trunc(Hr(o));sh(s,r),lh(c),hh(a),ch(l);return(l/a-1)/jc.compute(e,t,o)},isExported:!0},Rd={description:s("Annual yield of a security paying interest at maturity."),args:Lr(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n issue (date) ${s("The date the security was initially issued.")}\n rate (number) ${s("The annualized rate of interest.")}\n price (number) ${s("The price at which the security is bought.")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,r=0){r=r||0;const a=Math.trunc(Hr(e)),l=Math.trunc(Hr(t)),c=Math.trunc(Hr(i)),h=Hr(n),d=Hr(o),u=Math.trunc(Hr(r));sh(a,l),lh(u),zr((()=>a>=c),s("The settlement (%s) must be greater than or equal to the issue (%s).",a.toString(),c.toString())),zr((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),hh(d);const g=jc.compute(c,l,u),p=jc.compute(c,a,u),m=jc.compute(a,l,u);return(100*(1+h*g)/(d+100*h*p)-1)/m},isExported:!0};var Id=Object.freeze({__proto__:null,ACCRINTM:Nh,AMORLINC:Mh,COUPDAYS:_h,COUPDAYBS:Fh,COUPDAYSNC:Dh,COUPNCD:kh,COUPNUM:$h,COUPPCD:Lh,CUMIPMT:Ph,CUMPRINC:Uh,DB:Vh,DDB:zh,DISC:Bh,DOLLARDE:Hh,DOLLARFR:Wh,DURATION:Gh,EFFECT:qh,FV:Zh,FVSCHEDULE:jh,INTRATE:Yh,IPMT:Xh,IRR:Kh,ISPMT:Qh,MDURATION:Jh,MIRR:ed,NOMINAL:td,NPER:id,NPV:nd,PDURATION:od,PMT:sd,PPMT:rd,PV:ad,PRICE:ld,PRICEDISC:cd,PRICEMAT:hd,RATE:ud,RECEIVED:gd,RRI:pd,SLN:md,SYD:fd,TBILLPRICE:vd,TBILLEQ:bd,TBILLYIELD:Sd,VDB:Cd,XIRR:Ed,XNPV:wd,YIELD:yd,YIELDDISC:xd,YIELDMAT:Rd});const Td={description:s("Whether a value is an error other than #N/A."),args:Lr(`value (any, lazy) ${s("The value to be verified as an error type.")}`),returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return(null==e?void 0:e.errorType)!=a.NotAvailable}},isExported:!0},Ad={description:s("Whether a value is an error."),args:Lr(`value (any, lazy) ${s("The value to be verified as an error type.")}`),returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},Od={description:s("Whether a value is `true` or `false`."),args:Lr(`value (any, lazy) ${s("The value to be verified as a logical TRUE or FALSE.")}`),returns:["BOOLEAN"],compute:function(e){try{return"boolean"==typeof e()}catch(e){return!1}},isExported:!0},Nd={description:s("Whether a value is the error #N/A."),args:Lr(`value (any, lazy) ${s("The value to be verified as an error type.")}`),returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return(null==e?void 0:e.errorType)==a.NotAvailable}},isExported:!0},Md={description:s("Whether a value is non-textual."),args:Lr(`value (any, lazy) ${s("The value to be checked.")}`),returns:["BOOLEAN"],compute:function(e){try{return"string"!=typeof e()}catch(e){return!0}},isExported:!0},_d={description:s("Whether a value is a number."),args:Lr(`value (any, lazy) ${s("The value to be verified as a number.")}`),returns:["BOOLEAN"],compute:function(e){try{return"number"==typeof e()}catch(e){return!1}},isExported:!0},Fd={description:s("Whether a value is text."),args:Lr(`value (any, lazy) ${s("The value to be verified as text.")}`),returns:["BOOLEAN"],compute:function(e){try{return"string"==typeof e()}catch(e){return!1}},isExported:!0},Dd={description:s("Whether the referenced cell is empty"),args:Lr(`value (any, lazy) ${s("Reference to the cell that will be checked for emptiness.")}`),returns:["BOOLEAN"],compute:function(e){try{return null===e()}catch(e){return!1}},isExported:!0},kd={description:s("Returns the error value #N/A."),args:Lr(""),returns:["BOOLEAN"],compute:function(e){throw new g},isExported:!0};var $d=Object.freeze({__proto__:null,ISERR:Td,ISERROR:Ad,ISLOGICAL:Od,ISNA:Nd,ISNONTEXT:Md,ISNUMBER:_d,ISTEXT:Fd,ISBLANK:Dd,NA:kd});const Ld={description:s("Logical `and` operator."),args:Lr(`\n logical_expression1 (boolean, range<boolean>) ${s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${s("More expressions that represent logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!0;return oa(e,(e=>(t=!0,i=i&&e,i))),zr((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0},Pd={description:s("Returns value depending on logical expression."),args:Lr(`\n logical_expression (boolean) ${s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")}\n value_if_true (any, lazy) ${s("The value the function returns if logical_expression is TRUE.")}\n value_if_false (any, lazy, default=FALSE) ${s("The value the function returns if logical_expression is FALSE.")}\n `),returns:["ANY"],compute:function(e,t,i=(()=>!1)){const n=Yr(e)?t():i();return null==n?"":n},isExported:!0},Ud={description:s("Value if it is not an error, otherwise 2nd argument."),args:Lr(`\n value (any, lazy) ${s("The value to return if value itself is not an error.")}\n value_if_error (any, lazy, default=${s("An empty value")}) ${s("The value the function returns if value is an error.")}\n `),returns:["ANY"],computeFormat:(e,t=(()=>({value:""})))=>{var i;try{return e().format}catch(e){return null===(i=t())||void 0===i?void 0:i.format}},compute:function(e,t=(()=>"")){let i;try{i=e()}catch(e){i=t()}return null==i?"":i},isExported:!0},Vd={description:s("Value if it is not an #N/A error, otherwise 2nd argument."),args:Lr(`\n value (any, lazy) ${s("The value to return if value itself is not #N/A an error.")}\n value_if_error (any, lazy, default=${s("An empty value")}) ${s("The value the function returns if value is an #N/A error.")}\n `),returns:["ANY"],compute:function(e,t=(()=>"")){let i;try{i=e()}catch(n){i=n.errorType===a.NotAvailable?t():e()}return null==i?"":i},isExported:!0},zd={description:s("Returns a value depending on multiple logical expressions."),args:Lr(`\n condition1 (boolean, lazy) ${s("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")}\n value1 (any, lazy) ${s("The returned value if condition1 is TRUE.")}\n condition2 (boolean, lazy, repeating) ${s("Additional conditions to be evaluated if the previous ones are FALSE.")}\n value2 (any, lazy, repeating) ${s("Additional values to be returned if their corresponding conditions are TRUE.")}\n `),returns:["ANY"],compute:function(...e){zr((()=>e.length%2==0),s("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(Yr(e[t]())){const i=e[t+1]();return null!==i?i:""}throw new Error(s("No match."))},isExported:!0},Bd={description:s("Returns opposite of provided logical value."),args:Lr(`logical_expression (boolean) ${s("An expression or reference to a cell holding an expression that represents some logical value.")}\n `),returns:["BOOLEAN"],compute:function(e){return!Yr(e)},isExported:!0},Hd={description:s("Logical `or` operator."),args:Lr(`\n logical_expression1 (boolean, range<boolean>) ${s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${s("More expressions that evaluate to logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!1;return oa(e,(e=>(t=!0,i=i||e,!i))),zr((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0},Wd={description:s("Logical `xor` operator."),args:Lr(`\n logical_expression1 (boolean, range<boolean>) ${s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${s("More expressions that evaluate to logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!1;return oa(e,(e=>(t=!0,i=i?!e:e,!0))),zr((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0};var Gd=Object.freeze({__proto__:null,AND:Ld,IF:Pd,IFERROR:Ud,IFNA:Vd,IFS:zd,NOT:Bd,OR:Hd,XOR:Wd});const qd={description:s("Column number of a specified cell."),args:Lr(`cell_reference (meta, default=${s("The cell in which the formula is entered")}) ${s("The cell whose column number will be returned. Column A corresponds to 1.")}\n `),returns:["NUMBER"],compute:function(e){var t;const i=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this));zr((()=>!!i),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Mi(i).left+1},isExported:!0},Zd={description:s("Number of columns in a specified array or range."),args:Lr(`range (meta) ${s("The range whose column count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=Mi(e);return t.right-t.left+1},isExported:!0},jd={description:s("Horizontal lookup"),args:Lr(`\n search_key (any) ${s("The value to search for. For example, 42, 'Cats', or I24.")}\n range (range) ${s("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")}\n index (number) ${s("The row index of the value to be returned, where the first row in range is numbered 1.")}\n is_sorted (boolean, default=true) ${s("Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned.")}\n `),returns:["ANY"],compute:function(e,t,i,n=true){const o=Math.trunc(Hr(i)),r=Zr(e);zr((()=>1<=o&&o<=t[0].length),s("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const a=Yr(n);let l;return l=a?ha(t,r,"nextSmaller","asc",t.length,ca):da(t,r,"strict",t.length,ca),zr((()=>l>-1),s("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",Gr(e))),t[l][o-1]},isExported:!0},Yd={description:s("Returns the content of a cell, specified by row and column offset."),args:Lr(`\n reference (any, range) ${s("The range of cells from which the value is returned.")}\n row (number) ${s("The index of the row to be returned from within the reference range of cells.")}\n column (number) ${s("The index of the column to be returned from within the reference range of cells.")}\n`),returns:["ANY"],computeFormat:(e,t,i)=>{var n;const o=Hr(t.value);return null===(n=e[Hr(i.value)-1][o-1])||void 0===n?void 0:n.format},compute:function(e,t,i){const n=(o=e,Array.isArray(o)&&Array.isArray(o[0])?e:[[e]]);var o;const r=Hr(t),a=Hr(i);return zr((()=>a>=0&&a-1<n.length&&r>=0&&r-1<n[0].length),s("Index out of range.")),zr((()=>0!==t&&0!==i),s("This function can only return a single cell value, not an array. Provide valid row and column indices.")),n[a-1][r-1]},isExported:!0},Xd={description:s("Look up a value."),args:Lr(`\n search_key (any) ${s("The value to search for. For example, 42, 'Cats', or I24.")}\n search_array (range) ${s("One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.")}\n result_range (range, optional) ${s("The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method.")}\n `),returns:["ANY"],compute:function(e,t,i){let n=t.length,o=t[0].length;const r=Zr(e),a=o>=n,l=ha(t,r,"nextSmaller","asc",a?o:n,a?la:ca);return zr((()=>l>=0),s("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",Gr(e))),void 0===i?a?t[n-1][l]:t[l][o-1]:(n=i.length,o=i[0].length,zr((()=>1===n||1===o),s("The result_range must be a single row or a single column.")),n>1?(zr((()=>l<=n-1),s("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(l+1).toString())),i[l][0]):(zr((()=>l<=o-1),s("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(l+1).toString())),i[0][l]))},isExported:!0},Kd={description:s("Position of item in range that matches value."),args:Lr(`\n search_key (any) ${s("The value to search for. For example, 42, 'Cats', or I24.")}\n range (any, range) ${s("The one-dimensional array to be searched.")}\n search_type (number, default=1) ${s("The search method. 1 (default) finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order.")}\n `),returns:["NUMBER"],compute:function(e,t,i=1){let n=Hr(i);const o=Zr(e),r=t.length,a=t[0].length;zr((()=>1===r||1===a),s("The range must be a single row or a single column."));let l=-1;const c=1===r?la:ca,h=1===r?t[0].length:t.length;switch(n=Math.sign(n),n){case 1:l=ha(t,o,"nextSmaller","asc",h,c);break;case 0:l=da(t,o,"strict",h,c);break;case-1:l=ha(t,o,"nextGreater","desc",h,c)}return zr((()=>l>=0),s("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",Gr(e))),l+1},isExported:!0},Qd={description:s("Row number of a specified cell."),args:Lr(`cell_reference (meta, default=${s("The cell in which the formula is entered by default")}) ${s("The cell whose row number will be returned.")}`),returns:["NUMBER"],compute:function(e){var t;e=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this)),zr((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Mi(e).top+1},isExported:!0},Jd={description:s("Number of rows in a specified array or range."),args:Lr(`range (meta) ${s("The range whose row count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=Mi(e);return t.bottom-t.top+1},isExported:!0},eu={description:s("Vertical lookup."),args:Lr(`\n search_key (any) ${s("The value to search for. For example, 42, 'Cats', or I24.")}\n range (any, range) ${s("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")}\n index (number) ${s("The column index of the value to be returned, where the first column in range is numbered 1.")}\n is_sorted (boolean, default=true) ${s("Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned.")}\n `),returns:["ANY"],compute:function(e,t,i,n=true){const o=Math.trunc(Hr(i)),r=Zr(e);zr((()=>1<=o&&o<=t.length),s("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const a=Yr(n);let l;return l=a?ha(t,r,"nextSmaller","asc",t[0].length,la):da(t,r,"strict",t[0].length,la),zr((()=>l>-1),s("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",Gr(e))),t[o-1][l]},isExported:!0},tu={description:s("Search a range for a match and return the corresponding item from a second range."),args:Lr(`\n search_key (any) ${s("The value to search for.")}\n lookup_range (any, range) ${s("The range to consider for the search. Should be a single column or a single row.")}\n return_range (any, range) ${s("The range containing the return value. Should have the same dimensions as lookup_range.")}\n if_not_found (any, lazy, optional) ${s("If a valid match is not found, return this value.")}\n match_mode (any, default=0) ${s("(0) Exact match. (-1) Return next smaller item if no match. (1) Return next greater item if no match.")}\n search_mode (any, default=1) ${s("(1) Search starting at first item. (-1) Search starting at last item. (2) Perform a binary search that relies on lookup_array being sorted in ascending order. If not sorted, invalid results will be returned. (-2) Perform a binary search that relies on lookup_array being sorted in descending order. If not sorted, invalid results will be returned. ")}\n\n `),returns:["ANY"],compute:function(e,t,i,n,o=0,r=1){const a=Math.trunc(Hr(o)),l=Math.trunc(Hr(r)),c=Zr(e);zr((()=>1===t.length||1===t[0].length),s("lookup_range should be either a single row or single column.")),zr((()=>1===i.length||1===i[0].length),s("return_range should be either a single row or single column.")),zr((()=>i.length===t.length&&i[0].length===t[0].length),s("return_range should have the same dimensions as lookup_range.")),zr((()=>[-1,1,-2,2].includes(l)),s("searchMode should be a value in [-1, 1, -2, 2].")),zr((()=>[-1,0,1].includes(a)),s("matchMode should be a value in [-1, 0, 1]."));const h=1===t.length?la:ca,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=ha(t,c,u,2===l?"asc":"desc",d,h)}else p=da(t,c,u,d,h,g);if(-1!==p)return 1===t.length?i[0][p]:i[p][0];const m=null==n?void 0:n();return zr((()=>!!m),s("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",Gr(e))),m},isExported:!0};var iu=Object.freeze({__proto__:null,COLUMN:qd,COLUMNS:Zd,HLOOKUP:jd,INDEX:Yd,LOOKUP:Xd,MATCH:Kd,ROW:Qd,ROWS:Jd,VLOOKUP:eu,XLOOKUP:tu});const nu={description:s("Sum of two numbers."),args:Lr(`\n value1 (number) ${s("The first addend.")}\n value2 (number) ${s("The second addend.")}\n `),returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return Hr(e)+Hr(t)}},ou={description:s("Concatenation of two values."),args:Lr(`\n value1 (string) ${s("The value to which value2 will be appended.")}\n value2 (string) ${s("The value to append to value1.")}\n `),returns:["STRING"],compute:function(e,t){return Gr(e)+Gr(t)},isExported:!0},su={description:s("One number divided by another."),args:Lr(`\n dividend (number) ${s("The number to be divided.")}\n divisor (number) ${s("The number to divide by.")}\n `),returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){const i=Hr(t);return zr((()=>0!==i),s("The divisor must be different from zero.")),Hr(e)/i}};function ru(e){return null==e}const au={number:0,string:"",boolean:!1},lu={description:s("Equal."),args:Lr(`\n value1 (any) ${s("The first value.")}\n value2 (any) ${s("The value to test against value1 for equality.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return e=ru(e)?au[typeof t]:e,t=ru(t)?au[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function cu(e,t,i){e=ru(e)?au[typeof t]:e,t=ru(t)?au[typeof e]:t,"number"!=typeof e&&(e=Gr(e).toUpperCase()),"number"!=typeof t&&(t=Gr(t).toUpperCase());const n=typeof e,o=typeof t;return"string"===n&&"number"===o||("string"!==o||"number"!==n)&&i(e,t)}const hu={description:s("Strictly greater than."),args:Lr(`\n value1 (any) ${s("The value to test as being greater than value2.")}\n value2 (any) ${s("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return cu(e,t,((e,t)=>e>t))}},du={description:s("Greater than or equal to."),args:Lr(`\n value1 (any) ${s("The value to test as being greater than or equal to value2.")}\n value2 (any) ${s("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return cu(e,t,((e,t)=>e>=t))}},uu={description:s("Less than."),args:Lr(`\n value1 (any) ${s("The value to test as being less than value2.")}\n value2 (any) ${s("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!du.compute(e,t)}},gu={description:s("Less than or equal to."),args:Lr(`\n value1 (any) ${s("The value to test as being less than or equal to value2.")}\n value2 (any) ${s("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!hu.compute(e,t)}},pu={description:s("Difference of two numbers."),args:Lr(`\n value1 (number) ${s("The minuend, or number to be subtracted from.")}\n value2 (number) ${s("The subtrahend, or number to subtract from value1.")}\n `),returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return Hr(e)-Hr(t)}},mu={description:s("Product of two numbers"),args:Lr(`\n factor1 (number) ${s("The first multiplicand.")}\n factor2 (number) ${s("The second multiplicand.")}\n `),returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return Hr(e)*Hr(t)}},fu={description:s("Not equal."),args:Lr(`\n value1 (any) ${s("The first value.")}\n value2 (any) ${s("The value to test against value1 for inequality.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!lu.compute(e,t)}},vu={description:s("A number raised to a power."),args:Lr(`\n base (number) ${s("The number to raise to the exponent power.")}\n exponent (number) ${s("The exponent to raise base to.")}\n `),returns:["NUMBER"],compute:function(e,t){return el.compute(e,t)}},bu={description:s("A number with the sign reversed."),args:Lr(`\n value (number) ${s("The number to have its sign reversed. Equivalently, the number to multiply by -1.")}\n `),computeFormat:e=>null==e?void 0:e.format,returns:["NUMBER"],compute:function(e){return-Hr(e)}},Su={description:s("Value interpreted as a percentage."),args:Lr(`\n percentage (number) ${s("The value to interpret as a percentage.")}\n `),returns:["NUMBER"],compute:function(e){return Hr(e)/100}},Cu={description:s("A specified number, unchanged."),args:Lr(`\n value (any) ${s("The number to return.")}\n `),returns:["ANY"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){return null===e?"":e}};var Eu=Object.freeze({__proto__:null,ADD:nu,CONCAT:ou,DIVIDE:su,EQ:lu,GT:hu,GTE:du,LT:uu,LTE:gu,MINUS:pu,MULTIPLY:mu,NE:fu,POW:vu,UMINUS:bu,UNARY_PERCENT:Su,UPLUS:Cu});const wu=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,yu={description:s("Gets character associated with number."),args:Lr(`\n table_number (number) ${s("The number of the character to look up from the current Unicode table in decimal format.")}\n `),returns:["STRING"],compute:function(e){const t=Math.trunc(Hr(e));return zr((()=>t>=1),s("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},xu={description:s("Remove non-printable characters from a piece of text."),args:Lr(`\n text (string) ${s("The text whose non-printable characters are to be removed.")}\n `),returns:["STRING"],compute:function(e){const t=Gr(e);let i="";for(const e of t)e&&e.charCodeAt(0)>31&&(i+=e);return i},isExported:!0},Ru={description:s("Appends strings to one another."),args:Lr(`\n string1 (string, range<string>) ${s("The initial string.")}\n string2 (string, range<string>, repeating) ${s("More strings to append in sequence.")}\n `),returns:["STRING"],compute:function(...e){return ta(e,((e,t)=>e+Gr(t)),"")},isExported:!0},Iu={description:s("Tests whether two strings are identical."),args:Lr(`\n string1 (string) ${s("The first string to compare.")}\n string2 (string) ${s("The second string to compare.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return Gr(e)===Gr(t)},isExported:!0},Tu={description:s("First position of string found in text, case-sensitive."),args:Lr(`\n search_for (string) ${s("The string to look for within text_to_search.")}\n text_to_search (string) ${s("The text to search for the first occurrence of search_for.")}\n starting_at (number, default=1) ${s("The character within text_to_search at which to start the search.")}\n `),returns:["NUMBER"],compute:function(e,t,i=1){const n=Gr(e),o=Gr(t),r=Hr(i);zr((()=>""!==o),s("The text_to_search must be non-empty.")),zr((()=>r>=1),s("The starting_at (%s) must be greater than or equal to 1.",r.toString()));const a=o.indexOf(n,r-1);return zr((()=>a>=0),s("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",n.toString(),o)),a+1},isExported:!0},Au={description:s("Concatenates elements of arrays with delimiter."),args:Lr(`\n delimiter (string) ${s("The character or string to place between each concatenated value.")}\n value_or_array1 (string, range<string>) ${s("The value or values to be appended using delimiter.")}\n value_or_array2 (string, range<string>, repeating) ${s("More values to be appended using delimiter.")}\n `),returns:["STRING"],compute:function(e,...t){const i=Gr(e);return ta(t,((e,t)=>(e?e+i:"")+Gr(t)),"")}},Ou={description:s("Substring from beginning of specified string."),args:Lr(`\n text (string) ${s("The string from which the left portion will be returned.")}\n number_of_characters (number, optional) ${s("The number of characters to return from the left side of string.")}\n `),returns:["STRING"],compute:function(e,...t){const i=t.length?Hr(t[0]):1;return zr((()=>i>=0),s("The number_of_characters (%s) must be positive or null.",i.toString())),Gr(e).substring(0,i)},isExported:!0},Nu={description:s("Length of a string."),args:Lr(`\n text (string) ${s("The string whose length will be returned.")}\n `),returns:["NUMBER"],compute:function(e){return Gr(e).length},isExported:!0},Mu={description:s("Converts a specified string to lowercase."),args:Lr(`\n text (string) ${s("The string to convert to lowercase.")}\n `),returns:["STRING"],compute:function(e){return Gr(e).toLowerCase()},isExported:!0},_u={description:s("A segment of a string."),args:Lr(`\n text (string) ${s("The string to extract a segment from.")}\n starting_at (number) ${s("The index from the left of string from which to begin extracting. The first character in string has the index 1.")}\n extract_length (number) ${s("The length of the segment to extract.")}\n `),returns:["STRING"],compute:function(e,t,i){const n=Gr(e),o=Hr(t),r=Hr(i);return zr((()=>o>=1),s("The starting_at argument (%s) must be positive greater than one.",o.toString())),zr((()=>r>=0),s("The extract_length argument (%s) must be positive or null.",r.toString())),n.slice(o-1,o+r-1)},isExported:!0},Fu={description:s("Capitalizes each word in a specified string."),args:Lr(`\n text_to_capitalize (string) ${s("The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase.")}\n `),returns:["STRING"],compute:function(e){return Gr(e).replace(wu,(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()))},isExported:!0},Du={description:s("Replaces part of a text string with different text."),args:Lr(`\n text (string) ${s("The text, a part of which will be replaced.")}\n position (number) ${s("The position where the replacement will begin (starting from 1).")}\n length (number) ${s("The number of characters in the text to be replaced.")}\n new_text (string) ${s("The text which will be inserted into the original text.")}\n `),returns:["STRING"],compute:function(e,t,i,n){const o=Hr(t);zr((()=>o>=1),s("The position (%s) must be greater than or equal to 1.",o.toString()));const r=Gr(e),a=Hr(i),l=Gr(n);return r.substring(0,o-1)+l+r.substring(o-1+a)},isExported:!0},ku={description:s("A substring from the end of a specified string."),args:Lr(`\n text (string) ${s("The string from which the right portion will be returned.")}\n number_of_characters (number, optional) ${s("The number of characters to return from the right side of string.")}\n `),returns:["STRING"],compute:function(e,...t){const i=t.length?Hr(t[0]):1;zr((()=>i>=0),s("The number_of_characters (%s) must be positive or null.",i.toString()));const n=Gr(e),o=n.length;return n.substring(o-i,o)},isExported:!0},$u={description:s("First position of string found in text, ignoring case."),args:Lr(`\n search_for (string) ${s("The string to look for within text_to_search.")}\n text_to_search (string) ${s("The text to search for the first occurrence of search_for.")}\n starting_at (number, default=1) ${s("The character within text_to_search at which to start the search.")}\n `),returns:["NUMBER"],compute:function(e,t,i=1){const n=Gr(e).toLowerCase(),o=Gr(t).toLowerCase(),r=Hr(i);zr((()=>""!==o),s("The text_to_search must be non-empty.")),zr((()=>r>=1),s("The starting_at (%s) must be greater than or equal to 1.",r.toString()));const a=o.indexOf(n,r-1);return zr((()=>a>=0),s("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",n,o)),a+1},isExported:!0},Lu={description:s("Replaces existing text with new text in a string."),args:Lr(`\n text_to_search (string) ${s("The text within which to search and replace.")}\n search_for (string) ${s("The string to search for within text_to_search.")}\n replace_with (string) ${s("The string that will replace search_for.")}\n occurrence_number (number, optional) ${s("The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n){const o=Hr(n);zr((()=>o>=0),s("The occurrenceNumber (%s) must be positive or null.",o.toString()));const r=Gr(e),a=Gr(t);if(""===a)return r;const l=Gr(i),c=new RegExp(Te(a),"g");if(0===o)return r.replace(c,l);let h=0;return r.replace(c,(e=>++h===o?l:e))},isExported:!0},Pu={description:s("Combines text from multiple strings and/or arrays."),args:Lr(`\n delimiter (string) ${s(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")}\n ignore_empty (boolean) ${s("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")}\n text1 (string, range<string>) ${s("Any text item. This could be a string, or an array of strings in a range.")}\n text2 (string, range<string>, repeating) ${s("Additional text item(s).")}\n `),returns:["STRING"],compute:function(e,t,...i){const n=Gr(e),o=Yr(t);let s=0;return ta(i,((e,t)=>o&&""===Gr(t)?e:(s++?e+n:"")+Gr(t)),"")},isExported:!0},Uu={description:s("Removes space characters."),args:Lr(`\n text (string) ${s("The text or reference to a cell containing text to be trimmed.")}\n `),returns:["STRING"],compute:function(e){return Gr(e).trim()},isExported:!0},Vu={description:s("Converts a specified string to uppercase."),args:Lr(`\n text (string) ${s("The string to convert to uppercase.")}\n `),returns:["STRING"],compute:function(e){return Gr(e).toUpperCase()},isExported:!0},zu={description:s("Converts a number to text according to a specified format."),args:Lr(`\n number (number) ${s("The number, date or time to format.")}\n format (string) ${s("The pattern by which to format the number, enclosed in quotation marks.")}\n `),returns:["STRING"],compute:function(e,t){return Qt(Hr(e),Gr(t))},isExported:!0};const Bu={database:yc,date:ih,financial:Id,info:$d,lookup:iu,logical:Gd,math:bl,misc:pa,operators:Eu,statistical:lc,text:Object.freeze({__proto__:null,CHAR:yu,CLEAN:xu,CONCATENATE:Ru,EXACT:Iu,FIND:Tu,JOIN:Au,LEFT:Ou,LEN:Nu,LOWER:Mu,MID:_u,PROPER:Fu,REPLACE:Du,RIGHT:ku,SEARCH:$u,SUBSTITUTE:Lu,TEXTJOIN:Pu,TRIM:Uu,UPPER:Vu,TEXT:zu}),engineering:oh},Hu=/^[A-Z0-9\_\.]+$/;function Wu(e){return e.map((e=>{if(void 0!==e)return"function"==typeof e?()=>Gu(e()):Gu(e)}))}function Gu(e){return Array.isArray(e)?e.map((e=>e.map((e=>null==e?void 0:e.value)))):null==e?void 0:e.value}const qu=new class extends nn{constructor(){super(...arguments),this.mapping={}}add(e,t){if(!(e=e.toUpperCase()).match(Hu))throw new Error(s("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const i=Ur(t);return function(e){let t=!1,i=!1,n=!1;for(let o of e){if(o.type.includes("META")&&o.type.length>1)throw new Error(s("Function ${name} has an argument that has been declared with more than one type whose type 'META'. The 'META' type can only be declared alone."));if(t&&!o.repeating)throw new Error(s("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=i||t||n,r=!(o.optional||o.repeating||o.default);if(e&&r)throw new Error(s("Function ${name} has at mandatory arguments declared after optional ones. All optional arguments must be after all mandatory arguments."));t=o.repeating,i=o.optional,n=o.default}}(i.args),this.mapping[e]=function(...e){const t=i.compute.bind(this),n=i.computeFormat?i.computeFormat.bind(this):()=>{};return{value:t(...Wu(e)),format:n(...e)}},super.add(e,i),this}};for(let e in Bu){const t=Bu[e];for(let i in t){const n=t[i];n.category=e,i=i.replace(/_/g,"."),qu.add(i,{isExported:!1,...n})}}const Zu=qu.content,ju=["%"],Yu="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(ju);function Xu(e){const t=e.split(""),i=[];for(;t.length;){let e=lg(t)||Ju(t)||tg(t)||ng(t)||Ku(t)||cg(t)||ig(t)||rg(t);e||(e={type:"UNKNOWN",value:t.shift()}),i.push(e)}return i}function Ku(e){return"?"===e[0]?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const Qu={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function Ju(e){if(e[0]in Qu){const t=e.shift();return{type:Qu[t],value:t}}return null}function eg(e,t){for(let i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0}function tg(e){for(let t of Yu)if(eg(e,t))return e.splice(0,t.length),{type:"OPERATOR",value:t};return null}function ig(e){const t=et(e).match(pi);return t?(e.splice(0,t[0].length),{type:"NUMBER",value:t[0]}):null}function ng(e){if('"'===e[0]){const t=e.shift();let i=t;for(;e[0]&&(e[0]!==t||"\\"===i[i.length-1]);)i+=e.shift();return'"'===e[0]&&(i+=e.shift()),{type:"STRING",value:i}}return null}const og=/\p{L}|\p{N}|_|\.|!|\$/u,sg=new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$");function rg(e){let t="";if("'"===e[0]){let i=e.shift();for(t+=i;e[0];)if(i=e.shift(),t+=i,"'"===i){if(!e[0]||"'"!==e[0])break;i=e.shift(),t+=i}if("'"!==i)return{type:"UNKNOWN",value:t}}for(;e[0]&&(sg.has(e[0])||e[0].match(og));)t+=e.shift();if(t.length){const e=t;if(e.toUpperCase()in Zu)return{type:"FUNCTION",value:e};return e.match(Nt)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}const ag=/\s/;function lg(e){let t="";for(;e[0]&&e[0].match(ag);)t+=e.shift();return t?{type:"SPACE",value:t}:null}function cg(e){return eg(e,X)?(e.splice(0,X.length),{type:"INVALID_REFERENCE",value:X}):null}var hg;!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"}(hg||(hg={}));const dg=(e,t=(()=>!0))=>[{goTo:e,guard:t}],ug=(e,t=(()=>!0))=>({goTo:e,guard:t}),gg={[hg.LeftRef]:{REFERENCE:dg(hg.Separator),NUMBER:dg(hg.FullRowSeparator),SYMBOL:[ug(hg.FullColumnSeparator,(e=>Mt(e.value))),ug(hg.FullRowSeparator,(e=>_t(e.value)))]},[hg.FullColumnSeparator]:{SPACE:dg(hg.FullColumnSeparator),OPERATOR:dg(hg.RightColumnRef,(e=>":"===e.value))},[hg.FullRowSeparator]:{SPACE:dg(hg.FullRowSeparator),OPERATOR:dg(hg.RightRowRef,(e=>":"===e.value))},[hg.Separator]:{SPACE:dg(hg.Separator),OPERATOR:dg(hg.RightRef,(e=>":"===e.value))},[hg.RightRef]:{SPACE:dg(hg.RightRef),NUMBER:dg(hg.Found),REFERENCE:dg(hg.Found,(e=>kt(e.value))),SYMBOL:dg(hg.Found,(e=>Ft(e.value)||Dt(e.value)))},[hg.RightColumnRef]:{SPACE:dg(hg.RightColumnRef),SYMBOL:dg(hg.Found,(e=>Ft(e.value))),REFERENCE:dg(hg.Found,(e=>kt(e.value)))},[hg.RightRowRef]:{SPACE:dg(hg.RightRowRef),NUMBER:dg(hg.Found),REFERENCE:dg(hg.Found,(e=>kt(e.value))),SYMBOL:dg(hg.Found,(e=>Dt(e.value)))},[hg.Found]:{}};function pg(e){var t;let i=0,n=gg[hg.LeftRef],o="";for(;void 0!==n;){const s=e[i++];if(!s)return null;const r=null===(t=n[s.type])||void 0===t?void 0:t.find((e=>e.guard(s))),a=r?r.goTo:void 0;switch(a){case void 0:return null;case hg.Found:return o+=s.value,e.splice(0,i),{type:"REFERENCE",value:o};default:n=gg[a],o+=s.value}}return null}function mg(e){const t=Xu(e),i=[];for(;t.length;)i.push(pg(t)||t.shift());return i}const fg=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,vg=["-","+"],bg=["%"],Sg=["*","+","&"],Cg={"^":30,"%":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10},Eg=6;function wg(e){switch(e.type){case"NUMBER":case"SYMBOL":case"REFERENCE":return 0;case"COMMA":return 3;case"LEFT_PAREN":case"RIGHT_PAREN":return 5;case"OPERATOR":return Cg[e.value]||15}throw new Error(s("Unknown token: %s",e.value))}function yg(e,t,i){if("OPERATOR"===t.type){const n=wg(t);if(bg.includes(t.value))return{type:"UNARY_OPERATION",value:t.value,operand:e,postfix:!0};{const o=xg(i,n);return{type:"BIN_OPERATION",value:t.value,left:e,right:o}}}throw new Error(ne)}function xg(e,t){const i=e.shift();if(!i)throw new Error(ne);let n=function(e,t){var i,n,o,r;switch(e.type){case"DEBUGGER":const l=xg(t,1e3);return l.debug=!0,l;case"NUMBER":return{type:"NUMBER",value:wi(e.value)};case"STRING":return{type:"STRING",value:Ie(e.value)};case"FUNCTION":if("LEFT_PAREN"!==t.shift().type)throw new Error(s("Wrong function call"));{const n=[];if(t[0]&&"RIGHT_PAREN"!==t[0].type)for("COMMA"===t[0].type?n.push({type:"UNKNOWN",value:""}):n.push(xg(t,Eg));"COMMA"===(null===(i=t[0])||void 0===i?void 0:i.type);){t.shift();const e=t[0];if("RIGHT_PAREN"===(null==e?void 0:e.type)){n.push({type:"UNKNOWN",value:""});break}"COMMA"===(null==e?void 0:e.type)?n.push({type:"UNKNOWN",value:""}):n.push(xg(t,Eg))}const o=t.shift();if(!o||"RIGHT_PAREN"!==o.type)throw new Error(s("Wrong function call"));return{type:"FUNCALL",value:e.value,args:n}}case"INVALID_REFERENCE":return{type:"REFERENCE",value:a.InvalidReference};case"REFERENCE":if(":"===(null===(n=t[0])||void 0===n?void 0:n.value)&&"REFERENCE"===(null===(o=t[1])||void 0===o?void 0:o.type)){t.shift();const i=t.shift();return{type:"REFERENCE",value:`${e.value}:${null==i?void 0:i.value}`}}return{type:"REFERENCE",value:e.value};case"SYMBOL":if(["TRUE","FALSE"].includes(e.value.toUpperCase()))return{type:"BOOLEAN",value:"TRUE"===e.value.toUpperCase()};if(e.value){if(fg.test(e.value)&&"LEFT_PAREN"===(null===(r=t[0])||void 0===r?void 0:r.type))throw new p(e.value);throw new Error(s("Invalid formula"))}return{type:"STRING",value:e.value};case"LEFT_PAREN":const c=xg(t,5);if(!t.length||"RIGHT_PAREN"!==t[0].type)throw new Error(s("Unmatched left parenthesis"));return t.shift(),c;default:if("OPERATOR"===e.type&&vg.includes(e.value))return{type:"UNARY_OPERATION",value:e.value,operand:xg(t,Cg[e.value])};throw new Error(s("Unexpected token: %s",e.value))}}(i,e);for(;e[0]&&wg(e[0])>t;)n=yg(n,e.shift(),e);return n}function Rg(e){return Ig(mg(e))}function Ig(e){(e=e.filter((e=>"SPACE"!==e.type)))[0]&&"OPERATOR"===e[0].type&&"="===e[0].value&&e.splice(0,1);const t=xg(e,0);if(e.length)throw new Error(ne);return t}function Tg(e,t,i){switch(t===e.type&&(e=i(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>Tg(e,t,i)))};case"UNARY_OPERATION":return{...e,operand:Tg(e.operand,t,i)};case"BIN_OPERATION":return{...e,right:Tg(e.right,t,i),left:Tg(e.left,t,i)};default:return e}}function Ag(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>Ag(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?Og(e)+e.value:e.value+Ng(e);case"BIN_OPERATION":return Og(e)+e.value+Ng(e)}}function Og(e){const t=e.value,i="left"in e?e.left:e.operand,n=i.value;return"BIN_OPERATION"===i.type&&Cg[n]<Cg[t]?`(${Ag(i)})`:Ag(i)}function Ng(e){const t=e.value,i="right"in e?e.right:e.operand,n=Cg[i.value],o=Cg[t];let s=!1;return"BIN_OPERATION"!==i.type?s=!1:n<o?s=!0:n!==o||Sg.includes(t)||(s=!0),s?`(${Ag(i)})`:Ag(i)}const Mg=qu.content,_g={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},Fg={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"};function Dg(e){return e.join("\n").split("\n").filter((e=>""!==e.trim()))}const kg={};function $g(e){const t=mg(e),{dependencies:i,constantValues:n}=function(e){const t={numbers:[],strings:[]},i=[];for(const n of e)switch(n.type){case"INVALID_REFERENCE":case"REFERENCE":i.push(n.value);break;case"STRING":const e=Ie(n.value);t.strings.includes(e)||t.strings.push(e);break;case"NUMBER":{const e=wi(n.value);t.numbers.includes(e)||t.numbers.push(e);break}}return{dependencies:i,constantValues:t}}(t),o=function(e,t,i){return et(e.map((e=>{switch(e.type){case"STRING":const n=Ie(e.value);return`|S${i.strings.indexOf(n)}|`;case"NUMBER":return`|N${i.numbers.indexOf(wi(e.value))}|`;case"REFERENCE":case"INVALID_REFERENCE":return`|${t.indexOf(e.value)}|`;case"SPACE":return"";default:return e.value}})))}(t,i,n);if(!kg[o]){const r=Ig([...t]);let a=1;if("BIN_OPERATION"===r.type&&":"===r.value)throw new Error(s("Invalid formula"));if("UNKNOWN"===r.type)throw new Error(s("Invalid formula"));const l=u(r),c=Dg([`// ${o}`,l.code,`return ${l.id};`]).join("\n");let h=new Function("deps","ref","range","ctx",c);function d(e){const t=Mg[e.value.toUpperCase()],i=e.args,n=i.length;if(n<t.minArgRequired)throw new Error(s("Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.",e.value.toUpperCase(),t.minArgRequired.toString(),n.toString()));if(n>t.maxArgPossible)throw new Error(s("Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.",e.value.toUpperCase(),t.maxArgPossible.toString(),n.toString()));const o=t.nbrArgRepeating;if(o>1){const i=t.args.length-o;if((n-i)%o!=0)throw new Error(s("Invalid number of arguments for the %s function. Expected all arguments after position %s to be supplied by groups of %s arguments",e.value.toUpperCase(),i.toString(),o.toString()))}let r=[];for(let o=0;o<n;o++){const n=t.getArgToFocus(o+1)-1;if(0<=n&&n<t.args.length){const a=i[o],l=t.args[n],c=l.type||[],h=c.includes("META"),d=l.lazy,g=c.some((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e)),p=c.every((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e));if(p&&"REFERENCE"!==a.type)throw new Error(s("Function %s expects the parameter %s to be reference to a cell or range, not a %s.",e.value.toUpperCase(),(o+1).toString(),a.type.toLowerCase()));const m=u(a,d,h,g,{functionName:e.value.toUpperCase(),paramIndex:o+1});r.push(m)}}return r}function u(e,t=!1,o=!1,r=!1,l={}){const c=[];let h,g,p;if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&o)throw new Error(s("Argument must be a reference to a cell or range."));switch(e.debug&&c.push("debugger;"),e.type){case"BOOLEAN":if(!t)return{id:`{ value: ${e.value} }`,code:""};h=a++,p=`{ value: ${e.value} }`;break;case"NUMBER":h=a++,p=`{ value: this.constantValues.numbers[${n.numbers.indexOf(e.value)}] }`;break;case"STRING":h=a++,p=`{ value: this.constantValues.strings[${n.strings.indexOf(e.value)}] }`;break;case"REFERENCE":const s=i.indexOf(e.value);h=a++,p=r?`range(deps[${s}])`:`ref(deps[${s}], ${o?"true":"false"}, "${l.functionName||_g["="]}", ${l.paramIndex})`;break;case"FUNCALL":h=a++;const m=d(e);c.push(m.map((e=>e.code)).join("\n")),g=e.value.toUpperCase(),c.push(`ctx.__lastFnCalled = '${g}';`),p=`ctx['${g}'](${m.map((e=>e.id))})`;break;case"UNARY_OPERATION":{h=a++,g=Fg[e.value];const t=u(e.operand,!1,!1,!1,{functionName:g});c.push(t.code),c.push(`ctx.__lastFnCalled = '${g}';`),p=`ctx['${g}'](${t.id})`;break}case"BIN_OPERATION":{h=a++,g=_g[e.value];const t=u(e.left,!1,!1,!1,{functionName:g}),i=u(e.right,!1,!1,!1,{functionName:g});c.push(t.code),c.push(i.code),c.push(`ctx.__lastFnCalled = '${g}';`),p=`ctx['${g}'](${t.id}, ${i.id})`;break}case"UNKNOWN":if(!t)return{id:"undefined",code:""};h=a++,p="undefined"}if(t){return{id:`_${h}`,code:`const _${h} = () => {\n\t${Dg(c).join("\n\t")}\n\treturn ${p};\n}`}}return c.push(`let _${h} = ${p};`),{id:`_${h}`,code:c.join("\n")}}kg[o]={execute:h}}return{execute:kg[o].execute,dependencies:i,constantValues:n,tokens:t}}function Lg(e){return function(e){let t=[],i="";return e.map(((e,n)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(i=""),e.type){case"FUNCTION":i=e.value;break;case"LEFT_PAREN":t.push({parent:i,argPosition:0}),i="";break;case"RIGHT_PAREN":t.pop();break;case"COMMA":t.length&&t[t.length-1].argPosition++}if(t.length){const i=t[t.length-1];i.parent&&(e.functionContext=Object.assign({},i))}return e}))}(function(e){let t=1;const i=[];return e.map((e=>("LEFT_PAREN"===e.type?(i.push(t),e.parenIndex=t,t++):"RIGHT_PAREN"===e.type&&(e.parenIndex=i.pop()),e)))}(function(e){let t=0;return e.map((e=>{const i=e.value.toString().length,n=Object.assign({},e,{start:t,end:t+i,length:i});return t=n.end,n}))}(mg(e))))}function Pg(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:i}=$t(e.value),[n,o]=t.split(":"),s=i?`${Ne(i)}!`:"",r=Ug(n),a=o?`:${Ug(o)}`:"";return{...e,value:s+r+a}}function Ug(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=Vg(e,"colrow");break;case"colrow":e=Vg(e,"row");break;case"row":e=Vg(e,"col");break;case"col":e=Vg(e,"none")}return e}function Vg(e,t){let i;switch(e=e.replace(/\$/g,""),t){case"col":return"$"+e;case"row":return i=e.search(/[0-9]/),e.slice(0,i)+"$"+e.slice(i);case"colrow":return i=e.search(/[0-9]/),-1===i||0===i?"$"+e:"$"+(e=e.slice(0,i)+"$"+e.slice(i));case"none":return e}}class zg{constructor(e,t,i){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t}exportForExcel(e){}allowDispatch(e){return 0}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map((e=>e.call(this,t))).flat()}chainValidations(...e){return t=>{for(const i of e){let e=i.call(this,t);Array.isArray(e)||(e=[e]);const n=e.filter((e=>0!==e));if(n.length)return n}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}zg.getters=[];class Bg extends zg{constructor(e,t,i,n,o){super(t,i,n),this.getters=e,this.ui=n,this.selection=o}drawGrid(e,t){}}Bg.layers=[];const Hg=s("The cell you are trying to edit has been deleted.");class Wg extends Bg{constructor(){super(...arguments),this.col=0,this.row=0,this.mode="inactive",this.sheetId="",this.currentContent="",this.currentTokens=[],this.selectionStart=0,this.selectionEnd=0,this.selectionInitialStart=0,this.initialContent="",this.previousRef="",this.previousRange=void 0,this.colorIndexByRange={}}allowDispatch(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":return this.validateSelection(this.currentContent.length,e.start,e.end);case"SET_CURRENT_CONTENT":return e.selection?this.validateSelection(e.content.length,e.selection.start,e.selection.end):0;case"START_EDITION":if(e.selection){const t=this.getters.getActiveCell(),i=e.text||(null==t?void 0:t.composerContent)||"";return this.validateSelection(i.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":this.startEdition(e.text,e.selection),this.updateRangeColor();break;case"STOP_EDITION":e.cancel?(this.resetContent(),this.cancelEditionAndActivateSheet()):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.resetContent(),this.cancelEditionAndActivateSheet();break;case"ADD_COLUMNS_ROWS":this.onAddElements(e);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case"START_CHANGE_HIGHLIGHT":this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const t=this.getters.getRangeFromRangeData(e.range),i=this.currentTokens.filter((e=>"REFERENCE"===e.type)).find((e=>{const{xc:i,sheetName:n}=$t(e.value),o=n||this.getters.getSheetName(this.sheetId),s=this.getters.getActiveSheetId();if(!Ai(this.getters.getSheetName(s),o))return!1;const r=this.getters.getRangeFromSheetXC(s,i);return Vi(this.getters.expandZone(s,r.zone),t.zone)}));this.previousRef=i.value,this.previousRange=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),this.previousRef),this.selectionInitialStart=i.start;break;case"CHANGE_HIGHLIGHT":const n=this.getters.getRangeFromRangeData(e.range),o=this.getRangeReference(n,this.previousRange.parts);this.selectionStart=this.selectionInitialStart,this.selectionEnd=this.selectionInitialStart+this.previousRef.length,this.replaceSelection(o),this.previousRef=o,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{col:t,row:i}=this.getters.getNextVisibleCellPosition(e.sheetIdTo,0,0),n=this.getters.expandZone(e.sheetIdTo,Qi({col:t,row:i}));this.selection.resetAnchor(this,{cell:{col:t,row:i},zone:n})}break;case"DELETE_SHEET":case"UNDO":case"REDO":!!this.getters.tryGetSheet(this.sheetId)||"inactive"===this.mode||(this.sheetId=this.getters.getActiveSheetId(),this.resetContent(),this.cancelEditionAndActivateSheet(),this.ui.notifyUI({type:"ERROR",text:Hg}));break;case"CYCLE_EDITION_REFERENCES":this.cycleReferences()}}getEditionMode(){return this.mode}getCurrentContent(){if("inactive"===this.mode){const e=this.getters.getActiveCell();return(null==e?void 0:e.composerContent)||""}return this.currentContent}getEditionSheet(){return this.sheetId}getComposerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}isSelectingForComposer(){return"selecting"===this.mode}showSelectionIndicator(){return this.isSelectingForComposer()&&this.canStartComposerRangeSelection()}getCurrentTokens(){return this.currentTokens}getTokenAtCursor(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return e===t&&0===t?void 0:this.currentTokens.find((i=>i.start<=e&&i.end>=t))}cycleReferences(){const e=this.getTokensInSelection(),t=e.filter((e=>"REFERENCE"===e.type));if(0===t.length)return;const i=e.map(Pg).map((e=>e.value)).join(""),n=this.currentContent,o=e[0].start,s=e[e.length-1].end,r=n.slice(0,o)+i+n.slice(s),a=r.length-n.length,l={start:t[0].start,end:t[t.length-1].end+a};1===t.length&&this.selectionStart===this.selectionEnd&&(l.start=l.end),this.dispatch("SET_CURRENT_CONTENT",{content:r,selection:l})}validateSelection(e,t,i){return t>=0&&t<=e&&i>=0&&i<=e?0:47}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:Hg});const{top:t,left:i}=$i({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",[...e.elements]);this.col=i,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:Hg});const{top:t,left:i}=$i({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",[...e.elements]);this.col=i,this.row=t}onAddElements(e){const{top:t,left:i}=ki({left:this.col,right:this.col,top:this.row,bottom:this.row},"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.col=i,this.row=t}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){const e=Qi({col:this.col,row:this.row});this.selection.resetAnchor(this,{cell:{col:this.col,row:this.row},zone:e})}this.mode="selecting",this.selectionInitialStart=this.selectionStart}startEdition(e,t){var i;const n=this.getters.getActiveCell();e&&(null===(i=null==n?void 0:n.format)||void 0===i?void 0:i.includes("%"))&&Ci(e)&&(t=t||{start:e.length,end:e.length},e=`${e}%`),this.initialContent=(null==n?void 0:n.composerContent)||"",this.mode="editing";const{col:o,row:s}=this.getters.getPosition();this.col=o,this.row=s,this.sheetId=this.getters.getActiveSheetId(),this.setContent(e||this.initialContent,t),this.colorIndexByRange={};const r=Qi({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){const e=this.getters.getActiveSheetId();this.cancelEditionAndActivateSheet();const{col:t,row:i}=this.getters.getMainCellPosition(this.sheetId,this.col,this.row);let n=this.currentContent;if(!(this.initialContent!==n))return;if(n){const o=this.getters.getCell(e,t,i);if(n.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&&(n+=et(new Array(i).fill(")")))}else(null==o?void 0:o.isLink())&&(n=We(n,o.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,col:t,row:i,content:n})}else this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,content:"",col:t,row:i});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})}cancelEdition(){"inactive"!==this.mode&&(this.mode="inactive",this.selection.release(this))}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,i){e=e.replace(/[\r\n]/g,"");const n=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(n||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?Lg(e):[],this.currentTokens.length>100&&i&&this.ui.notifyUI({type:"ERROR",text:s("This formula has over 100 parts. It can't be processed properly, consider splitting it into multiple cells")})),this.canStartComposerRangeSelection()&&this.startComposerRangeSelection()}insertSelectedRange(e){const t=Math.min(this.selectionStart,this.selectionEnd),i=this.getZoneReference(e);this.canStartComposerRangeSelection()?(this.insertText(i,t),this.selectionInitialStart=t):(this.insertText(","+i,t),this.selectionInitialStart=t+1)}replaceSelectedRanges(e){const t=this.getZoneReference(e);this.replaceText(t,this.selectionInitialStart,this.selectionEnd)}getZoneReference(e,t=[{colFixed:!1,rowFixed:!1}]){const i=this.getters.getActiveSheetId();let n=this.getters.zoneToXC(i,e,t);if(this.getters.getEditionSheet()!==this.getters.getActiveSheetId()){n=`${Ne(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${n}`}return n}getRangeReference(e,t=[{colFixed:!1,rowFixed:!1}]){1===t.length&&en(e.zone)>1?t.push({...t[0]}):2===t.length&&1===en(e.zone)&&t.pop();const i=e.clone({parts:this.previousRange.parts});return this.getters.getSelectionRangeString(i,this.getters.getEditionSheet())}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),i=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,i)}replaceText(e,t,i){this.currentContent=this.currentContent.slice(0,t)+this.currentContent.slice(i,this.currentContent.length),this.insertText(e,t)}insertText(e,t){const i=this.currentContent.slice(0,t)+e+this.currentContent.slice(t),n=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:i,selection:{start:n,end:n}})}updateRangeColor(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return;const e=this.getters.getEditionSheet(),t=this.getReferencedRanges().map((t=>this.getters.getRangeString(t,e))),i={};for(const e of t)void 0!==this.colorIndexByRange[e]&&(i[e]=this.colorIndexByRange[e]);const n=new Set(Object.values(i));let o=0;const s=()=>{for(;n.has(o);)o++;return n.add(o),o};for(const e of t){const t=e in i?i[e]:s();i[e]=t}this.colorIndexByRange=i}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=this.getters.getEditionSheet(),t=e=>{const t=this.colorIndexByRange[e];return ut[t%ut.length]};return this.getReferencedRanges().map((i=>{const n=this.getters.getRangeString(i,e);return{zone:i.zone,color:t(n),sheetId:i.sheetId}}))}getReferencedRanges(){const e=this.getters.getEditionSheet();return this.currentTokens.filter((e=>"REFERENCE"===e.type)).map((t=>this.getters.getRangeFromSheetXC(e,t.value))).filter((e=>!e.invalidSheetName&&!e.invalidXc))}canStartComposerRangeSelection(){if(this.currentContent.startsWith("=")){const e=this.getTokenAtCursor();if(!e)return!1;const t=this.currentTokens.map((e=>e.start)).indexOf(e.start);let i=t,n=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(n.type)||ju.includes(n.value);){if("SPACE"!==n.type||i<1)return!1;i--,n=this.currentTokens[i]}for(i=t+1,n=this.currentTokens[i];n&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(n.type);){if("SPACE"!==n.type)return!1;i++,n=this.currentTokens[i]}return!0}return!1}getTokensInSelection(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return this.currentTokens.filter((i=>i.start<=e&&i.end>=e||i.start>=e&&i.start<t))}}Wg.getters=["getEditionMode","isSelectingForComposer","showSelectionIndicator","getCurrentContent","getEditionSheet","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights"];const Gg=qu.content,qg=new nn;qg.add("functions",(()=>Object.keys(Gg).map((e=>({text:e,description:Gg[e].description}))))),wn`
983
+ `;class $r extends t.Component{get tagStyle(){const{col:e,row:t,color:i}=this.props,{height:n}=this.env.model.getters.getSheetViewDimensionWithHeaders(),{x:o,y:s}=this.env.model.getters.getVisibleRect({left:e,top:t,right:e,bottom:t});return`bottom: ${n-s+15}px;left: ${o-1}px;border: 1px solid ${i};background-color: ${i};${this.props.active?"opacity:1 !important":""}`}}$r.template="o-spreadsheet-ClientTag";const Lr=/(.*?)\((.*?)\)(.*)/,Pr=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function Ur(e){let t=e.split("\n");const i=[];for(let e of t)e=e.trim(),e&&i.push(Vr(e));return i}function Vr(e){let t,i=e.match(Lr),n=i[1].trim(),o=[],s=!1,r=!1,a=!1;for(let e of i[2].split(",")){const i=e.trim().toUpperCase();let n=Pr.find((e=>i===e));n?o.push(n):"RANGE<ANY>"===i?o.push("RANGE"):"OPTIONAL"===i?s=!0:"REPEATING"===i?r=!0:"LAZY"===i?a=!0:i.startsWith("DEFAULT=")&&(t=e.trim().slice(8))}const l={name:n,description:i[3].trim(),type:o};return s&&(l.optional=!0),r&&(l.repeating=!0),a&&(l.lazy=!0),void 0!==t&&(l.default=!0,l.defaultValue=t),l}function zr(e){let t=0,i=0,n=0;for(let o of e.args)t++,o.optional||o.repeating||o.default||i++,o.repeating&&n++;const o=e;return o.minArgRequired=i,o.maxArgPossible=n?1/0:t,o.nbrArgRepeating=n,o.getArgToFocus=function(e,t){if(!t)return e=>e;if(1===t)return t=>Math.min(t,e);const i=e-t;return e=>{if(e<=i)return e;return i+((e-i)%t||t)}}(t,n),o}const Br=["number","string","boolean","undefined"];function Hr(e,t){if(!e())throw new Error(t)}const Wr=e=>s("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function Gr(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(Ci(e)||""===e)return wi(e);const t=ve(e);if(t)return t.value;throw new Error(Wr(e));default:return 0}}function qr(e){if(""===e)throw new Error(Wr(e));return Gr(e)}function Zr(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}const jr=function(e){const t=new Map,i=e.name?e.name+" (memoized)":"memoized";return{[i]:(...i)=>(t.has(i[0])||t.set(i[0],e(...i)),t.get(i[0]))}[i]}((function(e){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"")}));function Yr(e){return"string"==typeof e?jr(e):e}const Xr=e=>s("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function Kr(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(Xr(e))}return!1;case"number":return!!e;default:return!1}}function Qr(e){return Se(Gr(e))}function Jr(e,t,i){for(let n of e)if(Array.isArray(n)){const e=n.length,i=n[0].length;for(let o=0;o<i;o++)for(let i=0;i<e;i++)t(n[i][o])}else i(n)}function ea(e,t){Jr(e,t,t)}function ta(e,t){Jr(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(qr(e))}))}function ia(e,t,i,n){let o=n;for(let n of e)if(Array.isArray(n)){const e=n.length,i=n[0].length;for(let s=0;s<i;s++)for(let i=0;i<e;i++)o=t(o,n[i][s])}else o=i(o,n);return o}function na(e,t,i){return ia(e,t,t,i)}function oa(e,t,i){return ia(e,((e,i)=>"number"==typeof i?t(e,i):e),((e,i)=>t(e,qr(i))),i)}function sa(e,t,i){return ia(e,((e,i)=>null!=i?t(e,"number"==typeof i?i:"boolean"==typeof i?Gr(i):0):e),((e,i)=>t(e,Gr(i))),i)}function ra(e,t){return function(e,t,i){for(let n of e)if(Array.isArray(n)){const e=n.length,i=n[0].length;for(let o=0;o<i;o++)for(let i=0;i<e;i++)if(!t(n[i][o]))return}else if(!i(n))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error(Xr(e));return Kr(e)}(e))))}function aa(e,t){let i,n,o=e.substring(0,2);"<="===o||">="===o||"<>"===o?(i=o,n=e.substring(2)):(o=e.substring(0,1),"<"===o||">"===o||"="===o?(i=o,n=e.substring(1)):(i="=",n=e)),Ci(n)||Ve(n)?n=Gr(n):"TRUE"!==n&&"FALSE"!==n||(n=Kr(n));const s={operator:i,operand:n};return"string"==typeof n&&(t&&(n+="*"),s.regexp=function(e){if("*"===e)return/.+/;let t="",i="";for(let n of e)"?"===n&&"~"!==i?t+=".":"*"===n&&"~"!==i?t+=".*":("*"!==n&&"?"!==n||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(n)&&(t+="\\"),t+=n),i=n;return new RegExp("^"+t+"$","i")}(n)),s}function la(e="",t){const{operator:i,operand:n}=t;if(void 0===n)return!1;if("number"==typeof n&&"="===i)return"string"==typeof e&&(Ci(e)||Ve(e))?Gr(e)===n:e===n;if("<>"===i||"="===i){let o;return o=typeof e==typeof n&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===n),"="===i?o:!o}if(typeof e==typeof n)switch(i){case"<":return e<n;case">":return e>n;case"<=":return e<=n;case">=":return e>=n}return!1}function ca(e,t,i=!1){const n=e.length;if(n%2==1)throw new Error(s("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const o=e[0].length,r=e[0][0].length;let a=[];for(let t=0;t<n-1;t+=2){const n=e[t];if(!Array.isArray(n)||n.length!==o||n[0].length!==r)throw new Error(s("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=Zr(e[t+1]);a.push(aa(l,i))}for(let i=0;i<o;i++)for(let o=0;o<r;o++){let s=!0;for(let t=0;t<n-1;t+=2){if(s=la(e[t][i][o],a[t/2]),!s)break}s&&t(i,o)}}function ha(e,t){return Yr(e[0][t])}function da(e,t){return Yr(e[t][0])}function ua(e,t,i,n,o,s){if(null==t)return-1;const r=typeof t;let a,l,c,h,d,u,g=0,p=o-1;const m="desc"===n?t=>s(e,o-t-1):t=>s(e,t);for(;p-g>=0;){for(c=Math.floor((g+p)/2),h=c,d=m(h),u=typeof d;g<h&&r!==u;)h--,d=m(h),u=typeof d;u===r&&void 0!==d?("strict"===i&&d===t?(a=d,l=h):"nextSmaller"===i&&d<=t?(void 0===a||a<d||a===d&&l<h)&&(a=d,l=h):"nextGreater"===i&&d>=t&&(void 0===a||a>d||a===d&&l<h)&&(a=d,l=h),d>t||"strict"===i&&d===t?p=h-1:g=c+1):g=c+1}return void 0===l?-1:"desc"===n?o-l-1:l}function ga(e,t,i,n,o,s=!1){if(null==t)return-1;const r=s?(e,t)=>o(e,n-t-1):o;let a,l=-1;for(let o=0;o<n;o++){const c=r(e,o);if(c===t)return s?n-o-1:o;"nextSmaller"===i?(!a&&pa(t,c)>=0||pa(t,c)>=0&&pa(c,a)>0)&&(a=c,l=o):"nextGreater"===i&&(!a&&pa(t,c)<=0||pa(t,c)<=0&&pa(c,a)<0)&&(a=c,l=o)}return s?n-l-1:l}function pa(e,t){let i=Br.indexOf(typeof e)-Br.indexOf(typeof t);return 0===i&&("string"==typeof e&&"string"==typeof t?i=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?i=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(i=Number(e)-Number(t))),i}const ma={description:s("Apply a large number format"),args:Ur(`\n value (number) ${s("The number.")}\n unit (string, optional) ${s("The formatting unit. Use 'k', 'm', or 'b' to force the unit")}\n `),returns:["NUMBER"],computeFormat:(e,t)=>{const i=Math.abs(Gr(e.value)),n=e.format;if(void 0!==t){switch(null==t?void 0:t.value){case"k":return li(n,1e3,"k");case"m":return li(n,1e6,"m");case"b":return li(n,1e9,"b");default:throw new Error(s("The formatting unit should be 'k', 'm' or 'b'."))}}return i<1e5?li(n,0,""):i<1e8?li(n,1e3,"k"):i<1e11?li(n,1e6,"m"):li(n,1e9,"b")},compute:function(e){return Gr(e)}};var fa=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:ma});const va={description:s("Absolute value of a number."),args:Ur(`\n value (number) ${s("The number of which to return the absolute value.")}\n `),returns:["NUMBER"],compute:function(e){return Math.abs(Gr(e))},isExported:!0},ba={description:s("Inverse cosine of a value, in radians."),args:Ur(`\n value (number) ${s("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=Gr(e);return Hr((()=>Math.abs(t)<=1),s("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},Sa={description:s("Inverse hyperbolic cosine of a number."),args:Ur(`\n value (number) ${s("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.")}\n `),returns:["NUMBER"],compute:function(e){const t=Gr(e);return Hr((()=>t>=1),s("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},Ca={description:s("Inverse cotangent of a value."),args:Ur(`\n value (number) ${s("The value for which to calculate the inverse cotangent.")}\n `),returns:["NUMBER"],compute:function(e){const t=Gr(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},Ea={description:s("Inverse hyperbolic cotangent of a value."),args:Ur(`\n value (number) ${s("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=Gr(e);return Hr((()=>Math.abs(t)>1),s("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},wa={description:s("Inverse sine of a value, in radians."),args:Ur(`\n value (number) ${s("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=Gr(e);return Hr((()=>Math.abs(t)<=1),s("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},ya={description:s("Inverse hyperbolic sine of a number."),args:Ur(`\n value (number) ${s("The value for which to calculate the inverse hyperbolic sine.")}\n `),returns:["NUMBER"],compute:function(e){return Math.asinh(Gr(e))},isExported:!0},xa={description:s("Inverse tangent of a value, in radians."),args:Ur(`\n value (number) ${s("The value for which to calculate the inverse tangent.")}\n `),returns:["NUMBER"],compute:function(e){return Math.atan(Gr(e))},isExported:!0},Ra={description:s("Angle from the X axis to a point (x,y), in radians."),args:Ur(`\n x (number) ${s("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")}\n y (number) ${s("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")}\n `),returns:["NUMBER"],compute:function(e,t){const i=Gr(e),n=Gr(t);return Hr((()=>0!==i||0!==n),s("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(n,i)},isExported:!0},Ia={description:s("Inverse hyperbolic tangent of a number."),args:Ur(`\n value (number) ${s("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=Gr(e);return Hr((()=>Math.abs(t)<1),s("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},Ta={description:s("Rounds number up to nearest multiple of factor."),args:Ur(`\n value (number) ${s("The value to round up to the nearest integer multiple of factor.")}\n factor (number, default=1) ${s("The number to whose multiples value will be rounded.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){const i=Gr(e),n=Gr(t);return Hr((()=>n>=0||i<=0),s("The factor (%s) must be positive when the value (%s) is positive.",n.toString(),i.toString())),n?Math.ceil(i/n)*n:0},isExported:!0},Aa={description:s("Rounds number up to nearest multiple of factor."),args:Ur(`\n number (number) ${s("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${s("The number to whose multiples number will be rounded. The sign of significance will be ignored.")}\n mode (number, default=0) ${s("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1,i=0){let n=Gr(t);if(0===n)return 0;const o=Gr(e);if(n=Math.abs(n),o>=0)return Math.ceil(o/n)*n;return 0===Gr(i)?-Math.floor(Math.abs(o)/n)*n:-Math.ceil(Math.abs(o)/n)*n},isExported:!0},Na={description:s("Rounds number up to nearest multiple of factor."),args:Ur(`\n number (number) ${s("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${s("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){return Aa.compute(e,t,0)},isExported:!0},Oa={description:s("Cosine of an angle provided in radians."),args:Ur(`\n angle (number) ${s("The angle to find the cosine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cos(Gr(e))},isExported:!0},Ma={description:s("Hyperbolic cosine of any real number."),args:Ur(`\n value (number) ${s("Any real value to calculate the hyperbolic cosine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cosh(Gr(e))},isExported:!0},_a={description:s("Cotangent of an angle provided in radians."),args:Ur(`\n angle (number) ${s("The angle to find the cotangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=Gr(e);return Hr((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},Fa={description:s("Hyperbolic cotangent of any real number."),args:Ur(`\n value (number) ${s("Any real value to calculate the hyperbolic cotangent of.")}\n `),returns:["NUMBER"],compute:function(e){const t=Gr(e);return Hr((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},Da={description:s("Number of empty values."),args:Ur(`\n value1 (any, range) ${s("The first value or range in which to count the number of blanks.")}\n value2 (any, range, repeating) ${s("Additional values or ranges in which to count the number of blanks.")}\n `),returns:["NUMBER"],compute:function(...e){return na(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},ka={description:s("A conditional count across a range."),args:Ur(`\n range (range) ${s("The range that is tested against criterion.")}\n criterion (string) ${s("The pattern or test to apply to range.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;return ca(e,((e,i)=>{t+=1})),t},isExported:!0},$a={description:s("Count values depending on multiple criteria."),args:Ur(`\n criteria_range1 (range) ${s("The range to check against criterion1.")}\n criterion1 (string) ${s("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${s("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${s("Additional criteria to check.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;return ca(e,((e,i)=>{t+=1})),t},isExported:!0};function La(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const Pa={description:s("Counts number of unique values in a range."),args:Ur(`\n value1 (any, range) ${s("The first value or range to consider for uniqueness.")}\n value2 (any, range, repeating) ${s("Additional values or ranges to consider for uniqueness.")}\n `),returns:["NUMBER"],compute:function(...e){return na(e,((e,t)=>La(t)?e.add(t):e),new Set).size}},Ua={description:s("Counts number of unique values in a range, filtered by a set of criteria."),args:Ur(`\n range (range) ${s("The range of cells from which the number of unique values will be counted.")}\n criteria_range1 (range) ${s("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${s("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${s("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let i=new Set;return ca(t,((t,n)=>{const o=e[t][n];La(o)&&i.add(o)})),i.size}},Va={description:s("Cosecant of an angle provided in radians."),args:Ur(`\n angle (number) ${s("The angle to find the cosecant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=Gr(e);return Hr((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},za={description:s("Hyperbolic cosecant of any real number."),args:Ur(`\n value (number) ${s("Any real value to calculate the hyperbolic cosecant of.")}\n `),returns:["NUMBER"],compute:function(e){const t=Gr(e);return Hr((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},Ba={description:s("Converts from another base to decimal."),args:Ur(`\n value (string) ${s("The number to convert.")},\n base (number) ${s("The base to convert the value from.")},\n `),returns:["NUMBER"],compute:function(e,t){let i=Gr(t);i=Math.floor(i),Hr((()=>2<=i&&i<=36),s("The base (%s) must be between 2 and 36 inclusive.",i.toString()));const n=Zr(e);if(""===n)return 0;Hr((()=>!!n.match(/^-?[a-z0-9]+$/i)),s("The value (%s) must be a valid base %s representation.",n,i.toString()));const o=parseInt(n,i);return Hr((()=>!isNaN(o)),s("The value (%s) must be a valid base %s representation.",n,i.toString())),o},isExported:!0},Ha={description:s("Converts an angle value in radians to degrees."),args:Ur(`\n angle (number) ${s("The angle to convert from radians to degrees.")}\n `),returns:["NUMBER"],compute:function(e){return 180*Gr(e)/Math.PI},isExported:!0},Wa={description:s("Euler's number, e (~2.718) raised to a power."),args:Ur(`\n value (number) ${s("The exponent to raise e.")}\n `),returns:["NUMBER"],compute:function(e){return Math.exp(Gr(e))},isExported:!0},Ga={description:s("Rounds number down to nearest multiple of factor."),args:Ur(`\n value (number) ${s("The value to round down to the nearest integer multiple of factor.")}\n factor (number, default=1) ${s("The number to whose multiples value will be rounded.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){const i=Gr(e),n=Gr(t);return Hr((()=>n>=0||i<=0),s("The factor (%s) must be positive when the value (%s) is positive.",n.toString(),i.toString())),n?Math.floor(i/n)*n:0},isExported:!0},qa={description:s("Rounds number down to nearest multiple of factor."),args:Ur(`\n number (number) ${s("The value to round down to the nearest integer multiple of significance.")}\n significance (number, default=1) ${s("The number to whose multiples number will be rounded. The sign of significance will be ignored.")}\n mode (number, default=0) ${s("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1,i=0){let n=Gr(t);if(0===n)return 0;const o=Gr(e);if(n=Math.abs(n),o>=0)return Math.floor(o/n)*n;return 0===Gr(i)?-Math.ceil(Math.abs(o)/n)*n:-Math.floor(Math.abs(o)/n)*n},isExported:!0},Za={description:s("Rounds number down to nearest multiple of factor."),args:Ur(`\n number (number) ${s("The value to round down to the nearest integer multiple of significance.")}\n significance (number, default=1) ${s("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){return qa.compute(e,t,0)},isExported:!0},ja={description:s("Whether the provided value is even."),args:Ur(`\n value (number) ${s("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=qr(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},Ya={description:s("Rounds number up to nearest multiple of factor."),args:Ur(`\n number (number) ${s("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${s("The number to whose multiples number will be rounded.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){return Aa.compute(e,t,0)},isExported:!0},Xa={description:s("Whether the provided value is even."),args:Ur(`\n value (number) ${s("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=qr(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},Ka={description:s("The logarithm of a number, base e (euler's number)."),args:Ur(`\n value (number) ${s("The value for which to calculate the logarithm, base e.")}\n `),returns:["NUMBER"],compute:function(e){const t=Gr(e);return Hr((()=>t>0),s("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},Qa={description:s("The logarithm of a number, for a given base."),args:Ur(`\n value (number) ${s("The value for which to calculate the logarithm, base e.")}\n base (number, default=10) ${s("The base of the logarithm.")}\n `),returns:["NUMBER"],compute:function(e,t=10){const i=Gr(e),n=Gr(t);return Hr((()=>i>0),s("The value (%s) must be strictly positive.",i.toString())),Hr((()=>n>0),s("The base (%s) must be strictly positive.",n.toString())),Hr((()=>1!==n),s("The base must be different from 1.")),Math.log10(i)/Math.log10(n)},isExported:!0},Ja={description:s("Modulo (remainder) operator."),args:Ur(`\n dividend (number) ${s("The number to be divided to find the remainder.")}\n divisor (number) ${s("The number to divide by.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){const i=Gr(t);Hr((()=>0!==i),s("The divisor must be different from 0."));const n=Gr(e)%i;return n>0&&i<0||n<0&&i>0?n+i:n},isExported:!0},el={description:s("Rounds a number up to the nearest odd integer."),args:Ur(`\n value (number) ${s("The value to round to the next greatest odd number.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){const t=Gr(e);let i=Math.ceil(Math.abs(t));return i=1&i?i:i+1,t<0?-i:i},isExported:!0},tl={description:s("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},il={description:s("A number raised to a power."),args:Ur(`\n base (number) ${s("The number to raise to the exponent power.")}\n exponent (number) ${s("The exponent to raise base to.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){const i=Gr(e),n=Gr(t);return Hr((()=>i>=0||Number.isInteger(n)),s("The exponent (%s) must be an integer when the base is negative.",n.toString())),Math.pow(i,n)},isExported:!0},nl={description:s("Result of multiplying a series of numbers together."),args:Ur(`\n factor1 (number, range<number>) ${s("The first number or range to calculate for the product.")}\n factor2 (number, range<number>, repeating) ${s("More numbers or ranges to calculate for the product.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0,i=1;for(let n of e)if(Array.isArray(n))for(let e of n)for(let n of e)"number"==typeof n&&(i*=n,t+=1);else null!=n&&(i*=qr(n),t+=1);return 0===t?0:i},isExported:!0},ol={description:s("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},sl={description:s("Random integer between two values, inclusive."),args:Ur(`\n low (number) ${s("The low end of the random range.")}\n high (number) ${s("The high end of the random range.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){let i=Gr(e);Number.isInteger(i)||(i=Math.ceil(i));let n=Gr(t);return Number.isInteger(n)||(n=Math.floor(n)),Hr((()=>i<=n),s("The high (%s) must be greater than or equal to the low (%s).",n.toString(),i.toString())),i+Math.ceil((n-i+1)*Math.random())-1},isExported:!0},rl={description:s("Rounds a number according to standard rules."),args:Ur(`\n value (number) ${s("The value to round to places number of places.")}\n places (number, default=0) ${s("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Gr(e);let n=Gr(t);const o=Math.abs(i);let s;return 0===n?s=Math.round(o):(Number.isInteger(n)||(n=Math.trunc(n)),s=Math.round(o*Math.pow(10,n))/Math.pow(10,n)),i>=0?s:-s},isExported:!0},al={description:s("Rounds down a number."),args:Ur(`\n value (number) ${s("The value to round to places number of places, always rounding down.")}\n places (number, default=0) ${s("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Gr(e);let n=Gr(t);const o=Math.abs(i);let s;return 0===n?s=Math.floor(o):(Number.isInteger(n)||(n=Math.trunc(n)),s=Math.floor(o*Math.pow(10,n))/Math.pow(10,n)),i>=0?s:-s},isExported:!0},ll={description:s("Rounds up a number."),args:Ur(`\n value (number) ${s("The value to round to places number of places, always rounding up.")}\n places (number, default=0) ${s("The number of decimal places to which to round.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Gr(e);let n=Gr(t);const o=Math.abs(i);let s;return 0===n?s=Math.ceil(o):(Number.isInteger(n)||(n=Math.trunc(n)),s=Math.ceil(o*Math.pow(10,n))/Math.pow(10,n)),i>=0?s:-s},isExported:!0},cl={description:s("Secant of an angle provided in radians."),args:Ur(`\n angle (number) ${s("The angle to find the secant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cos(Gr(e))},isExported:!0},hl={description:s("Hyperbolic secant of any real number."),args:Ur(`\n value (number) ${s("Any real value to calculate the hyperbolic secant of.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cosh(Gr(e))},isExported:!0},dl={description:s("Sine of an angle provided in radians."),args:Ur(`\n angle (number) ${s("The angle to find the sine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sin(Gr(e))},isExported:!0},ul={description:s("Hyperbolic sine of any real number."),args:Ur(`\n value (number) ${s("Any real value to calculate the hyperbolic sine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sinh(Gr(e))},isExported:!0},gl={description:s("Positive square root of a positive number."),args:Ur(`\n value (number) ${s("The number for which to calculate the positive square root.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){const t=Gr(e);return Hr((()=>t>=0),s("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},pl={description:s("Sum of a series of numbers and/or cells."),args:Ur(`\n value1 (number, range<number>) ${s("The first number or range to add together.")}\n value2 (number, range<number>, repeating) ${s("Additional numbers or ranges to add to value1.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){return oa(e,((e,t)=>e+t),0)},isExported:!0},ml={description:s("A conditional sum across a range."),args:Ur(`\n criteria_range (range) ${s("The range which is tested against criterion.")}\n criterion (string) ${s("The pattern or test to apply to range.")}\n sum_range (range, default=criteria_range) ${s("The range to be summed, if different from range.")}\n `),returns:["NUMBER"],compute:function(e,t,i){void 0===i&&(i=e);let n=0;return ca([e,t],((e,t)=>{const o=i[e][t];"number"==typeof o&&(n+=o)})),n},isExported:!0},fl={description:s("Sums a range depending on multiple criteria."),args:Ur(`\n sum_range (range) ${s("The range to sum.")}\n criteria_range1 (range) ${s("The range to check against criterion1.")}\n criterion1 (string) ${s("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${s("Additional ranges to check.")}\n criterion2 (string, repeating) ${s("Additional criteria to check.")}\n `),returns:["NUMBER"],compute:function(e,...t){let i=0;return ca(t,((t,n)=>{const o=e[t][n];"number"==typeof o&&(i+=o)})),i},isExported:!0},vl={description:s("Tangent of an angle provided in radians."),args:Ur(`\n angle (number) ${s("The angle to find the tangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tan(Gr(e))},isExported:!0},bl={description:s("Hyperbolic tangent of any real number."),args:Ur(`\n value (number) ${s("Any real value to calculate the hyperbolic tangent of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tanh(Gr(e))},isExported:!0},Sl={description:s("Truncates a number."),args:Ur(`\n value (number) ${s("The value to be truncated.")}\n places (number, default=0) ${s("The number of significant digits to the right of the decimal point to retain.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Gr(e);let n=Gr(t);return 0===n?Math.trunc(i):(Number.isInteger(n)||(n=Math.trunc(n)),Math.trunc(i*Math.pow(10,n))/Math.pow(10,n))},isExported:!0};var Cl=Object.freeze({__proto__:null,ABS:va,ACOS:ba,ACOSH:Sa,ACOT:Ca,ACOTH:Ea,ASIN:wa,ASINH:ya,ATAN:xa,ATAN2:Ra,ATANH:Ia,CEILING:Ta,CEILING_MATH:Aa,CEILING_PRECISE:Na,COS:Oa,COSH:Ma,COT:_a,COTH:Fa,COUNTBLANK:Da,COUNTIF:ka,COUNTIFS:$a,COUNTUNIQUE:Pa,COUNTUNIQUEIFS:Ua,CSC:Va,CSCH:za,DECIMAL:Ba,DEGREES:Ha,EXP:Wa,FLOOR:Ga,FLOOR_MATH:qa,FLOOR_PRECISE:Za,ISEVEN:ja,ISO_CEILING:Ya,ISODD:Xa,LN:Ka,LOG:Qa,MOD:Ja,ODD:el,PI:tl,POWER:il,PRODUCT:nl,RAND:ol,RANDBETWEEN:sl,ROUND:rl,ROUNDDOWN:al,ROUNDUP:ll,SEC:cl,SECH:hl,SIN:dl,SINH:ul,SQRT:gl,SUM:pl,SUMIF:ml,SUMIFS:fl,TAN:vl,TANH:bl,TRUNC:Sl});function El(e,t,i){let n=[],o=[],r=0,a=0;ea([e],(e=>{n.push(e),r+=1})),ea([t],(e=>{o.push(e),a+=1})),Hr((()=>r===a),s("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",r.toString(),a.toString()));let l=0,c=0,h=0;for(let e=0;e<r;e++){const t=n[e],i=o[e];"number"==typeof t&&"number"==typeof i&&(l+=1,c+=t,h+=i)}Hr((()=>0!==l&&(!i||1!==l)),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const d=c/l,u=h/l;let g=0;for(let e=0;e<r;e++){const t=n[e],i=o[e];"number"==typeof t&&"number"==typeof i&&(g+=(t-d)*(i-u))}return g/(l-(i?1:0))}function wl(e,t,i){let n=0,o=0;const r=i?sa:oa;o=r(e,((e,t)=>(n+=1,e+t)),0),Hr((()=>0!==n&&(!t||1!==n)),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const a=o/n;return r(e,((e,t)=>e+Math.pow(t-a,2)),0)/(n-(t?1:0))}function yl(e,t,i){const n=Gr(t);Hr((()=>i?0<=n&&n<=1:0<n&&n<1),s("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let o,r=[],a=0;return ea(e,(e=>{"number"==typeof e&&(o=ua(r,e,"nextSmaller","asc",r.length,((e,t)=>e[t])),r.splice(o+1,0,e),a++)})),Hr((()=>0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),i||Hr((()=>1/(a+1)<=n&&n<=a/(a+1)),s("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),yi(r,n,i)}const xl={description:s("Average magnitude of deviations from mean."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;const i=oa(e,((e,i)=>(t+=1,e+i)),0);Hr((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const n=i/t;return oa(e,((e,t)=>e+Math.abs(n-t)),0)/t},isExported:!0},Rl={description:s("Numerical average value in a dataset, ignoring text."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range to consider when calculating the average value.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to consider when calculating the average value.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0;const i=oa(e,((e,i)=>(t+=1,e+i)),0);return Hr((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/t},isExported:!0},Il=s("[[FUNCTION_NAME]] has mismatched range sizes."),Tl=s("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),Al={description:s("Weighted average."),args:Ur(`\n values (number, range<number>) ${s("Values to average.")}\n weights (number, range<number>) ${s("Weights for each corresponding value.")}\n additional_values (number, range<number>, repeating) ${s("Additional values to average.")}\n additional_weights (number, range<number>, repeating) ${s("Additional weights.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t,i,n=0,o=0;Hr((()=>e.length%2==0),s("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let r=0;r<e.length-1;r+=2)if(t=e[r],i=e[r+1],Array.isArray(t)){Hr((()=>Array.isArray(i)),Il);let e=t.length,r=t[0].length;Hr((()=>e===i.length&&r===i[0].length),Il);for(let a=0;a<e;a++)for(let e=0;e<r;e++){let r=t[a][e],l=i[a][e],c="number"==typeof r,h="number"==typeof l;Hr((()=>c===h),s("[[FUNCTION_NAME]] expects number values.")),h&&(Hr((()=>l>=0),Tl),n+=r*l,o+=l)}}else i=Gr(i),t=Gr(t),Hr((()=>i>=0),Tl),n+=t*i,o+=i;return Hr((()=>0!==o),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),n/o}},Nl={description:s("Numerical average value in a dataset."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range to consider when calculating the average value.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to consider when calculating the average value.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0;const i=sa(e,((e,i)=>(t+=1,e+i)),0);return Hr((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/t},isExported:!0},Ol={description:s("Average of values depending on criteria."),args:Ur(`\n criteria_range (range) ${s("The range to check against criterion.")}\n criterion (string) ${s("The pattern or test to apply to criteria_range.")}\n average_range (range, default=criteria_range) ${s("The range to average. If not included, criteria_range is used for the average instead.")}\n `),returns:["NUMBER"],compute:function(e,t,i){null==i&&(i=e);let n=0,o=0;return ca([e,t],((t,s)=>{const r=(i||e)[t][s];"number"==typeof r&&(n+=1,o+=r)})),Hr((()=>0!==n),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/n},isExported:!0},Ml={description:s("Average of values depending on multiple criteria."),args:Ur(`\n average_range (range) ${s("The range to average.")}\n criteria_range1 (range) ${s("The range to check against criterion1.")}\n criterion1 (string) ${s("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${s("Additional criteria_range and criterion to check.")}\n criterion2 (string, repeating) ${s("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let i=0,n=0;return ca(t,((t,o)=>{const s=e[t][o];"number"==typeof s&&(i+=1,n+=s)})),Hr((()=>0!==i),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),n/i},isExported:!0},_l={description:s("The number of numeric values in dataset."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range to consider when counting.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to consider when counting.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;for(let i of e)if(Array.isArray(i))for(let e of i)for(let i of e)"number"==typeof i&&(t+=1);else("string"!=typeof i||Ci(i)||ve(i))&&(t+=1);return t},isExported:!0},Fl={description:s("The number of values in a dataset."),args:Ur(`\n value1 (any, range) ${s("The first value or range to consider when counting.")}\n value2 (any, range, repeating) ${s("Additional values or ranges to consider when counting.")}\n `),returns:["NUMBER"],compute:function(...e){return na(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},Dl={description:s("The covariance of a dataset."),args:Ur(`\n data_y (any, range) ${s("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${s("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return El(e,t,!1)},isExported:!0},kl={description:s("The covariance of a dataset."),args:Ur(`\n data_y (any, range) ${s("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${s("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return El(e,t,!1)},isExported:!0},$l={description:s("The sample covariance of a dataset."),args:Ur(`\n data_y (any, range) ${s("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${s("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return El(e,t,!0)},isExported:!0},Ll={description:s("Nth largest element from a data set."),args:Ur(`\n data (any, range) ${s("Array or range containing the dataset to consider.")}\n n (number) ${s("The rank from largest to smallest of the element to return.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){const i=Math.trunc(Gr(t));let n,o=[],r=0;ea([e],(e=>{"number"==typeof e&&(n=ua(o,e,"nextSmaller","asc",o.length,((e,t)=>e[t])),o.splice(n+1,0,e),r++,r>i&&(o.shift(),r--))}));const a=o.shift();return Hr((()=>void 0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),Hr((()=>r>=i),s("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",i.toString())),a},isExported:!0},Pl={description:s("Maximum value in a numeric dataset."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range to consider when calculating the maximum value.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to consider when calculating the maximum value.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=oa(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},Ul={description:s("Maximum numeric value in a dataset."),args:Ur(`\n value1 (any, range) ${s("The first value or range to consider when calculating the maximum value.")}\n value2 (any, range, repeating) ${s("Additional values or ranges to consider when calculating the maximum value.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=sa(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},Vl={description:s("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:Ur(`\n range (range) ${s("The range of cells from which the maximum will be determined.")}\n criteria_range1 (range) ${s("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${s("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${s("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let i=-1/0;return ca(t,((t,n)=>{const o=e[t][n];"number"==typeof o&&(i=i<o?o:i)})),i===-1/0?0:i},isExported:!0},zl={description:s("Median value in a numeric dataset."),args:Ur(`\n value1 (any, range) ${s("The first value or range to consider when calculating the median value.")}\n value2 (any, range, repeating) ${s("Additional values or ranges to consider when calculating the median value.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=[];return ta(e,(e=>{t.push(e)})),yl(t,.5,!0)},isExported:!0},Bl={description:s("Minimum value in a numeric dataset."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range to consider when calculating the minimum value.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to consider when calculating the minimum value.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=oa(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},Hl={description:s("Minimum numeric value in a dataset."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range to consider when calculating the minimum value.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to consider when calculating the minimum value.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=sa(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},Wl={description:s("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:Ur(`\n range (range) ${s("The range of cells from which the minimum will be determined.")}\n criteria_range1 (range) ${s("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${s("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${s("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let i=1/0;return ca(t,((t,n)=>{const o=e[t][n];"number"==typeof o&&(i=i>o?o:i)})),i===1/0?0:i},isExported:!0},Gl={description:s("Value at a given percentile of a dataset."),args:Ur(`\n data (any, range) ${s("The array or range containing the dataset to consider.")}\n percentile (number) ${s("The percentile whose value within data will be calculated and returned.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return Zl.compute(e,t)},isExported:!0},ql={description:s("Value at a given percentile of a dataset exclusive of 0 and 1."),args:Ur(`\n data (any, range) ${s("The array or range containing the dataset to consider.")}\n percentile (number) ${s("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return yl([e],t,!1)},isExported:!0},Zl={description:s("Value at a given percentile of a dataset."),args:Ur(`\n data (any, range) ${s("The array or range containing the dataset to consider.")}\n percentile (number) ${s("The percentile whose value within data will be calculated and returned.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return yl([e],t,!0)},isExported:!0},jl={description:s("Value nearest to a specific quartile of a dataset."),args:Ur(`\n data (any, range) ${s("The array or range containing the dataset to consider.")}\n quartile_number (number) ${s("Which quartile value to return.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return Xl.compute(e,t)},isExported:!0},Yl={description:s("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:Ur(`\n data (any, range) ${s("The array or range containing the dataset to consider.")}\n quartile_number (number) ${s("Which quartile value, exclusive of 0 and 4, to return.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return yl([e],.25*Math.trunc(Gr(t)),!1)},isExported:!0},Xl={description:s("Value nearest to a specific quartile of a dataset."),args:Ur(`\n data (any, range) ${s("The array or range containing the dataset to consider.")}\n quartile_number (number) ${s("Which quartile value to return.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return yl([e],.25*Math.trunc(Gr(t)),!0)},isExported:!0},Kl={description:s("Nth smallest element in a data set."),args:Ur(`\n data (any, range) ${s("The array or range containing the dataset to consider.")}\n n (number) ${s("The rank from smallest to largest of the element to return.")}\n `),returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){const i=Math.trunc(Gr(t));let n,o=[],r=0;ea([e],(e=>{"number"==typeof e&&(n=ua(o,e,"nextSmaller","asc",o.length,((e,t)=>e[t])),o.splice(n+1,0,e),r++,r>i&&(o.pop(),r--))}));const a=o.pop();return Hr((()=>void 0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),Hr((()=>r>=i),s("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",i.toString())),a},isExported:!0},Ql={description:s("Standard deviation."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(oc.compute(...e))},isExported:!0},Jl={description:s("Standard deviation of entire population."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(sc.compute(...e))},isExported:!0},ec={description:s("Standard deviation."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(rc.compute(...e))},isExported:!0},tc={description:s("Standard deviation of sample (text as 0)."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(ac.compute(...e))},isExported:!0},ic={description:s("Standard deviation of entire population."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(lc.compute(...e))},isExported:!0},nc={description:s("Standard deviation of entire population (text as 0)."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(cc.compute(...e))},isExported:!0},oc={description:s("Variance."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return wl(e,!0,!1)},isExported:!0},sc={description:s("Variance of entire population."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return wl(e,!1,!1)},isExported:!0},rc={description:s("Variance."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return wl(e,!0,!1)},isExported:!0},ac={description:s("Variance of sample (text as 0)."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return wl(e,!0,!0)},isExported:!0},lc={description:s("Variance of entire population."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return wl(e,!1,!1)},isExported:!0},cc={description:s("Variance of entire population (text as 0)."),args:Ur(`\n value1 (number, range<number>) ${s("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${s("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return wl(e,!1,!0)},isExported:!0};var hc=Object.freeze({__proto__:null,AVEDEV:xl,AVERAGE:Rl,AVERAGE_WEIGHTED:Al,AVERAGEA:Nl,AVERAGEIF:Ol,AVERAGEIFS:Ml,COUNT:_l,COUNTA:Fl,COVAR:Dl,COVARIANCE_P:kl,COVARIANCE_S:$l,LARGE:Ll,MAX:Pl,MAXA:Ul,MAXIFS:Vl,MEDIAN:zl,MIN:Bl,MINA:Hl,MINIFS:Wl,PERCENTILE:Gl,PERCENTILE_EXC:ql,PERCENTILE_INC:Zl,QUARTILE:jl,QUARTILE_EXC:Yl,QUARTILE_INC:Xl,SMALL:Kl,STDEV:Ql,STDEV_P:Jl,STDEV_S:ec,STDEVA:tc,STDEVP:ic,STDEVPA:nc,VAR:oc,VAR_P:sc,VAR_S:rc,VARA:ac,VARP:lc,VARPA:cc});function dc(e,t,i){var n;const o=new Map,r=e.length;for(let t=r-1;t>=0;t--)o.set(Zr(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(s("The field must be a number or a string"));let a;if("number"==typeof t){if(a=Math.trunc(t)-1,a<0||r-1<a)throw new Error(s("The field (%s) must be one of %s or must be a number between 1 and %s inclusive.",t.toString(),r.toString()))}else{const e=Zr(t).toUpperCase();if(a=null!==(n=o.get(e))&&void 0!==n?n:-1,-1===a)throw new Error(s("The field (%s) must be one of %s.",Zr(t),[...o.keys()].toString()))}const l=i[0].length;if(l<2)throw new Error(s("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const h=e[0].length;for(let t=1;t<l;t++){let n=[],s=!0;for(let r=0;r<i.length;r++){const a=Zr(i[r][0]).toUpperCase(),l=o.get(a),c=i[r][t];if(void 0!==c){if(void 0===l){s=!1;break}n.push([e[l].slice(1,h)]),n.push(c)}}if(s){if(!(n.length>0)){c=new Set(Array(h-1).keys());break}ca(n,((e,t)=>{c.add(t)}),!0)}}const d=e[a];return[...c].map((e=>d[e+1]))}const uc=Ur(`\n database (range) ${s("The array or range containing the data to consider, structured in such a way that the first row contains the labels for each column's values.")}\n field (any) ${s("Indicates which column in database contains the values to be extracted and operated on.")}\n criteria (range) ${s("An array or range containing zero or more criteria to filter the database values by before operating.")}\n`),gc={description:s("Average of a set of values from a table-like range."),args:uc,returns:["NUMBER"],compute:function(e,t,i){const n=dc(e,t,i);return Rl.compute([n])},isExported:!0},pc={description:s("Counts values from a table-like range."),args:uc,returns:["NUMBER"],compute:function(e,t,i){const n=dc(e,t,i);return _l.compute([n])},isExported:!0},mc={description:s("Counts values and text from a table-like range."),args:uc,returns:["NUMBER"],compute:function(e,t,i){const n=dc(e,t,i);return Fl.compute([n])},isExported:!0},fc={description:s("Single value from a table-like range."),args:uc,returns:["NUMBER"],compute:function(e,t,i){const n=dc(e,t,i);return Hr((()=>1===n.length),s("More than one match found in DGET evaluation.")),n[0]},isExported:!0},vc={description:s("Maximum of values from a table-like range."),args:uc,returns:["NUMBER"],compute:function(e,t,i){const n=dc(e,t,i);return Pl.compute([n])},isExported:!0},bc={description:s("Minimum of values from a table-like range."),args:uc,returns:["NUMBER"],compute:function(e,t,i){const n=dc(e,t,i);return Bl.compute([n])},isExported:!0},Sc={description:s("Product of values from a table-like range."),args:uc,returns:["NUMBER"],compute:function(e,t,i){const n=dc(e,t,i);return nl.compute([n])},isExported:!0},Cc={description:s("Standard deviation of population sample from table."),args:uc,returns:["NUMBER"],compute:function(e,t,i){const n=dc(e,t,i);return Ql.compute([n])},isExported:!0},Ec={description:s("Standard deviation of entire population from table."),args:uc,returns:["NUMBER"],compute:function(e,t,i){const n=dc(e,t,i);return ic.compute([n])},isExported:!0},wc={description:s("Sum of values from a table-like range."),args:uc,returns:["NUMBER"],compute:function(e,t,i){const n=dc(e,t,i);return pl.compute([n])},isExported:!0},yc={description:s("Variance of population sample from table-like range."),args:uc,returns:["NUMBER"],compute:function(e,t,i){const n=dc(e,t,i);return oc.compute([n])},isExported:!0},xc={description:s("Variance of a population from a table-like range."),args:uc,returns:["NUMBER"],compute:function(e,t,i){const n=dc(e,t,i);return lc.compute([n])},isExported:!0};var Rc=Object.freeze({__proto__:null,DAVERAGE:gc,DCOUNT:pc,DCOUNTA:mc,DGET:fc,DMAX:vc,DMIN:bc,DPRODUCT:Sc,DSTDEV:Cc,DSTDEVP:Ec,DSUM:wc,DVAR:yc,DVARP:xc});const Ic={description:s("Converts year/month/day into a date."),args:Ur(`\n year (number) ${s("The year component of the date.")}\n month (number) ${s("The month component of the date.")}\n day (number) ${s("The day component of the date.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i){let n=Math.trunc(Gr(e));const o=Math.trunc(Gr(t)),r=Math.trunc(Gr(i));Hr((()=>0<=n&&n<=9999),s("The year (%s) must be between 0 and 9999 inclusive.",n.toString())),n<1900&&(n+=1900);const a=Ce(new ae(n,o-1,r));return Hr((()=>a>=0),s("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),a},isExported:!0},Tc={description:s("Converts a date string to a date value."),args:Ur(`\n date_string (string) ${s("The string representing the date.")}\n `),returns:["NUMBER"],compute:function(e){const t=Zr(e),i=ve(t);return Hr((()=>null!==i),s("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(i.value)},isExported:!0},Ac={description:s("Day of the month that a specific date falls on."),args:Ur(`\n date (string) ${s("The date from which to extract the day.")}\n `),returns:["NUMBER"],compute:function(e){return Qr(e).getDate()},isExported:!0},Nc={description:s("Number of days between two dates."),args:Ur(`\n end_date (date) ${s("The end of the date range.")}\n start_date (date) ${s("The start of the date range.")}\n `),returns:["NUMBER"],compute:function(e,t){const i=Qr(e),n=Qr(t),o=i.getTime()-n.getTime();return Math.round(o/ce)},isExported:!0},Oc={description:s("Number of days between two dates on a 360-day year (months of 30 days)."),args:Ur(`\n start_date (date) ${s("The start date to consider in the calculation.")}\n end_date (date) ${s("The end date to consider in the calculation.")}\n method (number, default=0) ${s("An indicator of what day count method to use. (0) US NASD method (1) European method")}\n `),returns:["NUMBER"],compute:function(e,t,i=0){const n=Gr(e),o=Gr(t),s=Kr(i)?4:0,r=Xc.compute(e,t,s);return Math.sign(o-n)*Math.round(360*r)},isExported:!0},Mc={description:s("Date a number of months before/after another date."),args:Ur(`\n start_date (date) ${s("The date from which to calculate the result.")}\n months (number) ${s("The number of months before (negative) or after (positive) 'start_date' to calculate.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){return Ce(ye(Qr(e),Math.trunc(Gr(t)),!1))},isExported:!0},_c={description:s("Last day of a month before or after a date."),args:Ur(`\n start_date (date) ${s("The date from which to calculate the result.")}\n months (number) ${s("The number of months before (negative) or after (positive) 'start_date' to consider.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){const i=Qr(e),n=Math.trunc(Gr(t)),o=i.getFullYear(),s=i.getMonth();return Ce(new ae(o,s+n+1,0))},isExported:!0},Fc={description:s("Hour component of a specific time."),args:Ur(`\n time (date) ${s("The time from which to calculate the hour component.")}\n `),returns:["NUMBER"],compute:function(e){return Qr(e).getHours()},isExported:!0},Dc={description:s("ISO week number of the year."),args:Ur(`\n date (date) ${s("The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n `),returns:["NUMBER"],compute:function(e){const t=Qr(e),i=t.getFullYear();let n=1;for(;4!==new ae(i,0,n).getDay();)n+=1;const o=new ae(i,0,n-3);let s=31;for(;4!==new ae(i,11,s).getDay();)s-=1;const r=new ae(i,11,s+3);let a,l;switch(a=o.getTime()<=t.getTime()?t.getTime()<=r.getTime()?0:1:-1,a){case 0:l=o;break;case 1:l=new ae(i,11,s+3+1);break;case-1:let e=1;for(;4!==new ae(i-1,0,e).getDay();)e+=1;l=new ae(i-1,0,e-3)}const c=(t.getTime()-l.getTime())/ce;return Math.floor(c/7)+1},isExported:!0},kc={description:s("Minute component of a specific time."),args:Ur(`\n time (date) ${s("The time from which to calculate the minute component.")}\n `),returns:["NUMBER"],compute:function(e){return Qr(e).getMinutes()},isExported:!0},$c={description:s("Month of the year a specific date falls in"),args:Ur(`\n date (date) ${s("The date from which to extract the month.")}\n `),returns:["NUMBER"],compute:function(e){return Qr(e).getMonth()+1},isExported:!0},Lc={description:s("Net working days between two provided days."),args:Ur(`\n start_date (date) ${s("The start date of the period from which to calculate the number of net working days.")}\n end_date (date) ${s("The end date of the period from which to calculate the number of net working days.")}\n holidays (date, range<date>, optional) ${s("A range or array constant containing the date serial numbers to consider holidays.")}\n `),returns:["NUMBER"],compute:function(e,t,i){return Uc.compute(e,t,1,i)},isExported:!0};function Pc(e){if("string"==typeof e){Hr((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),s('When weekend is a string (%s) it must be composed of "0" or "1".',e));let t=[];for(let i=0;i<7;i++)"1"===e[i]&&t.push((i+1)%7);return t}if("number"==typeof e)return Hr((()=>1<=e&&e<=7||11<=e&&e<=17),s("The weekend (%s) must be a string or a number in the range 1-7 or 11-17.",e.toString())),e<=7?[e-2==-1?6:e-2,e-1]:[e-11];throw Error(s("The weekend must be a number or a string."))}const Uc={description:s("Net working days between two dates (specifying weekends)."),args:Ur(`\n start_date (date) ${s("The start date of the period from which to calculate the number of net working days.")}\n end_date (date) ${s("The end date of the period from which to calculate the number of net working days.")}\n weekend (any, default=1) ${s("A number or string representing which days of the week are considered weekends.")}\n holidays (date, range<date>, optional) ${s("A range or array constant containing the dates to consider as holidays.")}\n `),returns:["NUMBER"],compute:function(e,t,i=1,n){const o=Qr(e),s=Qr(t),r=Pc(i);let a=new Set;void 0!==n&&ea([n],(e=>{const t=Qr(e);a.add(t.getTime())}));const l=o.getTime()>s.getTime(),c=ae.fromTimestamp((l?o:s).getTime());let h=ae.fromTimestamp((l?s:o).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},Vc={description:s("Current date and time as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy hh:mm:ss",compute:function(){let e=ae.now();const t=e.getTime()-le.getTime(),i=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/ce)+i},isExported:!0},zc={description:s("Minute component of a specific time."),args:Ur(`\n time (date) ${s("The time from which to calculate the second component.")}\n `),returns:["NUMBER"],compute:function(e){return Qr(e).getSeconds()},isExported:!0},Bc={description:s("Converts hour/minute/second into a time."),args:Ur(`\n hour (number) ${s("The hour component of the time.")}\n minute (number) ${s("The minute component of the time.")}\n second (number) ${s("The second component of the time.")}\n `),returns:["DATE"],computeFormat:()=>"hh:mm:ss a",compute:function(e,t,i){let n=Math.trunc(Gr(e)),o=Math.trunc(Gr(t)),r=Math.trunc(Gr(i));return o+=Math.floor(r/60),r=r%60+(r<0?60:0),n+=Math.floor(o/60),o=o%60+(o<0?60:0),n%=24,Hr((()=>n>=0),s("The function [[FUNCTION_NAME]] result cannot be negative")),n/24+o/1440+r/86400},isExported:!0},Hc={description:s("Converts a time string into its serial number representation."),args:Ur(`\n time_string (string) ${s("The string that holds the time representation.")}\n `),returns:["NUMBER"],compute:function(e){const t=Zr(e),i=ve(t);Hr((()=>null!==i),s("The time_string (%s) cannot be parsed to date/time.",t));const n=i.value-Math.trunc(i.value);return n<0?1+n:n},isExported:!0},Wc={description:s("Current date as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(){const e=ae.now();return Ce(new ae(e.getFullYear(),e.getMonth(),e.getDate()))},isExported:!0},Gc={description:s("Day of the week of the date provided (as number)."),args:Ur(`\n date (date) ${s("The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n type (number, default=1) ${s("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.")}\n `),returns:["NUMBER"],compute:function(e,t=1){const i=Qr(e),n=Math.round(Gr(t)),o=i.getDay();return Hr((()=>[1,2,3].includes(n)),s("The type (%s) must be 1, 2 or 3.",n.toString())),1===n?o+1:2===n?0===o?7:o:0===o?6:o-1},isExported:!0},qc={description:s("Week number of the year."),args:Ur(`\n date (date) ${s("The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n type (number, default=1) ${s("A number representing the day that a week starts on. Sunday = 1.")}\n `),returns:["NUMBER"],compute:function(e,t=1){const i=Qr(e),n=Math.round(Gr(t));if(Hr((()=>1===n||2===n||11<=n&&n<=17||21===n),s("The type (%s) is out of range.",n.toString())),21===n)return Dc.compute(e);let o;o=1===n||2===n?n-1:n-10==7?0:n-10;const r=i.getFullYear();let a=1,l=new ae(r,0,a);for(;l.getDay()!==o;)a+=1,l=new ae(r,0,a);const c=(i.getTime()-l.getTime())/ce;return c<0?1:Math.floor(c/7)+(1===a?1:2)},isExported:!0},Zc={description:s("Date after a number of workdays."),args:Ur(`\n start_date (date) ${s("The date from which to begin counting.")}\n num_days (number) ${s("The number of working days to advance from start_date. If negative, counts backwards.")}\n holidays (date, range<date>, optional) ${s("A range or array constant containing the dates to consider holidays.")}\n `),returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i){return jc.compute(e,t,1,i)},isExported:!0},jc={description:s("Date after a number of workdays (specifying weekends)."),args:Ur(`\n start_date (date) ${s("The date from which to begin counting.")}\n num_days (number) ${s("The number of working days to advance from start_date. If negative, counts backwards.")}\n weekend (any, default=1) ${s("A number or string representing which days of the week are considered weekends.")}\n holidays (date, range<date>, optional) ${s("A range or array constant containing the dates to consider holidays.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i=1,n){let o=Qr(e),r=Math.trunc(Gr(t));"string"==typeof i&&Hr((()=>"1111111"!==i),s("The weekend (%s) must be different from '1111111'.",i));const a=Pc(i);let l=new Set;void 0!==n&&ea([n],(e=>{const t=Qr(e);l.add(t.getTime())}));let c=ae.fromTimestamp(o.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-le.getTime();return Math.round(g/ce)},isExported:!0},Yc={description:s("Year specified by a given date."),args:Ur(`\n date (date) ${s("The date from which to extract the year.")}\n `),returns:["NUMBER"],compute:function(e){return Qr(e).getFullYear()},isExported:!0},Xc={description:s("Exact number of years between two dates."),args:Ur(`\n start_date (date) ${s("The start date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n end_date (date) ${s("The end date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n day_count_convention (number, default=0) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i=0){let n=Math.trunc(Gr(e)),o=Math.trunc(Gr(t));const r=Math.trunc(Gr(i));return Hr((()=>n>=0),s("The start_date (%s) must be positive or null.",n.toString())),Hr((()=>o>=0),s("The end_date (%s) must be positive or null.",o.toString())),Hr((()=>0<=r&&r<=4),s("The day_count_convention (%s) must be between 0 and 4 inclusive.",r.toString())),Re(n,o,r)}},Kc={description:s("First day of the month preceding a date."),args:Ur(`\n date (date) ${s("The date from which to calculate the result.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Qr(e),i=t.getFullYear(),n=t.getMonth();return Ce(new ae(i,n,1))}},Qc={description:s("Last day of the month following a date."),args:Ur(`\n date (date) ${s("The date from which to calculate the result.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){return _c.compute(e,0)}},Jc={description:s("Quarter of the year a specific date falls in"),args:Ur(`\n date (date) ${s("The date from which to extract the quarter.")}\n `),returns:["NUMBER"],compute:function(e){return Math.ceil((Qr(e).getMonth()+1)/3)}},eh={description:s("First day of the quarter of the year a specific date falls in."),args:Ur(`\n date (date) ${s("The date from which to calculate the start of quarter.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Jc.compute(e),i=Yc.compute(e);return Ce(new ae(i,3*(t-1),1))}},th={description:s("Last day of the quarter of the year a specific date falls in."),args:Ur(`\n date (date) ${s("The date from which to calculate the end of quarter.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Jc.compute(e),i=Yc.compute(e);return Ce(new ae(i,3*t,0))}},ih={description:s("First day of the year a specific date falls in."),args:Ur(`\n date (date) ${s("The date from which to calculate the start of the year.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Yc.compute(e);return Ce(new ae(t,0,1))}},nh={description:s("Last day of the year a specific date falls in."),args:Ur(`\n date (date) ${s("The date from which to calculate the end of the year.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Yc.compute(e);return Ce(new ae(t+1,0,0))}};var oh=Object.freeze({__proto__:null,DATE:Ic,DATEVALUE:Tc,DAY:Ac,DAYS:Nc,DAYS360:Oc,EDATE:Mc,EOMONTH:_c,HOUR:Fc,ISOWEEKNUM:Dc,MINUTE:kc,MONTH:$c,NETWORKDAYS:Lc,NETWORKDAYS_INTL:Uc,NOW:Vc,SECOND:zc,TIME:Bc,TIMEVALUE:Hc,TODAY:Wc,WEEKDAY:Gc,WEEKNUM:qc,WORKDAY:Zc,WORKDAY_INTL:jc,YEAR:Yc,YEARFRAC:Xc,MONTH_START:Kc,MONTH_END:Qc,QUARTER:Jc,QUARTER_START:eh,QUARTER_END:th,YEAR_START:ih,YEAR_END:nh});const sh={description:s("Compare two numeric values, returning 1 if they're equal."),args:Ur(`\n number1 (number) ${s("The first number to compare.")}\n number2 (number, default=0) ${s("The second number to compare.")}\n `),returns:["NUMBER"],compute:function(e,t=0){return Gr(e)===Gr(t)?1:0},isExported:!0};var rh=Object.freeze({__proto__:null,DELTA:sh});function ah(e,t){Hr((()=>e<t),s("The maturity (%s) must be strictly greater than the settlement (%s).",t.toString(),e.toString()))}function lh(e,t){Hr((()=>t<e),s("The settlement date (%s) must be strictly greater than the issue date (%s).",e.toString(),t.toString()))}function ch(e){Hr((()=>[1,2,4].includes(e)),s("The frequency (%s) must be one of %s",e.toString(),[1,2,4].toString()))}function hh(e){Hr((()=>0<=e&&e<=4),s("The day_count_convention (%s) must be between 0 and 4 inclusive.",e.toString()))}function dh(e){Hr((()=>e>0),s("The redemption (%s) must be strictly positive.",e.toString()))}function uh(e){Hr((()=>e>0),s("The price (%s) must be strictly positive.",e.toString()))}function gh(e){Hr((()=>e>0),s("The number_of_periods (%s) must be greater than 0.",e.toString()))}function ph(e){Hr((()=>e>0),s("The rate (%s) must be strictly positive.",e.toString()))}function mh(e){Hr((()=>e>0),s("The life (%s) must be strictly positive.",e.toString()))}function fh(e){Hr((()=>e>=0),s("The cost (%s) must be positive or null.",e.toString()))}function vh(e){Hr((()=>e>0),s("The period (%s) must be strictly positive.",e.toString()))}function bh(e){Hr((()=>e>=0),s("The salvage (%s) must be positive or null.",e.toString()))}function Sh(e){Hr((()=>e>0),s("The present value (%s) must be strictly positive.",e.toString()))}function Ch(e,t){Hr((()=>e<=t),s("The period (%s) must be less than or equal life (%.",e.toString(),t.toString()))}function Eh(e){Hr((()=>e>0),s("The investment (%s) must be strictly positive.",e.toString()))}function wh(e){Hr((()=>e>0),s("The discount (%s) must be strictly positive.",e.toString()))}function yh(e){Hr((()=>e<1),s("The discount (%s) must be smaller than 1.",e.toString()))}function xh(e){Hr((()=>e>0),s("The depreciation factor (%s) must be strictly positive.",e.toString()))}function Rh(e,t){const i=Qr(e),n=Qr(t),o=Qr(e);o.setFullYear(i.getFullYear()+1),Hr((()=>n.getTime()<=o.getTime()),s("The settlement date (%s) must at most one year after the maturity date (%s).",e.toString(),t.toString()))}function Ih(e,t,i){gh(i),Hr((()=>e>0),s("The first_period (%s) must be strictly positive.",e.toString())),Hr((()=>t>0),s("The last_period (%s) must be strictly positive.",t.toString())),Hr((()=>e<=t),s("The first_period (%s) must be smaller or equal to the last_period (%s).",e.toString(),t.toString())),Hr((()=>t<=i),s("The last_period (%s) must be smaller or equal to the number_of_periods (%s).",e.toString(),i.toString()))}function Th(e){Hr((()=>e>-1),s("The rate_guess (%s) must be strictly greater than -1.",e.toString()))}function Ah(e,t){Hr((()=>e.length===t.length&&e[0].length===t[0].length),s("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."))}function Nh(e){Hr((()=>e.every((t=>t>=e[0]))),s("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e[0].toString()))}const Oh=Ur(`\nsettlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\nmaturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\nfrequency (number) ${s("The number of interest or coupon payments per year (1, 2, or 4).")}\nday_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n`);function Mh(e,t,i,n,o=1e-10,r){let a,l,c,h,d=i,u=!1,g=0;do{c=e(d),isNaN(c)?(Hr((()=>g<n&&void 0!==r),s("Function [[FUNCTION_NAME]] didn't find any result.")),g++,d=r(h),h=d):(a=d-c/t(d),l=Math.abs(a-d),d=a,u=l<o||Math.abs(c)<o,Hr((()=>g<n),s("Function [[FUNCTION_NAME]] didn't find any result.")),g++)}while(!u);return d}const _h={description:s("Accrued interest of security paying at maturity."),args:Ur(`\n issue (date) ${s("The date the security was initially issued.")}\n maturity (date) ${s("The maturity date of the security.")}\n rate (number) ${s("The annualized rate of interest.")}\n redemption (number) ${s("The redemption amount per 100 face value, or par.")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o=0){o=o||0;const s=Math.trunc(Gr(e)),r=Math.trunc(Gr(t)),a=Gr(n),l=Gr(i),c=Math.trunc(Gr(o));lh(r,s),hh(c),dh(a),ph(l);return a*l*Xc.compute(s,r,o)},isExported:!0},Fh={description:s("Depreciation for an accounting period."),args:Ur(`\n cost (number) ${s("The initial cost of the asset.")}\n purchase_date (date) ${s("The date the asset was purchased.")}\n first_period_end (date) ${s("The date the first period ended.")}\n salvage (number) ${s("The value of the asset at the end of depreciation.")}\n period (number) ${s("The single period within life for which to calculate depreciation.")}\n rate (number) ${s("The deprecation rate.")}\n day_count_convention (number, optional) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,r,a=0){a=a||0;const l=Gr(e),c=Math.trunc(Gr(t)),h=Math.trunc(Gr(i)),d=Gr(n),u=Gr(o),g=Gr(r),p=Math.trunc(Gr(a));!function(e){Hr((()=>e>0),s("The cost (%s) must be strictly positive.",e.toString()))}(l),bh(d),function(e,t){Hr((()=>e<=t),s("The salvage (%s) must be smaller or equal than the cost (%s).",e.toString(),t.toString()))}(d,l),function(e){Hr((()=>e>=0),s("The period (%s) must be positive or null.",e.toString()))}(u),ph(g),hh(p),Hr((()=>c<=h),s("The purchase_date (%s) must be before the first_period_end (%s).",c.toString(),h.toString()));const m=u<1&&u>0?1:Math.trunc(u),f=l*g,v=Xc.compute(c,h,p),b=c===h?f:f*v,S=l-b-f*m;return S>=d?0===m?b:f:d-S<f?f-(d-S):0},isExported:!0},Dh={description:s("Days in coupon period containing settlement date."),args:Oh,returns:["NUMBER"],compute:function(e,t,i,n=0){n=n||0;const o=Math.trunc(Gr(e)),s=Math.trunc(Gr(t)),r=Math.trunc(Gr(i)),a=Math.trunc(Gr(n));if(ah(o,s),ch(r),hh(a),1===a){const o=Uh.compute(e,t,i,n);return Lh.compute(e,t,i,n)-o}return(3===a?365:360)/r},isExported:!0},kh={description:s("Days from settlement until next coupon."),args:Oh,returns:["NUMBER"],compute:function(e,t,i,n=0){n=n||0;const o=Math.trunc(Gr(e)),s=Math.trunc(Gr(t)),r=Math.trunc(Gr(i)),a=Math.trunc(Gr(n));ah(o,s),ch(r),hh(a);const l=Uh.compute(o,s,i,n);if([1,2,3].includes(a))return o-l;if(4===a){const e=Re(l,o,a);return Math.round(360*e)}const c=Qr(o),h=Qr(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&&we(h)&&we(c)&&(f=30),31!==f||30!==m&&31!==m||(f=30),2===g&&we(h)&&(m=30),31===m&&(m=30),360*(u-d)+30*(p-g)+(f-m)},isExported:!0},$h={description:s("Days from settlement until next coupon."),args:Oh,returns:["NUMBER"],compute:function(e,t,i,n=0){n=n||0;const o=Math.trunc(Gr(e)),s=Math.trunc(Gr(t)),r=Math.trunc(Gr(i)),a=Math.trunc(Gr(n));ah(o,s),ch(r),hh(a);const l=Lh.compute(o,s,i,n);if([1,2,3].includes(a))return l-o;if(4===a){const e=Re(o,l,a);return Math.round(360*e)}const c=kh.compute(e,t,i,a);return Dh.compute(e,t,i,a)-c},isExported:!0},Lh={description:s("Next coupon date after the settlement date."),args:Oh,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i,n=0){n=n||0;const o=Math.trunc(Gr(e)),s=Math.trunc(Gr(t)),r=Math.trunc(Gr(i)),a=Math.trunc(Gr(n));ah(o,s),ch(r),hh(a);const l=12/r,c=Ph.compute(e,t,i,n);return Ce(ye(Qr(s),-(c-1)*l,!0))},isExported:!0},Ph={description:s("Number of coupons between settlement and maturity."),args:Oh,returns:["NUMBER"],compute:function(e,t,i,n=0){n=n||0;const o=Math.trunc(Gr(e)),s=Math.trunc(Gr(t)),r=Math.trunc(Gr(i)),a=Math.trunc(Gr(n));ah(o,s),ch(r),hh(a);let l=1,c=s;const h=12/r;for(;c>o;)c=Ce(ye(Qr(c),-h,!1)),l++;return l-1},isExported:!0},Uh={description:s("Last coupon date prior to or on the settlement date."),args:Oh,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i,n=0){n=n||0;const o=Math.trunc(Gr(e)),s=Math.trunc(Gr(t)),r=Math.trunc(Gr(i)),a=Math.trunc(Gr(n));ah(o,s),ch(r),hh(a);const l=12/r,c=Ph.compute(e,t,i,n);return Ce(ye(Qr(s),-c*l,!0))},isExported:!0},Vh={description:s("Cumulative interest paid over a set of periods."),args:Ur(`\n rate (number) ${s("The interest rate.")}\n number_of_periods (number) ${s("The number of payments to be made.")}\n present_value (number) ${s("The current value of the annuity.")}\n first_period (number) ${s("The number of the payment period to begin the cumulative calculation.")}\n last_period (number) ${s("The number of the payment period to end the cumulative calculation.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,s=0){const r=Gr(n),a=Gr(o),l=Gr(e),c=Gr(i),h=Gr(t);Ih(r,a,h),ph(l),Sh(c);let d=0;for(let t=r;t<=a;t++){d+=Qh.compute(e,t,h,i,0,s)}return d},isExported:!0},zh={description:s("Cumulative principal paid over a set of periods."),args:Ur(`\n rate (number) ${s("The interest rate.")}\n number_of_periods (number) ${s("The number of payments to be made.")}\n present_value (number) ${s("The current value of the annuity.")}\n first_period (number) ${s("The number of the payment period to begin the cumulative calculation.")}\n last_period (number) ${s("The number of the payment period to end the cumulative calculation.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,s=0){const r=Gr(n),a=Gr(o),l=Gr(e),c=Gr(i),h=Gr(t);Ih(r,a,h),ph(l),Sh(c);let d=0;for(let t=r;t<=a;t++){d+=ld.compute(e,t,h,i,0,s)}return d},isExported:!0},Bh={description:s("Depreciation via declining balance method."),args:Ur(`\n cost (number) ${s("The initial cost of the asset.")}\n salvage (number) ${s("The value of the asset at the end of depreciation.")}\n life (number) ${s("The number of periods over which the asset is depreciated.")}\n period (number) ${s("The single period within life for which to calculate depreciation.")}\n month (number, optional) ${s("The number of months in the first year of depreciation.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,n,...o){const r=Gr(e),a=Gr(t),l=Gr(i),c=Math.trunc(Gr(n)),h=o.length?Math.trunc(Gr(o[0])):12,d=l+(12===h?0:1);fh(r),bh(a),vh(c),mh(l),Hr((()=>1<=h&&h<=12),s("The month (%s) must be between 1 and 12 inclusive.",h.toString())),Hr((()=>c<=d),s("The period (%s) must be less than or equal to %s.",c.toString(),d.toString()));const u=h/12;let g=1-Math.pow(a/r,1/l);g=Math.round(1e3*g)/1e3;let p=r,m=r*(1-g*u);for(let e=1;e<c;e++)p=m,m=p*(1-g),e===l&&(m=p*(1-g*(1-u)));return p-m},isExported:!0},Hh={description:s("Depreciation via double-declining balance method."),args:Ur(`\n cost (number) ${s("The initial cost of the asset.")}\n salvage (number) ${s("The value of the asset at the end of depreciation.")}\n life (number) ${s("The number of periods over which the asset is depreciated.")}\n period (number) ${s("The single period within life for which to calculate depreciation.")}\n factor (number, default=2) ${s("The factor by which depreciation decreases.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,n,o=2){o=o||0;const s=Gr(e),r=Gr(t),a=Gr(i),l=Gr(n),c=Gr(o);if(fh(s),bh(r),vh(l),mh(a),Ch(l,a),xh(c),0===s||r>=s)return 0;const h=c/a;if(h>1)return 1===n?s-r:0;if(l<=1)return s*h;const d=s*Math.pow(1-h,l-1),u=s*Math.pow(1-h,l),g=u<r?d-r:d-u;return Math.max(g,0)},isExported:!0},Wh={description:s("Discount rate of a security based on price."),args:Ur(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n price (number) ${s("The price at which the security is bought per 100 face value.")}\n redemption (number) ${s("The redemption amount per 100 face value, or par.")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o=0){o=o||0;const s=Math.trunc(Gr(e)),r=Math.trunc(Gr(t)),a=Gr(i),l=Gr(n),c=Math.trunc(Gr(o));ah(s,r),hh(c),uh(a),dh(l);return(l-a)/l/Xc.compute(s,r,c)},isExported:!0},Gh={description:s("Convert a decimal fraction to decimal value."),args:Ur(`\n fractional_price (number) ${s("The price quotation given using fractional decimal conventions.")}\n unit (number) ${s("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.")}\n `),returns:["NUMBER"],compute:function(e,t){const i=Gr(e),n=Math.trunc(Gr(t));Hr((()=>n>0),s("The unit (%s) must be strictly positive.",n.toString()));const o=Math.trunc(i);return o+(i-o)*(10**Math.ceil(Math.log10(n))/n)},isExported:!0},qh={description:s("Convert a decimal value to decimal fraction."),args:Ur(`\n decimal_price (number) ${s("The price quotation given as a decimal value.")}\n unit (number) ${s("The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.")}\n `),returns:["NUMBER"],compute:function(e,t){const i=Gr(e),n=Math.trunc(Gr(t));Hr((()=>n>0),s("The unit (%s) must be strictly positive.",n.toString()));const o=Math.trunc(i);return o+(i-o)*(n/10**Math.ceil(Math.log10(n)))},isExported:!0},Zh={description:s("Number of periods for an investment to reach a value."),args:Ur(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${s("The annualized rate of interest.")}\n yield (number) ${s("The expected annual yield of the security.")}\n frequency (number) ${s("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,r=0){r=r||0;const a=Math.trunc(Gr(e)),l=Math.trunc(Gr(t)),c=Gr(i),h=Gr(n),d=Math.trunc(Gr(o)),u=Math.trunc(Gr(r));ah(a,l),ch(d),hh(u),Hr((()=>c>=0),s("The rate (%s) must be positive or null.",c.toString())),Hr((()=>h>=0),s("The yield (%s) must be positive or null.",h.toString()));const g=Xc.compute(a,l,u),p=g-Math.trunc(g)||1/d,m=Math.ceil(g*d),f=c/d,v=h/d;let b=0,S=0;for(let e=1;e<=m;e++){const t=(f+(e===m?1:0))/(1+v)**e;S+=(p+(e-1)/d)*t,b+=t}return 0===b?0:S/b},isExported:!0},jh={description:s("Annual effective interest rate."),args:Ur(`\n nominal_rate (number) ${s("The nominal interest rate per year.")}\n periods_per_year (number) ${s("The number of compounding periods per year.")}\n `),returns:["NUMBER"],compute:function(e,t){const i=Gr(e),n=Math.trunc(Gr(t));return Hr((()=>i>0),s("The nominal rate (%s) must be strictly greater than 0.",i.toString())),Hr((()=>n>0),s("The number of periods by year (%s) must strictly greater than 0.",n.toString())),Math.pow(1+i/n,n)-1},isExported:!0},Yh={description:s("Future value of an annuity investment."),args:Ur(`\n rate (number) ${s("The interest rate.")}\n number_of_periods (number) ${s("The number of payments to be made.")}\n payment_amount (number) ${s("The amount per period to be paid.")}\n present_value (number, default=0) ${s("The current value of the annuity.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,n=0,o=0){n=n||0,o=o||0;const s=Gr(e),r=Gr(t),a=Gr(i),l=Gr(n),c=Kr(o)?1:0;return s?-l*(1+s)**r-a*(1+s*c)*((1+s)**r-1)/s:-(l+a*r)},isExported:!0},Xh={description:s("Future value of principal from series of rates."),args:Ur(`\n principal (number) ${s("The amount of initial capital or value to compound against.")}\n rate_schedule (number, range<number>) ${s("A series of interest rates to compound against the principal.")}\n `),returns:["NUMBER"],compute:function(e,t){return na([t],((e,t)=>e*(1+Gr(t))),Gr(e))},isExported:!0},Kh={description:s("Calculates effective interest rate."),args:Ur(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n investment (number) ${s("The amount invested in the security.")}\n redemption (number) ${s("The amount to be received at maturity.")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o=0){const s=Math.trunc(Gr(e)),r=Math.trunc(Gr(t)),a=Gr(n),l=Gr(i);ah(s,r),Eh(l),dh(a);return(a-l)/l/Xc.compute(s,r,o)},isExported:!0},Qh={description:s("Payment on the principal of an investment."),args:Ur(`\n rate (number) ${s("The annualized rate of interest.")}\n period (number) ${s("The amortization period, in terms of number of periods.")}\n number_of_periods (number) ${s("The number of payments to be made.")}\n present_value (number) ${s("The current value of the annuity.")}\n future_value (number, default=0) ${s("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,n,o=0,s=0){return ad.compute(e,i,n,o,s)-ld.compute(e,t,i,n,o,s)},isExported:!0},Jh={description:s("Internal rate of return given periodic cashflows."),args:Ur(`\n cashflow_amounts (number, range<number>) ${s("An array or range containing the income or payments associated with the investment.")}\n rate_guess (number, default=0.1) ${s("An estimate for what the internal rate of return will be.")}\n `),returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t=.1){const i=Gr(t);Th(i);let n=!1,o=!1,r=[];ta([e],(e=>{e>0&&(n=!0),e<0&&(o=!0),r.push(e)})),Hr((()=>n&&o),s("The cashflow_amounts must include negative and positive values."));const a=r.shift();return Mh((function(e){return function(e,t,i){const n=i.length;let o=0;return i.reduce(((t,i)=>(o++,t+i*e**(n-o))),t*e**n)}(e,a,r)}),(function(e){return function(e,t,i){const n=i.length;let o=0;return i.reduce(((t,i)=>(o++,t+i*(n-o)*e**(n-o-1))),t*n*e**(n-1))}(e,a,r)}),i+1,20,1e-5)-1},isExported:!0},ed={description:s("Returns the interest paid at a particular period of an investment."),args:Ur(`\n rate (number) ${s("The interest rate.")}\n period (number) ${s("The period for which you want to view the interest payment.")}\n number_of_periods (number) ${s("The number of payments to be made.")}\n present_value (number) ${s("The current value of the annuity.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n){const o=Gr(e),r=Gr(t),a=Gr(i),l=Gr(n);Hr((()=>0!==a),s("The number of periods must be different than 0.",a.toString()));return-1*(l-l*(r/a))*o},isExported:!0},td={description:s("Modified Macaulay duration."),args:Ur(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${s("The annualized rate of interest.")}\n yield (number) ${s("The expected annual yield of the security.")}\n frequency (number) ${s("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,s=0){return Zh.compute(e,t,i,n,o,s)/(1+Gr(n)/Math.trunc(Gr(o)))},isExported:!0},id={description:s("Modified internal rate of return."),args:Ur(`\n cashflow_amounts (range<number>) ${s("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")}\n financing_rate (number) ${s("The interest rate paid on funds invested.")}\n reinvestment_return_rate (number) ${s("The return (as a percentage) earned on reinvestment of income received from the investment.")}\n `),returns:["NUMBER"],compute:function(e,t,i){const n=Gr(t),o=Gr(i),r=(a=e,a.length?a[0].map(((e,t)=>a.map((e=>e[t])))):a).flat().filter(Xe).map(Gr);var a;const l=r.length;let c=0,h=0;for(const e of $e(0,l)){const t=r[e];t>=0?c+=t*(o+1)**(l-e-1):h+=t/(n+1)**e}Hr((()=>0!==h&&0!==c),s("There must be both positive and negative values in cashflow_amounts."));return(-c/h)**(1/(l-1))-1},isExported:!0},nd={description:s("Annual nominal interest rate."),args:Ur(`\n effective_rate (number) ${s("The effective interest rate per year.")}\n periods_per_year (number) ${s("The number of compounding periods per year.")}\n `),returns:["NUMBER"],compute:function(e,t){const i=Gr(e),n=Math.trunc(Gr(t));return Hr((()=>i>0),s("The effective rate (%s) must must strictly greater than 0.",i.toString())),Hr((()=>n>0),s("The number of periods by year (%s) must strictly greater than 0.",n.toString())),(Math.pow(i+1,1/n)-1)*n},isExported:!0},od={description:s("Number of payment periods for an investment."),args:Ur(`\n rate (number) ${s("The interest rate.")}\n payment_amount (number) ${s("The amount of each payment made.")}\n present_value (number) ${s("The current value of the annuity.")}\n future_value (number, default=0) ${s("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n=0,o=0){n=n||0,o=o||0;const s=Gr(e),r=Gr(t),a=Gr(i),l=Gr(n),c=Kr(o)?1:0;if(0===s)return-(l+a)/r;const h=r*(1+s*c)/s;return Math.log((h-l)/(a+h))/Math.log(1+s)},isExported:!0};const sd={description:s("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:Ur(`\n discount (number) ${s("The discount rate of the investment over one period.")}\n cashflow1 (number, range<number>) ${s("The first future cash flow.")}\n cashflow2 (number, range<number>, repeating) ${s("Additional future cash flows.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,...t){const i=Gr(e);return Hr((()=>-1!==i),s("The discount (%s) must be different from -1.",i.toString())),function(e,t,i){let n=0;return oa(i,((t,i)=>(n++,t+i/(1+e)**n)),t)}(i,0,t)},isExported:!0},rd={description:s("Computes the number of periods needed for an investment to reach a value."),args:Ur(`\n rate (number) ${s("The rate at which the investment grows each period.")}\n present_value (number) ${s("The investment's current value.")}\n future_value (number) ${s("The investment's desired future value.")}\n `),returns:["NUMBER"],compute:function(e,t,i){const n=Gr(e),o=Gr(t),r=Gr(i);return ph(n),Hr((()=>o>0),s("The present_value (%s) must be strictly positive.",o.toString())),Hr((()=>r>0),s("The future_value (%s) must be strictly positive.",r.toString())),(Math.log(r)-Math.log(o))/Math.log(1+n)},isExported:!0},ad={description:s("Periodic payment for an annuity investment."),args:Ur(`\n rate (number) ${s("The annualized rate of interest.")}\n number_of_periods (number) ${s("The number of payments to be made.")}\n present_value (number) ${s("The current value of the annuity.")}\n future_value (number, default=0) ${s("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,n=0,o=0){n=n||0,o=o||0;const s=Gr(t),r=Gr(e),a=Kr(o)?1:0;let l=Gr(n),c=Gr(i);if(gh(s),0===r)return-(l+c)/s;let h=-(c*(1+r)**s+l);return h=h*r/((1+r*a)*((1+r)**s-1)),h},isExported:!0},ld={description:s("Payment on the principal of an investment."),args:Ur(`\n rate (number) ${s("The annualized rate of interest.")}\n period (number) ${s("The amortization period, in terms of number of periods.")}\n number_of_periods (number) ${s("The number of payments to be made.")}\n present_value (number) ${s("The current value of the annuity.")}\n future_value (number, default=0) ${s("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,n,o=0,r=0){o=o||0,r=r||0;const a=Gr(i),l=Gr(e),c=Gr(t),h=Kr(r)?1:0,d=Gr(o),u=Gr(n);gh(a),Hr((()=>c>0&&c<=a),s("The period must be between 1 and number_of_periods",a.toString()));const g=ad.compute(l,a,u,d,r);if(1===h&&1===c)return g;return g+-Yh.compute(l,0===h?c-1:c-2,g,u+g*h,0)*l},isExported:!0},cd={description:s("Present value of an annuity investment."),args:Ur(`\n rate (number) ${s("The interest rate.")}\n number_of_periods (number) ${s("The number of payments to be made.")}\n payment_amount (number) ${s("The amount per period to be paid.")}\n future_value (number, default=0) ${s("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,n=0,o=0){n=n||0,o=o||0;const s=Gr(e),r=Gr(t),a=Gr(i),l=Gr(n),c=Kr(o)?1:0;return s?-(a*(1+s*c)*((1+s)**r-1)/s+l)/(1+s)**r:-(l+a*r)},isExported:!0},hd={description:s("Price of a security paying periodic interest."),args:Ur(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${s("The annualized rate of interest.")}\n yield (number) ${s("The expected annual yield of the security.")}\n redemption (number) ${s("The redemption amount per 100 face value, or par.")}\n frequency (number) ${s("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,r,a=0){a=a||0;const l=Math.trunc(Gr(e)),c=Math.trunc(Gr(t)),h=Gr(i),d=Gr(n),u=Gr(o),g=Math.trunc(Gr(r)),p=Math.trunc(Gr(a));ah(l,c),ch(g),hh(p),Hr((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),Hr((()=>d>=0),s("The yield (%s) must be positive or null.",d.toString())),dh(u);const m=Xc.compute(l,c,p)*g,f=Math.ceil(m),v=m-Math.floor(m)||1,b=1+d/g,S=100*h/g;if(1===f)return(S+u)/(v*d/g+1)-S*(1-v);let C=0;for(let e=1;e<=f;e++)C+=S/b**(e-1+v);return u/b**(f-1+v)+C-S*(1-v)},isExported:!0},dd={description:s("Price of a discount security."),args:Ur(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n discount (number) ${s("The discount rate of the security at time of purchase.")}\n redemption (number) ${s("The redemption amount per 100 face value, or par.")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o=0){o=o||0;const s=Math.trunc(Gr(e)),r=Math.trunc(Gr(t)),a=Gr(i),l=Gr(n),c=Math.trunc(Gr(o));ah(s,r),hh(c),wh(a),dh(l);return l-a*l*Xc.compute(s,r,c)},isExported:!0},ud={description:s("Calculates the price of a security paying interest at maturity, based on expected yield."),args:Ur(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n issue (date) ${s("The date the security was initially issued.")}\n rate (number) ${s("The annualized rate of interest.")}\n yield (number) ${s("The expected annual yield of the security.")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,r=0){r=r||0;const a=Math.trunc(Gr(e)),l=Math.trunc(Gr(t)),c=Math.trunc(Gr(i)),h=Gr(n),d=Gr(o),u=Math.trunc(Gr(r));lh(a,c),ah(a,l),hh(u),Hr((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),Hr((()=>d>=0),s("The yield (%s) must be positive or null.",d.toString()));const g=Xc.compute(a,l,u),p=Xc.compute(a,c,u);return(100+Xc.compute(c,l,u)*h*100)/(1+g*d)-p*h*100},isExported:!0},gd=.1,pd={description:s("Interest rate of an annuity investment."),args:Ur(`\n number_of_periods (number) ${s("The number of payments to be made.")}\n payment_per_period (number) ${s("The amount per period to be paid.")}\n present_value (number) ${s("The current value of the annuity.")}\n future_value (number, default=0) ${s("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${s("Whether payments are due at the end (0) or beginning (1) of each period.")}\n rate_guess (number, default=0.1) ${s("An estimate for what the interest rate will be.")}\n `),returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t,i,n=0,o=0,r=.1){n=n||0,o=o||0,r=r||gd;const a=Gr(e),l=Gr(t),c=Kr(o)?1:0,h=Gr(r);let d=Gr(n),u=Gr(i);gh(a),Hr((()=>[l,u,d].some((e=>e>0))&&[l,u,d].some((e=>e<0))),s("There must be both positive and negative values in [payment_amount, present_value, future_value].",a.toString())),Th(h),d-=l*c,u+=l*c;return Mh((e=>{const t=Math.pow(1+e,a);return d+u*t+l*((t-1)/e)}),(e=>{const t=Math.pow(1+e,a-1),i=Math.pow(1+e,a);return u*a*t+l*(a*t/e-(i-1)/e/e)}),h,40,1e-5)},isExported:!0},md={description:s("Amount received at maturity for a security."),args:Ur(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n investment (number) ${s("The amount invested (irrespective of face value of each security).")}\n discount (number) ${s("The discount rate of the security invested in.")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o=0){o=o||0;const s=Math.trunc(Gr(e)),r=Math.trunc(Gr(t)),a=Gr(i),l=Gr(n),c=Math.trunc(Gr(o));ah(s,r),hh(c),Eh(a),wh(l);return a/(1-l*Xc.compute(s,r,c))},isExported:!0},fd={description:s("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:Ur(`\n number_of_periods (number) ${s("The number of periods.")}\n present_value (number) ${s("The present value of the investment.")}\n future_value (number) ${s("The future value of the investment.")}\n `),returns:["NUMBER"],compute:function(e,t,i){const n=Gr(e),o=Gr(t),s=Gr(i);return gh(n),(s/o)**(1/n)-1},isExported:!0},vd={description:s("Depreciation of an asset using the straight-line method."),args:Ur(`\n cost (number) ${s("The initial cost of the asset.")}\n salvage (number) ${s("The value of the asset at the end of depreciation.")}\n life (number) ${s("The number of periods over which the asset is depreciated.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i){return(Gr(e)-Gr(t))/Gr(i)},isExported:!0},bd={description:s("Depreciation via sum of years digit method."),args:Ur(`\n cost (number) ${s("The initial cost of the asset.")}\n salvage (number) ${s("The value of the asset at the end of depreciation.")}\n life (number) ${s("The number of periods over which the asset is depreciated.")}\n period (number) ${s("The single period within life for which to calculate depreciation.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,n){const o=Gr(e),s=Gr(t),r=Gr(i),a=Gr(n);vh(a),mh(r),Ch(a,r);return(r-a+1)/(r*(r+1)/2)*(o-s)},isExported:!0},Sd={description:s("Price of a US Treasury bill."),args:Ur(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n discount (number) ${s("The discount rate of the bill at time of purchase.")}\n `),returns:["NUMBER"],compute:function(e,t,i){const n=Math.trunc(Gr(e)),o=Math.trunc(Gr(t)),s=Gr(i);ah(n,o),Rh(n,o),wh(s),yh(s);return 100*(1-s*Xc.compute(n,o,2))},isExported:!0},Cd={description:s("Equivalent rate of return for a US Treasury bill."),args:Ur(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n discount (number) ${s("The discount rate of the bill at time of purchase.")}\n `),returns:["NUMBER"],compute:function(e,t,i){const n=Math.trunc(Gr(e)),o=Math.trunc(Gr(t)),s=Gr(i);ah(n,o),Rh(n,o),wh(s),yh(s);const r=Nc.compute(o,n);if(r<=182)return 365*s/(360-s*r);const a=Sd.compute(n,o,s)/100,l=r/(366===r?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},Ed={description:s("The yield of a US Treasury bill based on price."),args:Ur(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n price (number) ${s("The price at which the security is bought per 100 face value.")}\n `),returns:["NUMBER"],compute:function(e,t,i){const n=Math.trunc(Gr(e)),o=Math.trunc(Gr(t)),s=Gr(i);ah(n,o),Rh(n,o),uh(s);return(100-s)/s*(1/Xc.compute(n,o,2))},isExported:!0},wd={description:s("Variable declining balance. WARNING : does not handle decimal periods."),args:Ur(`\n cost (number) ${s("The initial cost of the asset.")}\n salvage (number) ${s("The value of the asset at the end of depreciation.")}\n life (number) ${s("The number of periods over which the asset is depreciated.")}\n start (number) ${s("Starting period to calculate depreciation.")}\n end (number) ${s("Ending period to calculate depreciation.")}\n factor (number, default=2) ${s("The number of months in the first year of depreciation.")}\n no_switch (number, default=false) ${s("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,r=2,a=false){r=r||0;const l=Gr(e),c=Gr(t),h=Gr(i),d=Math.trunc(Gr(n)),u=Math.trunc(Gr(o)),g=Gr(r),p=Kr(a);if(fh(l),bh(c),function(e,t,i){mh(i),Hr((()=>e>=0),s("The start_period (%s) must be greater or equal than 0.",e.toString())),Hr((()=>t>=0),s("The end_period (%s) must be greater or equal than 0.",t.toString())),Hr((()=>e<=t),s("The start_period (%s) must be smaller or equal to the end_period (%s).",e.toString(),t.toString())),Hr((()=>t<=i),s("The end_period (%s) must be smaller or equal to the life (%s).",e.toString(),i.toString()))}(d,u,h),xh(g),0===l)return 0;if(c>=l)return d<1?l-c:0;const m=g/h;if(m>=1)return d<1?l-c:0;let f=l,v=0,b=0,S=!1;for(let e=0;e<u;e++){if(!S||p){const t=f*m,i=(f-c)/(h-e);!p&&i>t?(S=!0,v=i):v=t}const t=Math.max(f-v,c);e>=d&&(b+=f-t),f=t}return b},isExported:!0},yd={description:s("Internal rate of return given non-periodic cash flows."),args:Ur(`\n cashflow_amounts (range<number>) ${s("An range containing the income or payments associated with the investment.")}\n cashflow_dates (range<number>) ${s("An range with dates corresponding to the cash flows in cashflow_amounts.")}\n rate_guess (number, default=0.1) ${s("An estimate for what the internal rate of return will be.")}\n `),returns:["NUMBER"],compute:function(e,t,i=.1){const n=Gr(i=i||0),o=e.flat().map(Gr),r=t.flat().map(Gr);var a;Ah(e,t),a=o,Hr((()=>a.some((e=>e>0))&&a.some((e=>e<0))),s("There must be both positive and negative values in cashflow_amounts.")),Nh(r),Th(n);const l=new Map;for(const e of $e(0,r.length)){const t=r[e];l.has(t)?l.set(t,l.get(t)+o[e]):l.set(t,o[e])}const c=Array.from(l.keys()),h=c.map((e=>l.get(e)));return Mh((e=>{let t=h[0];for(const i of $e(1,h.length)){const n=(c[0]-c[i])/365;t+=h[i]*(1+e)**n}return t}),(e=>{let t=0;for(const i of $e(1,h.length)){const n=(c[0]-c[i])/365;t+=n*h[i]*(1+e)**(n-1)}return t}),n,40,1e-5,(e=>e?e/10-.9:-.9))},isExported:!0},xd={description:s("Net present value given to non-periodic cash flows.."),args:Ur(`\n discount (number) ${s("The discount rate of the investment over one period.")}\n cashflow_amounts (number, range<number>) ${s("An range containing the income or payments associated with the investment.")}\n cashflow_dates (number, range<number>) ${s("An range with dates corresponding to the cash flows in cashflow_amounts.")}\n `),returns:["NUMBER"],compute:function(e,t,i){const n=Gr(e),o=Array.isArray(t)?t.flat().map(qr):[qr(t)],r=Array.isArray(i)?i.flat().map(qr):[qr(i)];if(Array.isArray(i)&&Array.isArray(t)?Ah(t,i):Hr((()=>o.length===r.length),s("There must be the same number of values in cashflow_amounts and cashflow_dates.")),Nh(r),ph(n),1===o.length)return o[0];const a=new Map;for(const e of $e(0,r.length)){const t=r[e];a.has(t)?a.set(t,a.get(t)+o[e]):a.set(t,o[e])}const l=Array.from(a.keys()),c=l.map((e=>a.get(e)));let h=c[0];for(const e of $e(1,c.length)){const t=(l[0]-l[e])/365;h+=c[e]*(1+n)**t}return h},isExported:!0},Rd={description:s("Annual yield of a security paying periodic interest."),args:Ur(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${s("The annualized rate of interest.")}\n price (number) ${s("The price at which the security is bought per 100 face value.")}\n redemption (number) ${s("The redemption amount per 100 face value, or par.")}\n frequency (number) ${s("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,r,a=0){a=a||0;const l=Math.trunc(Gr(e)),c=Math.trunc(Gr(t)),h=Gr(i),d=Gr(n),u=Gr(o),g=Math.trunc(Gr(r)),p=Math.trunc(Gr(a));ah(l,c),ch(g),hh(p),Hr((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),uh(d),dh(u);const m=Xc.compute(l,c,p)*g,f=Math.ceil(m),v=m-Math.floor(m)||1,b=100*h/g;if(1===f){const e=d+b*(1-v);return(u+b-e)*g*(1/v)/e}const S=Mh((function(e){return function(e,t,i,n,o,s){let r=s-(e+o*(1-t))*n**(i-1+t);for(let e=1;e<=i;e++)r+=o*n**(e-1);return r}(d,v,f,e,b,u)}),(function(e){return function(e,t,i,n,o){let s=-(e+o*(1-t))*(i-1+t)*n**(i-2+t);for(let e=1;e<=i;e++)s+=o*(e-1)*n**(e-2);return s}(d,v,f,e,b)}),1+(h+1)/g,100,1e-5);return(S-1)*g},isExported:!0},Id={description:s("Annual yield of a discount security."),args:Ur(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n price (number) ${s("The price at which the security is bought per 100 face value.")}\n redemption (number) ${s("The redemption amount per 100 face value, or par.")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o=0){o=o||0;const s=Math.trunc(Gr(e)),r=Math.trunc(Gr(t)),a=Gr(i),l=Gr(n),c=Math.trunc(Gr(o));ah(s,r),hh(c),uh(a),dh(l);return(l/a-1)/Xc.compute(e,t,o)},isExported:!0},Td={description:s("Annual yield of a security paying interest at maturity."),args:Ur(`\n settlement (date) ${s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${s("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n issue (date) ${s("The date the security was initially issued.")}\n rate (number) ${s("The annualized rate of interest.")}\n price (number) ${s("The price at which the security is bought.")}\n day_count_convention (number, default=0 ) ${s("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n,o,r=0){r=r||0;const a=Math.trunc(Gr(e)),l=Math.trunc(Gr(t)),c=Math.trunc(Gr(i)),h=Gr(n),d=Gr(o),u=Math.trunc(Gr(r));ah(a,l),hh(u),Hr((()=>a>=c),s("The settlement (%s) must be greater than or equal to the issue (%s).",a.toString(),c.toString())),Hr((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),uh(d);const g=Xc.compute(c,l,u),p=Xc.compute(c,a,u),m=Xc.compute(a,l,u);return(100*(1+h*g)/(d+100*h*p)-1)/m},isExported:!0};var Ad=Object.freeze({__proto__:null,ACCRINTM:_h,AMORLINC:Fh,COUPDAYS:Dh,COUPDAYBS:kh,COUPDAYSNC:$h,COUPNCD:Lh,COUPNUM:Ph,COUPPCD:Uh,CUMIPMT:Vh,CUMPRINC:zh,DB:Bh,DDB:Hh,DISC:Wh,DOLLARDE:Gh,DOLLARFR:qh,DURATION:Zh,EFFECT:jh,FV:Yh,FVSCHEDULE:Xh,INTRATE:Kh,IPMT:Qh,IRR:Jh,ISPMT:ed,MDURATION:td,MIRR:id,NOMINAL:nd,NPER:od,NPV:sd,PDURATION:rd,PMT:ad,PPMT:ld,PV:cd,PRICE:hd,PRICEDISC:dd,PRICEMAT:ud,RATE:pd,RECEIVED:md,RRI:fd,SLN:vd,SYD:bd,TBILLPRICE:Sd,TBILLEQ:Cd,TBILLYIELD:Ed,VDB:wd,XIRR:yd,XNPV:xd,YIELD:Rd,YIELDDISC:Id,YIELDMAT:Td});const Nd={description:s("Whether a value is an error other than #N/A."),args:Ur(`value (any, lazy) ${s("The value to be verified as an error type.")}`),returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return(null==e?void 0:e.errorType)!=a.NotAvailable}},isExported:!0},Od={description:s("Whether a value is an error."),args:Ur(`value (any, lazy) ${s("The value to be verified as an error type.")}`),returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},Md={description:s("Whether a value is `true` or `false`."),args:Ur(`value (any, lazy) ${s("The value to be verified as a logical TRUE or FALSE.")}`),returns:["BOOLEAN"],compute:function(e){try{return"boolean"==typeof e()}catch(e){return!1}},isExported:!0},_d={description:s("Whether a value is the error #N/A."),args:Ur(`value (any, lazy) ${s("The value to be verified as an error type.")}`),returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return(null==e?void 0:e.errorType)==a.NotAvailable}},isExported:!0},Fd={description:s("Whether a value is non-textual."),args:Ur(`value (any, lazy) ${s("The value to be checked.")}`),returns:["BOOLEAN"],compute:function(e){try{return"string"!=typeof e()}catch(e){return!0}},isExported:!0},Dd={description:s("Whether a value is a number."),args:Ur(`value (any, lazy) ${s("The value to be verified as a number.")}`),returns:["BOOLEAN"],compute:function(e){try{return"number"==typeof e()}catch(e){return!1}},isExported:!0},kd={description:s("Whether a value is text."),args:Ur(`value (any, lazy) ${s("The value to be verified as text.")}`),returns:["BOOLEAN"],compute:function(e){try{return"string"==typeof e()}catch(e){return!1}},isExported:!0},$d={description:s("Whether the referenced cell is empty"),args:Ur(`value (any, lazy) ${s("Reference to the cell that will be checked for emptiness.")}`),returns:["BOOLEAN"],compute:function(e){try{return null===e()}catch(e){return!1}},isExported:!0},Ld={description:s("Returns the error value #N/A."),args:Ur(""),returns:["BOOLEAN"],compute:function(e){throw new g},isExported:!0};var Pd=Object.freeze({__proto__:null,ISERR:Nd,ISERROR:Od,ISLOGICAL:Md,ISNA:_d,ISNONTEXT:Fd,ISNUMBER:Dd,ISTEXT:kd,ISBLANK:$d,NA:Ld});const Ud={description:s("Logical `and` operator."),args:Ur(`\n logical_expression1 (boolean, range<boolean>) ${s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${s("More expressions that represent logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!0;return ra(e,(e=>(t=!0,i=i&&e,i))),Hr((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0},Vd={description:s("Returns value depending on logical expression."),args:Ur(`\n logical_expression (boolean) ${s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")}\n value_if_true (any, lazy) ${s("The value the function returns if logical_expression is TRUE.")}\n value_if_false (any, lazy, default=FALSE) ${s("The value the function returns if logical_expression is FALSE.")}\n `),returns:["ANY"],compute:function(e,t,i=(()=>!1)){const n=Kr(e)?t():i();return null==n?"":n},isExported:!0},zd={description:s("Value if it is not an error, otherwise 2nd argument."),args:Ur(`\n value (any, lazy) ${s("The value to return if value itself is not an error.")}\n value_if_error (any, lazy, default=${s("An empty value")}) ${s("The value the function returns if value is an error.")}\n `),returns:["ANY"],computeFormat:(e,t=(()=>({value:""})))=>{var i;try{return e().format}catch(e){return null===(i=t())||void 0===i?void 0:i.format}},compute:function(e,t=(()=>"")){let i;try{i=e()}catch(e){i=t()}return null==i?"":i},isExported:!0},Bd={description:s("Value if it is not an #N/A error, otherwise 2nd argument."),args:Ur(`\n value (any, lazy) ${s("The value to return if value itself is not #N/A an error.")}\n value_if_error (any, lazy, default=${s("An empty value")}) ${s("The value the function returns if value is an #N/A error.")}\n `),returns:["ANY"],compute:function(e,t=(()=>"")){let i;try{i=e()}catch(n){i=n.errorType===a.NotAvailable?t():e()}return null==i?"":i},isExported:!0},Hd={description:s("Returns a value depending on multiple logical expressions."),args:Ur(`\n condition1 (boolean, lazy) ${s("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")}\n value1 (any, lazy) ${s("The returned value if condition1 is TRUE.")}\n condition2 (boolean, lazy, repeating) ${s("Additional conditions to be evaluated if the previous ones are FALSE.")}\n value2 (any, lazy, repeating) ${s("Additional values to be returned if their corresponding conditions are TRUE.")}\n `),returns:["ANY"],compute:function(...e){Hr((()=>e.length%2==0),s("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(Kr(e[t]())){const i=e[t+1]();return null!==i?i:""}throw new Error(s("No match."))},isExported:!0},Wd={description:s("Returns opposite of provided logical value."),args:Ur(`logical_expression (boolean) ${s("An expression or reference to a cell holding an expression that represents some logical value.")}\n `),returns:["BOOLEAN"],compute:function(e){return!Kr(e)},isExported:!0},Gd={description:s("Logical `or` operator."),args:Ur(`\n logical_expression1 (boolean, range<boolean>) ${s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${s("More expressions that evaluate to logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!1;return ra(e,(e=>(t=!0,i=i||e,!i))),Hr((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0},qd={description:s("Logical `xor` operator."),args:Ur(`\n logical_expression1 (boolean, range<boolean>) ${s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${s("More expressions that evaluate to logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!1;return ra(e,(e=>(t=!0,i=i?!e:e,!0))),Hr((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0};var Zd=Object.freeze({__proto__:null,AND:Ud,IF:Vd,IFERROR:zd,IFNA:Bd,IFS:Hd,NOT:Wd,OR:Gd,XOR:qd});const jd={description:s("Column number of a specified cell."),args:Ur(`cell_reference (meta, default=${s("The cell in which the formula is entered")}) ${s("The cell whose column number will be returned. Column A corresponds to 1.")}\n `),returns:["NUMBER"],compute:function(e){var t;const i=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this));Hr((()=>!!i),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Fi(i).left+1},isExported:!0},Yd={description:s("Number of columns in a specified array or range."),args:Ur(`range (meta) ${s("The range whose column count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=Fi(e);return t.right-t.left+1},isExported:!0},Xd={description:s("Horizontal lookup"),args:Ur(`\n search_key (any) ${s("The value to search for. For example, 42, 'Cats', or I24.")}\n range (range) ${s("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")}\n index (number) ${s("The row index of the value to be returned, where the first row in range is numbered 1.")}\n is_sorted (boolean, default=true) ${s("Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned.")}\n `),returns:["ANY"],compute:function(e,t,i,n=true){const o=Math.trunc(Gr(i)),r=Yr(e);Hr((()=>1<=o&&o<=t[0].length),s("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const a=Kr(n);let l;return l=a?ua(t,r,"nextSmaller","asc",t.length,da):ga(t,r,"strict",t.length,da),Hr((()=>l>-1),s("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",Zr(e))),t[l][o-1]},isExported:!0},Kd={description:s("Returns the content of a cell, specified by row and column offset."),args:Ur(`\n reference (any, range) ${s("The range of cells from which the value is returned.")}\n row (number) ${s("The index of the row to be returned from within the reference range of cells.")}\n column (number) ${s("The index of the column to be returned from within the reference range of cells.")}\n`),returns:["ANY"],computeFormat:(e,t,i)=>{var n;const o=Gr(t.value);return null===(n=e[Gr(i.value)-1][o-1])||void 0===n?void 0:n.format},compute:function(e,t,i){const n=(o=e,Array.isArray(o)&&Array.isArray(o[0])?e:[[e]]);var o;const r=Gr(t),a=Gr(i);return Hr((()=>a>=0&&a-1<n.length&&r>=0&&r-1<n[0].length),s("Index out of range.")),Hr((()=>0!==t&&0!==i),s("This function can only return a single cell value, not an array. Provide valid row and column indices.")),n[a-1][r-1]},isExported:!0},Qd={description:s("Look up a value."),args:Ur(`\n search_key (any) ${s("The value to search for. For example, 42, 'Cats', or I24.")}\n search_array (range) ${s("One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.")}\n result_range (range, optional) ${s("The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method.")}\n `),returns:["ANY"],compute:function(e,t,i){let n=t.length,o=t[0].length;const r=Yr(e),a=o>=n,l=ua(t,r,"nextSmaller","asc",a?o:n,a?ha:da);return Hr((()=>l>=0),s("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",Zr(e))),void 0===i?a?t[n-1][l]:t[l][o-1]:(n=i.length,o=i[0].length,Hr((()=>1===n||1===o),s("The result_range must be a single row or a single column.")),n>1?(Hr((()=>l<=n-1),s("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(l+1).toString())),i[l][0]):(Hr((()=>l<=o-1),s("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(l+1).toString())),i[0][l]))},isExported:!0},Jd={description:s("Position of item in range that matches value."),args:Ur(`\n search_key (any) ${s("The value to search for. For example, 42, 'Cats', or I24.")}\n range (any, range) ${s("The one-dimensional array to be searched.")}\n search_type (number, default=1) ${s("The search method. 1 (default) finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order.")}\n `),returns:["NUMBER"],compute:function(e,t,i=1){let n=Gr(i);const o=Yr(e),r=t.length,a=t[0].length;Hr((()=>1===r||1===a),s("The range must be a single row or a single column."));let l=-1;const c=1===r?ha:da,h=1===r?t[0].length:t.length;switch(n=Math.sign(n),n){case 1:l=ua(t,o,"nextSmaller","asc",h,c);break;case 0:l=ga(t,o,"strict",h,c);break;case-1:l=ua(t,o,"nextGreater","desc",h,c)}return Hr((()=>l>=0),s("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",Zr(e))),l+1},isExported:!0},eu={description:s("Row number of a specified cell."),args:Ur(`cell_reference (meta, default=${s("The cell in which the formula is entered by default")}) ${s("The cell whose row number will be returned.")}`),returns:["NUMBER"],compute:function(e){var t;e=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this)),Hr((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Fi(e).top+1},isExported:!0},tu={description:s("Number of rows in a specified array or range."),args:Ur(`range (meta) ${s("The range whose row count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=Fi(e);return t.bottom-t.top+1},isExported:!0},iu={description:s("Vertical lookup."),args:Ur(`\n search_key (any) ${s("The value to search for. For example, 42, 'Cats', or I24.")}\n range (any, range) ${s("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")}\n index (number) ${s("The column index of the value to be returned, where the first column in range is numbered 1.")}\n is_sorted (boolean, default=true) ${s("Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned.")}\n `),returns:["ANY"],compute:function(e,t,i,n=true){const o=Math.trunc(Gr(i)),r=Yr(e);Hr((()=>1<=o&&o<=t.length),s("[[FUNCTION_NAME]] evaluates to an out of bounds range."));const a=Kr(n);let l;return l=a?ua(t,r,"nextSmaller","asc",t[0].length,ha):ga(t,r,"strict",t[0].length,ha),Hr((()=>l>-1),s("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",Zr(e))),t[o-1][l]},isExported:!0},nu={description:s("Search a range for a match and return the corresponding item from a second range."),args:Ur(`\n search_key (any) ${s("The value to search for.")}\n lookup_range (any, range) ${s("The range to consider for the search. Should be a single column or a single row.")}\n return_range (any, range) ${s("The range containing the return value. Should have the same dimensions as lookup_range.")}\n if_not_found (any, lazy, optional) ${s("If a valid match is not found, return this value.")}\n match_mode (any, default=0) ${s("(0) Exact match. (-1) Return next smaller item if no match. (1) Return next greater item if no match.")}\n search_mode (any, default=1) ${s("(1) Search starting at first item. (-1) Search starting at last item. (2) Perform a binary search that relies on lookup_array being sorted in ascending order. If not sorted, invalid results will be returned. (-2) Perform a binary search that relies on lookup_array being sorted in descending order. If not sorted, invalid results will be returned. ")}\n\n `),returns:["ANY"],compute:function(e,t,i,n,o=0,r=1){const a=Math.trunc(Gr(o)),l=Math.trunc(Gr(r)),c=Yr(e);Hr((()=>1===t.length||1===t[0].length),s("lookup_range should be either a single row or single column.")),Hr((()=>1===i.length||1===i[0].length),s("return_range should be either a single row or single column.")),Hr((()=>i.length===t.length&&i[0].length===t[0].length),s("return_range should have the same dimensions as lookup_range.")),Hr((()=>[-1,1,-2,2].includes(l)),s("searchMode should be a value in [-1, 1, -2, 2].")),Hr((()=>[-1,0,1].includes(a)),s("matchMode should be a value in [-1, 0, 1]."));const h=1===t.length?ha:da,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=ua(t,c,u,2===l?"asc":"desc",d,h)}else p=ga(t,c,u,d,h,g);if(-1!==p)return 1===t.length?i[0][p]:i[p][0];const m=null==n?void 0:n();return Hr((()=>!!m),s("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",Zr(e))),m},isExported:!0};var ou=Object.freeze({__proto__:null,COLUMN:jd,COLUMNS:Yd,HLOOKUP:Xd,INDEX:Kd,LOOKUP:Qd,MATCH:Jd,ROW:eu,ROWS:tu,VLOOKUP:iu,XLOOKUP:nu});const su={description:s("Sum of two numbers."),args:Ur(`\n value1 (number) ${s("The first addend.")}\n value2 (number) ${s("The second addend.")}\n `),returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return Gr(e)+Gr(t)}},ru={description:s("Concatenation of two values."),args:Ur(`\n value1 (string) ${s("The value to which value2 will be appended.")}\n value2 (string) ${s("The value to append to value1.")}\n `),returns:["STRING"],compute:function(e,t){return Zr(e)+Zr(t)},isExported:!0},au={description:s("One number divided by another."),args:Ur(`\n dividend (number) ${s("The number to be divided.")}\n divisor (number) ${s("The number to divide by.")}\n `),returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){const i=Gr(t);return Hr((()=>0!==i),s("The divisor must be different from zero.")),Gr(e)/i}};function lu(e){return null==e}const cu={number:0,string:"",boolean:!1},hu={description:s("Equal."),args:Ur(`\n value1 (any) ${s("The first value.")}\n value2 (any) ${s("The value to test against value1 for equality.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return e=lu(e)?cu[typeof t]:e,t=lu(t)?cu[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function du(e,t,i){e=lu(e)?cu[typeof t]:e,t=lu(t)?cu[typeof e]:t,"number"!=typeof e&&(e=Zr(e).toUpperCase()),"number"!=typeof t&&(t=Zr(t).toUpperCase());const n=typeof e,o=typeof t;return"string"===n&&"number"===o||("string"!==o||"number"!==n)&&i(e,t)}const uu={description:s("Strictly greater than."),args:Ur(`\n value1 (any) ${s("The value to test as being greater than value2.")}\n value2 (any) ${s("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return du(e,t,((e,t)=>e>t))}},gu={description:s("Greater than or equal to."),args:Ur(`\n value1 (any) ${s("The value to test as being greater than or equal to value2.")}\n value2 (any) ${s("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return du(e,t,((e,t)=>e>=t))}},pu={description:s("Less than."),args:Ur(`\n value1 (any) ${s("The value to test as being less than value2.")}\n value2 (any) ${s("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!gu.compute(e,t)}},mu={description:s("Less than or equal to."),args:Ur(`\n value1 (any) ${s("The value to test as being less than or equal to value2.")}\n value2 (any) ${s("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!uu.compute(e,t)}},fu={description:s("Difference of two numbers."),args:Ur(`\n value1 (number) ${s("The minuend, or number to be subtracted from.")}\n value2 (number) ${s("The subtrahend, or number to subtract from value1.")}\n `),returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return Gr(e)-Gr(t)}},vu={description:s("Product of two numbers"),args:Ur(`\n factor1 (number) ${s("The first multiplicand.")}\n factor2 (number) ${s("The second multiplicand.")}\n `),returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return Gr(e)*Gr(t)}},bu={description:s("Not equal."),args:Ur(`\n value1 (any) ${s("The first value.")}\n value2 (any) ${s("The value to test against value1 for inequality.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!hu.compute(e,t)}},Su={description:s("A number raised to a power."),args:Ur(`\n base (number) ${s("The number to raise to the exponent power.")}\n exponent (number) ${s("The exponent to raise base to.")}\n `),returns:["NUMBER"],compute:function(e,t){return il.compute(e,t)}},Cu={description:s("A number with the sign reversed."),args:Ur(`\n value (number) ${s("The number to have its sign reversed. Equivalently, the number to multiply by -1.")}\n `),computeFormat:e=>null==e?void 0:e.format,returns:["NUMBER"],compute:function(e){return-Gr(e)}},Eu={description:s("Value interpreted as a percentage."),args:Ur(`\n percentage (number) ${s("The value to interpret as a percentage.")}\n `),returns:["NUMBER"],compute:function(e){return Gr(e)/100}},wu={description:s("A specified number, unchanged."),args:Ur(`\n value (any) ${s("The number to return.")}\n `),returns:["ANY"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){return null===e?"":e}};var yu=Object.freeze({__proto__:null,ADD:su,CONCAT:ru,DIVIDE:au,EQ:hu,GT:uu,GTE:gu,LT:pu,LTE:mu,MINUS:fu,MULTIPLY:vu,NE:bu,POW:Su,UMINUS:Cu,UNARY_PERCENT:Eu,UPLUS:wu});const xu=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,Ru={description:s("Gets character associated with number."),args:Ur(`\n table_number (number) ${s("The number of the character to look up from the current Unicode table in decimal format.")}\n `),returns:["STRING"],compute:function(e){const t=Math.trunc(Gr(e));return Hr((()=>t>=1),s("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},Iu={description:s("Remove non-printable characters from a piece of text."),args:Ur(`\n text (string) ${s("The text whose non-printable characters are to be removed.")}\n `),returns:["STRING"],compute:function(e){const t=Zr(e);let i="";for(const e of t)e&&e.charCodeAt(0)>31&&(i+=e);return i},isExported:!0},Tu={description:s("Appends strings to one another."),args:Ur(`\n string1 (string, range<string>) ${s("The initial string.")}\n string2 (string, range<string>, repeating) ${s("More strings to append in sequence.")}\n `),returns:["STRING"],compute:function(...e){return na(e,((e,t)=>e+Zr(t)),"")},isExported:!0},Au={description:s("Tests whether two strings are identical."),args:Ur(`\n string1 (string) ${s("The first string to compare.")}\n string2 (string) ${s("The second string to compare.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return Zr(e)===Zr(t)},isExported:!0},Nu={description:s("First position of string found in text, case-sensitive."),args:Ur(`\n search_for (string) ${s("The string to look for within text_to_search.")}\n text_to_search (string) ${s("The text to search for the first occurrence of search_for.")}\n starting_at (number, default=1) ${s("The character within text_to_search at which to start the search.")}\n `),returns:["NUMBER"],compute:function(e,t,i=1){const n=Zr(e),o=Zr(t),r=Gr(i);Hr((()=>""!==o),s("The text_to_search must be non-empty.")),Hr((()=>r>=1),s("The starting_at (%s) must be greater than or equal to 1.",r.toString()));const a=o.indexOf(n,r-1);return Hr((()=>a>=0),s("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",n.toString(),o)),a+1},isExported:!0},Ou={description:s("Concatenates elements of arrays with delimiter."),args:Ur(`\n delimiter (string) ${s("The character or string to place between each concatenated value.")}\n value_or_array1 (string, range<string>) ${s("The value or values to be appended using delimiter.")}\n value_or_array2 (string, range<string>, repeating) ${s("More values to be appended using delimiter.")}\n `),returns:["STRING"],compute:function(e,...t){const i=Zr(e);return na(t,((e,t)=>(e?e+i:"")+Zr(t)),"")}},Mu={description:s("Substring from beginning of specified string."),args:Ur(`\n text (string) ${s("The string from which the left portion will be returned.")}\n number_of_characters (number, optional) ${s("The number of characters to return from the left side of string.")}\n `),returns:["STRING"],compute:function(e,...t){const i=t.length?Gr(t[0]):1;return Hr((()=>i>=0),s("The number_of_characters (%s) must be positive or null.",i.toString())),Zr(e).substring(0,i)},isExported:!0},_u={description:s("Length of a string."),args:Ur(`\n text (string) ${s("The string whose length will be returned.")}\n `),returns:["NUMBER"],compute:function(e){return Zr(e).length},isExported:!0},Fu={description:s("Converts a specified string to lowercase."),args:Ur(`\n text (string) ${s("The string to convert to lowercase.")}\n `),returns:["STRING"],compute:function(e){return Zr(e).toLowerCase()},isExported:!0},Du={description:s("A segment of a string."),args:Ur(`\n text (string) ${s("The string to extract a segment from.")}\n starting_at (number) ${s("The index from the left of string from which to begin extracting. The first character in string has the index 1.")}\n extract_length (number) ${s("The length of the segment to extract.")}\n `),returns:["STRING"],compute:function(e,t,i){const n=Zr(e),o=Gr(t),r=Gr(i);return Hr((()=>o>=1),s("The starting_at argument (%s) must be positive greater than one.",o.toString())),Hr((()=>r>=0),s("The extract_length argument (%s) must be positive or null.",r.toString())),n.slice(o-1,o+r-1)},isExported:!0},ku={description:s("Capitalizes each word in a specified string."),args:Ur(`\n text_to_capitalize (string) ${s("The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase.")}\n `),returns:["STRING"],compute:function(e){return Zr(e).replace(xu,(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()))},isExported:!0},$u={description:s("Replaces part of a text string with different text."),args:Ur(`\n text (string) ${s("The text, a part of which will be replaced.")}\n position (number) ${s("The position where the replacement will begin (starting from 1).")}\n length (number) ${s("The number of characters in the text to be replaced.")}\n new_text (string) ${s("The text which will be inserted into the original text.")}\n `),returns:["STRING"],compute:function(e,t,i,n){const o=Gr(t);Hr((()=>o>=1),s("The position (%s) must be greater than or equal to 1.",o.toString()));const r=Zr(e),a=Gr(i),l=Zr(n);return r.substring(0,o-1)+l+r.substring(o-1+a)},isExported:!0},Lu={description:s("A substring from the end of a specified string."),args:Ur(`\n text (string) ${s("The string from which the right portion will be returned.")}\n number_of_characters (number, optional) ${s("The number of characters to return from the right side of string.")}\n `),returns:["STRING"],compute:function(e,...t){const i=t.length?Gr(t[0]):1;Hr((()=>i>=0),s("The number_of_characters (%s) must be positive or null.",i.toString()));const n=Zr(e),o=n.length;return n.substring(o-i,o)},isExported:!0},Pu={description:s("First position of string found in text, ignoring case."),args:Ur(`\n search_for (string) ${s("The string to look for within text_to_search.")}\n text_to_search (string) ${s("The text to search for the first occurrence of search_for.")}\n starting_at (number, default=1) ${s("The character within text_to_search at which to start the search.")}\n `),returns:["NUMBER"],compute:function(e,t,i=1){const n=Zr(e).toLowerCase(),o=Zr(t).toLowerCase(),r=Gr(i);Hr((()=>""!==o),s("The text_to_search must be non-empty.")),Hr((()=>r>=1),s("The starting_at (%s) must be greater than or equal to 1.",r.toString()));const a=o.indexOf(n,r-1);return Hr((()=>a>=0),s("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",n,o)),a+1},isExported:!0},Uu={description:s("Replaces existing text with new text in a string."),args:Ur(`\n text_to_search (string) ${s("The text within which to search and replace.")}\n search_for (string) ${s("The string to search for within text_to_search.")}\n replace_with (string) ${s("The string that will replace search_for.")}\n occurrence_number (number, optional) ${s("The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced.")}\n `),returns:["NUMBER"],compute:function(e,t,i,n){const o=Gr(n);Hr((()=>o>=0),s("The occurrenceNumber (%s) must be positive or null.",o.toString()));const r=Zr(e),a=Zr(t);if(""===a)return r;const l=Zr(i),c=new RegExp(Te(a),"g");if(0===o)return r.replace(c,l);let h=0;return r.replace(c,(e=>++h===o?l:e))},isExported:!0},Vu={description:s("Combines text from multiple strings and/or arrays."),args:Ur(`\n delimiter (string) ${s(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")}\n ignore_empty (boolean) ${s("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")}\n text1 (string, range<string>) ${s("Any text item. This could be a string, or an array of strings in a range.")}\n text2 (string, range<string>, repeating) ${s("Additional text item(s).")}\n `),returns:["STRING"],compute:function(e,t,...i){const n=Zr(e),o=Kr(t);let s=0;return na(i,((e,t)=>o&&""===Zr(t)?e:(s++?e+n:"")+Zr(t)),"")},isExported:!0},zu={description:s("Removes space characters."),args:Ur(`\n text (string) ${s("The text or reference to a cell containing text to be trimmed.")}\n `),returns:["STRING"],compute:function(e){return Zr(e).trim()},isExported:!0},Bu={description:s("Converts a specified string to uppercase."),args:Ur(`\n text (string) ${s("The string to convert to uppercase.")}\n `),returns:["STRING"],compute:function(e){return Zr(e).toUpperCase()},isExported:!0},Hu={description:s("Converts a number to text according to a specified format."),args:Ur(`\n number (number) ${s("The number, date or time to format.")}\n format (string) ${s("The pattern by which to format the number, enclosed in quotation marks.")}\n `),returns:["STRING"],compute:function(e,t){return Qt(Gr(e),Zr(t))},isExported:!0};const Wu={database:Rc,date:oh,financial:Ad,info:Pd,lookup:ou,logical:Zd,math:Cl,misc:fa,operators:yu,statistical:hc,text:Object.freeze({__proto__:null,CHAR:Ru,CLEAN:Iu,CONCATENATE:Tu,EXACT:Au,FIND:Nu,JOIN:Ou,LEFT:Mu,LEN:_u,LOWER:Fu,MID:Du,PROPER:ku,REPLACE:$u,RIGHT:Lu,SEARCH:Pu,SUBSTITUTE:Uu,TEXTJOIN:Vu,TRIM:zu,UPPER:Bu,TEXT:Hu}),engineering:rh},Gu=/^[A-Z0-9\_\.]+$/;function qu(e){return e.map((e=>{if(void 0!==e)return"function"==typeof e?()=>Zu(e()):Zu(e)}))}function Zu(e){return Array.isArray(e)?e.map((e=>e.map((e=>null==e?void 0:e.value)))):null==e?void 0:e.value}const ju=new class extends sn{constructor(){super(...arguments),this.mapping={}}add(e,t){if(!(e=e.toUpperCase()).match(Gu))throw new Error(s("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const i=zr(t);return function(e){let t=!1,i=!1,n=!1;for(let o of e){if(o.type.includes("META")&&o.type.length>1)throw new Error(s("Function ${name} has an argument that has been declared with more than one type whose type 'META'. The 'META' type can only be declared alone."));if(t&&!o.repeating)throw new Error(s("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=i||t||n,r=!(o.optional||o.repeating||o.default);if(e&&r)throw new Error(s("Function ${name} has at mandatory arguments declared after optional ones. All optional arguments must be after all mandatory arguments."));t=o.repeating,i=o.optional,n=o.default}}(i.args),this.mapping[e]=function(...e){const t=i.compute.bind(this),n=i.computeFormat?i.computeFormat.bind(this):()=>{};return{value:t(...qu(e)),format:n(...e)}},super.add(e,i),this}};for(let e in Wu){const t=Wu[e];for(let i in t){const n=t[i];n.category=e,i=i.replace(/_/g,"."),ju.add(i,{isExported:!1,...n})}}const Yu=ju.content,Xu=["%"],Ku="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(Xu);function Qu(e){const t=e.split(""),i=[];for(;t.length;){let e=hg(t)||tg(t)||ng(t)||sg(t)||Ju(t)||dg(t)||og(t)||lg(t);e||(e={type:"UNKNOWN",value:t.shift()}),i.push(e)}return i}function Ju(e){return"?"===e[0]?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const eg={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function tg(e){if(e[0]in eg){const t=e.shift();return{type:eg[t],value:t}}return null}function ig(e,t){for(let i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0}function ng(e){for(let t of Ku)if(ig(e,t))return e.splice(0,t.length),{type:"OPERATOR",value:t};return null}function og(e){const t=et(e).match(pi);return t?(e.splice(0,t[0].length),{type:"NUMBER",value:t[0]}):null}function sg(e){if('"'===e[0]){const t=e.shift();let i=t;for(;e[0]&&(e[0]!==t||"\\"===i[i.length-1]);)i+=e.shift();return'"'===e[0]&&(i+=e.shift()),{type:"STRING",value:i}}return null}const rg=/\p{L}|\p{N}|_|\.|!|\$/u,ag=new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$");function lg(e){let t="";if("'"===e[0]){let i=e.shift();for(t+=i;e[0];)if(i=e.shift(),t+=i,"'"===i){if(!e[0]||"'"!==e[0])break;i=e.shift(),t+=i}if("'"!==i)return{type:"UNKNOWN",value:t}}for(;e[0]&&(ag.has(e[0])||e[0].match(rg));)t+=e.shift();if(t.length){const e=t;if(e.toUpperCase()in Yu)return{type:"FUNCTION",value:e};return e.match(Ot)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}const cg=/\s/;function hg(e){let t="";for(;e[0]&&e[0].match(cg);)t+=e.shift();return t?{type:"SPACE",value:t}:null}function dg(e){return ig(e,X)?(e.splice(0,X.length),{type:"INVALID_REFERENCE",value:X}):null}var ug;!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"}(ug||(ug={}));const gg=(e,t=(()=>!0))=>[{goTo:e,guard:t}],pg=(e,t=(()=>!0))=>({goTo:e,guard:t}),mg={[ug.LeftRef]:{REFERENCE:gg(ug.Separator),NUMBER:gg(ug.FullRowSeparator),SYMBOL:[pg(ug.FullColumnSeparator,(e=>Mt(e.value))),pg(ug.FullRowSeparator,(e=>_t(e.value)))]},[ug.FullColumnSeparator]:{SPACE:gg(ug.FullColumnSeparator),OPERATOR:gg(ug.RightColumnRef,(e=>":"===e.value))},[ug.FullRowSeparator]:{SPACE:gg(ug.FullRowSeparator),OPERATOR:gg(ug.RightRowRef,(e=>":"===e.value))},[ug.Separator]:{SPACE:gg(ug.Separator),OPERATOR:gg(ug.RightRef,(e=>":"===e.value))},[ug.RightRef]:{SPACE:gg(ug.RightRef),NUMBER:gg(ug.Found),REFERENCE:gg(ug.Found,(e=>kt(e.value))),SYMBOL:gg(ug.Found,(e=>Ft(e.value)||Dt(e.value)))},[ug.RightColumnRef]:{SPACE:gg(ug.RightColumnRef),SYMBOL:gg(ug.Found,(e=>Ft(e.value))),REFERENCE:gg(ug.Found,(e=>kt(e.value)))},[ug.RightRowRef]:{SPACE:gg(ug.RightRowRef),NUMBER:gg(ug.Found),REFERENCE:gg(ug.Found,(e=>kt(e.value))),SYMBOL:gg(ug.Found,(e=>Dt(e.value)))},[ug.Found]:{}};function fg(e){var t;let i=0,n=mg[ug.LeftRef],o="";for(;void 0!==n;){const s=e[i++];if(!s)return null;const r=null===(t=n[s.type])||void 0===t?void 0:t.find((e=>e.guard(s))),a=r?r.goTo:void 0;switch(a){case void 0:return null;case ug.Found:return o+=s.value,e.splice(0,i),{type:"REFERENCE",value:o};default:n=mg[a],o+=s.value}}return null}function vg(e){const t=Qu(e),i=[];for(;t.length;)i.push(fg(t)||t.shift());return i}const bg=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,Sg=["-","+"],Cg=["%"],Eg=["*","+","&"],wg={"^":30,"%":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10},yg=6;function xg(e){switch(e.type){case"NUMBER":case"SYMBOL":case"REFERENCE":return 0;case"COMMA":return 3;case"LEFT_PAREN":case"RIGHT_PAREN":return 5;case"OPERATOR":return wg[e.value]||15}throw new Error(s("Unknown token: %s",e.value))}function Rg(e,t,i){if("OPERATOR"===t.type){const n=xg(t);if(Cg.includes(t.value))return{type:"UNARY_OPERATION",value:t.value,operand:e,postfix:!0};{const o=Ig(i,n);return{type:"BIN_OPERATION",value:t.value,left:e,right:o}}}throw new Error(ne)}function Ig(e,t){const i=e.shift();if(!i)throw new Error(ne);let n=function(e,t){var i,n,o,r;switch(e.type){case"DEBUGGER":const l=Ig(t,1e3);return l.debug=!0,l;case"NUMBER":return{type:"NUMBER",value:wi(e.value)};case"STRING":return{type:"STRING",value:Ie(e.value)};case"FUNCTION":if("LEFT_PAREN"!==t.shift().type)throw new Error(s("Wrong function call"));{const n=[];if(t[0]&&"RIGHT_PAREN"!==t[0].type)for("COMMA"===t[0].type?n.push({type:"UNKNOWN",value:""}):n.push(Ig(t,yg));"COMMA"===(null===(i=t[0])||void 0===i?void 0:i.type);){t.shift();const e=t[0];if("RIGHT_PAREN"===(null==e?void 0:e.type)){n.push({type:"UNKNOWN",value:""});break}"COMMA"===(null==e?void 0:e.type)?n.push({type:"UNKNOWN",value:""}):n.push(Ig(t,yg))}const o=t.shift();if(!o||"RIGHT_PAREN"!==o.type)throw new Error(s("Wrong function call"));return{type:"FUNCALL",value:e.value,args:n}}case"INVALID_REFERENCE":return{type:"REFERENCE",value:a.InvalidReference};case"REFERENCE":if(":"===(null===(n=t[0])||void 0===n?void 0:n.value)&&"REFERENCE"===(null===(o=t[1])||void 0===o?void 0:o.type)){t.shift();const i=t.shift();return{type:"REFERENCE",value:`${e.value}:${null==i?void 0:i.value}`}}return{type:"REFERENCE",value:e.value};case"SYMBOL":if(["TRUE","FALSE"].includes(e.value.toUpperCase()))return{type:"BOOLEAN",value:"TRUE"===e.value.toUpperCase()};if(e.value){if(bg.test(e.value)&&"LEFT_PAREN"===(null===(r=t[0])||void 0===r?void 0:r.type))throw new p(e.value);throw new Error(s("Invalid formula"))}return{type:"STRING",value:e.value};case"LEFT_PAREN":const c=Ig(t,5);if(!t.length||"RIGHT_PAREN"!==t[0].type)throw new Error(s("Unmatched left parenthesis"));return t.shift(),c;default:if("OPERATOR"===e.type&&Sg.includes(e.value))return{type:"UNARY_OPERATION",value:e.value,operand:Ig(t,wg[e.value])};throw new Error(s("Unexpected token: %s",e.value))}}(i,e);for(;e[0]&&xg(e[0])>t;)n=Rg(n,e.shift(),e);return n}function Tg(e){return Ag(vg(e))}function Ag(e){(e=e.filter((e=>"SPACE"!==e.type)))[0]&&"OPERATOR"===e[0].type&&"="===e[0].value&&e.splice(0,1);const t=Ig(e,0);if(e.length)throw new Error(ne);return t}function Ng(e,t,i){switch(t===e.type&&(e=i(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>Ng(e,t,i)))};case"UNARY_OPERATION":return{...e,operand:Ng(e.operand,t,i)};case"BIN_OPERATION":return{...e,right:Ng(e.right,t,i),left:Ng(e.left,t,i)};default:return e}}function Og(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>Og(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?Mg(e)+e.value:e.value+_g(e);case"BIN_OPERATION":return Mg(e)+e.value+_g(e)}}function Mg(e){const t=e.value,i="left"in e?e.left:e.operand,n=i.value;return"BIN_OPERATION"===i.type&&wg[n]<wg[t]?`(${Og(i)})`:Og(i)}function _g(e){const t=e.value,i="right"in e?e.right:e.operand,n=wg[i.value],o=wg[t];let s=!1;return"BIN_OPERATION"!==i.type?s=!1:n<o?s=!0:n!==o||Eg.includes(t)||(s=!0),s?`(${Og(i)})`:Og(i)}const Fg=ju.content,Dg={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},kg={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"};function $g(e){return e.join("\n").split("\n").filter((e=>""!==e.trim()))}const Lg={};function Pg(e){const t=vg(e),{dependencies:i,constantValues:n}=function(e){const t={numbers:[],strings:[]},i=[];for(const n of e)switch(n.type){case"INVALID_REFERENCE":case"REFERENCE":i.push(n.value);break;case"STRING":const e=Ie(n.value);t.strings.includes(e)||t.strings.push(e);break;case"NUMBER":{const e=wi(n.value);t.numbers.includes(e)||t.numbers.push(e);break}}return{dependencies:i,constantValues:t}}(t),o=function(e,t,i){return et(e.map((e=>{switch(e.type){case"STRING":const n=Ie(e.value);return`|S${i.strings.indexOf(n)}|`;case"NUMBER":return`|N${i.numbers.indexOf(wi(e.value))}|`;case"REFERENCE":case"INVALID_REFERENCE":return`|${t.indexOf(e.value)}|`;case"SPACE":return"";default:return e.value}})))}(t,i,n);if(!Lg[o]){const r=Ag([...t]);let a=1;if("BIN_OPERATION"===r.type&&":"===r.value)throw new Error(s("Invalid formula"));if("UNKNOWN"===r.type)throw new Error(s("Invalid formula"));const l=u(r),c=$g([`// ${o}`,l.code,`return ${l.id};`]).join("\n");let h=new Function("deps","ref","range","ctx",c);function d(e){const t=Fg[e.value.toUpperCase()],i=e.args,n=i.length;if(n<t.minArgRequired)throw new Error(s("Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.",e.value.toUpperCase(),t.minArgRequired.toString(),n.toString()));if(n>t.maxArgPossible)throw new Error(s("Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.",e.value.toUpperCase(),t.maxArgPossible.toString(),n.toString()));const o=t.nbrArgRepeating;if(o>1){const i=t.args.length-o;if((n-i)%o!=0)throw new Error(s("Invalid number of arguments for the %s function. Expected all arguments after position %s to be supplied by groups of %s arguments",e.value.toUpperCase(),i.toString(),o.toString()))}let r=[];for(let o=0;o<n;o++){const n=t.getArgToFocus(o+1)-1;if(0<=n&&n<t.args.length){const a=i[o],l=t.args[n],c=l.type||[],h=c.includes("META"),d=l.lazy,g=c.some((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e)),p=c.every((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e));if(p&&"REFERENCE"!==a.type)throw new Error(s("Function %s expects the parameter %s to be reference to a cell or range, not a %s.",e.value.toUpperCase(),(o+1).toString(),a.type.toLowerCase()));const m=u(a,d,h,g,{functionName:e.value.toUpperCase(),paramIndex:o+1});r.push(m)}}return r}function u(e,t=!1,o=!1,r=!1,l={}){const c=[];let h,g,p;if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&o)throw new Error(s("Argument must be a reference to a cell or range."));switch(e.debug&&c.push("debugger;"),e.type){case"BOOLEAN":if(!t)return{id:`{ value: ${e.value} }`,code:""};h=a++,p=`{ value: ${e.value} }`;break;case"NUMBER":h=a++,p=`{ value: this.constantValues.numbers[${n.numbers.indexOf(e.value)}] }`;break;case"STRING":h=a++,p=`{ value: this.constantValues.strings[${n.strings.indexOf(e.value)}] }`;break;case"REFERENCE":const s=i.indexOf(e.value);h=a++,p=r?`range(deps[${s}])`:`ref(deps[${s}], ${o?"true":"false"}, "${l.functionName||Dg["="]}", ${l.paramIndex})`;break;case"FUNCALL":h=a++;const m=d(e);c.push(m.map((e=>e.code)).join("\n")),g=e.value.toUpperCase(),c.push(`ctx.__lastFnCalled = '${g}';`),p=`ctx['${g}'](${m.map((e=>e.id))})`;break;case"UNARY_OPERATION":{h=a++,g=kg[e.value];const t=u(e.operand,!1,!1,!1,{functionName:g});c.push(t.code),c.push(`ctx.__lastFnCalled = '${g}';`),p=`ctx['${g}'](${t.id})`;break}case"BIN_OPERATION":{h=a++,g=Dg[e.value];const t=u(e.left,!1,!1,!1,{functionName:g}),i=u(e.right,!1,!1,!1,{functionName:g});c.push(t.code),c.push(i.code),c.push(`ctx.__lastFnCalled = '${g}';`),p=`ctx['${g}'](${t.id}, ${i.id})`;break}case"UNKNOWN":if(!t)return{id:"undefined",code:""};h=a++,p="undefined"}if(t){return{id:`_${h}`,code:`const _${h} = () => {\n\t${$g(c).join("\n\t")}\n\treturn ${p};\n}`}}return c.push(`let _${h} = ${p};`),{id:`_${h}`,code:c.join("\n")}}Lg[o]={execute:h}}return{execute:Lg[o].execute,dependencies:i,constantValues:n,tokens:t}}function Ug(e){return function(e){let t=[],i="";return e.map(((e,n)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(i=""),e.type){case"FUNCTION":i=e.value;break;case"LEFT_PAREN":t.push({parent:i,argPosition:0}),i="";break;case"RIGHT_PAREN":t.pop();break;case"COMMA":t.length&&t[t.length-1].argPosition++}if(t.length){const i=t[t.length-1];i.parent&&(e.functionContext=Object.assign({},i))}return e}))}(function(e){let t=1;const i=[];return e.map((e=>("LEFT_PAREN"===e.type?(i.push(t),e.parenIndex=t,t++):"RIGHT_PAREN"===e.type&&(e.parenIndex=i.pop()),e)))}(function(e){let t=0;return e.map((e=>{const i=e.value.toString().length,n=Object.assign({},e,{start:t,end:t+i,length:i});return t=n.end,n}))}(vg(e))))}function Vg(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:i}=$t(e.value),[n,o]=t.split(":"),s=i?`${Oe(i)}!`:"",r=zg(n),a=o?`:${zg(o)}`:"";return{...e,value:s+r+a}}function zg(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=Bg(e,"colrow");break;case"colrow":e=Bg(e,"row");break;case"row":e=Bg(e,"col");break;case"col":e=Bg(e,"none")}return e}function Bg(e,t){let i;switch(e=e.replace(/\$/g,""),t){case"col":return"$"+e;case"row":return i=e.search(/[0-9]/),e.slice(0,i)+"$"+e.slice(i);case"colrow":return i=e.search(/[0-9]/),-1===i||0===i?"$"+e:"$"+(e=e.slice(0,i)+"$"+e.slice(i));case"none":return e}}class Hg{constructor(e,t,i){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t}exportForExcel(e){}allowDispatch(e){return 0}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map((e=>e.call(this,t))).flat()}chainValidations(...e){return t=>{for(const i of e){let e=i.call(this,t);Array.isArray(e)||(e=[e]);const n=e.filter((e=>0!==e));if(n.length)return n}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}Hg.getters=[];class Wg extends Hg{constructor(e,t,i,n,o){super(t,i,n),this.getters=e,this.ui=n,this.selection=o}drawGrid(e,t){}}Wg.layers=[];const Gg=s("The cell you are trying to edit has been deleted.");class qg extends Wg{constructor(){super(...arguments),this.col=0,this.row=0,this.mode="inactive",this.sheetId="",this.currentContent="",this.currentTokens=[],this.selectionStart=0,this.selectionEnd=0,this.selectionInitialStart=0,this.initialContent="",this.previousRef="",this.previousRange=void 0,this.colorIndexByRange={}}allowDispatch(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":return this.validateSelection(this.currentContent.length,e.start,e.end);case"SET_CURRENT_CONTENT":return e.selection?this.validateSelection(e.content.length,e.selection.start,e.selection.end):0;case"START_EDITION":if(e.selection){const t=this.getters.getActiveCell(),i=e.text||(null==t?void 0:t.composerContent)||"";return this.validateSelection(i.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":this.startEdition(e.text,e.selection),this.updateRangeColor();break;case"STOP_EDITION":e.cancel?(this.resetContent(),this.cancelEditionAndActivateSheet()):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.resetContent(),this.cancelEditionAndActivateSheet();break;case"ADD_COLUMNS_ROWS":this.onAddElements(e);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case"START_CHANGE_HIGHLIGHT":this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const t=this.getters.getRangeFromRangeData(e.range),i=this.currentTokens.filter((e=>"REFERENCE"===e.type)).find((e=>{const{xc:i,sheetName:n}=$t(e.value),o=n||this.getters.getSheetName(this.sheetId),s=this.getters.getActiveSheetId();if(!Ai(this.getters.getSheetName(s),o))return!1;const r=this.getters.getRangeFromSheetXC(s,i);return Bi(this.getters.expandZone(s,r.zone),t.zone)}));this.previousRef=i.value,this.previousRange=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),this.previousRef),this.selectionInitialStart=i.start;break;case"CHANGE_HIGHLIGHT":const n=this.getters.getRangeFromRangeData(e.range),o=this.getRangeReference(n,this.previousRange.parts);this.selectionStart=this.selectionInitialStart,this.selectionEnd=this.selectionInitialStart+this.previousRef.length,this.replaceSelection(o),this.previousRef=o,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{col:t,row:i}=this.getters.getNextVisibleCellPosition(e.sheetIdTo,0,0),n=this.getters.expandZone(e.sheetIdTo,en({col:t,row:i}));this.selection.resetAnchor(this,{cell:{col:t,row:i},zone:n})}break;case"DELETE_SHEET":case"UNDO":case"REDO":!!this.getters.tryGetSheet(this.sheetId)||"inactive"===this.mode||(this.sheetId=this.getters.getActiveSheetId(),this.resetContent(),this.cancelEditionAndActivateSheet(),this.ui.notifyUI({type:"ERROR",text:Gg}));break;case"CYCLE_EDITION_REFERENCES":this.cycleReferences()}}getEditionMode(){return this.mode}getCurrentContent(){if("inactive"===this.mode){const e=this.getters.getActiveCell();return(null==e?void 0:e.composerContent)||""}return this.currentContent}getEditionSheet(){return this.sheetId}getComposerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}isSelectingForComposer(){return"selecting"===this.mode}showSelectionIndicator(){return this.isSelectingForComposer()&&this.canStartComposerRangeSelection()}getCurrentTokens(){return this.currentTokens}getTokenAtCursor(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return e===t&&0===t?void 0:this.currentTokens.find((i=>i.start<=e&&i.end>=t))}cycleReferences(){const e=this.getTokensInSelection(),t=e.filter((e=>"REFERENCE"===e.type));if(0===t.length)return;const i=e.map(Vg).map((e=>e.value)).join(""),n=this.currentContent,o=e[0].start,s=e[e.length-1].end,r=n.slice(0,o)+i+n.slice(s),a=r.length-n.length,l={start:t[0].start,end:t[t.length-1].end+a};1===t.length&&this.selectionStart===this.selectionEnd&&(l.start=l.end),this.dispatch("SET_CURRENT_CONTENT",{content:r,selection:l})}validateSelection(e,t,i){return t>=0&&t<=e&&i>=0&&i<=e?0:47}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:Gg});const{top:t,left:i}=Pi({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",[...e.elements]);this.col=i,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:Gg});const{top:t,left:i}=Pi({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",[...e.elements]);this.col=i,this.row=t}onAddElements(e){const{top:t,left:i}=Li({left:this.col,right:this.col,top:this.row,bottom:this.row},"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.col=i,this.row=t}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){const e=en({col:this.col,row:this.row});this.selection.resetAnchor(this,{cell:{col:this.col,row:this.row},zone:e})}this.mode="selecting",this.selectionInitialStart=this.selectionStart}startEdition(e,t){var i;const n=this.getters.getActiveCell();e&&(null===(i=null==n?void 0:n.format)||void 0===i?void 0:i.includes("%"))&&Ci(e)&&(t=t||{start:e.length,end:e.length},e=`${e}%`),this.initialContent=(null==n?void 0:n.composerContent)||"",this.mode="editing";const{col:o,row:s}=this.getters.getPosition();this.col=o,this.row=s,this.sheetId=this.getters.getActiveSheetId(),this.setContent(e||this.initialContent,t),this.colorIndexByRange={};const r=en({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){const e=this.getters.getActiveSheetId();this.cancelEditionAndActivateSheet();const{col:t,row:i}=this.getters.getMainCellPosition(this.sheetId,this.col,this.row);let n=this.currentContent;if(!(this.initialContent!==n))return;if(n){const o=this.getters.getCell(e,t,i);if(n.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&&(n+=et(new Array(i).fill(")")))}else(null==o?void 0:o.isLink())&&(n=We(n,o.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,col:t,row:i,content:n})}else this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,content:"",col:t,row:i});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})}cancelEdition(){"inactive"!==this.mode&&(this.mode="inactive",this.selection.release(this))}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,i){e=e.replace(/[\r\n]/g,"");const n=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(n||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?Ug(e):[],this.currentTokens.length>100&&i&&this.ui.notifyUI({type:"ERROR",text:s("This formula has over 100 parts. It can't be processed properly, consider splitting it into multiple cells")})),this.canStartComposerRangeSelection()&&this.startComposerRangeSelection()}insertSelectedRange(e){const t=Math.min(this.selectionStart,this.selectionEnd),i=this.getZoneReference(e);this.canStartComposerRangeSelection()?(this.insertText(i,t),this.selectionInitialStart=t):(this.insertText(","+i,t),this.selectionInitialStart=t+1)}replaceSelectedRanges(e){const t=this.getZoneReference(e);this.replaceText(t,this.selectionInitialStart,this.selectionEnd)}getZoneReference(e,t=[{colFixed:!1,rowFixed:!1}]){const i=this.getters.getActiveSheetId();let n=this.getters.zoneToXC(i,e,t);if(this.getters.getEditionSheet()!==this.getters.getActiveSheetId()){n=`${Oe(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${n}`}return n}getRangeReference(e,t=[{colFixed:!1,rowFixed:!1}]){1===t.length&&nn(e.zone)>1?t.push({...t[0]}):2===t.length&&1===nn(e.zone)&&t.pop();const i=e.clone({parts:this.previousRange.parts});return this.getters.getSelectionRangeString(i,this.getters.getEditionSheet())}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),i=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,i)}replaceText(e,t,i){this.currentContent=this.currentContent.slice(0,t)+this.currentContent.slice(i,this.currentContent.length),this.insertText(e,t)}insertText(e,t){const i=this.currentContent.slice(0,t)+e+this.currentContent.slice(t),n=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:i,selection:{start:n,end:n}})}updateRangeColor(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return;const e=this.getters.getEditionSheet(),t=this.getReferencedRanges().map((t=>this.getters.getRangeString(t,e))),i={};for(const e of t)void 0!==this.colorIndexByRange[e]&&(i[e]=this.colorIndexByRange[e]);const n=new Set(Object.values(i));let o=0;const s=()=>{for(;n.has(o);)o++;return n.add(o),o};for(const e of t){const t=e in i?i[e]:s();i[e]=t}this.colorIndexByRange=i}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=this.getters.getEditionSheet(),t=e=>{const t=this.colorIndexByRange[e];return ut[t%ut.length]};return this.getReferencedRanges().map((i=>{const n=this.getters.getRangeString(i,e);return{zone:i.zone,color:t(n),sheetId:i.sheetId}}))}getReferencedRanges(){const e=this.getters.getEditionSheet();return this.currentTokens.filter((e=>"REFERENCE"===e.type)).map((t=>this.getters.getRangeFromSheetXC(e,t.value))).filter((e=>!e.invalidSheetName&&!e.invalidXc))}canStartComposerRangeSelection(){if(this.currentContent.startsWith("=")){const e=this.getTokenAtCursor();if(!e)return!1;const t=this.currentTokens.map((e=>e.start)).indexOf(e.start);let i=t,n=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(n.type)||Xu.includes(n.value);){if("SPACE"!==n.type||i<1)return!1;i--,n=this.currentTokens[i]}for(i=t+1,n=this.currentTokens[i];n&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(n.type);){if("SPACE"!==n.type)return!1;i++,n=this.currentTokens[i]}return!0}return!1}getTokensInSelection(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return this.currentTokens.filter((i=>i.start<=e&&i.end>=e||i.start>=e&&i.start<t))}}qg.getters=["getEditionMode","isSelectingForComposer","showSelectionIndicator","getCurrentContent","getEditionSheet","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights"];const Zg=ju.content,jg=new sn;jg.add("functions",(()=>Object.keys(Zg).map((e=>({text:e,description:Zg[e].description}))))),xn`
984
984
  .o-autocomplete-dropdown {
985
985
  pointer-events: auto;
986
986
  background-color: #fff;
@@ -1004,7 +1004,7 @@
1004
1004
  }
1005
1005
  }
1006
1006
  }
1007
- `;class Zg extends t.Component{constructor(){super(...arguments),this.state=t.useState({values:[],selectedIndex:0})}setup(){t.onMounted((()=>this.filter(this.props.search))),t.onWillUpdateProps((e=>this.checkUpdateProps(e))),this.props.exposeAPI({getValueToFill:()=>this.getValueToFill(),moveDown:()=>this.moveDown(),moveUp:()=>this.moveUp()})}checkUpdateProps(e){e.search!==this.props.search&&this.filter(e.search)}async filter(e){let t=qg.get(this.props.provider)();t=this.props.filter?this.props.filter(e,t):t.filter((t=>t.text.toUpperCase().startsWith(e.toUpperCase()))).sort(((e,t)=>e.text<t.text?-1:e.text>t.text?1:0)),this.state.values=t.slice(0,10),this.state.selectedIndex=0}fillValue(e){this.state.selectedIndex=e,this.props.onCompleted(this.getValueToFill())}moveDown(){this.state.selectedIndex=(this.state.selectedIndex+1)%this.state.values.length}moveUp(){this.state.selectedIndex--,this.state.selectedIndex<0&&(this.state.selectedIndex=this.state.values.length-1)}getValueToFill(){if(this.state.values.length)return this.state.values[this.state.selectedIndex].text}}Zg.template="o-spreadsheet-TextValueProvider";class jg{constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){let i=window.getSelection();this.removeSelection();let n=document.createRange();if(e==t&&0===e)n.setStart(this.el,0),n.setEnd(this.el,0),i.addRange(n);else{(e<0||t>this.el.textContent.length)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${this.el.textContent.length}`),e<0&&(e=0),t>this.el.textContent.length&&(t=this.el.textContent.length),e>this.el.textContent.length&&(e=this.el.textContent.length));let o=this.findChildAtCharacterIndex(e),s=this.findChildAtCharacterIndex(t);n.setStart(o.node,o.offset),i.addRange(n),i.extend(s.node,s.offset)}}findChildAtCharacterIndex(e){let t,i,n=this.iterateChildren(this.el),o=e;do{t=n.next(),t.done||t.value.hasChildNodes()||(t.value.textContent&&t.value.textContent.length<o?o-=t.value.textContent.length:n.return(t.value),i=t.value)}while(!t.done);return t.value?{node:t.value,offset:o}:{node:i,offset:o}}*iterateChildren(e){if(yield e,e.hasChildNodes())for(let t of e.childNodes)yield*this.iterateChildren(t)}setText(e){if(0!==e.length)for(const t of e){const e=document.createElement("span");e.innerText=t.value,t.color&&(e.style.color=t.color),t.class&&e.classList.add(t.class),this.el.appendChild(e)}}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){let{startElement:e,endElement:t,startSelectionOffset:i,endSelectionOffset:n}=this.getStartAndEndSelection();return{start:this.findSelectionIndex(e,i),end:this.findSelectionIndex(t,n)}}findSelectionIndex(e,t){let i=this.iterateChildren(this.el),n=0,o=i.next();for(;!o.done&&o.value!==e;)o.value.hasChildNodes()||o.value.textContent&&(n+=o.value.textContent.length),o=i.next();if(o.value===e)if(o.value.hasChildNodes()){const e=[...o.value.childNodes].slice(0,t);for(const t of e)t.textContent&&(n+=t.textContent.length)}else n+=t;return n}getStartAndEndSelection(){const e=document.getSelection();return{startElement:e.anchorNode||this.el,startSelectionOffset:e.anchorOffset,endElement:e.focusNode||this.el,endSelectionOffset:e.focusOffset}}}wn`
1007
+ `;class Yg extends t.Component{constructor(){super(...arguments),this.state=t.useState({values:[],selectedIndex:0})}setup(){t.onMounted((()=>this.filter(this.props.search))),t.onWillUpdateProps((e=>this.checkUpdateProps(e))),this.props.exposeAPI({getValueToFill:()=>this.getValueToFill(),moveDown:()=>this.moveDown(),moveUp:()=>this.moveUp()})}checkUpdateProps(e){e.search!==this.props.search&&this.filter(e.search)}async filter(e){let t=jg.get(this.props.provider)();t=this.props.filter?this.props.filter(e,t):t.filter((t=>t.text.toUpperCase().startsWith(e.toUpperCase()))).sort(((e,t)=>e.text<t.text?-1:e.text>t.text?1:0)),this.state.values=t.slice(0,10),this.state.selectedIndex=0}fillValue(e){this.state.selectedIndex=e,this.props.onCompleted(this.getValueToFill())}moveDown(){this.state.selectedIndex=(this.state.selectedIndex+1)%this.state.values.length}moveUp(){this.state.selectedIndex--,this.state.selectedIndex<0&&(this.state.selectedIndex=this.state.values.length-1)}getValueToFill(){if(this.state.values.length)return this.state.values[this.state.selectedIndex].text}}Yg.template="o-spreadsheet-TextValueProvider";class Xg{constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){let i=window.getSelection();this.removeSelection();let n=document.createRange();if(e==t&&0===e)n.setStart(this.el,0),n.setEnd(this.el,0),i.addRange(n);else{(e<0||t>this.el.textContent.length)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${this.el.textContent.length}`),e<0&&(e=0),t>this.el.textContent.length&&(t=this.el.textContent.length),e>this.el.textContent.length&&(e=this.el.textContent.length));let o=this.findChildAtCharacterIndex(e),s=this.findChildAtCharacterIndex(t);n.setStart(o.node,o.offset),i.addRange(n),i.extend(s.node,s.offset)}}findChildAtCharacterIndex(e){let t,i,n=this.iterateChildren(this.el),o=e;do{t=n.next(),t.done||t.value.hasChildNodes()||(t.value.textContent&&t.value.textContent.length<o?o-=t.value.textContent.length:n.return(t.value),i=t.value)}while(!t.done);return t.value?{node:t.value,offset:o}:{node:i,offset:o}}*iterateChildren(e){if(yield e,e.hasChildNodes())for(let t of e.childNodes)yield*this.iterateChildren(t)}setText(e){if(0!==e.length)for(const t of e){const e=document.createElement("span");e.innerText=t.value,t.color&&(e.style.color=t.color),t.class&&e.classList.add(t.class),this.el.appendChild(e)}}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){let{startElement:e,endElement:t,startSelectionOffset:i,endSelectionOffset:n}=this.getStartAndEndSelection();return{start:this.findSelectionIndex(e,i),end:this.findSelectionIndex(t,n)}}findSelectionIndex(e,t){let i=this.iterateChildren(this.el),n=0,o=i.next();for(;!o.done&&o.value!==e;)o.value.hasChildNodes()||o.value.textContent&&(n+=o.value.textContent.length),o=i.next();if(o.value===e)if(o.value.hasChildNodes()){const e=[...o.value.childNodes].slice(0,t);for(const t of e)t.textContent&&(n+=t.textContent.length)}else n+=t;return n}getStartAndEndSelection(){const e=document.getSelection();return{startElement:e.anchorNode||this.el,startSelectionOffset:e.anchorOffset,endElement:e.focusNode||this.el,endSelectionOffset:e.focusOffset}}}xn`
1008
1008
  .o-formula-assistant {
1009
1009
  white-space: normal;
1010
1010
  background-color: #fff;
@@ -1051,7 +1051,7 @@
1051
1051
  .o-formula-assistant-transparency {
1052
1052
  opacity: 0.3;
1053
1053
  }
1054
- `;class Yg extends t.Component{constructor(){super(...arguments),this.assistantState=t.useState({allowCellSelectionBehind:!1}),this.timeOutId=0}setup(){t.onWillUnmount((()=>{this.timeOutId&&clearTimeout(this.timeOutId)}))}getContext(){return this.props}onMouseMove(){this.assistantState.allowCellSelectionBehind=!0,this.timeOutId&&clearTimeout(this.timeOutId),this.timeOutId=setTimeout((()=>{this.assistantState.allowCellSelectionBehind=!1}),2e3)}}Yg.template="o-spreadsheet-FunctionDescriptionProvider";const Xg=qu.content,Kg="#4a4e4d",Qg="#3da4ab",Jg="#02c39a",ep="selector-flag",tp={OPERATOR:Qg,NUMBER:Jg,STRING:"#00a82d",FUNCTION:Kg,DEBUGGER:Qg,LEFT_PAREN:Kg,RIGHT_PAREN:Kg,COMMA:Kg};wn`
1054
+ `;class Kg extends t.Component{constructor(){super(...arguments),this.assistantState=t.useState({allowCellSelectionBehind:!1}),this.timeOutId=0}setup(){t.onWillUnmount((()=>{this.timeOutId&&clearTimeout(this.timeOutId)}))}getContext(){return this.props}onMouseMove(){this.assistantState.allowCellSelectionBehind=!0,this.timeOutId&&clearTimeout(this.timeOutId),this.timeOutId=setTimeout((()=>{this.assistantState.allowCellSelectionBehind=!1}),2e3)}}Kg.template="o-spreadsheet-FunctionDescriptionProvider";const Qg=ju.content,Jg="#4a4e4d",ep="#3da4ab",tp="#02c39a",ip="selector-flag",np={OPERATOR:ep,NUMBER:tp,STRING:"#00a82d",FUNCTION:Jg,DEBUGGER:ep,LEFT_PAREN:Jg,RIGHT_PAREN:Jg,COMMA:Jg};xn`
1055
1055
  .o-composer-container {
1056
1056
  padding: 0;
1057
1057
  margin: 0;
@@ -1072,7 +1072,7 @@
1072
1072
  }
1073
1073
  span {
1074
1074
  white-space: pre;
1075
- &.${ep}:after {
1075
+ &.${ip}:after {
1076
1076
  content: "${"␣"}";
1077
1077
  color: ${"darkgrey"};
1078
1078
  }
@@ -1093,14 +1093,14 @@
1093
1093
  .o-topbar-toolbar .o-composer-container[active] {
1094
1094
  z-index: ${oe.TopBarComposer};
1095
1095
  }
1096
- `;class ip extends t.Component{constructor(){super(...arguments),this.composerRef=t.useRef("o_composer"),this.spreadsheetRect=Vn(),this.contentHelper=new jg(this.composerRef.el),this.composerState=t.useState({positionStart:0,positionEnd:0}),this.autoCompleteState=t.useState({showProvider:!1,provider:"functions",search:""}),this.functionDescriptionState=t.useState({showDescription:!1,functionName:"",functionDescription:{},argToFocus:0}),this.isKeyStillDown=!1,this.compositionActive=!1,this.borderStyle="box-shadow: 0 1px 4px 3px rgba(60, 64, 67, 0.15);",this.shouldProcessInputEvents=!1,this.tokens=[],this.keyMapping={ArrowUp:this.processArrowKeys,ArrowDown:this.processArrowKeys,ArrowLeft:this.processArrowKeys,ArrowRight:this.processArrowKeys,Enter:this.processEnterKey,Escape:this.processEscapeKey,F2:()=>console.warn("Not implemented"),F4:this.processF4Key,Tab:e=>this.processTabKey(e)}}get assistantStyle(){const e=this.composerRef.el.getBoundingClientRect(),t={width:"300px"};if(this.props.delimitation&&this.props.rect){const{x:e,y:i,height:n}=this.props.rect;return i>this.props.delimitation.height-(i+n)&&(t.top="-8px",t.transform="translate(0, -100%)"),e+300>this.props.delimitation.width&&(t.right="0px"),xn(t)}return e.left+300>this.spreadsheetRect.width&&(t.right="0px"),xn(t)}setup(){t.onMounted((()=>{const e=this.composerRef.el;this.props.isDefaultFocus&&this.env.focusableElement.setFocusableElement(e),this.contentHelper.updateEl(e),this.processContent()})),t.onPatched((()=>{this.isKeyStillDown||this.processContent(),"inactive"===this.env.model.getters.getEditionMode()&&this.processTokenAtCursor()}))}processArrowKeys(e){if(this.env.model.getters.isSelectingForComposer()||"inactive"===this.env.model.getters.getEditionMode())return this.functionDescriptionState.showDescription=!1,void e.preventDefault();const t=this.env.model.getters.getCurrentContent();"cellFocus"!==this.props.focus||this.autoCompleteState.showProvider||t.startsWith("=")?(e.stopPropagation(),["ArrowUp","ArrowDown"].includes(e.key)&&this.autoCompleteState.showProvider&&this.autocompleteAPI&&(e.preventDefault(),"ArrowUp"===e.key?this.autocompleteAPI.moveUp():this.autocompleteAPI.moveDown()),this.updateCursorIfNeeded()):this.env.model.dispatch("STOP_EDITION")}processTabKey(e){if(e.preventDefault(),e.stopPropagation(),"inactive"!==this.env.model.getters.getEditionMode()){if(this.autoCompleteState.showProvider&&this.autocompleteAPI){const e=this.autocompleteAPI.getValueToFill();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(),this.isKeyStillDown=!1,this.autoCompleteState.showProvider&&this.autocompleteAPI){const e=this.autocompleteAPI.getValueToFill();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():e.preventDefault()}onInput(e){var t,i;if(!this.shouldProcessInputEvents)return;let n;if(e.stopPropagation(),"inactive"===this.env.model.getters.getEditionMode())n=e.data||"";else{const e=this.composerRef.el;n=e.childNodes.length?e.textContent:""}if("inactive"===this.props.focus)return null===(i=(t=this.props).onComposerCellFocused)||void 0===i?void 0:i.call(t,n);this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION"),this.env.model.dispatch("SET_CURRENT_CONTENT",{content:n,selection:this.contentHelper.getCurrentSelection()})}onKeyup(e){if(this.isKeyStillDown=!1,"inactive"===this.props.focus||["Control","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.autoCompleteState.search="",this.autoCompleteState.showProvider=!0,void this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION");const{start:t,end:i}=this.env.model.getters.getComposerSelection(),{start:n,end:o}=this.contentHelper.getCurrentSelection();n===t&&o===i||this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",this.contentHelper.getCurrentSelection()),this.processTokenAtCursor(),this.processContent()}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}onCompleted(e){e&&this.autoComplete(e)}onContextMenu(e){var t,i;"inactive"===this.env.model.getters.getEditionMode()&&(null===(i=(t=this.props).onInputContextMenu)||void 0===i||i.call(t,e))}processContent(){if(this.compositionActive)return;this.contentHelper.removeAll(),this.shouldProcessInputEvents=!1,"inactive"!==this.props.focus&&(this.contentHelper.el.focus(),this.contentHelper.selectRange(0,0));const e=this.getContent();if(0!==e.length){this.contentHelper.setText(e);const{start:t,end:i}=this.env.model.getters.getComposerSelection();"inactive"!==this.props.focus&&this.contentHelper.selectRange(t,i)}this.shouldProcessInputEvents=!0}getContent(){let e;const t=this.env.model.getters.getCurrentContent(),i=t.startsWith("=")&&this.env.model.getters.getCurrentTokens().length>0;return e=""===t?[]:i&&"inactive"!==this.props.focus?this.getColoredTokens():[{value:t}],e}getColoredTokens(){const e=this.env.model.getters.getCurrentTokens(),t=this.env.model.getters.getTokenAtCursor(),i=[],{start:n,end:o}=this.env.model.getters.getComposerSelection();for(const s of e){switch(s.type){case"OPERATOR":case"NUMBER":case"FUNCTION":case"COMMA":case"STRING":i.push({value:s.value,color:tp[s.type]||"#000"});break;case"REFERENCE":const{xc:e,sheetName:n}=$t(s.value);i.push({value:s.value,color:this.rangeColor(e,n)||"#000"});break;case"SYMBOL":let o=s.value;["TRUE","FALSE"].includes(o.toUpperCase())?i.push({value:s.value,color:Jg}):i.push({value:s.value,color:"#000"});break;case"LEFT_PAREN":case"RIGHT_PAREN":t&&["LEFT_PAREN","RIGHT_PAREN"].includes(t.type)&&t.parenIndex&&t.parenIndex===s.parenIndex?i.push({value:s.value,color:"black"}):i.push({value:s.value,color:tp[s.type]||"#000"});break;default:i.push({value:s.value,color:"#000"})}this.env.model.getters.showSelectionIndicator()&&o===n&&o===s.end&&(i[i.length-1].class=ep)}return i}rangeColor(e,t){if("inactive"===this.props.focus)return;const i=this.env.model.getters.getHighlights(),n=t?this.env.model.getters.getSheetIdByName(t):this.env.model.getters.getEditionSheet(),o=i.find((t=>{if(t.sheetId!==n)return!1;let i=this.env.model.getters.getRangeFromSheetXC(n,e).zone;const{height:o,width:s}=qi(i);return i=o*s==1?this.env.model.getters.expandZone(n,i):i,Vi(i,t.zone)}));return o&&o.color?o.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}=$t(e.value);if("FUNCTION"===e.type||"SYMBOL"===e.type&&!Nt.test(t))this.autoCompleteState.search=e.value,this.autoCompleteState.showProvider=!0;else if(e.functionContext&&"UNKNOWN"!==e.type){const t=e.functionContext,i=t.parent.toUpperCase(),n=Xg[i],o=t.argPosition;this.functionDescriptionState.functionName=i,this.functionDescriptionState.functionDescription=n,this.functionDescriptionState.argToFocus=n.getArgToFocus(o+1)-1,this.functionDescriptionState.showDescription=!0}}}}autoComplete(e){if(e){const t=this.env.model.getters.getTokenAtCursor();if(t){let i=t.end,n=t.end;["SYMBOL","FUNCTION"].includes(t.type)&&(i=t.start);const o=this.env.model.getters.getCurrentTokens();if(this.autoCompleteState.provider&&o.length){e+="(";const i=o.map((e=>e.start)).indexOf(t.start);if(i+1<o.length){"LEFT_PAREN"===o[i+1].type&&n++}}this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:i,end:n})}this.env.model.dispatch("REPLACE_COMPOSER_CURSOR_SELECTION",{text:e})}this.processTokenAtCursor()}}ip.template="o-spreadsheet-Composer",ip.components={TextValueProvider:Zg,FunctionDescriptionProvider:Yg},ip.defaultProps={inputStyle:"",focus:"inactive",isDefaultFocus:!1};const np=3*.4*window.devicePixelRatio||1;wn`
1096
+ `;class op extends t.Component{constructor(){super(...arguments),this.composerRef=t.useRef("o_composer"),this.spreadsheetRect=Bn(),this.contentHelper=new Xg(this.composerRef.el),this.composerState=t.useState({positionStart:0,positionEnd:0}),this.autoCompleteState=t.useState({showProvider:!1,provider:"functions",search:""}),this.functionDescriptionState=t.useState({showDescription:!1,functionName:"",functionDescription:{},argToFocus:0}),this.isKeyStillDown=!1,this.compositionActive=!1,this.borderStyle="box-shadow: 0 1px 4px 3px rgba(60, 64, 67, 0.15);",this.shouldProcessInputEvents=!1,this.tokens=[],this.keyMapping={ArrowUp:this.processArrowKeys,ArrowDown:this.processArrowKeys,ArrowLeft:this.processArrowKeys,ArrowRight:this.processArrowKeys,Enter:this.processEnterKey,Escape:this.processEscapeKey,F2:()=>console.warn("Not implemented"),F4:this.processF4Key,Tab:e=>this.processTabKey(e)}}get assistantStyle(){const e=this.composerRef.el.getBoundingClientRect(),t={width:"300px"};if(this.props.delimitation&&this.props.rect){const{x:e,y:i,height:n}=this.props.rect;return i>this.props.delimitation.height-(i+n)&&(t.top="-8px",t.transform="translate(0, -100%)"),e+300>this.props.delimitation.width&&(t.right="0px"),In(t)}return e.left+300>this.spreadsheetRect.width&&(t.right="0px"),In(t)}setup(){t.onMounted((()=>{const e=this.composerRef.el;this.props.isDefaultFocus&&this.env.focusableElement.setFocusableElement(e),this.contentHelper.updateEl(e),this.processContent()})),t.onPatched((()=>{this.isKeyStillDown||this.processContent(),"inactive"===this.env.model.getters.getEditionMode()&&this.processTokenAtCursor()}))}processArrowKeys(e){if(this.env.model.getters.isSelectingForComposer()||"inactive"===this.env.model.getters.getEditionMode())return this.functionDescriptionState.showDescription=!1,void e.preventDefault();const t=this.env.model.getters.getCurrentContent();"cellFocus"!==this.props.focus||this.autoCompleteState.showProvider||t.startsWith("=")?(e.stopPropagation(),["ArrowUp","ArrowDown"].includes(e.key)&&this.autoCompleteState.showProvider&&this.autocompleteAPI&&(e.preventDefault(),"ArrowUp"===e.key?this.autocompleteAPI.moveUp():this.autocompleteAPI.moveDown()),this.updateCursorIfNeeded()):this.env.model.dispatch("STOP_EDITION")}processTabKey(e){if(e.preventDefault(),e.stopPropagation(),"inactive"!==this.env.model.getters.getEditionMode()){if(this.autoCompleteState.showProvider&&this.autocompleteAPI){const e=this.autocompleteAPI.getValueToFill();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(),this.isKeyStillDown=!1,this.autoCompleteState.showProvider&&this.autocompleteAPI){const e=this.autocompleteAPI.getValueToFill();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():e.preventDefault()}onInput(e){var t,i;if(!this.shouldProcessInputEvents)return;let n;if(e.stopPropagation(),"inactive"===this.env.model.getters.getEditionMode())n=e.data||"";else{const e=this.composerRef.el;n=e.childNodes.length?e.textContent:""}if("inactive"===this.props.focus)return null===(i=(t=this.props).onComposerCellFocused)||void 0===i?void 0:i.call(t,n);this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION"),this.env.model.dispatch("SET_CURRENT_CONTENT",{content:n,selection:this.contentHelper.getCurrentSelection()})}onKeyup(e){if(this.isKeyStillDown=!1,"inactive"===this.props.focus||["Control","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.autoCompleteState.search="",this.autoCompleteState.showProvider=!0,void this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION");const{start:t,end:i}=this.env.model.getters.getComposerSelection(),{start:n,end:o}=this.contentHelper.getCurrentSelection();n===t&&o===i||this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",this.contentHelper.getCurrentSelection()),this.processTokenAtCursor(),this.processContent()}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}onCompleted(e){e&&this.autoComplete(e)}onContextMenu(e){var t,i;"inactive"===this.env.model.getters.getEditionMode()&&(null===(i=(t=this.props).onInputContextMenu)||void 0===i||i.call(t,e))}processContent(){if(this.compositionActive)return;this.contentHelper.removeAll(),this.shouldProcessInputEvents=!1,"inactive"!==this.props.focus&&(this.contentHelper.el.focus(),this.contentHelper.selectRange(0,0));const e=this.getContent();if(0!==e.length){this.contentHelper.setText(e);const{start:t,end:i}=this.env.model.getters.getComposerSelection();"inactive"!==this.props.focus&&this.contentHelper.selectRange(t,i)}this.shouldProcessInputEvents=!0}getContent(){let e;const t=this.env.model.getters.getCurrentContent(),i=t.startsWith("=")&&this.env.model.getters.getCurrentTokens().length>0;return e=""===t?[]:i&&"inactive"!==this.props.focus?this.getColoredTokens():[{value:t}],e}getColoredTokens(){const e=this.env.model.getters.getCurrentTokens(),t=this.env.model.getters.getTokenAtCursor(),i=[],{start:n,end:o}=this.env.model.getters.getComposerSelection();for(const s of e){switch(s.type){case"OPERATOR":case"NUMBER":case"FUNCTION":case"COMMA":case"STRING":i.push({value:s.value,color:np[s.type]||"#000"});break;case"REFERENCE":const{xc:e,sheetName:n}=$t(s.value);i.push({value:s.value,color:this.rangeColor(e,n)||"#000"});break;case"SYMBOL":let o=s.value;["TRUE","FALSE"].includes(o.toUpperCase())?i.push({value:s.value,color:tp}):i.push({value:s.value,color:"#000"});break;case"LEFT_PAREN":case"RIGHT_PAREN":t&&["LEFT_PAREN","RIGHT_PAREN"].includes(t.type)&&t.parenIndex&&t.parenIndex===s.parenIndex?i.push({value:s.value,color:"black"}):i.push({value:s.value,color:np[s.type]||"#000"});break;default:i.push({value:s.value,color:"#000"})}this.env.model.getters.showSelectionIndicator()&&o===n&&o===s.end&&(i[i.length-1].class=ip)}return i}rangeColor(e,t){if("inactive"===this.props.focus)return;const i=this.env.model.getters.getHighlights(),n=t?this.env.model.getters.getSheetIdByName(t):this.env.model.getters.getEditionSheet(),o=i.find((t=>{if(t.sheetId!==n)return!1;let i=this.env.model.getters.getRangeFromSheetXC(n,e).zone;const{height:o,width:s}=ji(i);return i=o*s==1?this.env.model.getters.expandZone(n,i):i,Bi(i,t.zone)}));return o&&o.color?o.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}=$t(e.value);if("FUNCTION"===e.type||"SYMBOL"===e.type&&!Ot.test(t))this.autoCompleteState.search=e.value,this.autoCompleteState.showProvider=!0;else if(e.functionContext&&"UNKNOWN"!==e.type){const t=e.functionContext,i=t.parent.toUpperCase(),n=Qg[i],o=t.argPosition;this.functionDescriptionState.functionName=i,this.functionDescriptionState.functionDescription=n,this.functionDescriptionState.argToFocus=n.getArgToFocus(o+1)-1,this.functionDescriptionState.showDescription=!0}}}}autoComplete(e){if(e){const t=this.env.model.getters.getTokenAtCursor();if(t){let i=t.end,n=t.end;["SYMBOL","FUNCTION"].includes(t.type)&&(i=t.start);const o=this.env.model.getters.getCurrentTokens();if(this.autoCompleteState.provider&&o.length){e+="(";const i=o.map((e=>e.start)).indexOf(t.start);if(i+1<o.length){"LEFT_PAREN"===o[i+1].type&&n++}}this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:i,end:n})}this.env.model.dispatch("REPLACE_COMPOSER_CURSOR_SELECTION",{text:e})}this.processTokenAtCursor()}}op.template="o-spreadsheet-Composer",op.components={TextValueProvider:Yg,FunctionDescriptionProvider:Kg},op.defaultProps={inputStyle:"",focus:"inactive",isDefaultFocus:!1};const sp=3*.4*window.devicePixelRatio||1;xn`
1097
1097
  div.o-grid-composer {
1098
1098
  z-index: ${oe.GridComposer};
1099
1099
  box-sizing: border-box;
1100
1100
  position: absolute;
1101
- border: ${np}px solid ${E};
1101
+ border: ${sp}px solid ${E};
1102
1102
  }
1103
- `;class op extends t.Component{constructor(){super(...arguments),this.rect=void 0,this.isEditing=!1}get defaultRect(){return{x:0,y:0,width:0,height:0}}setup(){t.onWillUpdateProps((()=>{const e="inactive"!==this.env.model.getters.getEditionMode();if(this.isEditing!==e){if(this.isEditing=e,!e)return this.rect=void 0,void this.env.focusableElement.focus();const t=this.env.model.getters.getPosition(),i=this.env.model.getters.expandZone(this.env.model.getters.getActiveSheetId(),Qi(t));this.rect=this.env.model.getters.getVisibleRect(i)}}))}get composerProps(){const{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{rect:this.rect&&{...this.rect},delimitation:{width:e,height:t},inputStyle:this.composerStyle,focus:this.props.focus,isDefaultFocus:!0,onComposerContentFocused:this.props.onComposerContentFocused,onComposerCellFocused:this.props.onComposerCellFocused,onInputContextMenu:this.props.onInputContextMenu}}get containerStyle(){if("inactive"===this.env.model.getters.getEditionMode()||!this.rect)return"z-index: -1000;";const e=this.env.model.getters.getCurrentContent().startsWith("="),t=this.env.model.getters.getActiveCell();let i={};if(t){const e=this.env.model.getters.getCellPosition(t.id);i=this.env.model.getters.getCellComputedStyle(e.sheetId,e.col,e.row)}const{x:n,y:o,width:s,height:r}=this.rect,a=!e&&i.fillColor||"#ffffff",l=!e&&i.textColor||"#000000",c=!e&&i.fontSize||10,h=!e&&i.bold?"bold":500,d=!e&&i.italic?"italic":"normal",u=e?"none":yn(i);let g="left";e||(g=i.align||(null==t?void 0:t.defaultAlign)||"left");const p=this.env.model.getters.getSheetViewDimensionWithHeaders();return`\n left: ${n-1}px;\n top: ${o}px;\n min-width: ${s+2}px;\n min-height: ${r+1}px;\n\n max-width: ${p.width-this.rect.x}px;\n max-height: ${p.height-this.rect.y}px;\n\n background: ${a};\n color: ${l};\n\n font-size: ${re[c]}px;\n font-weight: ${h};\n font-style: ${d};\n text-decoration: ${u};\n\n text-align: ${g};\n `}get composerStyle(){return`\n line-height: ${F}px;\n max-height: inherit;\n overflow: hidden;\n `}}op.template="o-spreadsheet-GridComposer",op.components={Composer:ip};const sp=wn`
1103
+ `;class rp extends t.Component{constructor(){super(...arguments),this.rect=void 0,this.isEditing=!1}get defaultRect(){return{x:0,y:0,width:0,height:0}}setup(){t.onWillUpdateProps((()=>{const e="inactive"!==this.env.model.getters.getEditionMode();if(this.isEditing!==e){if(this.isEditing=e,!e)return this.rect=void 0,void this.env.focusableElement.focus();const t=this.env.model.getters.getPosition(),i=this.env.model.getters.expandZone(this.env.model.getters.getActiveSheetId(),en(t));this.rect=this.env.model.getters.getVisibleRect(i)}}))}get composerProps(){const{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{rect:this.rect&&{...this.rect},delimitation:{width:e,height:t},inputStyle:this.composerStyle,focus:this.props.focus,isDefaultFocus:!0,onComposerContentFocused:this.props.onComposerContentFocused,onComposerCellFocused:this.props.onComposerCellFocused,onInputContextMenu:this.props.onInputContextMenu}}get containerStyle(){if("inactive"===this.env.model.getters.getEditionMode()||!this.rect)return"z-index: -1000;";const e=this.env.model.getters.getCurrentContent().startsWith("="),t=this.env.model.getters.getActiveCell();let i={};if(t){const e=this.env.model.getters.getCellPosition(t.id);i=this.env.model.getters.getCellComputedStyle(e.sheetId,e.col,e.row)}const{x:n,y:o,width:s,height:r}=this.rect,a=!e&&i.fillColor||"#ffffff",l=!e&&i.textColor||"#000000",c=!e&&i.fontSize||10,h=!e&&i.bold?"bold":500,d=!e&&i.italic?"italic":"normal",u=e?"none":Rn(i);let g="left";e||(g=i.align||(null==t?void 0:t.defaultAlign)||"left");const p=this.env.model.getters.getSheetViewDimensionWithHeaders();return`\n left: ${n-1}px;\n top: ${o}px;\n min-width: ${s+2}px;\n min-height: ${r+1}px;\n\n max-width: ${p.width-this.rect.x}px;\n max-height: ${p.height-this.rect.y}px;\n\n background: ${a};\n color: ${l};\n\n font-size: ${re[c]}px;\n font-weight: ${h};\n font-style: ${d};\n text-decoration: ${u};\n\n text-align: ${g};\n `}get composerStyle(){return`\n line-height: ${F}px;\n max-height: inherit;\n overflow: hidden;\n `}}rp.template="o-spreadsheet-GridComposer",rp.components={Composer:op};const ap=xn`
1104
1104
  .o-filter-icon {
1105
1105
  color: ${I};
1106
1106
  position: absolute;
@@ -1124,7 +1124,7 @@
1124
1124
  }
1125
1125
  }
1126
1126
  }
1127
- `;class rp extends t.Component{get style(){const{x:e,y:t}=this.props.position;return`top:${t}px;left:${e}px`}}rp.style=sp,rp.template="o-spreadsheet-FilterIcon";const ap=wn``;class lp extends t.Component{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(),i=this.env.model.getters.getRowDimensionsInViewport(t,e.row),n=this.env.model.getters.getColDimensionsInViewport(t,e.col),o=Math.floor((i.size-z)/2);return{x:n.end-z+this.props.gridPosition.x-2-1,y:i.end-z+this.props.gridPosition.y-o}}isFilterActive(e){const t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.isFilterActive(t,e.col,e.row)}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:i,row:n}=e;this.env.model.dispatch("OPEN_CELL_POPOVER",{col:i,row:n,popoverType:"FilterMenu"})}isPositionVisible(e,t){const i=this.env.model.getters.getVisibleRect({left:e,right:e,top:t,bottom:t});return!(0===i.width||0===i.height)}}lp.style=ap,lp.template="o-spreadsheet-FilterIconsOverlay",lp.components={FilterIcon:rp},lp.defaultProps={gridPosition:{x:0,y:0}};wn`
1127
+ `;class lp extends t.Component{get style(){const{x:e,y:t}=this.props.position;return`top:${t}px;left:${e}px`}}lp.style=ap,lp.template="o-spreadsheet-FilterIcon";const cp=xn``;class hp extends t.Component{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(),i=this.env.model.getters.getRowDimensionsInViewport(t,e.row),n=this.env.model.getters.getColDimensionsInViewport(t,e.col),o=Math.floor((i.size-z)/2);return{x:n.end-z+this.props.gridPosition.x-2-1,y:i.end-z+this.props.gridPosition.y-o}}isFilterActive(e){const t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.isFilterActive(t,e.col,e.row)}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:i,row:n}=e;this.env.model.dispatch("OPEN_CELL_POPOVER",{col:i,row:n,popoverType:"FilterMenu"})}isPositionVisible(e,t){const i=this.env.model.getters.getVisibleRect({left:e,right:e,top:t,bottom:t});return!(0===i.width||0===i.height)}}hp.style=cp,hp.template="o-spreadsheet-FilterIconsOverlay",hp.components={FilterIcon:lp},hp.defaultProps={gridPosition:{x:0,y:0}};xn`
1128
1128
  div.o-figure {
1129
1129
  box-sizing: border-box;
1130
1130
  position: absolute;
@@ -1179,13 +1179,13 @@
1179
1179
  }
1180
1180
  }
1181
1181
  }
1182
- `;class cp extends t.Component{constructor(){super(...arguments),this.figureRegistry=io,this.figureRef=t.useRef("figure")}get isSelected(){return this.env.model.getters.getSelectedFigureId()===this.props.figure.id}getBorderWidth(){return this.env.isDashboard()?0:this.isSelected?2:1}get borderStyle(){return`border: ${this.getBorderWidth()}px solid ${this.isSelected?E:"#c9ccd2"};`}get wrapperStyle(){const{x:e,y:t,width:i,height:n}=this.props.figure;return xn({left:`${e}px`,top:`${t}px`,width:`${i}px`,height:`${n}px`,"z-index":String(oe.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);",t}setup(){t.useEffect(((e,t,i)=>{e===t&&(null==i||i.focus({preventScroll:!0}))}),(()=>[this.env.model.getters.getSelectedFigureId(),this.props.figure.id,this.figureRef.el])),t.onWillUnmount((()=>{this.props.onFigureDeleted()}))}clickAnchor(e,t,i){this.props.onClickAnchor(e,t,i)}onMouseDown(e){this.props.onMouseDown(e)}onKeyDown(e){const t=this.props.figure,i=function(e,t="key"){let i="";Dn.includes(e.key)||(Un(e)&&(i+="Ctrl+"),e.altKey&&(i+="Alt+"),e.shiftKey&&(i+="Shift+"));const n="key"===t?e.key:e.code;return i+=Ln.test(n)?n.toUpperCase():n,i}(e);switch(i){case"Delete":this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:t.id}),this.props.onFigureDeleted(),e.preventDefault(),e.stopPropagation();break;case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":const n={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+n[0],y:t.y+n[1]}),e.preventDefault(),e.stopPropagation();break;case"Ctrl+A":e.preventDefault(),e.stopPropagation();break;case"Ctrl+Y":case"Ctrl+Z":"Ctrl+Y"===i?this.env.model.dispatch("REQUEST_REDO"):"Ctrl+Z"===i&&this.env.model.dispatch("REQUEST_UNDO"),e.preventDefault(),e.stopPropagation()}}}cp.template="o-spreadsheet-FigureComponent",cp.components={},cp.defaultProps={onFigureDeleted:()=>{},onMouseDown:()=>{},onClickAnchor:()=>{}},cp.props={figure:Object,style:{type:String,optional:!0},onFigureDeleted:{type:Function,optional:!0},onMouseDown:{type:Function,optional:!0},onClickAnchor:{type:Function,optional:!0}};class hp extends t.Component{constructor(){super(...arguments),this.dnd=t.useState({figId:void 0,x:0,y:0,width:0,height:0,cancelDnd:void 0})}setup(){t.onMounted((()=>{this.render()})),t.onWillUpdateProps((()=>{const e=this.env.model.getters.getActiveSheetId();this.dnd.figId&&!this.env.model.getters.getFigure(e,this.dnd.figId)&&(this.dnd.cancelDnd&&this.dnd.cancelDnd(),this.dnd.figId=void 0,this.dnd.cancelDnd=void 0)}))}getVisibleFigures(){const e=this.env.model.getters.getVisibleFigures();if(this.dnd.figId&&!e.some((e=>e.id===this.dnd.figId))){const t=this.env.model.getters.getFigure(this.env.model.getters.getActiveSheetId(),this.dnd.figId);t&&e.push(t)}return e}get containers(){const e=this.getVisibleFigures(),t=[];for(const i of["topLeft","topRight","bottomLeft","bottomRight"]){const n=e.filter((e=>this.getFigureContainer(e)===i));n.length>0&&t.push({type:i,figures:n,style:this.getContainerStyle(i),inverseViewportStyle:this.getInverseViewportPositionStyle(i)})}return this.dnd.figId&&t.push({type:"dnd",figures:[this.getDndFigure()],style:this.getContainerStyle("dnd"),inverseViewportStyle:this.getInverseViewportPositionStyle("dnd")}),t}getContainerStyle(e){const{width:t,height:i}=this.env.model.getters.getSheetViewDimension(),{x:n,y:o}=this.env.model.getters.getMainViewportCoordinates(),s=["bottomRight","topRight"].includes(e)?n:0,r=t-s,a=["bottomRight","bottomLeft"].includes(e)?o:0;return xn({left:`${s}px`,top:`${a}px`,width:`${r}px`,height:`${i-a}px`})}getInverseViewportPositionStyle(e){const{scrollX:t,scrollY:i}=this.env.model.getters.getActiveSheetScrollInfo(),{x:n,y:o}=this.env.model.getters.getMainViewportCoordinates();return xn({left:`${["bottomRight","topRight"].includes(e)?-(n+t):0}px`,top:`${["bottomRight","bottomLeft"].includes(e)?-(o+i):0}px`})}getFigureContainer(e){const{x:t,y:i}=this.env.model.getters.getMainViewportCoordinates();return e.id===this.dnd.figId?"dnd":e.x<t&&e.y<i?"topLeft":e.x<t?"bottomLeft":e.y<i?"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 i=this.env.model.getters.getActiveSheetId(),n=t.clientX,o=t.clientY,{x:s,y:r}=this.internalToScreenCoordinates(e);this.dnd.x=s,this.dnd.y=r,this.dnd.width=e.width,this.dnd.height=e.height;this.dnd.cancelDnd=Nr((t=>{const{x:i,y:a}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:l,scrollY:c}=this.env.model.getters.getActiveSheetScrollInfo(),h=i?0:-l,d=a?0:-c;this.dnd.figId=e.id;let u=t.clientX-n;this.dnd.x=Math.max(s+u,h);let g=t.clientY-o;this.dnd.y=Math.max(r+g,d)}),(t=>{if(!this.dnd.figId)return;let{x:n,y:o}=this.screenCoordinatesToInternal(this.dnd);this.dnd.figId=void 0,this.env.model.dispatch("UPDATE_FIGURE",{sheetId:i,id:e.id,x:n,y:o})}))}startResize(e,t,i,n){n.stopPropagation();const o=n.clientX,s=n.clientY,{scrollX:r,scrollY:a}=this.env.model.getters.getActiveSheetScrollInfo(),{x:l,y:c}=this.internalToScreenCoordinates(e);let h;this.dnd.x=l,this.dnd.y=c,this.dnd.width=e.width,this.dnd.height=e.height,h=n=>{this.dnd.figId=e.id;const h=Math.max(t*(n.clientX-o),80-e.width),d=Math.max(i*(n.clientY-s),80-e.height);this.dnd.width=e.width+h,this.dnd.height=e.height+d,t<0&&(this.dnd.x=l-h),i<0&&(this.dnd.y=c-d),this.dnd.x+r<=0&&(this.dnd.width=this.dnd.width+this.dnd.x+r,this.dnd.x=-r),this.dnd.y+a<=0&&(this.dnd.height=this.dnd.height+this.dnd.y+a,this.dnd.y=-a)};this.dnd.cancelDnd=Nr(h,(n=>{if(!this.dnd.figId)return;this.dnd.figId=void 0;let{x:o,y:s}=this.screenCoordinatesToInternal(this.dnd);const r={x:o,y:s};t&&(r.width=this.dnd.width),i&&(r.height=this.dnd.height),this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:e.id,...r})}))}getDndFigure(){const e=this.getVisibleFigures().find((e=>e.id===this.dnd.figId));if(!e)throw new Error("Dnd figure not found");return{...e,x:this.dnd.x,y:this.dnd.y,width:this.dnd.width,height:this.dnd.height}}getFigureStyle(e){return e.id!==this.dnd.figId?"":xn({opacity:"0.9",cursor:"grabbing"})}internalToScreenCoordinates({x:e,y:t}){const{x:i,y:n}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:o,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo();return{x:e=e<i?e:e-o,y:t=t<n?t:t-s}}screenCoordinatesToInternal({x:e,y:t}){const{x:i,y:n}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:o,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo();return{x:e=i&&e<i?e:e+o,y:t=n&&t<n?t:t+s}}}function dp(e,i,n){let o={col:void 0,row:void 0};const{Date:s}=window;let r,a,l=0;function c(){if(void 0===r||void 0===a)return{col:-1,row:-1};return{col:e.model.getters.getColIndex(r),row:e.model.getters.getRowIndex(a)}}const{pause:h,resume:d}=function(e,i){let n;const{setInterval:o,clearInterval:s}=window,r=()=>{s(n),n=void 0},a=()=>{try{e()}catch(e){throw r(),e}};return t.useEffect((()=>(n=o(a,i),()=>s(n))),(()=>[i])),{pause:r,resume:()=>{void 0===n&&(n=o(a,i))}}}((function(){const{col:e,row:t}=c(),i=s.now()-l;i>300&&(e!==o.col||t!==o.row)&&p(void 0,void 0);if(i>300){if(e<0||t<0)return;p(e,t)}}),200);function u(e){i.el===e.target&&(r=e.offsetX,a=e.offsetY,l=s.now())}function g(){const{col:e,row:t}=c();e===o.col&&t===o.row||p(void 0,void 0)}function p(e,t){e===o.col&&t===o.row||(o.col=e,o.row=t,n({col:e,row:t}))}return t.onMounted((()=>{const e=i.el;e.addEventListener("mousemove",u),e.addEventListener("mouseleave",h),e.addEventListener("mouseenter",d),e.addEventListener("mousedown",g)})),t.onWillUnmount((()=>{const e=i.el;e.removeEventListener("mousemove",u),e.removeEventListener("mouseleave",h),e.removeEventListener("mouseenter",d),e.removeEventListener("mousedown",g)})),o}hp.template="o-spreadsheet-FiguresContainer",hp.components={FigureComponent:cp},io.add("chart",{Component:Or,SidePanelComponent:"ChartPanel"});class up extends t.Component{setup(){this.gridOverlay=t.useRef("gridOverlay"),dp(this.env,this.gridOverlay,this.props.onCellHovered),t.useEffect((()=>this.props.onGridResized({height:this.gridOverlayEl.clientHeight,width:this.gridOverlayEl.clientWidth})),(()=>[this.gridOverlayEl.clientHeight,this.gridOverlayEl.clientWidth])),function(e,i,n){let o=null,s=null;function r(e){1===e.touches.length&&(o=e.touches[0].clientX,s=e.touches[0].clientY)}function a(){o=null,s=null}function l(e){if(1!==e.touches.length)return;n()&&(e.preventDefault(),e.stopPropagation());const t=e.touches[0].clientX,r=e.touches[0].clientY;i(o-t,s-r),o=t,s=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,i]=this.getCartesianCoordinates(e);this.props.onCellClicked(t,i,{expandZone:e.shiftKey,addZone:Un(e)})}onDoubleClick(e){const[t,i]=this.getCartesianCoordinates(e);this.props.onCellDoubleClicked(t,i)}onContextMenu(e){e.preventDefault();const[t,i]=this.getCartesianCoordinates(e);this.props.onCellRightClicked(t,i,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){return[this.env.model.getters.getColIndex(e.offsetX),this.env.model.getters.getRowIndex(e.offsetY)]}}up.template="o-spreadsheet-GridOverlay",up.components={FiguresContainer:hp},up.defaultProps={onCellHovered:()=>{},onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{},onFigureDeleted:()=>{},sidePanelIsOpen:!1};class gp extends t.Component{constructor(){super(...arguments),this.zIndex=oe.GridPopover}get cellPopover(){const e=this.env.model.getters.getCellPopover(this.props.hoveredCell);if(!e.isOpen)return{isOpen:!1};const t=e.coordinates;return{...e,coordinates:{x:t.x+this.props.gridPosition.x,y:t.y+this.props.gridPosition.y}}}}gp.template="o-spreadsheet-GridPopover",gp.components={Popover:Bn};class pp extends t.Component{constructor(){super(...arguments),this.PADDING=0,this.MAX_SIZE_MARGIN=0,this.MIN_ELEMENT_SIZE=0,this.lastSelectedElementIndex=null,this.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),i=this._getElementIndex(t);if(i<0)return;const n=this._getDimensionsInViewport(i);t-n.start<this.PADDING&&i!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=n.start,this.state.activeElement=this._getPreviousVisibleElement(i)):n.end-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=n.end,this.state.activeElement=i):this.state.resizerIsActive=!1}_computeGrabDisplay(e){const t=this._getElementIndex(this._getEvOffset(e)),i=this._getActiveElements(),n=this._getSelectedZoneStart(),o=this._getSelectedZoneEnd();i.has(n)&&n<=t&&t<=o?this.state.waitingForMove=!0:this.state.waitingForMove=!1}onMouseMove(e){this.state.isResizing||this.state.isMoving||this.state.isSelecting||(this._computeHandleDisplay(e),this._computeGrabDisplay(e))}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(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),i=this.state.draggerLinePosition,n=this._getElementSize(this.state.activeElement),o=i-n+this.MIN_ELEMENT_SIZE,s=this._getMaxSize();Nr((e=>{this.state.delta=this._getClientPosition(e)-t,this.state.draggerLinePosition=i+this.state.delta,this.state.draggerLinePosition<o&&(this.state.draggerLinePosition=o,this.state.delta=this.MIN_ELEMENT_SIZE-n),this.state.draggerLinePosition>s&&(this.state.draggerLinePosition=s,this.state.delta=s-i)}),(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()),i=this._getDimensionsInViewport(this._getSelectedZoneEnd()),n=t.start;this.state.draggerLinePosition=n,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=n,this.state.draggerShadowThickness=i.end-t.start;Mr(this.env,((e,i)=>{let n="COL"===this._getType()?e:i;if(n>=0){const e=this._getDimensionsInViewport(n);n<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=e.start,this.state.draggerShadowPosition=e.start,this.state.base=n,this.state.position="before"):this._getSelectedZoneEnd()<n?(this.state.draggerLinePosition=e.end,this.state.draggerShadowPosition=e.end-this.state.draggerShadowThickness,this.state.base=n,this.state.position="after"):(this.state.draggerLinePosition=t.start,this.state.draggerShadowPosition=t.start,this.state.base=this._getSelectedZoneStart())}}),(()=>{this.state.isMoving=!1,this.state.base!==this._getSelectedZoneStart()&&this._moveElements(),this._computeGrabDisplay(e)}))}startSelection(e,t){this.state.isSelecting=!0,e.shiftKey?this._increaseSelection(t):this._selectElement(t,Un(e)),this.lastSelectedElementIndex=t;Mr(this.env,((e,t)=>{let i="COL"===this._getType()?e:t;i!==this.lastSelectedElementIndex&&-1!==i&&(this._increaseSelection(i),this.lastSelectedElementIndex=i)}),(()=>{this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this.env.model.dispatch(Un(e)?"PREPARE_SELECTION_INPUT_EXPANSION":"STOP_SELECTION_INPUT"),this._computeGrabDisplay(e)}))}onMouseUp(e){this.lastSelectedElementIndex=null}onContextMenu(e){e.preventDefault();const t=this._getElementIndex(this._getEvOffset(e));if(t<0)return;this._getActiveElements().has(t)||this._selectElement(t,!1);const i=this._getType();this.props.onOpenContextMenu(i,e.clientX,e.clientY)}}wn`
1182
+ `;class dp extends t.Component{constructor(){super(...arguments),this.figureRegistry=oo,this.figureRef=t.useRef("figure")}get isSelected(){return this.env.model.getters.getSelectedFigureId()===this.props.figure.id}getBorderWidth(){return this.env.isDashboard()?0:this.isSelected?2:1}get borderStyle(){return`border: ${this.getBorderWidth()}px solid ${this.isSelected?E:"#c9ccd2"};`}get wrapperStyle(){const{x:e,y:t,width:i,height:n}=this.props.figure;return In({left:`${e}px`,top:`${t}px`,width:`${i}px`,height:`${n}px`,"z-index":String(oe.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);",t}setup(){t.useEffect(((e,t,i)=>{e===t&&(null==i||i.focus({preventScroll:!0}))}),(()=>[this.env.model.getters.getSelectedFigureId(),this.props.figure.id,this.figureRef.el])),t.onWillUnmount((()=>{this.props.onFigureDeleted()}))}clickAnchor(e,t,i){this.props.onClickAnchor(e,t,i)}onMouseDown(e){this.props.onMouseDown(e)}onKeyDown(e){const t=this.props.figure,i=function(e,t="key"){let i="";$n.includes(e.key)||(zn(e)&&(i+="Ctrl+"),e.altKey&&(i+="Alt+"),e.shiftKey&&(i+="Shift+"));const n="key"===t?e.key:e.code;return i+=Un.test(n)?n.toUpperCase():n,i}(e);switch(i){case"Delete":this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:t.id}),this.props.onFigureDeleted(),e.preventDefault(),e.stopPropagation();break;case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":const n={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+n[0],y:t.y+n[1]}),e.preventDefault(),e.stopPropagation();break;case"Ctrl+A":e.preventDefault(),e.stopPropagation();break;case"Ctrl+Y":case"Ctrl+Z":"Ctrl+Y"===i?this.env.model.dispatch("REQUEST_REDO"):"Ctrl+Z"===i&&this.env.model.dispatch("REQUEST_UNDO"),e.preventDefault(),e.stopPropagation()}}}dp.template="o-spreadsheet-FigureComponent",dp.components={},dp.defaultProps={onFigureDeleted:()=>{},onMouseDown:()=>{},onClickAnchor:()=>{}},dp.props={figure:Object,style:{type:String,optional:!0},onFigureDeleted:{type:Function,optional:!0},onMouseDown:{type:Function,optional:!0},onClickAnchor:{type:Function,optional:!0}};class up extends t.Component{constructor(){super(...arguments),this.dnd=t.useState({figId:void 0,x:0,y:0,width:0,height:0,cancelDnd:void 0})}setup(){t.onMounted((()=>{this.render()})),t.onWillUpdateProps((()=>{const e=this.env.model.getters.getActiveSheetId();this.dnd.figId&&!this.env.model.getters.getFigure(e,this.dnd.figId)&&(this.dnd.cancelDnd&&this.dnd.cancelDnd(),this.dnd.figId=void 0,this.dnd.cancelDnd=void 0)}))}getVisibleFigures(){const e=this.env.model.getters.getVisibleFigures();if(this.dnd.figId&&!e.some((e=>e.id===this.dnd.figId))){const t=this.env.model.getters.getFigure(this.env.model.getters.getActiveSheetId(),this.dnd.figId);t&&e.push(t)}return e}get containers(){const e=this.getVisibleFigures(),t=[];for(const i of["topLeft","topRight","bottomLeft","bottomRight"]){const n=e.filter((e=>this.getFigureContainer(e)===i));n.length>0&&t.push({type:i,figures:n,style:this.getContainerStyle(i),inverseViewportStyle:this.getInverseViewportPositionStyle(i)})}return this.dnd.figId&&t.push({type:"dnd",figures:[this.getDndFigure()],style:this.getContainerStyle("dnd"),inverseViewportStyle:this.getInverseViewportPositionStyle("dnd")}),t}getContainerStyle(e){const{width:t,height:i}=this.env.model.getters.getSheetViewDimension(),{x:n,y:o}=this.env.model.getters.getMainViewportCoordinates(),s=["bottomRight","topRight"].includes(e)?n:0,r=t-s,a=["bottomRight","bottomLeft"].includes(e)?o:0;return In({left:`${s}px`,top:`${a}px`,width:`${r}px`,height:`${i-a}px`})}getInverseViewportPositionStyle(e){const{scrollX:t,scrollY:i}=this.env.model.getters.getActiveSheetScrollInfo(),{x:n,y:o}=this.env.model.getters.getMainViewportCoordinates();return In({left:`${["bottomRight","topRight"].includes(e)?-(n+t):0}px`,top:`${["bottomRight","bottomLeft"].includes(e)?-(o+i):0}px`})}getFigureContainer(e){const{x:t,y:i}=this.env.model.getters.getMainViewportCoordinates();return e.id===this.dnd.figId?"dnd":e.x<t&&e.y<i?"topLeft":e.x<t?"bottomLeft":e.y<i?"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 i=this.env.model.getters.getActiveSheetId(),n=t.clientX,o=t.clientY,{x:s,y:r}=this.internalToScreenCoordinates(e);this.dnd.x=s,this.dnd.y=r,this.dnd.width=e.width,this.dnd.height=e.height;this.dnd.cancelDnd=_r((t=>{const{x:i,y:a}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:l,scrollY:c}=this.env.model.getters.getActiveSheetScrollInfo(),h=i?0:-l,d=a?0:-c;this.dnd.figId=e.id;let u=t.clientX-n;this.dnd.x=Math.max(s+u,h);let g=t.clientY-o;this.dnd.y=Math.max(r+g,d)}),(t=>{if(!this.dnd.figId)return;let{x:n,y:o}=this.screenCoordinatesToInternal(this.dnd);this.dnd.figId=void 0,this.env.model.dispatch("UPDATE_FIGURE",{sheetId:i,id:e.id,x:n,y:o})}))}startResize(e,t,i,n){n.stopPropagation();const o=n.clientX,s=n.clientY,{scrollX:r,scrollY:a}=this.env.model.getters.getActiveSheetScrollInfo(),{x:l,y:c}=this.internalToScreenCoordinates(e);let h;this.dnd.x=l,this.dnd.y=c,this.dnd.width=e.width,this.dnd.height=e.height,h=n=>{this.dnd.figId=e.id;const h=Math.max(t*(n.clientX-o),80-e.width),d=Math.max(i*(n.clientY-s),80-e.height);this.dnd.width=e.width+h,this.dnd.height=e.height+d,t<0&&(this.dnd.x=l-h),i<0&&(this.dnd.y=c-d),this.dnd.x+r<=0&&(this.dnd.width=this.dnd.width+this.dnd.x+r,this.dnd.x=-r),this.dnd.y+a<=0&&(this.dnd.height=this.dnd.height+this.dnd.y+a,this.dnd.y=-a)};this.dnd.cancelDnd=_r(h,(n=>{if(!this.dnd.figId)return;this.dnd.figId=void 0;let{x:o,y:s}=this.screenCoordinatesToInternal(this.dnd);const r={x:o,y:s};t&&(r.width=this.dnd.width),i&&(r.height=this.dnd.height),this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:e.id,...r})}))}getDndFigure(){const e=this.getVisibleFigures().find((e=>e.id===this.dnd.figId));if(!e)throw new Error("Dnd figure not found");return{...e,x:this.dnd.x,y:this.dnd.y,width:this.dnd.width,height:this.dnd.height}}getFigureStyle(e){return e.id!==this.dnd.figId?"":In({opacity:"0.9",cursor:"grabbing"})}internalToScreenCoordinates({x:e,y:t}){const{x:i,y:n}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:o,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo();return{x:e=e<i?e:e-o,y:t=t<n?t:t-s}}screenCoordinatesToInternal({x:e,y:t}){const{x:i,y:n}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:o,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo();return{x:e=i&&e<i?e:e+o,y:t=n&&t<n?t:t+s}}}function gp(e,i,n){let o={col:void 0,row:void 0};const{Date:s}=window;let r,a,l=0;function c(){if(void 0===r||void 0===a)return{col:-1,row:-1};return{col:e.model.getters.getColIndex(r),row:e.model.getters.getRowIndex(a)}}const{pause:h,resume:d}=function(e,i){let n;const{setInterval:o,clearInterval:s}=window,r=()=>{s(n),n=void 0},a=()=>{try{e()}catch(e){throw r(),e}};return t.useEffect((()=>(n=o(a,i),()=>s(n))),(()=>[i])),{pause:r,resume:()=>{void 0===n&&(n=o(a,i))}}}((function(){const{col:e,row:t}=c(),i=s.now()-l;i>300&&(e!==o.col||t!==o.row)&&p(void 0,void 0);if(i>300){if(e<0||t<0)return;p(e,t)}}),200);function u(e){i.el===e.target&&(r=e.offsetX,a=e.offsetY,l=s.now())}function g(){const{col:e,row:t}=c();e===o.col&&t===o.row||p(void 0,void 0)}function p(e,t){e===o.col&&t===o.row||(o.col=e,o.row=t,n({col:e,row:t}))}return t.onMounted((()=>{const e=i.el;e.addEventListener("mousemove",u),e.addEventListener("mouseleave",h),e.addEventListener("mouseenter",d),e.addEventListener("mousedown",g)})),t.onWillUnmount((()=>{const e=i.el;e.removeEventListener("mousemove",u),e.removeEventListener("mouseleave",h),e.removeEventListener("mouseenter",d),e.removeEventListener("mousedown",g)})),o}up.template="o-spreadsheet-FiguresContainer",up.components={FigureComponent:dp},oo.add("chart",{Component:Mr,SidePanelComponent:"ChartPanel"});class pp extends t.Component{setup(){this.gridOverlay=t.useRef("gridOverlay"),gp(this.env,this.gridOverlay,this.props.onCellHovered),t.useEffect((()=>this.props.onGridResized({height:this.gridOverlayEl.clientHeight,width:this.gridOverlayEl.clientWidth})),(()=>[this.gridOverlayEl.clientHeight,this.gridOverlayEl.clientWidth])),function(e,i,n){let o=null,s=null;function r(e){1===e.touches.length&&(o=e.touches[0].clientX,s=e.touches[0].clientY)}function a(){o=null,s=null}function l(e){if(1!==e.touches.length)return;n()&&(e.preventDefault(),e.stopPropagation());const t=e.touches[0].clientX,r=e.touches[0].clientY;i(o-t,s-r),o=t,s=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,i]=this.getCartesianCoordinates(e);this.props.onCellClicked(t,i,{expandZone:e.shiftKey,addZone:zn(e)})}onDoubleClick(e){const[t,i]=this.getCartesianCoordinates(e);this.props.onCellDoubleClicked(t,i)}onContextMenu(e){e.preventDefault();const[t,i]=this.getCartesianCoordinates(e);this.props.onCellRightClicked(t,i,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){return[this.env.model.getters.getColIndex(e.offsetX),this.env.model.getters.getRowIndex(e.offsetY)]}}pp.template="o-spreadsheet-GridOverlay",pp.components={FiguresContainer:up},pp.defaultProps={onCellHovered:()=>{},onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{},onFigureDeleted:()=>{},sidePanelIsOpen:!1};class mp extends t.Component{constructor(){super(...arguments),this.zIndex=oe.GridPopover}get cellPopover(){const e=this.env.model.getters.getCellPopover(this.props.hoveredCell);if(!e.isOpen)return{isOpen:!1};const t=e.coordinates;return{...e,coordinates:{x:t.x+this.props.gridPosition.x,y:t.y+this.props.gridPosition.y}}}}mp.template="o-spreadsheet-GridPopover",mp.components={Popover:Wn};class fp extends t.Component{constructor(){super(...arguments),this.PADDING=0,this.MAX_SIZE_MARGIN=0,this.MIN_ELEMENT_SIZE=0,this.lastSelectedElementIndex=null,this.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),i=this._getElementIndex(t);if(i<0)return;const n=this._getDimensionsInViewport(i);t-n.start<this.PADDING&&i!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=n.start,this.state.activeElement=this._getPreviousVisibleElement(i)):n.end-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=n.end,this.state.activeElement=i):this.state.resizerIsActive=!1}_computeGrabDisplay(e){const t=this._getElementIndex(this._getEvOffset(e)),i=this._getActiveElements(),n=this._getSelectedZoneStart(),o=this._getSelectedZoneEnd();i.has(n)&&n<=t&&t<=o?this.state.waitingForMove=!0:this.state.waitingForMove=!1}onMouseMove(e){this.state.isResizing||this.state.isMoving||this.state.isSelecting||(this._computeHandleDisplay(e),this._computeGrabDisplay(e))}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(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),i=this.state.draggerLinePosition,n=this._getElementSize(this.state.activeElement),o=i-n+this.MIN_ELEMENT_SIZE,s=this._getMaxSize();_r((e=>{this.state.delta=this._getClientPosition(e)-t,this.state.draggerLinePosition=i+this.state.delta,this.state.draggerLinePosition<o&&(this.state.draggerLinePosition=o,this.state.delta=this.MIN_ELEMENT_SIZE-n),this.state.draggerLinePosition>s&&(this.state.draggerLinePosition=s,this.state.delta=s-i)}),(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()),i=this._getDimensionsInViewport(this._getSelectedZoneEnd()),n=t.start;this.state.draggerLinePosition=n,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=n,this.state.draggerShadowThickness=i.end-t.start;Fr(this.env,((e,i)=>{let n="COL"===this._getType()?e:i;if(n>=0){const e=this._getDimensionsInViewport(n);n<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=e.start,this.state.draggerShadowPosition=e.start,this.state.base=n,this.state.position="before"):this._getSelectedZoneEnd()<n?(this.state.draggerLinePosition=e.end,this.state.draggerShadowPosition=e.end-this.state.draggerShadowThickness,this.state.base=n,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,zn(e)),this.lastSelectedElementIndex=t;Fr(this.env,((e,t)=>{let i="COL"===this._getType()?e:t;i!==this.lastSelectedElementIndex&&-1!==i&&(this._increaseSelection(i),this.lastSelectedElementIndex=i)}),(()=>{this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this.env.model.dispatch(zn(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 i=this._getType();this.props.onOpenContextMenu(i,e.clientX,e.clientY)}}xn`
1183
1183
  .o-col-resizer {
1184
1184
  position: absolute;
1185
1185
  top: 0;
1186
1186
  left: ${M}px;
1187
- right: 0;
1188
- height: ${N}px;
1187
+ right: ${D}px;
1188
+ height: ${O}px;
1189
1189
  &.o-dragging {
1190
1190
  cursor: grabbing;
1191
1191
  }
@@ -1193,14 +1193,14 @@
1193
1193
  cursor: grab;
1194
1194
  }
1195
1195
  .dragging-col-line {
1196
- top: ${N}px;
1196
+ top: ${O}px;
1197
1197
  position: absolute;
1198
1198
  width: 2px;
1199
1199
  height: 10000px;
1200
1200
  background-color: black;
1201
1201
  }
1202
1202
  .dragging-col-shadow {
1203
- top: ${N}px;
1203
+ top: ${O}px;
1204
1204
  position: absolute;
1205
1205
  height: 10000px;
1206
1206
  background-color: black;
@@ -1208,13 +1208,13 @@
1208
1208
  }
1209
1209
  .o-handle {
1210
1210
  position: absolute;
1211
- height: ${N}px;
1211
+ height: ${O}px;
1212
1212
  width: 4px;
1213
1213
  cursor: e-resize;
1214
1214
  background-color: ${E};
1215
1215
  }
1216
1216
  .dragging-resizer {
1217
- top: ${N}px;
1217
+ top: ${O}px;
1218
1218
  position: absolute;
1219
1219
  margin-left: 2px;
1220
1220
  width: 1px;
@@ -1227,7 +1227,7 @@
1227
1227
  position: absolute;
1228
1228
  overflow: hidden;
1229
1229
  border-radius: 2px;
1230
- top: calc(${N}px / 2 - ${$}px / 2);
1230
+ top: calc(${O}px / 2 - ${$}px / 2);
1231
1231
  }
1232
1232
  .o-unhide:hover {
1233
1233
  z-index: ${oe.Grid+1};
@@ -1238,14 +1238,13 @@
1238
1238
  top: calc(${$}px / 2 - ${k}px / 2);
1239
1239
  }
1240
1240
  }
1241
- `;class mp extends pp{setup(){super.setup(),this.colResizerRef=t.useRef("colResizer"),this.PADDING=15,this.MAX_SIZE_MARGIN=90,this.MIN_ELEMENT_SIZE=5}get sheetId(){return this.env.model.getters.getActiveSheetId()}_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.sheetId,e)}_getElementSize(e){return this.env.model.getters.getColSize(this.sheetId,e)}_getMaxSize(){return this.colResizerRef.el.clientWidth}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),i=this.env.model.getters.getActiveCols();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"COL",sheetId:this.sheetId,elements:i.has(e)?[...i]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),i=this._getSelectedZoneEnd();for(let n=t;n<=i;n++)e.push(n);const n=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.sheetId,dimension:"COL",base:this.state.base,elements:e,position:this.state.position});!n.isSuccessful&&n.reasons.includes(2)&&this.env.raiseError(is)}_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.sheetId,cols:t.has(e)?[...t]:[e]})}_getType(){return"COL"}_getActiveElements(){return this.env.model.getters.getActiveCols()}_getPreviousVisibleElement(e){const t=this.sheetId;let i;for(i=e-1;i>=0&&this.env.model.getters.isColHidden(t,i);i--);return i}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.sheetId,elements:e,dimension:"COL"})}unhideStyleValue(e){return this._getDimensionsInViewport(e).start}}mp.template="o-spreadsheet-ColResizer",wn`
1241
+ `;class vp extends fp{setup(){super.setup(),this.colResizerRef=t.useRef("colResizer"),this.PADDING=15,this.MAX_SIZE_MARGIN=90,this.MIN_ELEMENT_SIZE=5}get sheetId(){return this.env.model.getters.getActiveSheetId()}_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.sheetId,e)}_getElementSize(e){return this.env.model.getters.getColSize(this.sheetId,e)}_getMaxSize(){return this.colResizerRef.el.clientWidth}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),i=this.env.model.getters.getActiveCols();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"COL",sheetId:this.sheetId,elements:i.has(e)?[...i]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),i=this._getSelectedZoneEnd();for(let n=t;n<=i;n++)e.push(n);const n=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.sheetId,dimension:"COL",base:this.state.base,elements:e,position:this.state.position});!n.isSuccessful&&n.reasons.includes(2)&&this.env.raiseError(os)}_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.sheetId,cols:t.has(e)?[...t]:[e]})}_getType(){return"COL"}_getActiveElements(){return this.env.model.getters.getActiveCols()}_getPreviousVisibleElement(e){const t=this.sheetId;let i;for(i=e-1;i>=0&&this.env.model.getters.isColHidden(t,i);i--);return i}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.sheetId,elements:e,dimension:"COL"})}unhideStyleValue(e){return this._getDimensionsInViewport(e).start}}vp.template="o-spreadsheet-ColResizer",xn`
1242
1242
  .o-row-resizer {
1243
1243
  position: absolute;
1244
- top: ${N}px;
1244
+ top: ${O}px;
1245
1245
  left: 0;
1246
- right: 0;
1246
+ bottom: ${D}px;
1247
1247
  width: ${M}px;
1248
- height: calc(100% - ${41}px);
1249
1248
  &.o-dragging {
1250
1249
  cursor: grabbing;
1251
1250
  }
@@ -1299,7 +1298,7 @@
1299
1298
  background-color: lightgrey;
1300
1299
  }
1301
1300
  }
1302
- `;class fp extends pp{setup(){super.setup(),this.rowResizerRef=t.useRef("rowResizer"),this.PADDING=5,this.MAX_SIZE_MARGIN=60,this.MIN_ELEMENT_SIZE=10}get sheetId(){return this.env.model.getters.getActiveSheetId()}_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.sheetId,e)}_getElementSize(e){return this.env.model.getters.getRowSize(this.sheetId,e)}_getMaxSize(){return this.rowResizerRef.el.clientHeight}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),i=this.env.model.getters.getActiveRows();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"ROW",sheetId:this.sheetId,elements:i.has(e)?[...i]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),i=this._getSelectedZoneEnd();for(let n=t;n<=i;n++)e.push(n);const n=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.sheetId,dimension:"ROW",base:this.state.base,elements:e,position:this.state.position});!n.isSuccessful&&n.reasons.includes(2)&&this.env.raiseError(is)}_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.sheetId,rows:t.has(e)?[...t]:[e]})}_getType(){return"ROW"}_getActiveElements(){return this.env.model.getters.getActiveRows()}_getPreviousVisibleElement(e){const t=this.sheetId;let i;for(i=e-1;i>=0&&this.env.model.getters.isRowHidden(t,i);i--);return i}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.sheetId,dimension:"ROW",elements:e})}unhideStyleValue(e){return this._getDimensionsInViewport(e).start}}fp.template="o-spreadsheet-RowResizer",wn`
1301
+ `;class bp extends fp{setup(){super.setup(),this.rowResizerRef=t.useRef("rowResizer"),this.PADDING=5,this.MAX_SIZE_MARGIN=60,this.MIN_ELEMENT_SIZE=10}get sheetId(){return this.env.model.getters.getActiveSheetId()}_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.sheetId,e)}_getElementSize(e){return this.env.model.getters.getRowSize(this.sheetId,e)}_getMaxSize(){return this.rowResizerRef.el.clientHeight}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),i=this.env.model.getters.getActiveRows();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"ROW",sheetId:this.sheetId,elements:i.has(e)?[...i]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),i=this._getSelectedZoneEnd();for(let n=t;n<=i;n++)e.push(n);const n=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.sheetId,dimension:"ROW",base:this.state.base,elements:e,position:this.state.position});!n.isSuccessful&&n.reasons.includes(2)&&this.env.raiseError(os)}_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.sheetId,rows:t.has(e)?[...t]:[e]})}_getType(){return"ROW"}_getActiveElements(){return this.env.model.getters.getActiveRows()}_getPreviousVisibleElement(e){const t=this.sheetId;let i;for(i=e-1;i>=0&&this.env.model.getters.isRowHidden(t,i);i--);return i}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.sheetId,dimension:"ROW",elements:e})}unhideStyleValue(e){return this._getDimensionsInViewport(e).start}}bp.template="o-spreadsheet-RowResizer",xn`
1303
1302
  .o-overlay {
1304
1303
  .all {
1305
1304
  position: absolute;
@@ -1307,10 +1306,10 @@
1307
1306
  left: 0;
1308
1307
  right: 0;
1309
1308
  width: ${M}px;
1310
- height: ${N}px;
1309
+ height: ${O}px;
1311
1310
  }
1312
1311
  }
1313
- `;class vp extends t.Component{selectAll(){this.env.model.selection.selectAll()}}function bp(e,i,n){const o=t.useRef(e);t.useEffect((function(){const e=o.el,t=window.devicePixelRatio||1,s=e.getContext("2d",{alpha:!1}),r={ctx:s,dpr:t,thinLineWidth:.4*t},{width:a,height:l}=n();if(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;`),0===a||0===l)return;s.translate(-m,-m),s.scale(t,t),i.drawGrid(r)}))}function Sp(e){function t(e,t){return e*(0===t?1:F)}return i=>{const n=t(i.shiftKey&&!Pn()?i.deltaY:i.deltaX,i.deltaMode),o=t(i.shiftKey&&!Pn()?i.deltaX:i.deltaY,i.deltaMode);e(n,o)}}vp.template="o-spreadsheet-HeadersOverlay",vp.components={ColResizer:mp,RowResizer:fp},wn`
1312
+ `;class Sp extends t.Component{selectAll(){this.env.model.selection.selectAll()}}function Cp(e,i,n){const o=t.useRef(e);t.useEffect((function(){const e=o.el,t=window.devicePixelRatio||1,s=e.getContext("2d",{alpha:!1}),r={ctx:s,dpr:t,thinLineWidth:.4*t},{width:a,height:l}=n();if(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;`),0===a||0===l)return;s.translate(-m,-m),s.scale(t,t),i.drawGrid(r)}))}function Ep(e){function t(e,t){return e*(0===t?1:F)}return i=>{const n=t(i.shiftKey&&!Vn()?i.deltaY:i.deltaX,i.deltaMode),o=t(i.shiftKey&&!Vn()?i.deltaX:i.deltaY,i.deltaMode);e(n,o)}}Sp.template="o-spreadsheet-HeadersOverlay",Sp.components={ColResizer:vp,RowResizer:bp},xn`
1314
1313
  .o-border {
1315
1314
  position: absolute;
1316
1315
  &:hover {
@@ -1320,7 +1319,7 @@
1320
1319
  .o-moving {
1321
1320
  cursor: grabbing;
1322
1321
  }
1323
- `;class Cp extends t.Component{get style(){const e=["n","w","e"].includes(this.props.orientation),t=["n","w","s"].includes(this.props.orientation),i=["n","s"].includes(this.props.orientation),n=["w","e"].includes(this.props.orientation),o=this.props.zone,s=this.env.model.getters.getVisibleRect(o),r=s.x,a=s.x+s.width-4,l=s.y,c=s.y+s.height-4;return`\n left:${t?r:a}px;\n top:${e?l:c}px;\n width:${i?a-r:4}px;\n height:${n?c-l:4}px;\n `}onMouseDown(e){this.props.onMoveHighlight(e.clientX,e.clientY)}}Cp.template="o-spreadsheet-Border",wn`
1322
+ `;class wp extends t.Component{get style(){const e=["n","w","e"].includes(this.props.orientation),t=["n","w","s"].includes(this.props.orientation),i=["n","s"].includes(this.props.orientation),n=["w","e"].includes(this.props.orientation),o=this.props.zone,s=this.env.model.getters.getVisibleRect(o),r=s.x,a=s.x+s.width-4,l=s.y,c=s.y+s.height-4;return`\n left:${t?r:a}px;\n top:${e?l:c}px;\n width:${i?a-r:4}px;\n height:${n?c-l:4}px;\n `}onMouseDown(e){this.props.onMoveHighlight(e.clientX,e.clientY)}}wp.template="o-spreadsheet-Border",xn`
1324
1323
  .o-corner {
1325
1324
  position: absolute;
1326
1325
  height: 6px;
@@ -1342,11 +1341,11 @@
1342
1341
  .o-resizing {
1343
1342
  cursor: grabbing;
1344
1343
  }
1345
- `;class Ep extends t.Component{constructor(){super(...arguments),this.isTop="n"===this.props.orientation[0],this.isLeft="w"===this.props.orientation[1]}get style(){const e=this.props.zone,t=this.isLeft?e.left:e.right,i=this.isTop?e.top:e.bottom,n=this.env.model.getters.getVisibleRect({left:t,right:t,top:i,bottom:i});if(n.width*n.height==0)return"display:none";return`\n left:${(this.isLeft?n.x:n.x+n.width)-4}px;\n top:${(this.isTop?n.y:n.y+n.height)-4}px;\n background-color:${this.props.color};\n `}onMouseDown(e){this.props.onResizeHighlight(this.isLeft,this.isTop)}}Ep.template="o-spreadsheet-Corner",wn`
1344
+ `;class yp extends t.Component{constructor(){super(...arguments),this.isTop="n"===this.props.orientation[0],this.isLeft="w"===this.props.orientation[1]}get style(){const e=this.props.zone,t=this.isLeft?e.left:e.right,i=this.isTop?e.top:e.bottom,n=this.env.model.getters.getVisibleRect({left:t,right:t,top:i,bottom:i});if(n.width*n.height==0)return"display:none";return`\n left:${(this.isLeft?n.x:n.x+n.width)-4}px;\n top:${(this.isTop?n.y:n.y+n.height)-4}px;\n background-color:${this.props.color};\n `}onMouseDown(e){this.props.onResizeHighlight(this.isLeft,this.isTop)}}yp.template="o-spreadsheet-Corner",xn`
1346
1345
  .o-highlight {
1347
1346
  z-index: ${oe.Highlight};
1348
1347
  }
1349
- `;class wp extends t.Component{constructor(){super(...arguments),this.highlightState=t.useState({shiftingMode:"none"})}onResizeHighlight(e,t){const i=this.env.model.getters.getActiveSheet();this.highlightState.shiftingMode="isResizing";const n=this.props.zone,o=e?n.right:n.left,s=t?n.bottom:n.top;let r=e?n.left:n.right,a=t?n.top:n.bottom,l=n;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(i.id,l)});Mr(this.env,((e,t)=>{if(r!==e||a!==t){const n=this.env.model.getters.getActiveSheetId();r=Me(-1===e?r:e,0,this.env.model.getters.getNumberCols(n)-1),a=Me(-1===t?a:t,0,this.env.model.getters.getNumberRows(n)-1);let c={left:Math.min(o,r),top:Math.min(s,a),right:Math.max(o,r),bottom:Math.max(s,a)};c=this.env.model.getters.expandZone(n,c),Vi(c,l)||(this.env.model.dispatch("CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(i.id,c)}),l=c)}}),(()=>{this.highlightState.shiftingMode="none",this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION")}))}onMoveHighlight(e,t){this.highlightState.shiftingMode="isMoving";const i=this.props.zone,n=$n(),o=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getColIndex(e-n.left),r=this.env.model.getters.getRowIndex(t-n.top),a=-i.left,l=this.env.model.getters.getNumberCols(o)-i.right-1,c=-i.top,h=this.env.model.getters.getNumberRows(o)-i.bottom-1;let d=i;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(o,d)});let u=s,g=r;Mr(this.env,((e,t)=>{if(u!==e||g!==t){u=-1===e?u:e,g=-1===t?g:t;const n=Me(u-s,a,l),p=Me(g-r,c,h);let m={left:i.left+n,top:i.top+p,right:i.right+n,bottom:i.bottom+p};m=this.env.model.getters.expandZone(o,m),Vi(m,d)||(this.env.model.dispatch("CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(o,m)}),d=m)}}),(()=>{this.highlightState.shiftingMode="none",this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION")}))}}wp.template="o-spreadsheet-Highlight",wp.components={Corner:Ep,Border:Cp};class yp{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}}wn`
1348
+ `;class xp extends t.Component{constructor(){super(...arguments),this.highlightState=t.useState({shiftingMode:"none"})}onResizeHighlight(e,t){const i=this.env.model.getters.getActiveSheet();this.highlightState.shiftingMode="isResizing";const n=this.props.zone,o=e?n.right:n.left,s=t?n.bottom:n.top;let r=e?n.left:n.right,a=t?n.top:n.bottom,l=n;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(i.id,l)});Fr(this.env,((e,t)=>{if(r!==e||a!==t){const n=this.env.model.getters.getActiveSheetId();r=Me(-1===e?r:e,0,this.env.model.getters.getNumberCols(n)-1),a=Me(-1===t?a:t,0,this.env.model.getters.getNumberRows(n)-1);let c={left:Math.min(o,r),top:Math.min(s,a),right:Math.max(o,r),bottom:Math.max(s,a)};c=this.env.model.getters.expandZone(n,c),Bi(c,l)||(this.env.model.dispatch("CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(i.id,c)}),l=c)}}),(()=>{this.highlightState.shiftingMode="none",this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION")}))}onMoveHighlight(e,t){this.highlightState.shiftingMode="isMoving";const i=this.props.zone,n=Pn(),o=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getColIndex(e-n.left),r=this.env.model.getters.getRowIndex(t-n.top),a=-i.left,l=this.env.model.getters.getNumberCols(o)-i.right-1,c=-i.top,h=this.env.model.getters.getNumberRows(o)-i.bottom-1;let d=i;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(o,d)});let u=s,g=r;Fr(this.env,((e,t)=>{if(u!==e||g!==t){u=-1===e?u:e,g=-1===t?g:t;const n=Me(u-s,a,l),p=Me(g-r,c,h);let m={left:i.left+n,top:i.top+p,right:i.right+n,bottom:i.bottom+p};m=this.env.model.getters.expandZone(o,m),Bi(m,d)||(this.env.model.dispatch("CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(o,m)}),d=m)}}),(()=>{this.highlightState.shiftingMode="none",this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION")}))}}xp.template="o-spreadsheet-Highlight",xp.components={Corner:yp,Border:wp};class Rp{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}}xn`
1350
1349
  .o-scrollbar {
1351
1350
  position: absolute;
1352
1351
  overflow: auto;
@@ -1362,7 +1361,7 @@
1362
1361
  border-left: 1px solid #e2e3e3;
1363
1362
  }
1364
1363
  }
1365
- `;class xp extends t.Component{setup(){this.scrollbarRef=t.useRef("scrollbar"),this.scrollbar=new yp(this.scrollbarRef.el,this.props.direction),t.onMounted((()=>{this.scrollbar.el=this.scrollbarRef.el})),t.useEffect((()=>{this.scrollbar.scroll!==this.props.offset&&(this.scrollbar.scroll=this.props.offset)}),(()=>[this.scrollbar.scroll,this.props.offset]))}get sizeCss(){return xn({width:`${this.props.width}px`,height:`${this.props.height}px`})}get positionCss(){return xn(this.props.position)}onScroll(e){this.props.offset!==this.scrollbar.scroll&&this.props.onScroll(this.scrollbar.scroll)}}xp.template=t.xml`
1364
+ `;class Ip extends t.Component{setup(){this.scrollbarRef=t.useRef("scrollbar"),this.scrollbar=new Rp(this.scrollbarRef.el,this.props.direction),t.onMounted((()=>{this.scrollbar.el=this.scrollbarRef.el})),t.useEffect((()=>{this.scrollbar.scroll!==this.props.offset&&(this.scrollbar.scroll=this.props.offset)}),(()=>[this.scrollbar.scroll,this.props.offset]))}get sizeCss(){return In({width:`${this.props.width}px`,height:`${this.props.height}px`})}get positionCss(){return In(this.props.position)}onScroll(e){this.props.offset!==this.scrollbar.scroll&&this.props.onScroll(this.scrollbar.scroll)}}Ip.template=t.xml`
1366
1365
  <div
1367
1366
  t-attf-class="o-scrollbar {{props.direction}}"
1368
1367
  t-on-scroll="onScroll"
@@ -1370,7 +1369,7 @@
1370
1369
  t-att-style="positionCss">
1371
1370
  <div t-att-style="sizeCss"/>
1372
1371
  </div>
1373
- `,xp.defaultProps={width:1,height:1};class Rp extends t.Component{get offset(){return this.env.model.getters.getActiveSheetDOMScrollInfo().scrollX}get width(){return this.env.model.getters.getMainViewportRect().width}get isDisplayed(){const{xRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){const{x:e}=this.env.model.getters.getMainViewportRect();return{left:`${this.props.position.left+e}px`,bottom:"0px",height:"15px",right:"0px"}}onScroll(e){const{scrollY:t}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:e,offsetY:t})}}Rp.components={ScrollBar:xp},Rp.template=t.xml`
1372
+ `,Ip.defaultProps={width:1,height:1};class Tp extends t.Component{get offset(){return this.env.model.getters.getActiveSheetDOMScrollInfo().scrollX}get width(){return this.env.model.getters.getMainViewportRect().width}get isDisplayed(){const{xRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){const{x:e}=this.env.model.getters.getMainViewportRect();return{left:`${this.props.position.left+e}px`,bottom:"0px",height:"15px",right:"0px"}}onScroll(e){const{scrollY:t}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:e,offsetY:t})}}Tp.components={ScrollBar:Ip},Tp.template=t.xml`
1374
1373
  <ScrollBar
1375
1374
  t-if="isDisplayed"
1376
1375
  width="width"
@@ -1378,7 +1377,7 @@
1378
1377
  offset="offset"
1379
1378
  direction="'horizontal'"
1380
1379
  onScroll.bind="onScroll"
1381
- />`,Rp.defaultProps={position:{left:0}};class Ip extends t.Component{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.position.top+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})}}Ip.components={ScrollBar:xp},Ip.template=t.xml`
1380
+ />`,Tp.defaultProps={position:{left:0}};class Ap extends t.Component{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.position.top+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})}}Ap.components={ScrollBar:Ip},Ap.template=t.xml`
1382
1381
  <ScrollBar
1383
1382
  t-if="isDisplayed"
1384
1383
  height="height"
@@ -1386,9 +1385,9 @@
1386
1385
  offset="offset"
1387
1386
  direction="'vertical'"
1388
1387
  onScroll.bind="onScroll"
1389
- />`,Ip.defaultProps={position:{top:0}};const Tp={ROW:jo,COL:Zo,CELL:qo};class Ap extends t.Component{constructor(){super(...arguments),this.HEADER_HEIGHT=N,this.HEADER_WIDTH=M,this.keyDownMapping={ENTER:()=>{const e=this.env.model.getters.getActiveCell();!e||e.isEmpty()?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()},TAB:()=>this.env.model.selection.moveAnchorCell("right",1),"SHIFT+TAB":()=>this.env.model.selection.moveAnchorCell("left",1),F2:()=>{const e=this.env.model.getters.getActiveCell();!e||e.isEmpty()?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()})},"CTRL+A":()=>this.env.model.selection.loopSelection(),"CTRL+S":()=>{var e,t;null===(t=(e=this.props).onSaveRequested)||void 0===t||t.call(e)},"CTRL+Z":()=>this.env.model.dispatch("REQUEST_UNDO"),"CTRL+Y":()=>this.env.model.dispatch("REQUEST_REDO"),"CTRL+B":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"CTRL+I":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"CTRL+U":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"ALT+=":()=>{var e;const t=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getSelectedZone(),{anchor:n}=this.env.model.getters.getSelection(),o=this.env.model.getters.getAutomaticSums(t,i,n.cell);if(this.env.model.getters.isSingleCellOrMerge(t,i)||this.env.model.getters.isEmpty(t,i)&&o.length<=1){const i=(null===(e=o[0])||void 0===e?void 0:e.zone)?this.env.model.getters.zoneToXC(t,o[0].zone):"",n=`=SUM(${i})`;this.props.onGridComposerCellFocused(n,{start:5,end:5+i.length})}else this.env.model.dispatch("SUM_SELECTION")},"CTRL+HOME":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:i}=this.env.model.getters.getNextVisibleCellPosition(e,0,0);this.env.model.selection.selectCell(t,i)},"CTRL+END":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,"COL",this.env.model.getters.getNumberCols(e)-1,0),i=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,i)},"SHIFT+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},i=this.env.model.getters.getPosition();this.env.model.selection.selectZone({cell:i,zone:t})},"CTRL+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},i=this.env.model.getters.getPosition();this.env.model.selection.selectZone({cell:i,zone:t})},"CTRL+SHIFT+ ":()=>{this.env.model.selection.selectAll()},"SHIFT+PAGEDOWN":()=>{this.env.model.dispatch("ACTIVATE_NEXT_SHEET")},"SHIFT+PAGEUP":()=>{this.env.model.dispatch("ACTIVATE_PREVIOUS_SHEET")},PAGEDOWN:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PAGEUP:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP")}}setup(){this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.canvasPosition=zn(this.gridRef),this.hoveredCell=t.useState({col:void 0,row:void 0}),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())),bp("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimensionWithHeaders())),t.useEffect((()=>this.focusDefaultElement()),(()=>[this.env.model.getters.getActiveSheetId()])),this.onMouseWheel=Sp(((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"\n top: 26px;\n left: 48px;\n height: calc(100% - 41px);\n width: calc(100% - 63px);\n "}onClosePopover(){this.closeOpenedPopover(),this.focusDefaultElement()}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}}isAutoFillActive(){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:M,gridOffsetY:N})}moveCanvas(e,t){const{scrollX:i,scrollY:n}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:Math.max(i+e,0),offsetY:Math.max(n+t,0)})}getClientPositionKey(e){var t,i,n;return`${e.id}-${null===(t=e.position)||void 0===t?void 0:t.sheetId}-${null===(i=e.position)||void 0===i?void 0:i.col}-${null===(n=e.position)||void 0===n?void 0:n.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}onCellClicked(e,t,{addZone:i,expandZone:n}){i&&this.env.model.dispatch("PREPARE_SELECTION_INPUT_EXPANSION"),this.closeOpenedPopover(),"editing"===this.env.model.getters.getEditionMode()&&this.env.model.dispatch("STOP_EDITION"),n?this.env.model.selection.setAnchorCorner(e,t):i?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t);let o=e,s=t;Mr(this.env,((e,t)=>{(e!==o&&-1!=e||t!==s&&-1!=t)&&(o=-1===e?o:e,s=-1===t?s:t,this.env.model.selection.setAnchorCorner(o,s))}),(()=>{this.env.model.dispatch("STOP_SELECTION_INPUT"),this.env.model.getters.isPaintingFormat()&&this.env.model.dispatch("PASTE",{target:this.env.model.getters.getSelectedZones()})}))}onCellDoubleClicked(e,t){const i=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition(i,e,t));const n=this.env.model.getters.getCell(i,e,t);!n||n.isEmpty()?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()}closeOpenedPopover(){this.env.model.dispatch("CLOSE_CELL_POPOVER")}processArrows(e){e.preventDefault(),e.stopPropagation(),this.closeOpenedPopover();const t={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"}[e.key];e.shiftKey?this.env.model.selection.resizeAnchorZone(t,Un(e)?"end":1):this.env.model.selection.moveAnchorCell(t,Un(e)?"end":1),this.env.model.getters.isPaintingFormat()&&this.env.model.dispatch("PASTE",{target:this.env.model.getters.getSelectedZones()})}onKeydown(e){if(e.key.startsWith("Arrow"))return void this.processArrows(e);let t="";Un(e)&&(t+="CTRL+"),e.altKey&&(t+="ALT+"),e.shiftKey&&(t+="SHIFT+"),t+=e.key.toUpperCase();let i=this.keyDownMapping[t];return i?(e.preventDefault(),e.stopPropagation(),void i()):void 0}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:i,top:n}=t;let o="CELL";this.env.model.dispatch("STOP_EDITION"),this.env.model.getters.getActiveCols().has(i)?o="COL":this.env.model.getters.getActiveRows().has(n)&&(o="ROW");const{x:s,y:r,width:a}=this.env.model.getters.getVisibleRect(t);this.toggleContextMenu(o,this.canvasPosition.x+s+a,this.canvasPosition.y+r)}onCellRightClicked(e,t,{x:i,y:n}){const o=this.env.model.getters.getSelectedZones();let s="CELL";Bi(e,t,o[o.length-1])?this.env.model.getters.getActiveCols().has(e)?s="COL":this.env.model.getters.getActiveRows().has(t)&&(s="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(s,i,n)}toggleContextMenu(e,t,i){this.closeOpenedPopover(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:i},this.menuState.menuItems=Tp[e].getAll()}copy(e,t){if(!this.gridEl.contains(document.activeElement))return;if("inactive"!==this.env.model.getters.getEditionMode())return;e?lo(this.env):this.env.model.dispatch("COPY");const i=this.env.model.getters.getClipboardContent();t.clipboardData.setData("text/plain",i),t.preventDefault()}paste(e){if(!this.gridEl.contains(document.activeElement))return;const t=e.clipboardData;if(t.types.indexOf("text/plain")>-1){const e=t.getData("text/plain"),i=this.env.model.getters.getSelectedZones();this.env.model.getters.getClipboardContent()===e?po(this.env,i):mo(this.env,i,e)}}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}}Ap.template="o-spreadsheet-Grid",Ap.components={GridComposer:op,GridOverlay:up,GridPopover:gp,HeadersOverlay:vp,Menu:Hn,Autofill:_r,ClientTag:Dr,Highlight:wp,Popover:Bn,VerticalScrollBar:Ip,HorizontalScrollBar:Rp,FilterIconsOverlay:lp};class Op{constructor(e,t,i){this.id=e,this.style=i.style,this.format=i.format,this.lazyEvaluated=t.map((e=>({...e,format:i.format||e.format})))}isFormula(){return!1}isLink(){return!1}isEmpty(){return!1}get evaluated(){return this.lazyEvaluated()}get formattedValue(){return Qt(this.evaluated.value,this.evaluated.format)}get composerContent(){return this.content}get defaultAlign(){switch(this.evaluated.type){case ln.number:case ln.empty:return"right";case ln.boolean:case ln.error:return"center";case ln.text:return"left"}}get isAutoSummable(){var e;switch(this.evaluated.type){case ln.empty:case ln.text:return!0;case ln.number:return!(null===(e=this.evaluated.format)||void 0===e?void 0:e.match(Y));case ln.error:case ln.boolean:return!1}}}class Np extends Op{constructor(e,t={}){super(e,tt({value:"",type:ln.empty}),t),this.content=""}isEmpty(){return!0}}class Mp extends Op{constructor(e,t,i={}){super(e,tt({value:t,type:ln.number}),i),this.content=Qt(this.evaluated.value)}get composerContent(){var e;return(null===(e=this.format)||void 0===e?void 0:e.includes("%"))?100*this.evaluated.value+"%":super.composerContent}}class _p extends Op{constructor(e,t,i={}){super(e,tt({value:t,type:ln.boolean}),i),this.content=this.evaluated.value?"TRUE":"FALSE"}}class Fp extends Op{constructor(e,t,i={}){super(e,tt({value:t,type:ln.text}),i),this.content=this.evaluated.value}}class Dp extends Mp{constructor(e,t,i){super(e,t,i),this.format=i.format}get composerContent(){return Qt(this.evaluated.value,this.format)}}class kp extends Op{constructor(e,t,i={}){const n=Ge(t);n.label=o(n.label),super(e,tt({value:n.label,type:ln.text}),i),this.link=n,this.content=t}isLink(){return!0}get composerContent(){return this.link.label}}class $p extends kp{constructor(e,t,i={}){super(e,t,i),this.link.url=this.withHttp(this.link.url),this.link.isExternal=!0,this.content=We(this.link.label,this.link.url),this.urlRepresentation=this.link.url,this.isUrlEditable=!0}action(e){window.open(this.link.url,"_blank")}withHttp(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}}class Lp extends kp{constructor(e,t,i={},n){super(e,t,i),this.sheetName=n,this.sheetId=Ye(this.link.url),this.isUrlEditable=!1}action(e){e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.model.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}get urlRepresentation(){return this.sheetName(this.sheetId)||s("Invalid sheet")}}class Pp extends Op{constructor(e,t,i,n,o){super(t,tt({value:"Loading...",type:ln.text}),o),this.buildFormulaString=e,this.compiledFormula=i,this.dependencies=n}get content(){return this.buildFormulaString(this)}isFormula(){return!0}assignEvaluation(e){this.lazyEvaluated=e.map((e=>{if(e instanceof c)return{value:e.errorType,type:ln.error,error:e};const{value:t,format:i}=e;switch(typeof t){case"number":return{value:t||0,format:i,type:ln.number};case"boolean":return{value:t,format:i,type:ln.boolean};case"string":return{value:t,format:i,type:ln.text};case"object":return{value:0,format:i,type:ln.number};default:return{value:"",type:ln.empty}}}))}}class Up extends Op{constructor(e,t,i,n){super(e,tt({value:i.errorType,type:ln.error,error:i}),n),this.content=t}}function Vp(e){return""===e?"":Ci(e)?wi(e):Ue(e)?"TRUE"===e.toUpperCase():Ve(e)?ve(e).value:e}eo.add("Formula",{sequence:10,match:e=>e.startsWith("="),createCell:(e,t,i,n,o)=>{const s=$g(t),r=s.dependencies.map((e=>o.getRangeFromSheetXC(n,e)));return new Pp((e=>o.buildFormulaContent(n,e)),e,s,r,i)}}).add("Empty",{sequence:20,match:e=>""===e,createCell:(e,t,i)=>new Np(e,i)}).add("NumberWithDateTimeFormat",{sequence:25,match:(e,t)=>!!t&&Ci(e)&&function(e){try{return oi(1,e),!0}catch(e){return!1}}(t),createCell:(e,t,i)=>{const n=i.format;return new Dp(e,wi(t),{...i,format:n})}}).add("Number",{sequence:30,match:e=>Ci(e),createCell:(e,t,i)=>(i.format||(i.format=function(e){const t=e.includes(".")?"0.00":"0",i=e.match(/[\$€]/);if(i){const n=e.match(/[\d]/),o="[$"+i.values().next().value+"]";return n.index<i.index?"#,##"+t+o:o+"#,##"+t}if(e.includes("%"))return t+"%";return}(t)),new Mp(e,wi(t),i))}).add("Boolean",{sequence:40,match:e=>Ue(e),createCell:(e,t,i)=>new _p(e,"TRUE"===t.toUpperCase(),i)}).add("DateTime",{sequence:50,match:e=>Ve(e),createCell:(e,t,i)=>{const n=ve(t),o=i.format||n.format;return new Dp(e,n.value,{...i,format:o})}}).add("MarkdownSheetLink",{sequence:60,match:e=>Ze(e),createCell:(e,t,i,n,o)=>new Lp(e,t,i,(e=>o.tryGetSheetName(e)))}).add("MarkdownLink",{sequence:70,match:e=>He(e),createCell:(e,t,i)=>new $p(e,t,i)}).add("WebLink",{sequence:80,match:e=>{return t=e,Be.test(t);var t},createCell:(e,t,i)=>new $p(e,We(t,t),i)});class zp{constructor(e){this.xmlString=e}toString(){return this.xmlString}}const Bp=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart"],Hp="000000",Wp={arrows:"3Arrows",smiley:"3Symbols",dots:"3TrafficLights1"},Gp={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"},qp="http://schemas.openxmlformats.org/drawingml/2006/main",Zp="http://schemas.openxmlformats.org/drawingml/2006/chart",jp={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"},Yp={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"},Xp="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Kp=.75,Qp=.1317,Jp=8.43,em=12.75,tm=30,im=100,nm=164,om={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}]},sm=["ACOT","ACOTH","AGGREGATE","ARABIC","BASE","BETA.DIST","BETA.INV","BINOM.DIST","BINOM.DIST.RANGE","BINOM.INV","BITAND","BITLSHIFT","BITOR","BITRSHIFT","BITXOR","BYCOL","BYROW","CEILING.MATH","CEILING.PRECISE","CHISQ.DIST","CHISQ.DIST.RT","CHISQ.INV","CHISQ.INV.RT","CHISQ.TEST","CHOOSECOLS","CHOOSEROWS","COMBINA","CONCAT","CONFIDENCE.NORM","CONFIDENCE.T","COT","COTH","COVARIANCE.P","COVARIANCE.S","CSC","CSCH","DAYS","DECIMAL","DROP","ERF.PRECISE","ERFC.PRECISE","EXPAND","EXPON.DIST","F.DIST","F.DIST.RT","F.INV","F.INV.RT","F.TEST","FIELDVALUE","FILTERXML","FLOOR.MATH","FLOOR.PRECISE","FORECAST.ETS","FORECAST.ETS.CONFINT","FORECAST.ETS.SEASONALITY","FORECAST.ETS.STAT","FORECAST.LINEAR","FORMULATEXT","GAMMA","GAMMA.DIST","GAMMA.INV","GAMMALN.PRECISE","GAUSS","HSTACK","HYPGEOM.DIST","IFNA","IFS","IMCOSH","IMCOT","IMCSC","IMCSCH","IMSEC","IMSECH","IMSINH","IMTAN","ISFORMULA","ISOMITTED","ISOWEEKNUM","LAMBDA","LET","LOGNORM.DIST","LOGNORM.INV","MAKEARRAY","MAP","MAXIFS","MINIFS","MODE.MULT","MODE.SNGL","MUNIT","NEGBINOM.DIST","NORM.DIST","NORM.INV","NORM.S.DIST","NORM.S.INV","NUMBERVALUE","PDURATION","PERCENTILE.EXC","PERCENTILE.INC","PERCENTRANK.EXC","PERCENTRANK.INC","PERMUTATIONA","PHI","POISSON.DIST","PQSOURCE","PYTHON_STR","PYTHON_TYPE","PYTHON_TYPENAME","QUARTILE.EXC","QUARTILE.INC","QUERYSTRING","RANDARRAY","RANK.AVG","RANK.EQ","REDUCE","RRI","SCAN","SEC","SECH","SEQUENCE","SHEET","SHEETS","SKEW.P","SORTBY","STDEV.P","STDEV.S","SWITCH","T.DIST","T.DIST.2T","T.DIST.RT","T.INV","T.INV.2T","T.TEST","TAKE","TEXTAFTER","TEXTBEFORE","TEXTJOIN","TEXTSPLIT","TOCOL","TOROW","UNICHAR","UNICODE","UNIQUE","VAR.P","VAR.S","VSTACK","WEBSERVICE","WEIBULL.DIST","WRAPCOLS","WRAPROWS","XLOOKUP","XOR","Z.TEST"],rm="[Content_Types].xml";var am;!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"}(am||(am={}));class lm{constructor(){this._parsingWarnings=new Set,this._conversionWarnings=new Set}addParsingWarning(e){this._parsingWarnings.add(e)}addConversionWarning(e){this._conversionWarnings.add(e)}get warnings(){return[...this._parsingWarnings,...this._conversionWarnings]}generateNotSupportedWarning(e,t,i){let n=`${e} ${t?'"'+t+'" is':"are"} not yet supported. `;i&&(n+=`Only ${i.join(", ")} are currently supported.`),this._conversionWarnings.has(n)||this._conversionWarnings.add(n)}}const cm=["thin"],hm=["general","left","center","right"],dm=["Arial"],um=["solid"],gm=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWith","containsBlanks","notContainsBlanks"],pm={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},mm={dashDot:"thin",dashDotDot:"thin",dashed:"thin",dotted:"thin",double:"thin",hair:"thin",medium:"thin",mediumDashDot:"thin",mediumDashDotDot:"thin",mediumDashed:"thin",none:void 0,slantDashDot:"thin",thick:"thin",thin:"thin"},fm={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"};const vm={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},bm={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},Sm={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"},Cm={none:"none",b:"bottom",t:"top",l:"left",r:"right",tr:"right"},Em={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},wm={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"},ym={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},xm={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},Rm={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"};function Im(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=Hp;else{if(!e.indexed)return;t=Rm[e.indexed]}var i;return t=6===(i=t).length?"#"+i+"FF":"#"+i.slice(2)+i.slice(0,2),e.tint&&(t=function(e,t){const i=Et(e),n=yt(i);t<0&&(n.l=n.l*(1+t));t>0&&(n.l=n.l*(1-t)+(100-100*(1-t)));return Ct(wt(n))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function Tm(e,t){const i=e.split("/"),n=t.split("/");let o="",s=0;for(let e=0;e<i.length-1;e++)i[e]===n[e]?s++:o+="../";return o+=n.slice(s).join("/"),o}function Am(e,t=0){const i={};for(let n=0;n<e.length;n++)e[n]&&(i[n+t]=e[n]);return i}function Om(e){const t=[];for(let i of Object.keys(e).map(Number))t[i]=e[i];return t}function Nm(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,((e,t)=>String.fromCharCode(parseInt(t,16))))}const Mm=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function _m(e,t,i){var n,o,s;if(0===e)return;let r=ym[e]||(null===(n=t.find((t=>t.id===e)))||void 0===n?void 0:n.format);if(r)try{let e=r.replace(/(.*?);.*/,"$1");e=e.replace(/\[(.*)-[A-Z0-9]{3}\]/g,"[$1]"),e=e.replace(/\[\$\]/g,"");const t=(null===(o=e.match(/"/g))||void 0===o?void 0:o.length)||0;if(t/2+((null===(s=e.match(/\[/g))||void 0===s?void 0:s.length)||0)>1)throw new Error("Multiple escaped blocks in format");if(e=e.replace(/"(.*)"/g,"[$$$1]"),e=e.replace(/_.{1}/g,""),e=e.replace(/\*.{1}/g,""),e=e.replace(/\\ /g," "),e=e.replace(/\\./g,(e=>e[1])),function(e){return null!==e.match(Mm)}(e)&&(e=function(e){return e=e.toLowerCase(),e=e.replace(/mmmmm|mmmm|mmm/g,"mm"),e=e.replace(/dddd|ddd/g,"dd"),e=e.replace(/am\/pm|a\/m/g,"a"),e=e.replace(/\byy\b/g,"yyyy"),e=e.replace(/hhhh/g,"hh"),e=e.replace(/\bh\b/g,"hh"),e}(e)),function(e){try{return Qt(0,e),!0}catch(e){return!1}}(e))return e}catch(e){}i.generateNotSupportedWarning(am.NumFmtIdNotSupported,r||`nmFmtId ${e}`)}function Fm(e,t){const i=e.borders.map((e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(am.DiagonalBorderNotSupported)}(e,t);const i={top:Dm(e.top,t),bottom:Dm(e.bottom,t),left:Dm(e.left,t),right:Dm(e.right,t)};return Object.keys(i).forEach((e=>void 0===i[e]&&delete i[e])),i}));return Am(i,1)}function Dm(e,t){if(!e)return;!function(e,t){cm.includes(e.style)||t.generateNotSupportedWarning(am.BorderStyleNotSupported,e.style,cm)}(e,t);const i=mm[e.style];return i?[i,Im(e.color)]:void 0}function km(e,t){return Am(e.styles.map((i=>$m({fontStyle:e.fonts[i.fontId],fillStyle:e.fills[i.fillId],alignment:i.alignment},t))),1)}function $m(e,t){var i,n,o,s,r,a,l,c,h,d,u,g;return function(e,t,i){e&&e.name&&!dm.includes(e.name)&&i.generateNotSupportedWarning(am.FontNotSupported,e.name,dm);t&&t.patternType&&!um.includes(t.patternType)&&i.generateNotSupportedWarning(am.FillStyleNotSupported,t.patternType,um)}(null==e?void 0:e.fontStyle,null==e?void 0:e.fillStyle,t),function(e,t){e&&!hm.includes(e)&&t.generateNotSupportedWarning(am.HorizontalAlignmentNotSupported,e,hm)}(null===(i=null==e?void 0:e.alignment)||void 0===i?void 0:i.horizontal,t),function(e,t){e&&t.generateNotSupportedWarning(am.VerticalAlignmentNotSupported)}(null===(n=null==e?void 0:e.alignment)||void 0===n?void 0:n.vertical,t),{bold:null===(o=e.fontStyle)||void 0===o?void 0:o.bold,italic:null===(s=e.fontStyle)||void 0===s?void 0:s.italic,strikethrough:null===(r=e.fontStyle)||void 0===r?void 0:r.strike,underline:null===(a=e.fontStyle)||void 0===a?void 0:a.underline,align:(null===(l=e.alignment)||void 0===l?void 0:l.horizontal)?fm[e.alignment.horizontal]:void 0,fillColor:"solid"===(null===(c=e.fillStyle)||void 0===c?void 0:c.patternType)?Im(null===(h=e.fillStyle)||void 0===h?void 0:h.fgColor):Im(null===(d=e.fillStyle)||void 0===d?void 0:d.bgColor),textColor:Im(null===(u=e.fontStyle)||void 0===u?void 0:u.color),fontSize:(null===(g=e.fontStyle)||void 0===g?void 0:g.size)?Pm(e.fontStyle.size):void 0}}function Lm(e,t){const i=[];for(let n of e.styles){const o=_m(n.numFmtId,e.numFmts,t);o&&(i[n.numFmtId]=o)}return Am(i,1)}function Pm(e){return Object.keys(re).map(Number).reduce(((t,i)=>Math.abs(i-e)<Math.abs(t-e)?i:t))}function Um(e,t,i){const n=[];let o=1;for(let r of e){if(0===r.cfRules.length)continue;Hm(r,t,i);const e=r.cfRules[0];let a;const l=[];if(void 0!==e.dxfId||"colorScale"===e.type||"iconSet"===e.type){switch(e.type){case"aboveAverage":case"containsErrors":case"notContainsErrors":case"dataBar":case"duplicateValues":case"expression":case"top10":case"uniqueValues":case"timePeriod":continue;case"colorScale":const t=Vm(o++,r);t&&n.push(t);continue;case"iconSet":const c=zm(o++,r,i);c&&n.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;a=vm[e.type],l.push(e.text);break;case"containsBlanks":case"notContainsBlanks":a=vm[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;a=(s=e.operator).slice(0,1).toUpperCase()+s.slice(1),l.push(e.formula[0]),2===e.formula.length&&l.push(e.formula[1])}a&&void 0!==e.dxfId&&n.push({id:(o++).toString(),ranges:r.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:a,values:l,style:$m({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},i)}})}}var s;return n}function Vm(e,t){const i=t.cfRules[0].colorScale;if(!i||i.cfvos.length!==i.colors.length||i.cfvos.length<2||i.cfvos.length>3)return;const n=[];for(let e=0;e<i.cfvos.length;e++)n.push({color:(o=Im(i.colors[e])||"#FFFFFF",9===o.length&&(o=o.slice(0,7)),parseInt(o.replace("#",""),16)),type:bm[i.cfvos[e].type],value:i.cfvos[e].value});var o;const s=n[0],r=2===n.length?n[1]:n[2],a=3===n.length?n[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"ColorScaleRule",minimum:s,midpoint:a,maximum:r}}}function zm(e,t,i){const n=t.cfRules[0].iconSet;if(!n)return;let o=n.cfvos,s=n.cfIcons;if(o.length<3||s&&s.length<3)return;o.length>3&&(o=[o[0],o[Math.floor(o.length/2)],o[o.length-1]]),s&&s.length>3&&(s=[s[0],s[Math.floor(s.length/2)],s[s.length-1]]);const r=[];for(let e=1;e<=2;e++){const t=bm[o[e].type];if("value"===t)return;r.push({value:o[e].value||"",operator:o[e].gte?"ge":"gt",type:t})}let a={lower:s?Bm(s[0].iconSet,s[0].iconId):Bm(n.iconSet,0),middle:s?Bm(s[1].iconSet,s[1].iconId):Bm(n.iconSet,1),upper:s?Bm(s[2].iconSet,s[2].iconId):Bm(n.iconSet,2)};n.reverse&&(a={upper:a.lower,middle:a.middle,lower:a.upper});for(let e of Object.keys(a))if(!a[e])switch(i.generateNotSupportedWarning(am.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=br.dots.good;break;case"middle":a[e]=br.dots.neutral;break;case"lower":a[e]=br.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 Bm(e,t){const i=Sm[e];return i?0===t?br[i].bad:1===t?br[i].neutral:br[i].good:""}function Hm(e,t,i){if(e.cfRules.length>1&&i.generateNotSupportedWarning(am.MultipleRulesCfNotSupported),gm.includes(e.cfRules[0].type)||i.generateNotSupportedWarning(am.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const n=t[e.cfRules[0].dxfId];n.border&&i.generateNotSupportedWarning(am.CfFormatBorderNotSupported),n.alignment&&i.generateNotSupportedWarning(am.CfFormatAlignmentNotSupported),n.numFmt&&i.generateNotSupportedWarning(am.CfFormatNumFmtNotSupported)}}function Wm(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function Gm(e){return Math.round(Kp*e*window.devicePixelRatio*100)/100}function qm(e){return Math.round(Qp*e*100)/100}function Zm(e,t){let i={};e.style&&(i=t.styles[e.style]);const n=function(e,t){if(e.format)return t.formats[e.format];if(e.isFormula){const t=Xu(e.content||""),i=qu.content;if(!t.filter((e=>"FUNCTION"===e.type)).every((e=>i[e.value.toUpperCase()].isExported)))return e.computedFormat}return}(e,t),o={font:{size:(null==i?void 0:i.fontSize)||G,color:{rgb:(null==i?void 0:i.textColor)?i.textColor:"000000"},family:2,name:"Arial"},fill:(null==i?void 0:i.fillColor)?{fgColor:{rgb:i.fillColor}}:{reservedAttribute:"none"},numFmt:n?{format:n,id:0}:void 0,border:e.border||0,alignment:{vertical:"center",horizontal:i.align}};return o.font.strike=!!(null==i?void 0:i.strikethrough)||void 0,o.font.underline=!!(null==i?void 0:i.underline)||void 0,o.font.bold=!!(null==i?void 0:i.bold)||void 0,o.font.italic=!!(null==i?void 0:i.italic)||void 0,o}function jm(e,t){const i=function(e,t){if(!e)return 0;let i=xm[e.format];i||(i=Xm(e,t)+nm);return i}(t.numFmt,e.numFmts),n={fontId:Xm(t.font,e.fonts),fillId:Xm(t.fill,e.fills),borderId:t.border,numFmtId:i,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal}};return Xm(n,e.styles)}function Ym(e,t,i){let n,o=e.find((e=>e.path===t));return o?(n=`rId${(o.rels.length+1).toString()}`,o.rels.push({...i,id:n})):(n="rId1",e.push({path:t,rels:[{...i,id:n}]})),n}function Xm(e,t){let i=t.length;const n="object"==typeof e?ot:(e,t)=>e===t;for(let o=0;o<i;o++)if(n(e,t[o]))return o;return t[t.length]=e,t.length-1}const Km=[];function Qm(e){const t=Km.findIndex((t=>t===e));return-1===t?(Km.push(e),Km.length):t+1}function Jm(e){return Math.round(914400*e/96)}function ef(e,t,i){let n,o,s=e;if(({xc:s,sheetName:n}=$t(e)),n){const e=i.sheets.findIndex((e=>Ai(e.name,n)));if(e<0)throw new Error("Unable to find a sheet with the name "+n);o=e}else o=Number(t);const r=Ni(s);return void 0===r.right&&(r.right=i.sheets[o].colNumber),void 0===r.bottom&&(r.bottom=i.sheets[o].rowNumber),(r.right-r.left+1)*(r.bottom-r.top+1)}function tf(e){return Math.round(96*e/914400)}function nf(e,t){var i;let n=0;for(let o=0;o<e;o++){const e=t.cols.find((e=>o>=e.min&&o<=e.max));(null==e?void 0:e.width)?n+=e.width:(null===(i=t.sheetFormat)||void 0===i?void 0:i.defaultColWidth)?n+=t.sheetFormat.defaultColWidth:n+=Jp}return n/Qp}function of(e,t){var i;let n=0;for(let o=0;o<e;o++){const e=t.rows[o];(null==e?void 0:e.height)?n+=e.height:(null===(i=t.sheetFormat)||void 0===i?void 0:i.defaultRowHeight)?n+=t.sheetFormat.defaultRowHeight:n+=em}return n/Kp}function sf(e){let t=1;return e.figures.map((i=>function(e,t,i){const n=nf(e.anchors[0].col,i)+tf(e.anchors[0].colOffset),o=nf(e.anchors[1].col,i)+tf(e.anchors[1].colOffset),s=of(e.anchors[0].row,i)+tf(e.anchors[0].rowOffset),r=of(e.anchors[1].row,i)+tf(e.anchors[1].rowOffset),a=o-n,l=r-s,c=rf(e.data);return c?{id:t,x:n,y:s,width:a,height:l,tag:"chart",data:rf(e.data)}:void 0}(i,(t++).toString(),e))).filter(Xe)}function rf(e){var t;if(0===e.dataSets.length)return;const i=null===(t=e.dataSets[0].label)||void 0===t?void 0:t.replace(/\$/g,"");let n=e.dataSets.map((e=>e.range.replace(/\$/g,"")));return"pie"===e.type&&n.reverse(),{dataSets:n,dataSetsHaveTitle:!1,labelRange:i,title:e.title||"",type:e.type,background:Im({rgb:e.backgroundColor})||"#FFFFFF",verticalAxisPosition:e.verticalAxisPosition,legendPosition:e.legendPosition,stacked:e.stacked||!1,cumulative:e.cumulative||!1,labelsAsText:!1}}const af=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),lf=new RegExp(/SUBTOTAL\(([0-9]*),/g),cf=new RegExp(xt.source,"ig");function hf(e,t){const i=function(e){const t={};for(let i of e.rows)for(let e of i.cells)e.formula&&void 0!==e.formula.sharedIndex&&e.formula.content&&(t[e.formula.sharedIndex]={refCellXc:e.xc,formula:e.formula.content});return t}(e);for(let n of e.rows.map((e=>e.cells)).flat())(null==n?void 0:n.formula)&&(n.formula.content=void 0===n.formula.sharedIndex||n.formula.content?"="+n.formula.content:"="+uf(n.xc,i[n.formula.sharedIndex]),n.formula.content=df(n.formula.content,t))}function df(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(lf,((e,t)=>{const i=wm[t];return i?i+"(":e}))).replace(af,((e,i,n,o)=>{var s;i=Number(i)-1,o=o.replace(/\$/g,"");const r=t.externalBooks[i].sheetNames.findIndex((e=>Ai(e,n)));if(-1===r)return e;const a=null===(s=t.externalBooks[i].datasets.find((e=>e.sheetId===r)))||void 0===s?void 0:s.data;if(!a)return e;const l=a&&a[o];return(Number(l)?l:`"${l}"`)||e}))}function uf(e,t){const i=Ut(t.refCellXc);let n,o=t.formula.slice();do{if(n=cf.exec(o),n){const t=Ut(n[0].replace("$","")),s=Ut(e),r={colFixed:n[0].startsWith("$"),rowFixed:n[0].includes("$",1)},a={col:s.col-i.col,row:s.row-i.row},l={col:r.colFixed?t.col:t.col+a.col,row:r.rowFixed?t.row:t.row+a.row};o=o.slice(0,n.index)+Vt(l.col,l.row,r)+o.slice(n.index+n[0].length)}}while(n);return o}function gf(e,t){return e.sheets.map((i=>{hf(i,e);const n=function(e){const t=[0,0];for(let i of e.rows)t[0]=Math.max(t[0],lt(i.cells.map((e=>Ut(e.xc).col)))),t[1]=Math.max(t[1],i.index);return t[0]=Math.max(t[0],tm),t[1]=Math.max(t[1],im),t}(i),o=i.sheetViews[0];return{id:i.sheetName,areGridLinesVisible:!o||o.showGridLines,name:i.sheetName,colNumber:n[0],rowNumber:n[1],cells:ff(i,e,n,t),merges:i.merges,cols:pf(i,n[0]),rows:mf(i,n[1]),conditionalFormats:Um(i.cfs,e.dxfs,t),figures:sf(i),isVisible:i.isVisible,panes:o?{xSplit:o.pane.xSplit,ySplit:o.pane.ySplit}:{xSplit:0,ySplit:0},filterTables:[]}}))}function pf(e,t){var i;const n={};for(let s=1;s<t+1;s++){const t=e.cols.find((e=>e.min<=s&&s<=e.max));let r;r=t&&t.width?t.width:(null===(i=e.sheetFormat)||void 0===i?void 0:i.defaultColWidth)?e.sheetFormat.defaultColWidth:Jp,n[s-1]={size:(o=r,o?Math.round(o/Qp*100)/100:o),isHidden:null==t?void 0:t.hidden}}var o;return n}function mf(e,t){var i;const n={};for(let s=1;s<t+1;s++){const t=e.rows.find((e=>e.index===s));let r;r=t&&t.height?t.height:(null===(i=e.sheetFormat)||void 0===i?void 0:i.defaultRowHeight)?e.sheetFormat.defaultRowHeight:em,n[s-1]={size:(o=r,o?Math.round(o/Kp*100)/100:o),isHidden:null==t?void 0:t.hidden}}var o;return n}function ff(e,t,i,n){const o={},s=t.sharedStrings.map((e=>e.replace(/\n/g,"")));const r=e.hyperlinks.reduce(((e,t)=>(e[t.xc]=t,e)),{});for(let i of e.rows)for(let e of i.cells)o[e.xc]={content:vf(e,r,s,n),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 n of e.rows.filter((e=>e.styleIndex)))for(let e=1;e<=i[0];e++){const i=Vt(e-1,n.index-1);let s=o[i];s||(s={},o[i]=s),s.style=s.style?s.style:n.styleIndex+1,s.border=s.border?s.border:t.styles[n.styleIndex].borderId+1,s.format=s.format?s.format:t.styles[n.styleIndex].numFmtId+1}for(let n of e.cols.filter((e=>e.styleIndex)))for(let e=n.min;e<=Math.min(n.max,i[0]);e++)for(let s=1;s<=i[1];s++){const i=Vt(e-1,s-1);let r=o[i];r||(r={},o[i]=r),r.style=r.style?r.style:n.styleIndex+1,r.border=r.border?r.border:t.styles[n.styleIndex].borderId+1,r.format=r.format?r.format:t.styles[n.styleIndex].numFmtId+1}return o}function vf(e,t,i,n){let o;switch(e.type){case"sharedString":o=i[parseInt(e.value,10)];break;case"boolean":o=Number(e.value)?"TRUE":"FALSE";break;case"date":case"error":case"inlineStr":case"number":case"str":o=e.value}return o&&t[e.xc]&&(o=function(e,t,i){const n=e.display||t;e.relTarget||e.location||i.generateNotSupportedWarning(am.BadlyFormattedHyperlink);const o=e.relTarget?e.relTarget:je($t(e.location).sheetName);return We(n,o)}(t[e.xc],o,n)),e.formula&&(o=e.formula.content),o}const bf={fillColor:"#000000",textColor:"#ffffff",bold:!0},Sf={bold:!0},Cf=["thin","#000000FF"];function Ef(e,t){for(const i of t.sheets)for(const t of i.tables){const n=e.sheets.find((e=>e.name===i.sheetName));n&&t.autoFilter&&(n.filterTables||(n.filterTables=[]),n.filterTables.push({range:t.ref}))}!function(e,t){var i,n,o,s;const r=Om(e.styles),a=Om(e.borders);for(let l of t.sheets)for(let t of l.tables){const c=e.sheets.find((e=>e.name===l.sheetName));if(!c)continue;const h=Mi(t.ref);for(let e=0;e<t.headerRowCount;e++)wf(bf,{...h,bottom:h.top+e},c.cells,r);for(let e=0;e<t.totalsRowCount;e++)wf(Sf,{...h,top:h.bottom-e},c.cells,r);(null===(i=t.style)||void 0===i?void 0:i.showFirstColumn)&&wf(Sf,{...h,right:h.left},c.cells,r),(null===(n=t.style)||void 0===n?void 0:n.showLastColumn)&&wf(Sf,{...h,left:h.right},c.cells,r);for(let e=h.left;e<=h.right;e++)for(let i=h.top;i<=h.bottom;i++){const n=Vt(e,i),r=c.cells[n],l={left:e===h.left||(null===(o=t.style)||void 0===o?void 0:o.showColumnStripes)?Cf:void 0,right:e===h.right?Cf:void 0,top:i===h.top||(null===(s=t.style)||void 0===s?void 0:s.showRowStripes)||i>h.bottom-t.totalsRowCount?Cf:void 0,bottom:i===h.bottom?Cf:void 0},d=(null==r?void 0:r.border)?{...a[r.border],...l}:l;let u=a.findIndex((e=>ot(e,d)));-1===u&&(u=a.length,a.push(d)),r?r.border=u:c.cells[n]={border:u}}}e.styles=Am(r),e.borders=Am(a)}(e,t),function(e,t){for(let i of e){const n=t.find((e=>Ai(e.sheetName,i.name))).tables;for(let t of n){const n=t.name+"[";for(let o of e)for(let e in o.cells){const s=o.cells[e];if(s&&s.content&&s.content.startsWith("=")){let r;for(;-1!==(r=s.content.indexOf(n));){let a=r+n.length,l=1;for(;l>0&&a<s.content.length;)"["===s.content[a]?l++:"]"===s.content[a]&&l--,a++;let c=s.content.slice(r+n.length,a-1);const h=yf(i.id===o.id?"":i.name+"!",c,t,e);s.content=s.content.slice(0,r)+h+s.content.slice(a)}}}}}}(e.sheets,t.sheets)}function wf(e,t,i,n){for(let o=t.left;o<=t.right;o++)for(let s=t.top;s<=t.bottom;s++){const t=Vt(o,s),r=i[t],a=(null==r?void 0:r.style)?{...n[r.style],...e}:e;let l=n.findIndex((e=>ot(e,a)));-1===l&&(l=n.length,n.push(a)),r?r.style=l:i[t]={style:l}}}function yf(e,t,i,n){const o=t.split(",").map((e=>e.trim())),s=Mi(i.ref),r=[],a=[],l=[];for(const e of o)if(xf(e).startsWith("#")){const t=xf(e);switch(l.push(t),t){case"#All":a.push(s.top,s.bottom);break;case"#Data":const e=i.headerRowCount?s.top+i.headerRowCount:s.top,t=i.totalsRowCount?s.bottom-i.totalsRowCount:s.bottom;a.push(e,t);break;case"#This Row":a.push(Ut(n).row);break;case"#Headers":if(!i.headerRowCount)return X;a.push(s.top);break;case"#Totals":if(!i.totalsRowCount)return X;a.push(s.bottom)}}else{const t=e.split(":").map((e=>e.trim())).map(xf);if(r.length)return X;const n=i.cols.findIndex((e=>e.name===t[0]));if(-1===n)return X;if(r.push(n+s.left),t[1]){const e=i.cols.findIndex((e=>e.name===t[1]));if(-1===e)return X;r.push(e+s.left)}}if(!function(e){if(e.length<2)return!0;if(e.length>2)return!1;if(e.includes("#Data")&&e.includes("#Totals"))return!0;if(e.includes("#Headers")&&e.includes("#Data"))return!0;return!1}(l))return X;if(0===a.length){const e=i.headerRowCount?s.top+i.headerRowCount:s.top,t=i.totalsRowCount?s.bottom-i.totalsRowCount:s.bottom;a.push(e,t)}0===r.length&&r.push(s.left,s.right);return e+Fi({top:Math.min(...a),left:Math.min(...r),bottom:Math.max(...a),right:Math.max(...r)})}function xf(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,e.length-1):e}function Rf(e,t,i){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:i}}function If(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 Tf(e){return new zp(e.map((([e,t])=>`${e}="${If(t)}"`)).join(" "))}function Af(e){const t=(new DOMParser).parseFromString(e.toString(),"text/xml"),i=t.querySelector("parsererror");if(i){const t=i.innerHTML,n=parseInt(t.split(":")[0],10),o=e.toString().trim().split("\n"),s=o.slice(Math.max(n-3,0),Math.min(n+2,o.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${s}`)}return t}function Of(e){if(e)return{style:e[0],color:{rgb:e[1]}}}function Nf(e,t){return _f`
1388
+ />`,Ap.defaultProps={position:{top:0}};const Np={ROW:Xo,COL:Yo,CELL:jo};class Op extends t.Component{constructor(){super(...arguments),this.HEADER_HEIGHT=O,this.HEADER_WIDTH=M,this.keyDownMapping={ENTER:()=>{const e=this.env.model.getters.getActiveCell();!e||e.isEmpty()?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()},TAB:()=>this.env.model.selection.moveAnchorCell("right",1),"SHIFT+TAB":()=>this.env.model.selection.moveAnchorCell("left",1),F2:()=>{const e=this.env.model.getters.getActiveCell();!e||e.isEmpty()?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()})},"CTRL+A":()=>this.env.model.selection.loopSelection(),"CTRL+S":()=>{var e,t;null===(t=(e=this.props).onSaveRequested)||void 0===t||t.call(e)},"CTRL+Z":()=>this.env.model.dispatch("REQUEST_UNDO"),"CTRL+Y":()=>this.env.model.dispatch("REQUEST_REDO"),"CTRL+B":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"CTRL+I":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"CTRL+U":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"ALT+=":()=>{var e;const t=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getSelectedZone(),{anchor:n}=this.env.model.getters.getSelection(),o=this.env.model.getters.getAutomaticSums(t,i,n.cell);if(this.env.model.getters.isSingleCellOrMerge(t,i)||this.env.model.getters.isEmpty(t,i)&&o.length<=1){const i=(null===(e=o[0])||void 0===e?void 0:e.zone)?this.env.model.getters.zoneToXC(t,o[0].zone):"",n=`=SUM(${i})`;this.props.onGridComposerCellFocused(n,{start:5,end:5+i.length})}else this.env.model.dispatch("SUM_SELECTION")},"CTRL+HOME":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:i}=this.env.model.getters.getNextVisibleCellPosition(e,0,0);this.env.model.selection.selectCell(t,i)},"CTRL+END":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,"COL",this.env.model.getters.getNumberCols(e)-1,0),i=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,i)},"SHIFT+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},i=this.env.model.getters.getPosition();this.env.model.selection.selectZone({cell:i,zone:t})},"CTRL+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},i=this.env.model.getters.getPosition();this.env.model.selection.selectZone({cell:i,zone:t})},"CTRL+SHIFT+ ":()=>{this.env.model.selection.selectAll()},"SHIFT+PAGEDOWN":()=>{this.env.model.dispatch("ACTIVATE_NEXT_SHEET")},"SHIFT+PAGEUP":()=>{this.env.model.dispatch("ACTIVATE_PREVIOUS_SHEET")},PAGEDOWN:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PAGEUP:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP")}}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.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())),Cp("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimensionWithHeaders())),t.useEffect((()=>this.focusDefaultElement()),(()=>[this.env.model.getters.getActiveSheetId()])),this.onMouseWheel=Ep(((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"\n top: 26px;\n left: 48px;\n height: calc(100% - 41px);\n width: calc(100% - 63px);\n "}onClosePopover(){this.closeOpenedPopover(),this.focusDefaultElement()}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}}isAutoFillActive(){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:M,gridOffsetY:O})}moveCanvas(e,t){const{scrollX:i,scrollY:n}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:Math.max(i+e,0),offsetY:Math.max(n+t,0)})}getClientPositionKey(e){var t,i,n;return`${e.id}-${null===(t=e.position)||void 0===t?void 0:t.sheetId}-${null===(i=e.position)||void 0===i?void 0:i.col}-${null===(n=e.position)||void 0===n?void 0:n.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}onCellClicked(e,t,{addZone:i,expandZone:n}){i&&this.env.model.dispatch("PREPARE_SELECTION_INPUT_EXPANSION"),this.closeOpenedPopover(),"editing"===this.env.model.getters.getEditionMode()&&this.env.model.dispatch("STOP_EDITION"),n?this.env.model.selection.setAnchorCorner(e,t):i?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t);let o=e,s=t;Fr(this.env,((e,t)=>{(e!==o&&-1!=e||t!==s&&-1!=t)&&(o=-1===e?o:e,s=-1===t?s:t,this.env.model.selection.setAnchorCorner(o,s))}),(()=>{this.env.model.dispatch("STOP_SELECTION_INPUT"),this.env.model.getters.isPaintingFormat()&&this.env.model.dispatch("PASTE",{target:this.env.model.getters.getSelectedZones()})}))}onCellDoubleClicked(e,t){const i=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition(i,e,t));const n=this.env.model.getters.getCell(i,e,t);!n||n.isEmpty()?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()}closeOpenedPopover(){this.env.model.dispatch("CLOSE_CELL_POPOVER")}processArrows(e){e.preventDefault(),e.stopPropagation(),this.closeOpenedPopover();const t={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"}[e.key];e.shiftKey?this.env.model.selection.resizeAnchorZone(t,zn(e)?"end":1):this.env.model.selection.moveAnchorCell(t,zn(e)?"end":1),this.env.model.getters.isPaintingFormat()&&this.env.model.dispatch("PASTE",{target:this.env.model.getters.getSelectedZones()})}onKeydown(e){if(e.key.startsWith("Arrow"))return void this.processArrows(e);let t="";zn(e)&&(t+="CTRL+"),e.altKey&&(t+="ALT+"),e.shiftKey&&(t+="SHIFT+"),t+=e.key.toUpperCase();let i=this.keyDownMapping[t];return i?(e.preventDefault(),e.stopPropagation(),void i()):void 0}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:i,top:n}=t;let o="CELL";this.env.model.dispatch("STOP_EDITION"),this.env.model.getters.getActiveCols().has(i)?o="COL":this.env.model.getters.getActiveRows().has(n)&&(o="ROW");const{x:s,y:r,width:a}=this.env.model.getters.getVisibleRect(t);this.toggleContextMenu(o,this.canvasPosition.x+s+a,this.canvasPosition.y+r)}onCellRightClicked(e,t,{x:i,y:n}){const o=this.env.model.getters.getSelectedZones();let s="CELL";Wi(e,t,o[o.length-1])?this.env.model.getters.getActiveCols().has(e)?s="COL":this.env.model.getters.getActiveRows().has(t)&&(s="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(s,i,n)}toggleContextMenu(e,t,i){this.closeOpenedPopover(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:i},this.menuState.menuItems=Np[e].getAll()}copy(e,t){if(!this.gridEl.contains(document.activeElement))return;if("inactive"!==this.env.model.getters.getEditionMode())return;e?ho(this.env):this.env.model.dispatch("COPY");const i=this.env.model.getters.getClipboardContent();t.clipboardData.setData("text/plain",i),t.preventDefault()}paste(e){if(!this.gridEl.contains(document.activeElement))return;const t=e.clipboardData;if(t.types.indexOf("text/plain")>-1){const e=t.getData("text/plain"),i=this.env.model.getters.getSelectedZones();this.env.model.getters.getClipboardContent()===e?fo(this.env,i):vo(this.env,i,e)}}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}}Op.template="o-spreadsheet-Grid",Op.components={GridComposer:rp,GridOverlay:pp,GridPopover:mp,HeadersOverlay:Sp,Menu:Gn,Autofill:Dr,ClientTag:$r,Highlight:xp,Popover:Wn,VerticalScrollBar:Ap,HorizontalScrollBar:Tp,FilterIconsOverlay:hp};class Mp{constructor(e,t,i){this.id=e,this.style=i.style,this.format=i.format,this.lazyEvaluated=t.map((e=>({...e,format:i.format||e.format})))}isFormula(){return!1}isLink(){return!1}isEmpty(){return!1}get evaluated(){return this.lazyEvaluated()}get formattedValue(){return Qt(this.evaluated.value,this.evaluated.format)}get composerContent(){return this.content}get defaultAlign(){switch(this.evaluated.type){case hn.number:case hn.empty:return"right";case hn.boolean:case hn.error:return"center";case hn.text:return"left"}}get isAutoSummable(){var e;switch(this.evaluated.type){case hn.empty:case hn.text:return!0;case hn.number:return!(null===(e=this.evaluated.format)||void 0===e?void 0:e.match(Y));case hn.error:case hn.boolean:return!1}}}class _p extends Mp{constructor(e,t={}){super(e,tt({value:"",type:hn.empty}),t),this.content=""}isEmpty(){return!0}}class Fp extends Mp{constructor(e,t,i={}){super(e,tt({value:t,type:hn.number}),i),this.content=Qt(this.evaluated.value)}get composerContent(){var e;return(null===(e=this.format)||void 0===e?void 0:e.includes("%"))?100*this.evaluated.value+"%":super.composerContent}}class Dp extends Mp{constructor(e,t,i={}){super(e,tt({value:t,type:hn.boolean}),i),this.content=this.evaluated.value?"TRUE":"FALSE"}}class kp extends Mp{constructor(e,t,i={}){super(e,tt({value:t,type:hn.text}),i),this.content=this.evaluated.value}}class $p extends Fp{constructor(e,t,i){super(e,t,i),this.format=i.format}get composerContent(){return Qt(this.evaluated.value,this.format)}}class Lp extends Mp{constructor(e,t,i={}){const n=Ge(t);n.label=o(n.label),super(e,tt({value:n.label,type:hn.text}),i),this.link=n,this.content=t}isLink(){return!0}get composerContent(){return this.link.label}}class Pp extends Lp{constructor(e,t,i={}){super(e,t,i),this.link.url=this.withHttp(this.link.url),this.link.isExternal=!0,this.content=We(this.link.label,this.link.url),this.urlRepresentation=this.link.url,this.isUrlEditable=!0}action(e){window.open(this.link.url,"_blank")}withHttp(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}}class Up extends Lp{constructor(e,t,i={},n){super(e,t,i),this.sheetName=n,this.sheetId=Ye(this.link.url),this.isUrlEditable=!1}action(e){e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.model.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}get urlRepresentation(){return this.sheetName(this.sheetId)||s("Invalid sheet")}}class Vp extends Mp{constructor(e,t,i,n,o){super(t,tt({value:"Loading...",type:hn.text}),o),this.buildFormulaString=e,this.compiledFormula=i,this.dependencies=n}get content(){return this.buildFormulaString(this)}isFormula(){return!0}assignEvaluation(e){this.lazyEvaluated=e.map((e=>{if(e instanceof c)return{value:e.errorType,type:hn.error,error:e};const{value:t,format:i}=e;switch(typeof t){case"number":return{value:t||0,format:i,type:hn.number};case"boolean":return{value:t,format:i,type:hn.boolean};case"string":return{value:t,format:i,type:hn.text};case"object":return{value:0,format:i,type:hn.number};default:return{value:"",type:hn.empty}}}))}}class zp extends Mp{constructor(e,t,i,n){super(e,tt({value:i.errorType,type:hn.error,error:i}),n),this.content=t}}function Bp(e){return""===e?"":Ci(e)?wi(e):Ue(e)?"TRUE"===e.toUpperCase():Ve(e)?ve(e).value:e}io.add("Formula",{sequence:10,match:e=>e.startsWith("="),createCell:(e,t,i,n,o)=>{const s=Pg(t),r=s.dependencies.map((e=>o.getRangeFromSheetXC(n,e)));return new Vp((e=>o.buildFormulaContent(n,e)),e,s,r,i)}}).add("Empty",{sequence:20,match:e=>""===e,createCell:(e,t,i)=>new _p(e,i)}).add("NumberWithDateTimeFormat",{sequence:25,match:(e,t)=>!!t&&Ci(e)&&function(e){try{return oi(1,e),!0}catch(e){return!1}}(t),createCell:(e,t,i)=>{const n=i.format;return new $p(e,wi(t),{...i,format:n})}}).add("Number",{sequence:30,match:e=>Ci(e),createCell:(e,t,i)=>(i.format||(i.format=function(e){const t=e.includes(".")?"0.00":"0",i=e.match(/[\$€]/);if(i){const n=e.match(/[\d]/),o="[$"+i.values().next().value+"]";return n.index<i.index?"#,##"+t+o:o+"#,##"+t}if(e.includes("%"))return t+"%";return}(t)),new Fp(e,wi(t),i))}).add("Boolean",{sequence:40,match:e=>Ue(e),createCell:(e,t,i)=>new Dp(e,"TRUE"===t.toUpperCase(),i)}).add("DateTime",{sequence:50,match:e=>Ve(e),createCell:(e,t,i)=>{const n=ve(t),o=i.format||n.format;return new $p(e,n.value,{...i,format:o})}}).add("MarkdownSheetLink",{sequence:60,match:e=>Ze(e),createCell:(e,t,i,n,o)=>new Up(e,t,i,(e=>o.tryGetSheetName(e)))}).add("MarkdownLink",{sequence:70,match:e=>He(e),createCell:(e,t,i)=>new Pp(e,t,i)}).add("WebLink",{sequence:80,match:e=>{return t=e,Be.test(t);var t},createCell:(e,t,i)=>new Pp(e,We(t,t),i)});class Hp{constructor(e){this.xmlString=e}toString(){return this.xmlString}}const Wp=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart"],Gp="000000",qp={arrows:"3Arrows",smiley:"3Symbols",dots:"3TrafficLights1"},Zp={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"},jp="http://schemas.openxmlformats.org/drawingml/2006/main",Yp="http://schemas.openxmlformats.org/drawingml/2006/chart",Xp={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"},Kp={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"},Qp="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Jp=.75,em=.1317,tm=8.43,im=12.75,nm=30,om=100,sm=164,rm={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}]},am=["ACOT","ACOTH","AGGREGATE","ARABIC","BASE","BETA.DIST","BETA.INV","BINOM.DIST","BINOM.DIST.RANGE","BINOM.INV","BITAND","BITLSHIFT","BITOR","BITRSHIFT","BITXOR","BYCOL","BYROW","CEILING.MATH","CEILING.PRECISE","CHISQ.DIST","CHISQ.DIST.RT","CHISQ.INV","CHISQ.INV.RT","CHISQ.TEST","CHOOSECOLS","CHOOSEROWS","COMBINA","CONCAT","CONFIDENCE.NORM","CONFIDENCE.T","COT","COTH","COVARIANCE.P","COVARIANCE.S","CSC","CSCH","DAYS","DECIMAL","DROP","ERF.PRECISE","ERFC.PRECISE","EXPAND","EXPON.DIST","F.DIST","F.DIST.RT","F.INV","F.INV.RT","F.TEST","FIELDVALUE","FILTERXML","FLOOR.MATH","FLOOR.PRECISE","FORECAST.ETS","FORECAST.ETS.CONFINT","FORECAST.ETS.SEASONALITY","FORECAST.ETS.STAT","FORECAST.LINEAR","FORMULATEXT","GAMMA","GAMMA.DIST","GAMMA.INV","GAMMALN.PRECISE","GAUSS","HSTACK","HYPGEOM.DIST","IFNA","IFS","IMCOSH","IMCOT","IMCSC","IMCSCH","IMSEC","IMSECH","IMSINH","IMTAN","ISFORMULA","ISOMITTED","ISOWEEKNUM","LAMBDA","LET","LOGNORM.DIST","LOGNORM.INV","MAKEARRAY","MAP","MAXIFS","MINIFS","MODE.MULT","MODE.SNGL","MUNIT","NEGBINOM.DIST","NORM.DIST","NORM.INV","NORM.S.DIST","NORM.S.INV","NUMBERVALUE","PDURATION","PERCENTILE.EXC","PERCENTILE.INC","PERCENTRANK.EXC","PERCENTRANK.INC","PERMUTATIONA","PHI","POISSON.DIST","PQSOURCE","PYTHON_STR","PYTHON_TYPE","PYTHON_TYPENAME","QUARTILE.EXC","QUARTILE.INC","QUERYSTRING","RANDARRAY","RANK.AVG","RANK.EQ","REDUCE","RRI","SCAN","SEC","SECH","SEQUENCE","SHEET","SHEETS","SKEW.P","SORTBY","STDEV.P","STDEV.S","SWITCH","T.DIST","T.DIST.2T","T.DIST.RT","T.INV","T.INV.2T","T.TEST","TAKE","TEXTAFTER","TEXTBEFORE","TEXTJOIN","TEXTSPLIT","TOCOL","TOROW","UNICHAR","UNICODE","UNIQUE","VAR.P","VAR.S","VSTACK","WEBSERVICE","WEIBULL.DIST","WRAPCOLS","WRAPROWS","XLOOKUP","XOR","Z.TEST"],lm="[Content_Types].xml";var cm;!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"}(cm||(cm={}));class hm{constructor(){this._parsingWarnings=new Set,this._conversionWarnings=new Set}addParsingWarning(e){this._parsingWarnings.add(e)}addConversionWarning(e){this._conversionWarnings.add(e)}get warnings(){return[...this._parsingWarnings,...this._conversionWarnings]}generateNotSupportedWarning(e,t,i){let n=`${e} ${t?'"'+t+'" is':"are"} not yet supported. `;i&&(n+=`Only ${i.join(", ")} are currently supported.`),this._conversionWarnings.has(n)||this._conversionWarnings.add(n)}}const dm=["thin"],um=["general","left","center","right"],gm=["Arial"],pm=["solid"],mm=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWith","containsBlanks","notContainsBlanks"],fm={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},vm={dashDot:"thin",dashDotDot:"thin",dashed:"thin",dotted:"thin",double:"thin",hair:"thin",medium:"thin",mediumDashDot:"thin",mediumDashDotDot:"thin",mediumDashed:"thin",none:void 0,slantDashDot:"thin",thick:"thin",thin:"thin"},bm={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"};const Sm={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},Cm={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},Em={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"},wm={none:"none",b:"bottom",t:"top",l:"left",r:"right",tr:"right"},ym={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},xm={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"},Rm={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},Im={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},Tm={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"};function Am(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=Gp;else{if(!e.indexed)return;t=Tm[e.indexed]}var i;return t=6===(i=t).length?"#"+i+"FF":"#"+i.slice(2)+i.slice(0,2),e.tint&&(t=function(e,t){const i=Et(e),n=yt(i);t<0&&(n.l=n.l*(1+t));t>0&&(n.l=n.l*(1-t)+(100-100*(1-t)));return Ct(wt(n))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function Nm(e,t){const i=e.split("/"),n=t.split("/");let o="",s=0;for(let e=0;e<i.length-1;e++)i[e]===n[e]?s++:o+="../";return o+=n.slice(s).join("/"),o}function Om(e,t=0){const i={};for(let n=0;n<e.length;n++)e[n]&&(i[n+t]=e[n]);return i}function Mm(e){const t=[];for(let i of Object.keys(e).map(Number))t[i]=e[i];return t}function _m(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,((e,t)=>String.fromCharCode(parseInt(t,16))))}const Fm=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function Dm(e,t,i){var n,o,s;if(0===e)return;let r=Rm[e]||(null===(n=t.find((t=>t.id===e)))||void 0===n?void 0:n.format);if(r)try{let e=r.replace(/(.*?);.*/,"$1");e=e.replace(/\[(.*)-[A-Z0-9]{3}\]/g,"[$1]"),e=e.replace(/\[\$\]/g,"");const t=(null===(o=e.match(/"/g))||void 0===o?void 0:o.length)||0;if(t/2+((null===(s=e.match(/\[/g))||void 0===s?void 0:s.length)||0)>1)throw new Error("Multiple escaped blocks in format");if(e=e.replace(/"(.*)"/g,"[$$$1]"),e=e.replace(/_.{1}/g,""),e=e.replace(/\*.{1}/g,""),e=e.replace(/\\ /g," "),e=e.replace(/\\./g,(e=>e[1])),function(e){return null!==e.match(Fm)}(e)&&(e=function(e){return e=e.toLowerCase(),e=e.replace(/mmmmm|mmmm|mmm/g,"mm"),e=e.replace(/dddd|ddd/g,"dd"),e=e.replace(/am\/pm|a\/m/g,"a"),e=e.replace(/\byy\b/g,"yyyy"),e=e.replace(/hhhh/g,"hh"),e=e.replace(/\bh\b/g,"hh"),e}(e)),function(e){try{return Qt(0,e),!0}catch(e){return!1}}(e))return e}catch(e){}i.generateNotSupportedWarning(cm.NumFmtIdNotSupported,r||`nmFmtId ${e}`)}function km(e,t){const i=e.borders.map((e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(cm.DiagonalBorderNotSupported)}(e,t);const i={top:$m(e.top,t),bottom:$m(e.bottom,t),left:$m(e.left,t),right:$m(e.right,t)};return Object.keys(i).forEach((e=>void 0===i[e]&&delete i[e])),i}));return Om(i,1)}function $m(e,t){if(!e)return;!function(e,t){dm.includes(e.style)||t.generateNotSupportedWarning(cm.BorderStyleNotSupported,e.style,dm)}(e,t);const i=vm[e.style];return i?[i,Am(e.color)]:void 0}function Lm(e,t){return Om(e.styles.map((i=>Pm({fontStyle:e.fonts[i.fontId],fillStyle:e.fills[i.fillId],alignment:i.alignment},t))),1)}function Pm(e,t){var i,n,o,s,r,a,l,c,h,d,u,g;return function(e,t,i){e&&e.name&&!gm.includes(e.name)&&i.generateNotSupportedWarning(cm.FontNotSupported,e.name,gm);t&&t.patternType&&!pm.includes(t.patternType)&&i.generateNotSupportedWarning(cm.FillStyleNotSupported,t.patternType,pm)}(null==e?void 0:e.fontStyle,null==e?void 0:e.fillStyle,t),function(e,t){e&&!um.includes(e)&&t.generateNotSupportedWarning(cm.HorizontalAlignmentNotSupported,e,um)}(null===(i=null==e?void 0:e.alignment)||void 0===i?void 0:i.horizontal,t),function(e,t){e&&t.generateNotSupportedWarning(cm.VerticalAlignmentNotSupported)}(null===(n=null==e?void 0:e.alignment)||void 0===n?void 0:n.vertical,t),{bold:null===(o=e.fontStyle)||void 0===o?void 0:o.bold,italic:null===(s=e.fontStyle)||void 0===s?void 0:s.italic,strikethrough:null===(r=e.fontStyle)||void 0===r?void 0:r.strike,underline:null===(a=e.fontStyle)||void 0===a?void 0:a.underline,align:(null===(l=e.alignment)||void 0===l?void 0:l.horizontal)?bm[e.alignment.horizontal]:void 0,fillColor:"solid"===(null===(c=e.fillStyle)||void 0===c?void 0:c.patternType)?Am(null===(h=e.fillStyle)||void 0===h?void 0:h.fgColor):Am(null===(d=e.fillStyle)||void 0===d?void 0:d.bgColor),textColor:Am(null===(u=e.fontStyle)||void 0===u?void 0:u.color),fontSize:(null===(g=e.fontStyle)||void 0===g?void 0:g.size)?Vm(e.fontStyle.size):void 0}}function Um(e,t){const i=[];for(let n of e.styles){const o=Dm(n.numFmtId,e.numFmts,t);o&&(i[n.numFmtId]=o)}return Om(i,1)}function Vm(e){return Object.keys(re).map(Number).reduce(((t,i)=>Math.abs(i-e)<Math.abs(t-e)?i:t))}function zm(e,t,i){const n=[];let o=1;for(let r of e){if(0===r.cfRules.length)continue;Gm(r,t,i);const e=r.cfRules[0];let a;const l=[];if(void 0!==e.dxfId||"colorScale"===e.type||"iconSet"===e.type){switch(e.type){case"aboveAverage":case"containsErrors":case"notContainsErrors":case"dataBar":case"duplicateValues":case"expression":case"top10":case"uniqueValues":case"timePeriod":continue;case"colorScale":const t=Bm(o++,r);t&&n.push(t);continue;case"iconSet":const c=Hm(o++,r,i);c&&n.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;a=Sm[e.type],l.push(e.text);break;case"containsBlanks":case"notContainsBlanks":a=Sm[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;a=(s=e.operator).slice(0,1).toUpperCase()+s.slice(1),l.push(e.formula[0]),2===e.formula.length&&l.push(e.formula[1])}a&&void 0!==e.dxfId&&n.push({id:(o++).toString(),ranges:r.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:a,values:l,style:Pm({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},i)}})}}var s;return n}function Bm(e,t){const i=t.cfRules[0].colorScale;if(!i||i.cfvos.length!==i.colors.length||i.cfvos.length<2||i.cfvos.length>3)return;const n=[];for(let e=0;e<i.cfvos.length;e++)n.push({color:(o=Am(i.colors[e])||"#FFFFFF",9===o.length&&(o=o.slice(0,7)),parseInt(o.replace("#",""),16)),type:Cm[i.cfvos[e].type],value:i.cfvos[e].value});var o;const s=n[0],r=2===n.length?n[1]:n[2],a=3===n.length?n[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"ColorScaleRule",minimum:s,midpoint:a,maximum:r}}}function Hm(e,t,i){const n=t.cfRules[0].iconSet;if(!n)return;let o=n.cfvos,s=n.cfIcons;if(o.length<3||s&&s.length<3)return;o.length>3&&(o=[o[0],o[Math.floor(o.length/2)],o[o.length-1]]),s&&s.length>3&&(s=[s[0],s[Math.floor(s.length/2)],s[s.length-1]]);const r=[];for(let e=1;e<=2;e++){const t=Cm[o[e].type];if("value"===t)return;r.push({value:o[e].value||"",operator:o[e].gte?"ge":"gt",type:t})}let a={lower:s?Wm(s[0].iconSet,s[0].iconId):Wm(n.iconSet,0),middle:s?Wm(s[1].iconSet,s[1].iconId):Wm(n.iconSet,1),upper:s?Wm(s[2].iconSet,s[2].iconId):Wm(n.iconSet,2)};n.reverse&&(a={upper:a.lower,middle:a.middle,lower:a.upper});for(let e of Object.keys(a))if(!a[e])switch(i.generateNotSupportedWarning(cm.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=Cr.dots.good;break;case"middle":a[e]=Cr.dots.neutral;break;case"lower":a[e]=Cr.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 Wm(e,t){const i=Em[e];return i?0===t?Cr[i].bad:1===t?Cr[i].neutral:Cr[i].good:""}function Gm(e,t,i){if(e.cfRules.length>1&&i.generateNotSupportedWarning(cm.MultipleRulesCfNotSupported),mm.includes(e.cfRules[0].type)||i.generateNotSupportedWarning(cm.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const n=t[e.cfRules[0].dxfId];n.border&&i.generateNotSupportedWarning(cm.CfFormatBorderNotSupported),n.alignment&&i.generateNotSupportedWarning(cm.CfFormatAlignmentNotSupported),n.numFmt&&i.generateNotSupportedWarning(cm.CfFormatNumFmtNotSupported)}}function qm(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function Zm(e){return Math.round(Jp*e*window.devicePixelRatio*100)/100}function jm(e){return Math.round(em*e*100)/100}function Ym(e,t){let i={};e.style&&(i=t.styles[e.style]);const n=function(e,t){if(e.format)return t.formats[e.format];if(e.isFormula){const t=Qu(e.content||""),i=ju.content;if(!t.filter((e=>"FUNCTION"===e.type)).every((e=>i[e.value.toUpperCase()].isExported)))return e.computedFormat}return}(e,t),o={font:{size:(null==i?void 0:i.fontSize)||G,color:{rgb:(null==i?void 0:i.textColor)?i.textColor:"000000"},family:2,name:"Arial"},fill:(null==i?void 0:i.fillColor)?{fgColor:{rgb:i.fillColor}}:{reservedAttribute:"none"},numFmt:n?{format:n,id:0}:void 0,border:e.border||0,alignment:{vertical:"center",horizontal:i.align}};return o.font.strike=!!(null==i?void 0:i.strikethrough)||void 0,o.font.underline=!!(null==i?void 0:i.underline)||void 0,o.font.bold=!!(null==i?void 0:i.bold)||void 0,o.font.italic=!!(null==i?void 0:i.italic)||void 0,o}function Xm(e,t){const i=function(e,t){if(!e)return 0;let i=Im[e.format];i||(i=Qm(e,t)+sm);return i}(t.numFmt,e.numFmts),n={fontId:Qm(t.font,e.fonts),fillId:Qm(t.fill,e.fills),borderId:t.border,numFmtId:i,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal}};return Qm(n,e.styles)}function Km(e,t,i){let n,o=e.find((e=>e.path===t));return o?(n=`rId${(o.rels.length+1).toString()}`,o.rels.push({...i,id:n})):(n="rId1",e.push({path:t,rels:[{...i,id:n}]})),n}function Qm(e,t){let i=t.length;const n="object"==typeof e?ot:(e,t)=>e===t;for(let o=0;o<i;o++)if(n(e,t[o]))return o;return t[t.length]=e,t.length-1}const Jm=[];function ef(e){const t=Jm.findIndex((t=>t===e));return-1===t?(Jm.push(e),Jm.length):t+1}function tf(e){return Math.round(914400*e/96)}function nf(e,t,i){let n,o,s=e;if(({xc:s,sheetName:n}=$t(e)),n){const e=i.sheets.findIndex((e=>Ai(e.name,n)));if(e<0)throw new Error("Unable to find a sheet with the name "+n);o=e}else o=Number(t);const r=_i(s);return void 0===r.right&&(r.right=i.sheets[o].colNumber),void 0===r.bottom&&(r.bottom=i.sheets[o].rowNumber),(r.right-r.left+1)*(r.bottom-r.top+1)}function of(e){return Math.round(96*e/914400)}function sf(e,t){var i;let n=0;for(let o=0;o<e;o++){const e=t.cols.find((e=>o>=e.min&&o<=e.max));(null==e?void 0:e.width)?n+=e.width:(null===(i=t.sheetFormat)||void 0===i?void 0:i.defaultColWidth)?n+=t.sheetFormat.defaultColWidth:n+=tm}return n/em}function rf(e,t){var i;let n=0;for(let o=0;o<e;o++){const e=t.rows[o];(null==e?void 0:e.height)?n+=e.height:(null===(i=t.sheetFormat)||void 0===i?void 0:i.defaultRowHeight)?n+=t.sheetFormat.defaultRowHeight:n+=im}return n/Jp}function af(e){let t=1;return e.figures.map((i=>function(e,t,i){const n=sf(e.anchors[0].col,i)+of(e.anchors[0].colOffset),o=sf(e.anchors[1].col,i)+of(e.anchors[1].colOffset),s=rf(e.anchors[0].row,i)+of(e.anchors[0].rowOffset),r=rf(e.anchors[1].row,i)+of(e.anchors[1].rowOffset),a=o-n,l=r-s,c=lf(e.data);return c?{id:t,x:n,y:s,width:a,height:l,tag:"chart",data:lf(e.data)}:void 0}(i,(t++).toString(),e))).filter(Xe)}function lf(e){var t;if(0===e.dataSets.length)return;const i=null===(t=e.dataSets[0].label)||void 0===t?void 0:t.replace(/\$/g,"");let n=e.dataSets.map((e=>e.range.replace(/\$/g,"")));return"pie"===e.type&&n.reverse(),{dataSets:n,dataSetsHaveTitle:!1,labelRange:i,title:e.title||"",type:e.type,background:Am({rgb:e.backgroundColor})||"#FFFFFF",verticalAxisPosition:e.verticalAxisPosition,legendPosition:e.legendPosition,stacked:e.stacked||!1,cumulative:e.cumulative||!1,labelsAsText:!1}}const cf=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),hf=new RegExp(/SUBTOTAL\(([0-9]*),/g),df=new RegExp(xt.source,"ig");function uf(e,t){const i=function(e){const t={};for(let i of e.rows)for(let e of i.cells)e.formula&&void 0!==e.formula.sharedIndex&&e.formula.content&&(t[e.formula.sharedIndex]={refCellXc:e.xc,formula:e.formula.content});return t}(e);for(let n of e.rows.map((e=>e.cells)).flat())(null==n?void 0:n.formula)&&(n.formula.content=void 0===n.formula.sharedIndex||n.formula.content?"="+n.formula.content:"="+pf(n.xc,i[n.formula.sharedIndex]),n.formula.content=gf(n.formula.content,t))}function gf(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(hf,((e,t)=>{const i=xm[t];return i?i+"(":e}))).replace(cf,((e,i,n,o)=>{var s;i=Number(i)-1,o=o.replace(/\$/g,"");const r=t.externalBooks[i].sheetNames.findIndex((e=>Ai(e,n)));if(-1===r)return e;const a=null===(s=t.externalBooks[i].datasets.find((e=>e.sheetId===r)))||void 0===s?void 0:s.data;if(!a)return e;const l=a&&a[o];return(Number(l)?l:`"${l}"`)||e}))}function pf(e,t){const i=Ut(t.refCellXc);let n,o=t.formula.slice();do{if(n=df.exec(o),n){const t=Ut(n[0].replace("$","")),s=Ut(e),r={colFixed:n[0].startsWith("$"),rowFixed:n[0].includes("$",1)},a={col:s.col-i.col,row:s.row-i.row},l={col:r.colFixed?t.col:t.col+a.col,row:r.rowFixed?t.row:t.row+a.row};o=o.slice(0,n.index)+Vt(l.col,l.row,r)+o.slice(n.index+n[0].length)}}while(n);return o}function mf(e,t){return e.sheets.map((i=>{uf(i,e);const n=function(e){const t=[0,0];for(let i of e.rows)t[0]=Math.max(t[0],lt(i.cells.map((e=>Ut(e.xc).col)))),t[1]=Math.max(t[1],i.index);return t[0]=Math.max(t[0],nm),t[1]=Math.max(t[1],om),t}(i),o=i.sheetViews[0];return{id:i.sheetName,areGridLinesVisible:!o||o.showGridLines,name:i.sheetName,colNumber:n[0],rowNumber:n[1],cells:bf(i,e,n,t),merges:i.merges,cols:ff(i,n[0]),rows:vf(i,n[1]),conditionalFormats:zm(i.cfs,e.dxfs,t),figures:af(i),isVisible:i.isVisible,panes:o?{xSplit:o.pane.xSplit,ySplit:o.pane.ySplit}:{xSplit:0,ySplit:0},filterTables:[]}}))}function ff(e,t){var i;const n={};for(let s=1;s<t+1;s++){const t=e.cols.find((e=>e.min<=s&&s<=e.max));let r;r=t&&t.width?t.width:(null===(i=e.sheetFormat)||void 0===i?void 0:i.defaultColWidth)?e.sheetFormat.defaultColWidth:tm,n[s-1]={size:(o=r,o?Math.round(o/em*100)/100:o),isHidden:null==t?void 0:t.hidden}}var o;return n}function vf(e,t){var i;const n={};for(let s=1;s<t+1;s++){const t=e.rows.find((e=>e.index===s));let r;r=t&&t.height?t.height:(null===(i=e.sheetFormat)||void 0===i?void 0:i.defaultRowHeight)?e.sheetFormat.defaultRowHeight:im,n[s-1]={size:(o=r,o?Math.round(o/Jp*100)/100:o),isHidden:null==t?void 0:t.hidden}}var o;return n}function bf(e,t,i,n){const o={},s=t.sharedStrings.map((e=>e.replace(/\n/g,"")));const r=e.hyperlinks.reduce(((e,t)=>(e[t.xc]=t,e)),{});for(let i of e.rows)for(let e of i.cells)o[e.xc]={content:Sf(e,r,s,n),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 n of e.rows.filter((e=>e.styleIndex)))for(let e=1;e<=i[0];e++){const i=Vt(e-1,n.index-1);let s=o[i];s||(s={},o[i]=s),s.style=s.style?s.style:n.styleIndex+1,s.border=s.border?s.border:t.styles[n.styleIndex].borderId+1,s.format=s.format?s.format:t.styles[n.styleIndex].numFmtId+1}for(let n of e.cols.filter((e=>e.styleIndex)))for(let e=n.min;e<=Math.min(n.max,i[0]);e++)for(let s=1;s<=i[1];s++){const i=Vt(e-1,s-1);let r=o[i];r||(r={},o[i]=r),r.style=r.style?r.style:n.styleIndex+1,r.border=r.border?r.border:t.styles[n.styleIndex].borderId+1,r.format=r.format?r.format:t.styles[n.styleIndex].numFmtId+1}return o}function Sf(e,t,i,n){let o;switch(e.type){case"sharedString":o=i[parseInt(e.value,10)];break;case"boolean":o=Number(e.value)?"TRUE":"FALSE";break;case"date":case"error":case"inlineStr":case"number":case"str":o=e.value}return o&&t[e.xc]&&(o=function(e,t,i){const n=e.display||t;e.relTarget||e.location||i.generateNotSupportedWarning(cm.BadlyFormattedHyperlink);const o=e.relTarget?e.relTarget:je($t(e.location).sheetName);return We(n,o)}(t[e.xc],o,n)),e.formula&&(o=e.formula.content),o}const Cf={fillColor:"#000000",textColor:"#ffffff",bold:!0},Ef={bold:!0},wf=["thin","#000000FF"];function yf(e,t){for(const i of t.sheets)for(const t of i.tables){const n=e.sheets.find((e=>e.name===i.sheetName));n&&t.autoFilter&&(n.filterTables||(n.filterTables=[]),n.filterTables.push({range:t.ref}))}!function(e,t){var i,n,o,s;const r=Mm(e.styles),a=Mm(e.borders);for(let l of t.sheets)for(let t of l.tables){const c=e.sheets.find((e=>e.name===l.sheetName));if(!c)continue;const h=Fi(t.ref);for(let e=0;e<t.headerRowCount;e++)xf(Cf,{...h,bottom:h.top+e},c.cells,r);for(let e=0;e<t.totalsRowCount;e++)xf(Ef,{...h,top:h.bottom-e},c.cells,r);(null===(i=t.style)||void 0===i?void 0:i.showFirstColumn)&&xf(Ef,{...h,right:h.left},c.cells,r),(null===(n=t.style)||void 0===n?void 0:n.showLastColumn)&&xf(Ef,{...h,left:h.right},c.cells,r);for(let e=h.left;e<=h.right;e++)for(let i=h.top;i<=h.bottom;i++){const n=Vt(e,i),r=c.cells[n],l={left:e===h.left||(null===(o=t.style)||void 0===o?void 0:o.showColumnStripes)?wf:void 0,right:e===h.right?wf:void 0,top:i===h.top||(null===(s=t.style)||void 0===s?void 0:s.showRowStripes)||i>h.bottom-t.totalsRowCount?wf:void 0,bottom:i===h.bottom?wf:void 0},d=(null==r?void 0:r.border)?{...a[r.border],...l}:l;let u=a.findIndex((e=>ot(e,d)));-1===u&&(u=a.length,a.push(d)),r?r.border=u:c.cells[n]={border:u}}}e.styles=Om(r),e.borders=Om(a)}(e,t),function(e,t){for(let i of e){const n=t.find((e=>Ai(e.sheetName,i.name))).tables;for(let t of n){const n=t.name+"[";for(let o of e)for(let e in o.cells){const s=o.cells[e];if(s&&s.content&&s.content.startsWith("=")){let r;for(;-1!==(r=s.content.indexOf(n));){let a=r+n.length,l=1;for(;l>0&&a<s.content.length;)"["===s.content[a]?l++:"]"===s.content[a]&&l--,a++;let c=s.content.slice(r+n.length,a-1);const h=Rf(i.id===o.id?"":i.name+"!",c,t,e);s.content=s.content.slice(0,r)+h+s.content.slice(a)}}}}}}(e.sheets,t.sheets)}function xf(e,t,i,n){for(let o=t.left;o<=t.right;o++)for(let s=t.top;s<=t.bottom;s++){const t=Vt(o,s),r=i[t],a=(null==r?void 0:r.style)?{...n[r.style],...e}:e;let l=n.findIndex((e=>ot(e,a)));-1===l&&(l=n.length,n.push(a)),r?r.style=l:i[t]={style:l}}}function Rf(e,t,i,n){const o=t.split(",").map((e=>e.trim())),s=Fi(i.ref),r=[],a=[],l=[];for(const e of o)if(If(e).startsWith("#")){const t=If(e);switch(l.push(t),t){case"#All":a.push(s.top,s.bottom);break;case"#Data":const e=i.headerRowCount?s.top+i.headerRowCount:s.top,t=i.totalsRowCount?s.bottom-i.totalsRowCount:s.bottom;a.push(e,t);break;case"#This Row":a.push(Ut(n).row);break;case"#Headers":if(!i.headerRowCount)return X;a.push(s.top);break;case"#Totals":if(!i.totalsRowCount)return X;a.push(s.bottom)}}else{const t=e.split(":").map((e=>e.trim())).map(If);if(r.length)return X;const n=i.cols.findIndex((e=>e.name===t[0]));if(-1===n)return X;if(r.push(n+s.left),t[1]){const e=i.cols.findIndex((e=>e.name===t[1]));if(-1===e)return X;r.push(e+s.left)}}if(!function(e){if(e.length<2)return!0;if(e.length>2)return!1;if(e.includes("#Data")&&e.includes("#Totals"))return!0;if(e.includes("#Headers")&&e.includes("#Data"))return!0;return!1}(l))return X;if(0===a.length){const e=i.headerRowCount?s.top+i.headerRowCount:s.top,t=i.totalsRowCount?s.bottom-i.totalsRowCount:s.bottom;a.push(e,t)}0===r.length&&r.push(s.left,s.right);return e+ki({top:Math.min(...a),left:Math.min(...r),bottom:Math.max(...a),right:Math.max(...r)})}function If(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,e.length-1):e}function Tf(e,t,i){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:i}}function Af(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 Nf(e){return new Hp(e.map((([e,t])=>`${e}="${Af(t)}"`)).join(" "))}function Of(e){const t=(new DOMParser).parseFromString(e.toString(),"text/xml"),i=t.querySelector("parsererror");if(i){const t=i.innerHTML,n=parseInt(t.split(":")[0],10),o=e.toString().trim().split("\n"),s=o.slice(Math.max(n-3,0),Math.min(n+2,o.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${s}`)}return t}function Mf(e){if(e)return{style:e[0],color:{rgb:e[1]}}}function _f(e,t){return Df`
1390
1389
  <Override ContentType="${t}" PartName="${e}" />
1391
- `}function Mf(e){return new zp(e.join("\n"))}function _f(e,...t){let i=[e[0]];for(let n=0;n<t.length;n++){const o=t[n]instanceof zp?t[n]:If(t[n]);i.push(o+e[n+1])}return new zp(et(i))}function Ff(e){return e.replace(/[a-z0-9]+:(?=[a-z0-9]+)/gi,"")}function Df(e){return e.replace(/([a-z0-9]+):(?=[a-z0-9]+)/gi,"$1\\:")}class kf{constructor(e){this.value=e}asString(){return Nm(String(this.value))}asBool(){return Boolean(Number(this.value))}asNum(){return Number(this.value)}}class $f{constructor(e,t,i){this.currentFile=void 0,this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=i,this.areNamespaceIgnored=null!==(new DOMParser).parseFromString("<t:test xmlns:t='a'/>","text/xml").querySelector("test"),this.relationships={},e.rels&&this.extractRelationships(e.rels).map((e=>{this.relationships[e.id]=e}))}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:"Relationship"},(e=>({id:this.extractAttr(e,"Id",{required:!0}).asString(),target:this.extractAttr(e,"Target",{required:!0}).asString(),type:this.extractAttr(e,"Type",{required:!0}).asString()})))}getListOfFiles(){return Object.values(this.xlsxFileStructure).flat().filter(Xe)}mapOnElements(e,t){var i;const n=[],o=this.currentFile;let s;if(e.children){const t=null===(i=this.querySelector(e.parent,e.query))||void 0===i?void 0:i.children;s=t||[]}else s=this.querySelectorAll(e.parent,e.query);if(s)for(let e of s)try{n.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=o,n}catchErrorOnElement(e,t){const i=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([i,e.message].join("\n"))}extractAttr(e,t,i){const n=e.attributes[t];n||this.handleMissingValue(e,`attribute "${t}"`,i);const o=(null==n?void 0:n.value)?n.value:null==i?void 0:i.default;return void 0===o?void 0:new kf(o)}extractTextContent(e,t){var i;if(void 0!==(null==t?void 0:t.default)&&"string"!=typeof t.default)throw new Error("extractTextContent default value should be a string");const n="preserve"===(null===(i=null==e?void 0:e.attributes["xml:space"])||void 0===i?void 0:i.value);let o=null==e?void 0:e.textContent;return e&&null!==o||this.handleMissingValue(e,"text content",t),o&&(o=n?o:o.trim()),o?Nm(o):null==t?void 0:t.default}extractChildAttr(e,t,i,n){var o;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}>`,n);const r=s?null===(o=this.extractAttr(s,i,n))||void 0===o?void 0:o.asString():null==n?void 0:n.default;return void 0!==r?new kf(r):void 0}extractChildTextContent(e,t,i){if(void 0!==(null==i?void 0:i.default)&&"string"!=typeof i.default)throw new Error("extractTextContent default value should be a string");let n=this.querySelector(e,t);return n||this.handleMissingValue(e,`child <${t}>`,i),n?this.extractTextContent(n,i):null==i?void 0:i.default}handleMissingValue(e,t,i){if(null==i?void 0:i.required){if(!(null==i?void 0:i.default))throw new Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`);this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${i.default}`)}}extractColor(e,t,i){var n,o,s,r,a;if(!e)return i?{rgb:i}:void 0;const l=null===(n=this.extractAttr(e,"theme"))||void 0===n?void 0:n.asString();let c;if(void 0!==l){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");c=this.getThemeColor(l,t.clrScheme)}else c=null===(o=this.extractAttr(e,"rgb"))||void 0===o?void 0:o.asString();return{rgb:c,auto:null===(s=this.extractAttr(e,"auto"))||void 0===s?void 0:s.asBool(),indexed:null===(r=this.extractAttr(e,"indexed"))||void 0===r?void 0:r.asNum(),tint:null===(a=this.extractAttr(e,"tint"))||void 0===a?void 0:a.asNum()}}getTargetXmlFile(e){if(!e)throw new Error("Undefined target file");let t=e.target;t=t.replace("../",""),t=t.replace("./","");const i=this.getListOfFiles().find((e=>e.file.fileName.endsWith(t)));if(!i||!i.file)throw new Error("Cannot find target file");return i}querySelector(e,t){return t=this.areNamespaceIgnored?Ff(t):Df(t),e.querySelector(t)}querySelectorAll(e,t){return t=this.areNamespaceIgnored?Ff(t):Df(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 Lf extends $f{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:Hp}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:Hp}).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 Pf extends $f{constructor(e,t,i,n){super(e,t,i),this.theme=n}extractConditionalFormattings(){const e=this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > conditionalFormatting"},(e=>{var t;return{sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),pivot:null===(t=this.extractAttr(e,"pivot"))||void 0===t?void 0:t.asBool(),cfRules:this.extractCFRules(e,this.theme)}}));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:"extLst x14:conditionalFormatting"},(e=>{var t;return{sqref:this.extractChildTextContent(e,"xm:sqref",{required:!0}).split(" "),pivot:null===(t=this.extractAttr(e,"xm:pivot"))||void 0===t?void 0:t.asBool(),cfRules:this.extractCFRules(e,this.theme)}}))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:"cfRule, x14:cfRule"},(e=>{var i,n,o,s,r,a,l,c,h,d,u;const g=this.extractAttr(e,"type",{required:!0}).asString();if("dataBar"===g)throw new Error("Databars conditional formats are not supported.");return{type:g,priority:this.extractAttr(e,"priority",{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:null===(i=this.extractAttr(e,"dxfId"))||void 0===i?void 0:i.asNum(),stopIfTrue:null===(n=this.extractAttr(e,"stopIfTrue"))||void 0===n?void 0:n.asBool(),aboveAverage:null===(o=this.extractAttr(e,"aboveAverage"))||void 0===o?void 0:o.asBool(),percent:null===(s=this.extractAttr(e,"percent"))||void 0===s?void 0:s.asBool(),bottom:null===(r=this.extractAttr(e,"bottom"))||void 0===r?void 0:r.asBool(),operator:null===(a=this.extractAttr(e,"operator"))||void 0===a?void 0:a.asString(),text:null===(l=this.extractAttr(e,"text"))||void 0===l?void 0:l.asString(),timePeriod:null===(c=this.extractAttr(e,"timePeriod"))||void 0===c?void 0:c.asString(),rank:null===(h=this.extractAttr(e,"rank"))||void 0===h?void 0:h.asNum(),stdDev:null===(d=this.extractAttr(e,"stdDev"))||void 0===d?void 0:d.asNum(),equalAverage:null===(u=this.extractAttr(e,"equalAverage"))||void 0===u?void 0:u.asBool()}}))}extractCfFormula(e){return this.mapOnElements({parent:e,query:"formula"},(e=>this.extractTextContent(e,{required:!0})))}extractCfColorScale(e,t){const i=this.querySelector(e,"colorScale");if(i)return{colors:this.mapOnElements({parent:i,query:"color"},(e=>this.extractColor(e,t,"ffffff"))),cfvos:this.extractCFVos(i)}}extractCfIconSet(e){var t,i;const n=this.querySelector(e,"iconSet, x14:iconSet");if(n)return{iconSet:this.extractAttr(n,"iconSet",{default:"3TrafficLights1"}).asString(),showValue:this.extractAttr(n,"showValue",{default:!0}).asBool(),percent:this.extractAttr(n,"percent",{default:!0}).asBool(),reverse:null===(t=this.extractAttr(n,"reverse"))||void 0===t?void 0:t.asBool(),custom:null===(i=this.extractAttr(n,"custom"))||void 0===i?void 0:i.asBool(),cfvos:this.extractCFVos(n),cfIcons:this.extractCfIcons(n)}}extractCfIcons(e){const t=this.mapOnElements({parent:e,query:"cfIcon, x14:cfIcon"},(e=>({iconSet:this.extractAttr(e,"iconSet",{required:!0}).asString(),iconId:this.extractAttr(e,"iconId",{required:!0}).asNum()})));return 0===t.length?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:"cfvo, x14:cfvo"},(e=>{var t,i;return{type:this.extractAttr(e,"type",{required:!0}).asString(),gte:null===(t=this.extractAttr(e,"gte",{default:!0}))||void 0===t?void 0:t.asBool(),value:e.attributes.val?null===(i=this.extractAttr(e,"val"))||void 0===i?void 0:i.asString():this.extractChildTextContent(e,"f, xm:f")}}))}}class Uf extends $f{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},(e=>{const t=this.getChartType(e);if(!Em[t])throw new Error(`Unsupported chart type ${t}`);const i=this.mapOnElements({parent:e,query:"c:title a:t"},(e=>e.textContent||"")).join(""),n=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString();return{title:i,type:Em[t],dataSets:this.extractChartDatasets(this.querySelector(e,`c:${t}`)),backgroundColor:this.extractChildAttr(e,"c:chartSpace > c:spPr a:srgbClr","val",{default:"ffffff"}).asString(),verticalAxisPosition:"r"===this.extractChildAttr(e,"c:valAx > c:axPos","val",{default:"l"}).asString()?"right":"left",legendPosition:Cm[this.extractChildAttr(e,"c:legendPos","val",{default:"none"}).asString()],stacked:"stacked"===n,fontColor:"000000"}}))[0]}extractChartDatasets(e){return this.mapOnElements({parent:e,query:"c:ser"},(e=>({label:this.extractChildTextContent(e,"c:cat c:f"),range:this.extractChildTextContent(e,"c:val c:f",{required:!0})})))}getChartType(e){const t=this.querySelector(e,"c:plotArea");if(!t)throw new Error("Missing plot area in the chart definition.");for(let e of t.children){const t=Ff(e.tagName);if(Bp.some((e=>e===t)))return t}throw new Error("Unknown chart type")}}class Vf extends $f{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},(e=>{if("twoCellAnchor"!==Ff(e.tagName))throw new Error("Only twoCellAnchor are supported for xlsx drawings.");const t=this.querySelector(e,"c:chart");if(!t)throw new Error("Only chart figures are currently supported.");return{anchors:[this.extractFigureAnchor("xdr:from",e),this.extractFigureAnchor("xdr:to",e)],data:this.extractChart(t)}}))}extractFigureAnchor(e,t){const i=this.querySelector(t,e);if(!i)throw new Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(i,"xdr:col",{required:!0})),colOffset:Number(this.extractChildTextContent(i,"xdr:colOff",{required:!0})),row:Number(this.extractChildTextContent(i,"xdr:row",{required:!0})),rowOffset:Number(this.extractChildTextContent(i,"xdr:rowOff",{required:!0}))}}extractChart(e){const t=this.extractAttr(e,"r:id",{required:!0}).asString(),i=this.getTargetXmlFile(this.relationships[t]),n=new Uf(i,this.xlsxFileStructure,this.warningManager).extractChart();if(!n)throw new Error("Unable to extract chart definition");return n}}class zf extends $f{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 Bf extends $f{getTable(){return this.mapOnElements({query:"table",parent:this.rootFile.file.xml},(e=>{var t;return{displayName:this.extractAttr(e,"displayName",{required:!0}).asString(),name:null===(t=this.extractAttr(e,"name"))||void 0===t?void 0:t.asString(),id:this.extractAttr(e,"id",{required:!0}).asString(),ref:this.extractAttr(e,"ref",{required:!0}).asString(),headerRowCount:this.extractAttr(e,"headerRowCount",{default:1}).asNum(),totalsRowCount:this.extractAttr(e,"totalsRowCount",{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)}}))[0]}extractTableCols(e){return this.mapOnElements({query:"tableColumn",parent:e},(e=>({id:this.extractAttr(e,"id",{required:!0}).asString(),name:this.extractAttr(e,"name",{required:!0}).asString(),colFormula:this.extractChildTextContent(e,"calculatedColumnFormula")})))}extractTableStyleInfo(e){return this.mapOnElements({query:"tableStyleInfo",parent:e},(e=>{var t,i,n,o,s;return{name:null===(t=this.extractAttr(e,"name"))||void 0===t?void 0:t.asString(),showFirstColumn:null===(i=this.extractAttr(e,"showFirstColumn"))||void 0===i?void 0:i.asBool(),showLastColumn:null===(n=this.extractAttr(e,"showLastColumn"))||void 0===n?void 0:n.asBool(),showRowStripes:null===(o=this.extractAttr(e,"showRowStripes"))||void 0===o?void 0:o.asBool(),showColumnStripes:null===(s=this.extractAttr(e,"showColumnStripes"))||void 0===s?void 0:s.asBool()}}))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:"autoFilter",parent:e},(e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,"ref",{required:!0}).asString()})))[0]}extractFilterColumns(e){return this.mapOnElements({query:"tableColumn",parent:e},(t=>({colId:this.extractAttr(e,"colId",{required:!0}).asNum(),hiddenButton:this.extractAttr(e,"hiddenButton",{default:!1}).asBool(),filters:this.extractSimpleFilter(t)})))}extractSimpleFilter(e){return this.mapOnElements({query:"filter",parent:e},(e=>({val:this.extractAttr(e,"val",{required:!0}).asString()})))}}class Hf extends $f{constructor(e,t,i,n){super(e,t,i),this.theme=n}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=Tm(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=Tm(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id,i=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:"sheet"},(e=>({relationshipId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetId:this.extractAttr(e,"sheetId",{required:!0}).asString(),sheetName:this.extractAttr(e,"name",{required:!0}).asString(),state:this.extractAttr(e,"state",{default:"visible"}).asString()}))).find((e=>e.relationshipId===t));if(!i)throw new Error("Cannot find corresponding workbook sheet");return i}extractConditionalFormats(){return new Pf(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractFigures(e){return this.mapOnElements({parent:e,query:"drawing"},(e=>{var t;const i=null===(t=this.extractAttr(e,"r:id",{required:!0}))||void 0===t?void 0:t.asString(),n=this.getTargetXmlFile(this.relationships[i]);return new Vf(n,this.xlsxFileStructure,this.warningManager).extractFigures()}))[0]||[]}extractTables(e){return this.mapOnElements({query:"tablePart",parent:e},(e=>{var t;const i=null===(t=this.extractAttr(e,"r:id",{required:!0}))||void 0===t?void 0:t.asString(),n=this.getTargetXmlFile(this.relationships[i]);return new Bf(n,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 zf(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:Jp.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:em.toString()}).asNum()}}extractCols(e){return this.mapOnElements({parent:e,query:"cols col"},(e=>{var t,i,n,o,s,r,a;return{width:null===(t=this.extractAttr(e,"width"))||void 0===t?void 0:t.asNum(),customWidth:null===(i=this.extractAttr(e,"customWidth"))||void 0===i?void 0:i.asBool(),bestFit:null===(n=this.extractAttr(e,"bestFit"))||void 0===n?void 0:n.asBool(),hidden:null===(o=this.extractAttr(e,"hidden"))||void 0===o?void 0:o.asBool(),min:null===(s=this.extractAttr(e,"min",{required:!0}))||void 0===s?void 0:s.asNum(),max:null===(r=this.extractAttr(e,"max",{required:!0}))||void 0===r?void 0:r.asNum(),styleIndex:null===(a=this.extractAttr(e,"style"))||void 0===a?void 0:a.asNum()}}))}extractRows(e){return this.mapOnElements({parent:e,query:"sheetData row"},(e=>{var t,i,n,o,s;return{index:null===(t=this.extractAttr(e,"r",{required:!0}))||void 0===t?void 0:t.asNum(),cells:this.extractCells(e),height:null===(i=this.extractAttr(e,"ht"))||void 0===i?void 0:i.asNum(),customHeight:null===(n=this.extractAttr(e,"customHeight"))||void 0===n?void 0:n.asBool(),hidden:null===(o=this.extractAttr(e,"hidden"))||void 0===o?void 0:o.asBool(),styleIndex:null===(s=this.extractAttr(e,"s"))||void 0===s?void 0:s.asNum()}}))}extractCells(e){return this.mapOnElements({parent:e,query:"c"},(e=>{var t,i,n;return{xc:null===(t=this.extractAttr(e,"r",{required:!0}))||void 0===t?void 0:t.asString(),styleIndex:null===(i=this.extractAttr(e,"s"))||void 0===i?void 0:i.asNum(),type:pm[null===(n=this.extractAttr(e,"t",{default:"n"}))||void 0===n?void 0:n.asString()],value:this.extractChildTextContent(e,"v"),formula:this.extractCellFormula(e)}}))}extractCellFormula(e){var t,i;const n=this.querySelector(e,"f");if(n)return{content:this.extractTextContent(n),sharedIndex:null===(t=this.extractAttr(n,"si"))||void 0===t?void 0:t.asNum(),ref:null===(i=this.extractAttr(n,"ref"))||void 0===i?void 0:i.asString()}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:"hyperlink"},(e=>{var t,i,n,o;const s=null===(t=this.extractAttr(e,"r:id"))||void 0===t?void 0:t.asString();return{xc:null===(i=this.extractAttr(e,"ref",{required:!0}))||void 0===i?void 0:i.asString(),location:null===(n=this.extractAttr(e,"location"))||void 0===n?void 0:n.asString(),display:null===(o=this.extractAttr(e,"display"))||void 0===o?void 0:o.asString(),relTarget:s?this.relationships[s].target:void 0}}))}extractSharedFormulas(e){const t=this.querySelectorAll(e,"f[si][ref]"),i={};for(let e of t){const t=this.extractAttr(e,"si",{required:!0}).asNum(),n=this.extractTextContent(e,{required:!0});i[t]=n}const n=[];for(let e=0;e<Object.keys(i).length;e++)i[e]?n.push(i[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),n.push(""));return n}}class Wf extends $f{constructor(e,t,i){super(e.styles,e,t),this.theme=i}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"numFmt"},(e=>this.extractNumFormats(e)))}extractNumFormats(e){return{id:this.extractAttr(e,"numFmtId",{required:!0}).asNum(),format:this.extractAttr(e,"formatCode",{required:!0,default:""}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"font"},(e=>this.extractFont(e)))}extractFont(e){var t,i,n,o;const s=this.extractChildAttr(e,"name","val",{default:"Arial"}).asString(),r=this.extractChildAttr(e,"sz","val",{default:G.toString()}).asNum(),a=this.extractColor(this.querySelector(e,"color"),this.theme),l=this.querySelector(e,"i")||void 0,c=l&&"0"!==(null===(t=l.attributes.val)||void 0===t?void 0:t.value),h=this.querySelector(e,"b")||void 0,d=h&&"0"!==(null===(i=h.attributes.val)||void 0===i?void 0:i.value),u=this.querySelector(e,"strike")||void 0,g=u&&"0"!==(null===(n=u.attributes.val)||void 0===n?void 0:n.value),p=this.querySelector(e,"u")||void 0;return{name:s,size:r,color:a,italic:c,bold:d,underline:p&&"none"!==(null===(o=p.attributes.val)||void 0===o?void 0:o.value),strike:g}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"fill"},(e=>this.extractFill(e)))}extractFill(e){var t;const i=e.children[0];return"patternFill"===i.tagName?{patternType:null===(t=i.attributes.patternType)||void 0===t?void 0:t.value,bgColor:this.extractColor(this.querySelector(i,"bgColor"),this.theme),fgColor:this.extractColor(this.querySelector(i,"fgColor"),this.theme)}:{patternType:"solid",fgColor:this.extractColor(this.querySelectorAll(i,"color")[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"border"},(e=>this.extractBorder(e)))}extractBorder(e){var t,i;const n={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 n.diagonal&&(n.diagonalUp=null===(t=this.extractAttr(e,"diagonalUp"))||void 0===t?void 0:t.asBool(),n.diagonalDown=null===(i=this.extractAttr(e,"diagonalDown"))||void 0===i?void 0:i.asBool()),n}extractSingleBorder(e,t,i){const n=this.querySelector(e,t);if(n&&n.attributes.style)return{style:this.extractAttr(n,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(n.children[0],i,"000000")}}extractAlignment(e){var t,i,n,o,s,r,a;return{horizontal:this.extractAttr(e,"horizontal",{default:"general"}).asString(),vertical:this.extractAttr(e,"vertical",{default:"center"}).asString(),textRotation:null===(t=this.extractAttr(e,"textRotation"))||void 0===t?void 0:t.asNum(),wrapText:null===(i=this.extractAttr(e,"wrapText"))||void 0===i?void 0:i.asBool(),indent:null===(n=this.extractAttr(e,"indent"))||void 0===n?void 0:n.asNum(),relativeIndent:null===(o=this.extractAttr(e,"relativeIndent"))||void 0===o?void 0:o.asNum(),justifyLastLine:null===(s=this.extractAttr(e,"justifyLastLine"))||void 0===s?void 0:s.asBool(),shrinkToFit:null===(r=this.extractAttr(e,"shrinkToFit"))||void 0===r?void 0:r.asBool(),readingOrder:null===(a=this.extractAttr(e,"readingOrder"))||void 0===a?void 0:a.asNum()}}getDxfs(){return this.mapOnElements({query:"dxf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"font"),i=this.querySelector(e,"fill"),n=this.querySelector(e,"border"),o=this.querySelector(e,"numFmt"),s=this.querySelector(e,"alignment");return{font:t?this.extractFont(t):void 0,fill:i?this.extractFill(i):void 0,numFmt:o?this.extractNumFormats(o):void 0,alignment:s?this.extractAlignment(s):void 0,border:n?this.extractBorder(n):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 Gf extends $f{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"externalBook"},(e=>({rId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:"sheetName"},(e=>this.extractAttr(e,"val",{required:!0}).asString())),datasets:this.extractExternalSheetData(e)})))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:"sheetData"},(e=>{const t=this.mapOnElements({parent:e,query:"cell"},(e=>({xc:this.extractAttr(e,"r",{required:!0}).asString(),value:this.extractChildTextContent(e,"v",{required:!0})}))),i={};for(let e of t)i[e.xc]=e.value;return{sheetId:this.extractAttr(e,"sheetId",{required:!0}).asNum(),data:i}}))}}function qf(e,t){const i=function(e,t){const i=t[rm],n=i.querySelectorAll(`Override[ContentType="${e}"]`),o=[];for(let e of n){const t=null==e?void 0:e.attributes.PartName.value;o.push(t.substring(1))}return o}(e,t);return function(e,t){const i=[];for(let n of e){const e=Zf(n,t);i.push({file:{fileName:n,xml:t[n]},rels:e?{fileName:e,xml:t[e]}:void 0})}return i}(i,t)}function Zf(e,t){if(e===rm)return"_rels/.rels";let i="";const n=e.split("/");for(let e=0;e<n.length-1;e++)i+=n[e]+"/";return i+="_rels/",i+=n[n.length-1]+".rels",t[i]||(i=void 0),i}class jf{constructor(e){this.warningManager=new lm,this.xmls={};for(let t of Object.keys(e))(t.endsWith(".xml")||t.endsWith(".rels"))&&(this.xmls[t]=Af(new zp(e[t])))}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new Lf(e.theme,e,this.warningManager).getTheme():void 0,i=e.sharedStrings?new Lf(e.sharedStrings,e,this.warningManager).getSharedStrings():[],n=e.sheets.sort(((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0}))).map((i=>new Hf(i,e,this.warningManager,t).getSheet())),o=e.externalLinks.map((t=>new Gf(t,e,this.warningManager).getExternalBook())),s=new Wf(e,this.warningManager,t);return{fonts:s.getFonts(),fills:s.getFills(),borders:s.getBorders(),dxfs:s.getDxfs(),numFmts:s.getNumFormats(),styles:s.getStyles(),sheets:n,sharedStrings:i,externalBooks:o}}buildXlsxFileStructure(){const e={sheets:qf(jp.sheet,this.xmls),workbook:qf(jp.workbook,this.xmls)[0],styles:qf(jp.styles,this.xmls)[0],sharedStrings:qf(jp.sharedStrings,this.xmls)[0],theme:qf(jp.themes,this.xmls)[0],charts:qf(jp.chart,this.xmls),figures:qf(jp.drawing,this.xmls),tables:qf(jp.table,this.xmls),pivots:qf(jp.pivot,this.xmls),externalLinks:qf(jp.externalLink,this.xmls)};if(!e.workbook.rels)throw Error(s("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:12,sheets:gf(e,this.warningManager),styles:km(e,this.warningManager),formats:Lm(e,this.warningManager),borders:Fm(e,this.warningManager),entities:{},revisionId:K};return Ef(t,e),Object.keys(e.styles).map((t=>{e.styles[t]=rt(e.styles[t])})),t}}function Yf(e){const t=mg(e);let i=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&xt.test(e.value)){const t=e.value.trim();return i.includes(t)||i.push(t),`${ie}${i.indexOf(t)}${ie}`}return e.value}))),dependencies:i}}const Xf=12.5,Kf="Sheet1";function Qf(e,t){if(!e)return nv();if(e["[Content_Types].xml"]){const i=new jf(e);if(e=i.convertXlsx(),t)for(let e of i.warningManager.warnings.sort())console.warn(e)}return"version"in(e=Ae(e))&&e.version<Xf&&(e=function(e){for(let t=Jf.findIndex((t=>t.from===e.version));t<Jf.length;t++)e=Jf[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,i=new Oi;for(const n of e.sheets||[])for(const e of n.figures||[])t.has(e.id)&&(e.id+=i.smallUuid()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){e=Object.assign(nv(),e,{version:Xf}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(iv(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(iv(Kf,"Sheet1"));return e}(e),e}(e),e}const Jf=[{description:"add the `activeSheet` field on data",from:1,to:2,applyMigration:e=>(e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e)},{description:"add an id field in each sheet",from:2,to:3,applyMigration(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}},{description:"activeSheet is now an id, not the name of a sheet",from:3,to:4,applyMigration(e){if(e.sheets&&e.activeSheet){const t=e.sheets.find((t=>t.name===e.activeSheet));e.activeSheet=t.id}return e}},{description:"add figures object in each sheets",from:4,to:5,applyMigration(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}},{description:"normalize the content of the cell if it is a formula to avoid parsing all the formula that vary only by the cells they use",from:5,to:6,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const i=t.cells[e];i.content&&i.content.startsWith("=")&&(i.formula=Yf(i.content))}return e}},{description:"transform chart data structure",from:6,to:7,applyMigration(e){for(let t of e.sheets||[])for(let e in t.figures||[]){const{dataSets:i,...n}=t.figures[e].data,o=[];for(let e of i)if(e.labelCell){const t=Mi(e.dataRange),i=e.labelCell+":"+Vt(t.right,t.bottom);o.push(i)}else o.push(e.dataRange);n.dataSetsHaveTitle=Boolean(i[0].labelCell),n.dataSets=o,t.figures[e].data=n}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){var t;const i=[],n=new RegExp(te,"g");for(let o of e.sheets||[]){if(!o.name)continue;const e=o.name,s=e.replace(n,"_");let r=1,a=s;for(;i.includes(a);)a=`${s}${r}`,r++;o.name=a,i.push(a);const l=t=>{if(void 0===t)return t;let i=t.replace(e,a),n=t;for(;n!==i;)n=i,i=n.replace(e,a);return n};for(let e in o.cells){const t=o.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(l))}for(let e of o.figures||[])if("chart"===e.type){const t=e.data.dataSets.map(l),i=l(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:i}}for(let e of o.conditionalFormats||[]){e.ranges=e.ranges.map(l);for(const i of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===(null===(t=e.rule[i])||void 0===t?void 0:t.type)&&(e.rule[i].value=l(e.rule[i].value))}}return e}},{description:"transform chart data structure with design attributes",from:8,to:9,applyMigration(e){for(const t of e.sheets||[])for(const e of t.figures||[])e.data.background=w,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stacked=!1;return e}},{description:"de-normalize formula to reduce exported json size (~30%)",from:9,to:10,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const i=t.cells[e];if(i.formula){let{text:e,dependencies:t}=i.formula;for(let[i,n]of Object.entries(t)){const t=`\\${ie}${i}\\${ie}`;e=e.replace(new RegExp(t,"g"),n)}i.content=e,delete i.formula}}return e}},{description:"normalize the formats of the cells",from:10,to:11,applyMigration(e){const t={};for(let i of e.sheets||[])for(let e in i.cells||[]){const n=i.cells[e];n.format&&(n.format=Je(n.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 i of t.filterTables||[]){const t=Mi(i.range),n=e.findIndex((e=>zi(e,t)));-1!==n?e[n]=t:e.push(t)}t.filterTables=e.map((e=>({range:Fi(e)})))}return e}}];function ev(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const i=[],n=[],o=e=>{if("CREATE_SHEET"===e.type)i.push(e.sheetId);else if("sheetId"in e&&!i.includes(e.sheetId))return{...e,sheetId:Kf};return e};for(const e of t)"REMOTE_REVISION"===e.type?n.push({...e,commands:e.commands.map(o)}):n.push(e);return n}(e,t),t=tv(t,"SORT_CELLS"),t=function(e,t){var i;const n=[],o={};for(const t of e.sheets||[])null===(i=t.figures)||void 0===i||i.forEach((e=>{"chart"===e.tag&&(o[e.id]=e.data)}));for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const i of e.commands){let e=i;switch(i.type){case"CREATE_CHART":o[i.id]=i.definition;break;case"UPDATE_CHART":if(!o[i.id]){console.log(`Fix chart definition: chart with id ${i.id} not found.`);continue}const t={...o[i.id],...i.definition};e={...i,definition:t},o[i.id]=t}t.push(e)}n.push({...e,commands:t})}else n.push(e);return n}(e,t=tv(t,"SET_DECIMAL")),t}function tv(e,t){const i=[];for(const n of e)"REMOTE_REVISION"===n.type?i.push({...n,commands:n.commands.filter((e=>e.type!==t))}):i.push(n);return i}function iv(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[],filterTables:[],isVisible:!0}}function nv(e="Sheet1"){return{version:Xf,sheets:[iv(Kf,e)],entities:{},styles:{},formats:{},borders:{},revisionId:K,uniqueFigureIds:!0}}function ov(e,t){return{...iv(e,t),charts:[]}}class sv extends zg{constructor(e,t,i,n,o,s){super(t,n,o),this.dispatch=n,this.range=i,i.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=s}import(e){}export(e){}adaptRanges(e,t){}}class rv extends sv{constructor(){super(...arguments),this.borders={}}allowDispatch(e){return"SET_BORDER"===e.type?this.checkBordersUnchanged(e):0}handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":const t=this.borders[e.sheetId];if(t){const i=t.slice().map((e=>null==e?void 0:e.slice().map((e=>({...e})))));this.history.update("borders",e.sheetIdTo,i)}break;case"DELETE_SHEET":const i={...this.borders};delete i[e.sheetId],this.history.update("borders",i);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_FORMATTING":if(e.border){const t=e.target.map((t=>this.getters.expandZone(e.sheetId,t)));this.setBorders(e.sheetId,t,e.border)}break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target);break;case"REMOVE_COLUMNS_ROWS":const n=[...e.elements].sort(((e,t)=>t-e));for(const t of Le(n))if("COL"===e.dimension){if(t[0]>=this.getters.getNumberCols(e.sheetId))for(let i=0;i<this.getters.getNumberRows(e.sheetId);i++)this.history.update("borders",e.sheetId,t[0]+1,i,"vertical",void 0);if(0===t[t.length-1])for(let t=0;t<this.getters.getNumberRows(e.sheetId);t++)this.history.update("borders",e.sheetId,0,t,"vertical",void 0);const i=this.getters.getColsZone(e.sheetId,t[t.length-1]+1,t[0]);this.clearInsideBorders(e.sheetId,[i]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{if(t[0]>=this.getters.getNumberRows(e.sheetId))for(let i=0;i<this.getters.getNumberCols(e.sheetId);i++)this.history.update("borders",e.sheetId,i,t[0]+1,"horizontal",void 0);if(0===t[t.length-1])for(let t=0;t<this.getters.getNumberCols(e.sheetId);t++)this.history.update("borders",e.sheetId,t,0,"horizontal",void 0);const i=this.getters.getRowsZone(e.sheetId,t[t.length-1]+1,t[0]);this.clearInsideBorders(e.sheetId,[i]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumns(e):this.handleAddRows(e)}}handleAddColumns(e){let t,i;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),t=e.base-1,i=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),t=e.base,i=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,i)}handleAddRows(e){let t,i;"before"===e.position?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity,{moveFirstTopBorder:!0}),t=e.base-1,i=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity,{moveFirstTopBorder:!1}),t=e.base,i=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,i)}getCellBorder(e,t,i){var n,o,s,r,a,l,c,h,d,u,g,p;const m={top:null===(s=null===(o=null===(n=this.borders[e])||void 0===n?void 0:n[t])||void 0===o?void 0:o[i])||void 0===s?void 0:s.horizontal,bottom:null===(l=null===(a=null===(r=this.borders[e])||void 0===r?void 0:r[t])||void 0===a?void 0:a[i+1])||void 0===l?void 0:l.horizontal,left:null===(d=null===(h=null===(c=this.borders[e])||void 0===c?void 0:c[t])||void 0===h?void 0:h[i])||void 0===d?void 0:d.vertical,right:null===(p=null===(g=null===(u=this.borders[e])||void 0===u?void 0:u[t+1])||void 0===g?void 0:g[i])||void 0===p?void 0:p.vertical};return m.bottom||m.left||m.right||m.top?m:null}ensureColumnBorderContinuity(e,t,i){const n=$e(t+1,i);for(let o=0;o<this.getters.getNumberRows(e);o++){const s=this.getCellBorder(e,t,o),r=this.getCellBorder(e,i,o);if(s&&r){const t=this.getCommonSides(s,r);for(let i of n)this.addBorder(e,i,o,t)}}}ensureRowBorderContinuity(e,t,i){const n=$e(t+1,i);for(let o=0;o<this.getters.getNumberCols(e);o++){const s=this.getCellBorder(e,o,t),r=this.getCellBorder(e,o,i);if(s&&r){const t=this.getCommonSides(s,r);for(let i of n)this.addBorder(e,o,i,t)}}}getCommonSides(e,t){const i={};for(let n of["top","bottom","left","right"])e[n]&&e[n]===t[n]&&(i[n]=e[n]);return i}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsWithBorders(e){var t;const i=null===(t=this.borders[e])||void 0===t?void 0:t.filter(Xe);if(!i)return[];const n=new Set;for(const e of i)for(const t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?$e(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,i,{moveFirstLeftBorder:n}={}){this.borders[e]&&(i<0&&this.moveBordersOfColumn(e,t,i,"vertical",{destructive:!1}),this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>i<0?e-t:t-e)).forEach((o=>{(o===t&&n||o!==t)&&this.moveBordersOfColumn(e,o,i,"vertical"),this.moveBordersOfColumn(e,o,i,"horizontal")})))}shiftBordersVertically(e,t,i,{moveFirstTopBorder:n}={}){this.borders[e]&&(i<0&&this.moveBordersOfRow(e,t,i,"horizontal",{destructive:!1}),this.getRowsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>i<0?e-t:t-e)).forEach((o=>{(o===t&&n||o!==t)&&this.moveBordersOfRow(e,o,i,"horizontal"),this.moveBordersOfRow(e,o,i,"vertical")})))}moveBordersOfRow(e,t,i,n,{destructive:o}={destructive:!0}){const s=this.borders[e];s&&this.getColumnsWithBorders(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=s[r])||void 0===a?void 0:a[t+i])||void 0===l?void 0:l[n],u=null===(h=null===(c=s[r])||void 0===c?void 0:c[t])||void 0===h?void 0:h[n];this.history.update("borders",e,r,t+i,n,o?u:u||d),this.history.update("borders",e,r,t,n,void 0)}))}moveBordersOfColumn(e,t,i,n,{destructive:o}={destructive:!0}){const s=this.borders[e];s&&this.getRowsRange(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=s[t+i])||void 0===a?void 0:a[r])||void 0===l?void 0:l[n],u=null===(h=null===(c=s[t])||void 0===c?void 0:c[r])||void 0===h?void 0:h[n];this.history.update("borders",e,t+i,r,n,o?u:u||d),this.history.update("borders",e,t,r,n,void 0)}))}setBorder(e,t,i,n,o=!0){var s,r,a,l,c,h,d,u,g,p,m,f,v,b,S,C;!o&&(null===(l=null===(a=null===(r=null===(s=this.borders)||void 0===s?void 0:s[e])||void 0===r?void 0:r[t])||void 0===a?void 0:a[i])||void 0===l?void 0:l.vertical)||this.history.update("borders",e,t,i,"vertical",null==n?void 0:n.left),!o&&(null===(u=null===(d=null===(h=null===(c=this.borders)||void 0===c?void 0:c[e])||void 0===h?void 0:h[t])||void 0===d?void 0:d[i])||void 0===u?void 0:u.horizontal)||this.history.update("borders",e,t,i,"horizontal",null==n?void 0:n.top),!o&&(null===(f=null===(m=null===(p=null===(g=this.borders)||void 0===g?void 0:g[e])||void 0===p?void 0:p[t+1])||void 0===m?void 0:m[i])||void 0===f?void 0:f.vertical)||this.history.update("borders",e,t+1,i,"vertical",null==n?void 0:n.right),!o&&(null===(C=null===(S=null===(b=null===(v=this.borders)||void 0===v?void 0:v[e])||void 0===b?void 0:b[t])||void 0===S?void 0:S[i+1])||void 0===C?void 0:C.horizontal)||this.history.update("borders",e,t,i+1,"horizontal",null==n?void 0:n.bottom)}clearBorders(e,t){for(let i of t){for(let t=i.top;t<=i.bottom;t++){this.history.update("borders",e,i.right+1,t,"vertical",void 0);for(let n=i.left;n<=i.right;n++)this.history.update("borders",e,n,t,void 0)}for(let t=i.left;t<=i.right;t++)this.history.update("borders",e,t,i.bottom+1,"horizontal",void 0)}}clearInsideBorders(e,t){for(let i of t)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.history.update("borders",e,n,t,void 0)}addBorder(e,t,i,n){this.setBorder(e,t,i,{...this.getCellBorder(e,t,i),...n})}setBorders(e,t,i){if("clear"===i)return this.clearBorders(e,t);for(let n of t){if("h"===i||"hv"===i||"all"===i)for(let t=n.top+1;t<=n.bottom;t++)for(let i=n.left;i<=n.right;i++)this.addBorder(e,i,t,{top:Z});if("v"===i||"hv"===i||"all"===i)for(let t=n.top;t<=n.bottom;t++)for(let i=n.left+1;i<=n.right;i++)this.addBorder(e,i,t,{left:Z});if("left"===i||"all"===i||"external"===i)for(let t=n.top;t<=n.bottom;t++)this.addBorder(e,n.left,t,{left:Z});if("right"===i||"all"===i||"external"===i)for(let t=n.top;t<=n.bottom;t++)this.addBorder(e,n.right+1,t,{left:Z});if("top"===i||"all"===i||"external"===i)for(let t=n.left;t<=n.right;t++)this.addBorder(e,t,n.top,{top:Z});if("bottom"===i||"all"===i||"external"===i)for(let t=n.left;t<=n.right;t++)this.addBorder(e,t,n.bottom+1,{top:Z})}}addBordersToMerge(e,t){const{left:i,right:n,top:o,bottom:s}=t,r=this.getCellBorder(e,i,o),a=this.getCellBorder(e,n,s);this.clearBorders(e,[t]),(null==r?void 0:r.top)&&this.setBorders(e,[{...t,bottom:o}],"top"),(null==r?void 0:r.left)&&this.setBorders(e,[{...t,right:i}],"left"),((null==a?void 0:a.bottom)||(null==r?void 0:r.bottom))&&this.setBorders(e,[{...t,top:s}],"bottom"),((null==a?void 0:a.right)||(null==r?void 0:r.right))&&this.setBorders(e,[{...t,left:n}],"right")}checkBordersUnchanged(e){var t,i,n,o;const s=this.getCellBorder(e.sheetId,e.col,e.row),r=!((null===(t=e.border)||void 0===t?void 0:t.bottom)||(null===(i=e.border)||void 0===i?void 0:i.left)||(null===(n=e.border)||void 0===n?void 0:n.right)||(null===(o=e.border)||void 0===o?void 0:o.top));return!s&&r||ot(s,e.border)?89:0}import(e){if(e.borders)for(let t of e.sheets)for(let[i,n]of Object.entries(t.cells))if(null==n?void 0:n.border){const o=e.borders[n.border],{col:s,row:r}=Ut(i);this.setBorder(t.id,s,r,o,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Mi(e))}export(e){let t=0;const i={};function n(e){for(let[t,n]of Object.entries(i))if(ot(n,e))return parseInt(t,10);return i[++t]=e,t}for(let t of e.sheets)for(let e=0;e<t.colNumber;e++)for(let i=0;i<t.rowNumber;i++){const o=this.getCellBorder(t.id,e,i);if(o){const s=Vt(e,i),r=t.cells[s],a=n(o);r?r.border=a:t.cells[s]={border:a}}}e.borders=i}exportForExcel(e){this.export(e)}}rv.getters=["getCellBorder"];const av={textColor:R};class lv extends sv{constructor(){super(...arguments),this.nextId=1,this.cells={},this.createCell=function(e){const t=eo.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(i,n,o,s){const r=t.find((e=>e.match(n,o.format)));if(!r)return new Fp(i,n,o);try{return r.createCell(i,n,o,s,e)}catch(e){return new Up(i,n,e instanceof c?e:new h(e.message||ne),o)}}}(this.getters)}adaptRanges(e,t){for(const i of Object.keys(this.cells))for(const n of Object.values(this.cells[i]||{}))if(n.isFormula())for(const o of n.dependencies)if(!t||o.sheetId===t){const t=e(o);"NONE"!==t.changeType&&this.history.update("cells",i,n.id,"dependencies",n.dependencies.indexOf(o),t.range)}}allowDispatch(e){var t;switch(e.type){case"UPDATE_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case"CLEAR_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case"UPDATE_CELL_POSITION":return!e.cellId||(null===(t=this.cells[e.sheetId])||void 0===t?void 0:t[e.cellId])?0:28;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:""});break;case"DELETE_SHEET":this.history.update("cells",e.sheetId,void 0)}}setFormatter(e,t,i){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let o=n.left;o<=n.right;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:o,row:t,format:i})}clearFormatting(e,t){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,style:null,format:""})}handleAddColumnsRows(e,t){let i,n;"before"===e.position?(i=$e(e.base,e.base+e.quantity),n=e.base+e.quantity):(i=$e(e.base+1,e.base+e.quantity+1),n=e.base),t(e.sheetId,n,i)}import(e){for(let t of e.sheets)for(let i in t.cells){const n=t.cells[i],{col:o,row:s}=Ut(i);if((null==n?void 0:n.content)||(null==n?void 0:n.format)||(null==n?void 0:n.style)){const i=this.importCell(t.id,n,e.styles,e.formats);this.history.update("cells",t.id,i.id,i),this.dispatch("UPDATE_CELL_POSITION",{cellId:i.id,col:o,row:s,sheetId:t.id})}}}export(e){const t={},i={};for(let n of e.sheets){const e={},o=Object.keys(this.cells[n.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const{col:s,row:r}of o){const o=this.getters.getCell(n.id,s,r);e[Vt(s,r)]={style:o.style?Je(o.style,t):void 0,format:o.format?Je(o.format,i):void 0,content:o.content||void 0}}n.cells=e}e.styles=t,e.formats=i}importCell(e,t,i,n){const o=t.style&&i[t.style]||void 0,s=t.format&&n[t.format]||void 0,r=this.getNextUid(),a={format:s,style:o};return this.createCell(r,(null==t?void 0:t.content)||"",a,e)}exportForExcel(e){this.export(e);for(let t of e.sheets)for(const e in t.cells){const{col:i,row:n}=Ut(e),o=this.getters.getCell(t.id,i,n),s=t.cells[e];s.value=o.evaluated.value,s.isFormula=o.isFormula(),o.isFormula()&&(s.content=this.buildFormulaContent(t.id,o,o.dependencies,!0)),o.format!==o.evaluated.format&&(s.computedFormat=o.evaluated.format)}}getCells(e){return this.cells[e]||{}}getCellById(e){const t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}buildFormulaContent(e,t,i,n=!1){const o=i||t.dependencies;let s=0;return et(t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=o[s++];return this.getters.getRangeString(t,e,n)}return t.value})))}getFormulaCellContent(e,t){return this.buildFormulaContent(e,t)}getCellStyle(e){if(!e)return{};return{...e.isLink()?av:{},...e.style}}zoneToXC(e,t,i=[{colFixed:!1,rowFixed:!1}]){const n=Vt((t=this.getters.expandZone(e,t)).left,t.top,i[0]),o=Vt(t.right,t.bottom,i.length>1?i[1]:i[0]),s=this.getters.getMainCellPosition(e,t.left,t.top),r=this.getters.getMainCellPosition(e,t.right,t.bottom),a=s.col===r.col&&s.row===r.row;return n==o||a?n:n+":"+o}setStyle(e,t,i){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let o=n.top;o<=n.bottom;o++){const n=this.getters.getCell(e,t,o);this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,style:i?{...null==n?void 0:n.style,...i}:void 0})}}copyColumnStyle(e,t,i){for(let n=0;n<this.getters.getNumberRows(e);n++){const o=this.getFormat(e,t,n);if(o.style||o.format)for(let t of i)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,...o})}}copyRowStyle(e,t,i){for(let n=0;n<this.getters.getNumberCols(e);n++){const o=this.getFormat(e,n,t);if(o.style||o.format)for(let t of i)this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,...o})}}getFormat(e,t,i){const n={},{col:o,row:s}=this.getters.getMainCellPosition(e,t,i),r=this.getters.getCell(e,o,s);return r&&(r.style&&(n.style=r.style),r.format&&(n.format=r.format)),n}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,i,n){const o=this.getters.getCell(e,t,i),s="content"in n||"formula"in n,r=(s?n.content:null==o?void 0:o.content)||"";let a;a=void 0!==n.style?n.style||void 0:o?o.style:void 0;let l=("format"in n?n.format:o&&o.format)||undefined;if((s&&!r&&!n.formula||!s&&(!o||o.isEmpty()))&&!a&&!l)return void(o&&(this.history.update("cells",e,o.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:i,sheetId:e})));const c=(null==o?void 0:o.id)||this.getNextUid(),h=s,d={format:l,style:a},u=this.createCell(c,r,d,e);o&&!h&&u.isFormula()&&u.assignEvaluation(tt(o.evaluated)),this.history.update("cells",e,u.id,u),this.dispatch("UPDATE_CELL_POSITION",{cellId:u.id,col:t,row:i,sheetId:e})}checkCellOutOfSheet(e){const{sheetId:t,col:i,row:n}=e;if(!this.getters.tryGetSheet(t))return 27;return Bi(i,n,this.getters.getSheetZone(t))?0:18}checkUselessClearCell(e){const t=this.getters.getCell(e.sheetId,e.col,e.row);return t&&(t.content||t.style||t.format)?0:89}checkUselessUpdateCell(e){const t=this.getters.getCell(e.sheetId,e.col,e.row),i="style"in e,n="format"in e;return("content"in e||"formula"in e)&&(null==t?void 0:t.content)!==e.content||i&&!ot(null==t?void 0:t.style,e.style)||n&&(null==t?void 0:t.format)!==e.format?0:89}}lv.getters=["zoneToXC","getCells","getFormulaCellContent","getCellStyle","buildFormulaContent","getCellById"];class cv extends sv{constructor(){super(...arguments),this.charts={},this.createChart=function(e){const t=on.getAll();return function(i,n,o){const s=t.find((e=>e.match(n.type)));if(!s)throw new Error(`No builder for this chart: ${n.type}`);return s.createChart(n,o,e)}}(this.getters),this.validateChartDefinition=e=>function(e,t){const i=on.getAll().find((e=>e.match(t.type)));if(!i)throw new Error("Unknown chart type.");return i.validateChartDefinition(e,t)}(this,e.definition)}adaptRanges(e){for(const[t,i]of Object.entries(this.charts))this.history.update("charts",t,null==i?void 0:i.updateRanges(e))}allowDispatch(e){switch(e.type){case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists));default:return 0}}handle(e){var t;switch(e.type){case"CREATE_CHART":this.addFigure(e.id,e.sheetId,e.position,e.size),this.addChart(e.id,e.definition);break;case"UPDATE_CHART":this.addChart(e.id,e.definition);break;case"DUPLICATE_SHEET":{const i=this.getters.getFigures(e.sheetId);for(const n of i)if("chart"===n.tag){const i=n.id.split("??").pop(),o=`${e.sheetIdTo}??${i}`,s=null===(t=this.charts[n.id])||void 0===t?void 0:t.copyForSheetId(e.sheetIdTo);s&&this.dispatch("CREATE_CHART",{id:o,position:{x:n.x,y:n.y},size:{width:n.width,height:n.height},definition:s.getDefinition(),sheetId:e.sheetIdTo})}break}case"DELETE_FIGURE":this.history.update("charts",e.id,void 0);break;case"DELETE_SHEET":for(let t of this.getChartIds(e.sheetId))this.history.update("charts",t,void 0)}}getContextCreationChart(e){var t;return null===(t=this.charts[e])||void 0===t?void 0:t.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){var t;const i=null===(t=this.charts[e])||void 0===t?void 0:t.type;if(!i)throw new Error("Chart not defined.");return i}isChartDefined(e){return e in this.charts&&void 0!==this.charts}getChartIds(e){return Object.entries(this.charts).filter((([,t])=>(null==t?void 0:t.sheetId)===e)).map((([e])=>e))}getChartDefinition(e){var t;const i=null===(t=this.charts[e])||void 0===t?void 0:t.getDefinition();if(!i)throw new Error(`There is no chart with the given figureId: ${e}`);return i}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)"chart"===e.tag&&(this.charts[e.id]=this.createChart(e.id,e.data,t.id))}export(e){var t;if(e.sheets)for(let i of e.sheets){const e=this.getters.getFigures(i.id),n=[];for(let i of e){const e=i;if(e&&"chart"===e.tag){const i=null===(t=this.charts[e.id])||void 0===t?void 0:t.getDefinition();i&&(e.data=i,n.push(e))}else n.push(e)}i.figures=n}}exportForExcel(e){var t;for(let i of e.sheets){const e=this.getters.getFigures(i.id),n=[];for(let i of e)if(i&&"chart"===i.tag){const e=null===(t=this.charts[i.id])||void 0===t?void 0:t.getDefinitionForExcel();e&&n.push({...i,data:e})}i.charts=n}}addFigure(e,t,i={x:0,y:0},n={width:536,height:335}){if(this.getters.getFigure(t,e))return;const o={id:e,x:i.x,y:i.y,width:n.width,height:n.height,tag:"chart"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:o})}addChart(e,t){const i=this.getters.getFigureSheetId(e);i&&this.history.update("charts",e,this.createChart(e,t,i))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.id)?85:0}checkChartExists(e){return this.getters.getFigureSheetId(e.id)?0:86}}function hv(e){return""===e?NaN:Number(e)}cv.getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];class dv extends sv{constructor(){super(...arguments),this.cfRules={}}loopThroughRangesOfSheet(e,t){for(const i of this.cfRules[e])for(const n of i.ranges){const o=t(n);switch(o.changeType){case"REMOVE":let t=i.ranges.slice();t.splice(i.ranges.indexOf(n),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(i),"ranges",t):this.removeConditionalFormatting(i.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(i),"ranges",i.ranges.indexOf(n),o.range)}}}adaptRanges(e,t){if(t)this.loopThroughRangesOfSheet(t,e);else for(const t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,e)}allowDispatch(e){switch(e.type){case"ADD_CONDITIONAL_FORMAT":return this.checkValidations(e,this.checkCFRule,this.checkEmptyRange);case"MOVE_CONDITIONAL_FORMAT":return this.checkValidReordering(e.cfId,e.direction,e.sheetId)}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const i={...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))};this.addConditionalFormatting(i,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId);break;case"MOVE_CONDITIONAL_FORMAT":this.reorderConditionalFormatting(e.cfId,e.direction,e.sheetId)}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map((e=>this.mapToConditionalFormatInternal(t.id,e)))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map((e=>this.mapToConditionalFormat(t.id,e))))}exportForExcel(e){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){var t;return(null===(t=this.cfRules[e])||void 0===t?void 0:t.map((t=>this.mapToConditionalFormat(e,t))))||[]}getRulesSelection(e,t){const i=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{i.add(e)}))})),Array.from(i)}getRulesByZone(e,t){const i=new Set;for(let n=t.top;n<=t.bottom;n++)for(let o=t.left;o<=t.right;o++){this.getRulesByCell(e,o,n).forEach((e=>{i.add(e.id)}))}return i}getRulesByCell(e,t,i){const n=[];for(let o of this.cfRules[e])for(let e of o.ranges)Bi(t,i,e.zone)&&n.push(o);return new Set(n.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t,i={useFixedReference:!1}){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e,i.useFixedReference)))}}mapToConditionalFormatInternal(e,t){const i={...t,ranges:t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)))};return i}addConditionalFormatting(e,t){const i=this.cfRules[t].slice(),n=i.findIndex((t=>t.id===e.id)),o=this.mapToConditionalFormatInternal(t,e);n>-1?i.splice(n,1,o):i.push(o),this.history.update("cfRules",t,i)}checkValidReordering(e,t,i){if(!this.cfRules[i])return 27;const n=this.cfRules[i].findIndex((t=>t.id===e));if(-1===n)return 72;const o="up"===t?n-1:n+1;return o<0||o>=this.cfRules[i].length?72:0}checkEmptyRange(e){return e.ranges.length?0:24}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber(2,["Between","NotBetween"]),this.checkOperatorArgsNumber(1,["BeginsWith","ContainsText","EndsWith","GreaterThan","GreaterThanOrEqual","LessThan","LessThanOrEqual","NotContains"]),this.checkOperatorArgsNumber(0,["IsEmpty","IsNotEmpty"]));case"ColorScaleRule":return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case"IconSetRule":return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)))}return 0}checkOperatorArgsNumber(e,t){if(e>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");return i=>{if(t.includes(i.operator)){const t=[],n=e=>void 0===e||""===e;return e>=1&&n(i.values[0])&&t.push(52),e>=2&&n(i.values[1])&&t.push(53),t.length?t:0}return 0}}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return 54;case"max":return 56;case"mid":return 55;case"upperInflectionPoint":return 57;case"lowerInflectionPoint":return 58}return 0}checkFormulaCompilation(e,t){if("formula"!==e.type)return 0;try{$g(e.value||"")}catch(e){switch(t){case"min":return 59;case"max":return 61;case"mid":return 60;case"upperInflectionPoint":return 62;case"lowerInflectionPoint":return 63}}return 0}checkThresholds(e){return this.batchValidations((t=>e(t.minimum,"min")),(t=>e(t.maximum,"max")),(t=>t.midpoint?e(t.midpoint,"mid"):0))}checkInflectionPoints(e){return this.batchValidations((t=>e(t.lowerInflectionPoint,"lowerInflectionPoint")),(t=>e(t.upperInflectionPoint,"upperInflectionPoint")))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,i=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(i)?49:0}checkMinBiggerThanMax(e){const t=e.minimum.value,i=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&hv(t)>=hv(i)?48:0}checkMidBiggerThanMax(e){var t;const i=null===(t=e.midpoint)||void 0===t?void 0:t.value,n=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&hv(i)>=hv(n)?50:0}checkMinBiggerThanMid(e){var t;const i=e.minimum.value,n=null===(t=e.midpoint)||void 0===t?void 0:t.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&hv(i)>=hv(n)?51:0}removeConditionalFormatting(e,t){const i=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==i){const e=this.cfRules[t].slice();e.splice(i,1),this.history.update("cfRules",t,e)}}reorderConditionalFormatting(e,t,i){const n=this.cfRules[i].findIndex((t=>t.id===e)),o="up"===t?n-1:n+1;if(!(o<0||o>=this.cfRules[i].length)&&-1!==n&&-1!==o){const e=[...this.cfRules[i]],t=e[n];e[n]=e[o],e[o]=t,this.history.update("cfRules",i,e)}}}dv.getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];class uv extends sv{constructor(){super(...arguments),this.figures={}}allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkFigureDuplicate(e.figure.id);case"UPDATE_FIGURE":case"DELETE_FIGURE":return this.checkFigureExists(e.sheetId,e.id);default:return 0}}beforeHandle(e){if("DELETE_SHEET"===e.type)this.getters.getFigures(e.sheetId).forEach((t=>{this.dispatch("DELETE_FIGURE",{id:t.id,sheetId:e.sheetId})}))}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":this.addFigure(e.figure,e.sheetId);break;case"UPDATE_FIGURE":const{type:t,sheetId:i,...n}=e,o=n;this.updateFigure(i,o);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId)}}updateFigure(e,t){if("id"in t)for(const[i,n]of Object.entries(t))switch(i){case"x":case"y":void 0!==n&&this.history.update("figures",e,t.id,i,Math.max(n,0));break;case"width":case"height":void 0!==n&&this.history.update("figures",e,t.id,i,n)}}addFigure(e,t){this.history.update("figures",t,e.id,e)}deleteSheet(e){this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){var i;return void 0===(null===(i=this.figures[e])||void 0===i?void 0:i[t])?71:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>null==t?void 0:t[e]))?83:0}getFigures(e){return Object.values(this.figures[e]||{}).filter(Xe)}getFigure(e,t){var i;return null===(i=this.figures[e])||void 0===i?void 0:i[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>{var i;return void 0!==(null===(i=this.figures[t])||void 0===i?void 0:i[e])}))}import(e){for(let t of e.sheets){const e={};t.figures.forEach((t=>{e[t.id]=t})),this.figures[t.id]=e}}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const i=void 0;t.figures.push({...e,data:i})}}exportForExcel(e){this.export(e)}}uv.getters=["getFigures","getFigure","getFigureSheetId"];class gv{constructor(e){this.filters=[],this.zone=e;const t=new Oi;this.id=t.smallUuid();for(const i of $e(e.left,e.right+1)){const e={...this.zone,left:i,right:i};this.filters.push(new pv(t.smallUuid(),e))}}get contentZone(){if(this.zone.bottom!==this.zone.top)return{...this.zone,top:this.zone.top+1}}getFilterId(e){var t;return null===(t=this.filters.find((t=>t.col===e)))||void 0===t?void 0:t.id}clone(){return new gv(this.zone)}}class pv{constructor(e,t){if(t.left!==t.right)throw new Error("Can only define a filter on a single column");this.id=e,this.zoneWithHeaders=t}get col(){return this.zoneWithHeaders.left}get filteredZone(){const e=this.zoneWithHeaders;if(e.bottom!==e.top)return{...e,top:e.top+1}}}class mv extends sv{constructor(){super(...arguments),this.tables={}}allowDispatch(e){switch(e.type){case"CREATE_FILTER_TABLE":if(!tn(...e.target))return 82;const t=Pi(...e.target),i=()=>this.getFilterTables(e.sheetId).some((e=>zi(e.zone,t)))?79:0,n=()=>{const i=this.getters.getMergesInZone(e.sheetId,t);for(let e of i)if(zi(t,e))return 81;return 0};return this.checkValidations(e,i,n);case"ADD_MERGE":for(let t of e.target)for(let i of this.getFilterTables(e.sheetId))if(zi(i.zone,t))return 81}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break;case"DUPLICATE_SHEET":const i={};for(const t of Object.values(this.tables[e.sheetId]||{}))if(t){const e=Ae(t);i[e.id]=e}this.history.update("tables",e.sheetIdTo,i);break;case"ADD_COLUMNS_ROWS":this.onAddColumnsRows(e);break;case"REMOVE_COLUMNS_ROWS":this.onDeleteColumnsRows(e);break;case"CREATE_FILTER_TABLE":{const t=Pi(...e.target),i=this.createFilterTable(t);this.history.update("tables",e.sheetId,i.id,i);break}case"REMOVE_FILTER_TABLE":{const t={};for(const i of this.getFilterTables(e.sheetId))e.target.every((e=>!Ui(e,i.zone)))&&(t[i.id]=i);this.history.update("tables",e.sheetId,t);break}case"UPDATE_CELL":{const t=e.sheetId;for(let i of this.getFilterTables(t))this.canUpdateCellCmdExtendTable(e,i)&&this.extendTableDown(t,i);break}}}getFilters(e){return this.getFilterTables(e).map((e=>e.filters)).flat()}getFilterTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(Xe):[]}getFilter(e,t,i){var n;return null===(n=this.getFilterTable(e,t,i))||void 0===n?void 0:n.filters.find((e=>e.col===t))}getFilterId(e,t,i){var n;return null===(n=this.getFilter(e,t,i))||void 0===n?void 0:n.id}getFilterTable(e,t,i){return this.getFilterTables(e).find((e=>Bi(t,i,e.zone)))}getFilterTablesInZone(e,t){return this.getFilterTables(e).filter((e=>Hi(e.zone,t)))}doesZonesContainFilter(e,t){for(const i of t)for(const t of this.getFilterTables(e))if(Ui(i,t.zone))return!0;return!1}onAddColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const i=Di(t.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),n=[];for(const i of t.filters){const t=Di(i.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);n.push(new pv(i.id,t))}if(n.length<qi(i).width){for(let e=i.left;e<=i.right;e++)n.find((t=>t.col===e))||n.push(new pv(this.uuidGenerator.smallUuid(),{...i,left:e,right:e}));n.sort(((e,t)=>e.col-t.col))}this.history.update("tables",e.sheetId,t.id,"zone",i),this.history.update("tables",e.sheetId,t.id,"filters",n)}}onDeleteColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){if("ROW"===e.dimension&&e.elements.includes(t.zone.top)){const i={...this.tables[e.sheetId]};delete i[t.id],this.history.update("tables",e.sheetId,i);continue}const i=Li(t.zone,"COL"===e.dimension?"left":"top",e.elements);if(i){if(Fi(i)!==Fi(t.zone)){const n=[];for(const i of t.filters){const t=Li(i.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.elements);t&&n.push(new pv(i.id,t))}this.history.update("tables",e.sheetId,t.id,"zone",i),this.history.update("tables",e.sheetId,t.id,"filters",n)}}else{const i={...this.tables[e.sheetId]};delete i[t.id],this.history.update("tables",e.sheetId,i)}}}createFilterTable(e){return new gv(e)}extendTableDown(e,t){const i={...t.zone,bottom:t.zone.bottom+1};this.history.update("tables",e,t.id,"zone",i);for(let i=0;i<t.filters.length;i++){const n=t.filters[i],o={...n.zoneWithHeaders,bottom:n.zoneWithHeaders.bottom+1};this.history.update("tables",e,t.id,"filters",i,"zoneWithHeaders",o)}}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:i,row:n},o){var s;if(!e)return;const r=o.zone;if(!(r.bottom+1===n&&i>=r.left&&i<=r.right))return!1;for(const e of $e(r.left,r.right+1)){if(null===(s=this.getters.getCell(t,e,n))||void 0===s?void 0:s.content)return!1;if(this.getters.getFilter(t,e,n))return!1;if(this.getters.isInMerge(t,e,n))return!1}return!0}import(e){for(const t of e.sheets)for(const e of t.filterTables||[]){const i=this.createFilterTable(Mi(e.range));this.history.update("tables",t.id,i.id,i)}}export(e){for(const t of e.sheets)for(const e of this.getFilterTables(t.id))t.filterTables.push({range:Fi(e.zone)})}exportForExcel(e){for(const t of e.sheets)for(const e of this.getFilterTables(t.id))1!==qi(e.zone).height&&t.filterTables.push({range:Fi(e.zone),filters:[]})}}mv.getters=["doesZonesContainFilter","getFilter","getFilters","getFilterTable","getFilterTables","getFilterTablesInZone","getFilterId"];class fv extends sv{constructor(){super(...arguments),this.sizes={}}handle(e){var t,i;switch(e.type){case"CREATE_SHEET":{const t=this.computeSheetSizes(e.sheetId),i={COL:t.COL.map((e=>({manualSize:void 0,computedSize:tt(e)}))),ROW:t.ROW.map((e=>({manualSize:void 0,computedSize:tt(e)})))};this.history.update("sizes",e.sheetId,i);break}case"DUPLICATE_SHEET":for(const t of this.sizes[e.sheetId].ROW)t.computedSize();for(const t of this.sizes[e.sheetId].COL)t.computedSize();this.history.update("sizes",e.sheetIdTo,Ae(this.sizes[e.sheetId]));break;case"DELETE_SHEET":const n={...this.sizes};delete n[e.sheetId],this.history.update("sizes",n);break;case"REMOVE_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];for(let i of[...e.elements].sort(((e,t)=>t-e)))t.splice(i,1);const i=ct(e.elements);t=t.map(((t,n)=>"ROW"===e.dimension&&n>=i?{manualSize:t.manualSize,computedSize:tt((()=>this.getRowTallestCellSize(e.sheetId,n)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];const i=nt(e.position,e.base),n=t[e.base],o=$e(0,e.quantity).map((()=>({manualSize:n.manualSize,computedSize:tt(n.computedSize())})));t.splice(i,0,...o),t=t.map(((t,i)=>"ROW"===e.dimension&&i>e.base+e.quantity?{manualSize:t.manualSize,computedSize:tt((()=>this.getRowTallestCellSize(e.sheetId,i)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"RESIZE_COLUMNS_ROWS":for(let t of e.elements)if("ROW"===e.dimension){const i=this.getRowTallestCellSize(e.sheetId,t);this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:tt(i)})}else this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:tt(e.size||_)});break;case"UPDATE_CELL":const o=null===(i=null===(t=this.sizes[e.sheetId])||void 0===t?void 0:t.ROW)||void 0===i?void 0:i[e.row];if(o&&!o.manualSize){const{sheetId:t,row:i}=e;this.history.update("sizes",t,"ROW",i,"computedSize",tt((()=>this.getRowTallestCellSize(t,i))))}break;case"ADD_MERGE":case"REMOVE_MERGE":for(let t of e.target)for(let i of $e(t.top,t.bottom+1)){const t=this.getRowTallestCellSize(e.sheetId,i);t!==this.getRowSize(e.sheetId,i)&&this.history.update("sizes",e.sheetId,"ROW",i,"computedSize",tt(t))}}}getColSize(e,t){return this.getHeaderSize(e,"COL",t)}getRowSize(e,t){return this.getHeaderSize(e,"ROW",t)}getHeaderSize(e,t,i){var n,o,s,r;return Math.round((null===(o=null===(n=this.sizes[e])||void 0===n?void 0:n[t][i])||void 0===o?void 0:o.manualSize)||(null===(r=null===(s=this.sizes[e])||void 0===s?void 0:s[t][i])||void 0===r?void 0:r.computedSize())||this.getDefaultHeaderSize(t))}computeSheetSizes(e){var t,i;const n={COL:[],ROW:[]};for(let t of $e(0,this.getters.getNumberCols(e)))n.COL.push(this.getHeaderSize(e,"COL",t));for(let o of $e(0,this.getters.getNumberRows(e))){let s=null===(i=null===(t=this.sizes[e])||void 0===t?void 0:t.ROW)||void 0===i?void 0:i[o].manualSize;if(!s){s=this.getRowTallestCellSize(e,o)}n.ROW.push(s)}return n}getDefaultHeaderSize(e){return"COL"===e?_:F}getCellHeight(e,t,i){const n=this.getters.getMerge(e,t,i);if(n&&n.bottom!==n.top)return F;const o=this.getters.getCell(e,t,i);return(null==(s=null==o?void 0:o.style)?void 0:s.fontSize)?(r||1)*(ke(s)+P)-P+2*U:F;var s,r}getRowTallestCellSize(e,t){const i=this.getters.getRowCells(e,t);let n=0;for(let t=0;t<i.length;t++){const o=this.getters.getCellById(i[t]);if(!o)continue;const{col:s,row:r}=this.getters.getCellPosition(o.id),a=this.getCellHeight(e,s,r);a>n&&a>F&&(n=a)}return n<=F?F:n}import(e){for(let t of e.sheets){const e={COL:[],ROW:[]};for(let[i,n]of Object.entries(t.rows))n.size&&(e.ROW[i]=n.size);for(let[i,n]of Object.entries(t.cols))n.size&&(e.COL[i]=n.size);const i=this.computeSheetSizes(t.id);this.sizes[t.id]={COL:i.COL.map(((t,i)=>({manualSize:e.COL[i],computedSize:tt(t)}))),ROW:i.ROW.map(((t,i)=>({manualSize:e.ROW[i],computedSize:tt(t)})))}}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){var i,n;for(let o of e.sheets){void 0===o.rows&&(o.rows={});for(let e of $e(0,this.getters.getNumberRows(o.id)))(t||(null===(i=this.sizes[o.id].ROW[e])||void 0===i?void 0:i.manualSize))&&(o.rows[e]={...o.rows[e],size:this.getRowSize(o.id,e)});void 0===o.cols&&(o.cols={});for(let e of $e(0,this.getters.getNumberCols(o.id)))(t||(null===(n=this.sizes[o.id].COL[e])||void 0===n?void 0:n.manualSize))&&(o.cols[e]={...o.cols[e],size:this.getColSize(o.id,e)})}}}fv.getters=["getRowSize","getColSize"];class vv extends sv{constructor(){super(...arguments),this.hiddenHeaders={}}allowDispatch(e){switch(e.type){case"HIDE_COLUMNS_ROWS":{if(!this.getters.tryGetSheet(e.sheetId))return 27;const t="COL"===e.dimension?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),i="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=i?67:ct(e.elements)<0||lt(e.elements)>i?87:0}case"REMOVE_COLUMNS_ROWS":return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?8:0:27}return 0}handle(e){switch(e.type){case"CREATE_SHEET":const t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update("hiddenHeaders",e.sheetId,t);break;case"DUPLICATE_SHEET":this.history.update("hiddenHeaders",e.sheetIdTo,Ae(this.hiddenHeaders[e.sheetId]));break;case"DELETE_SHEET":this.history.update("hiddenHeaders",e.sheetId,void 0);break;case"REMOVE_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let i of[...e.elements].sort(((e,t)=>t-e)))t.splice(i,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]],i=nt(e.position,e.base);t.splice(i,0,...Array(e.quantity).fill(!1)),this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"HIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!0);break;case"UNHIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!1)}}checkElementsIncludeAllVisibleHeaders(e,t,i){return st(i,this.getAllVisibleHeaders(e,t))}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]}getHiddenColsGroups(e){const t=[[]],i=this.hiddenHeaders[e].COL;for(let e=0;e<i.length;e++){i[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getHiddenRowsGroups(e){const t=[[]],i=this.hiddenHeaders[e].ROW;for(let e=0;e<i.length;e++){i[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getAllVisibleHeaders(e,t){return $e(0,this.hiddenHeaders[e][t].length).filter((i=>!this.hiddenHeaders[e][t][i]))}import(e){var t,i;for(let n of e.sheets){this.hiddenHeaders[n.id]={COL:[],ROW:[]};for(let e=0;e<n.rowNumber;e++)this.hiddenHeaders[n.id].ROW[e]=Boolean(null===(t=n.rows[e])||void 0===t?void 0:t.isHidden);for(let e=0;e<n.colNumber;e++)this.hiddenHeaders[n.id].COL[e]=Boolean(null===(i=n.cols[e])||void 0===i?void 0:i.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let i of e.sheets){void 0===i.rows&&(i.rows={});for(let e=0;e<this.getters.getNumberRows(i.id);e++)(t||this.hiddenHeaders[i.id].ROW[e])&&(void 0===i.rows[e]&&(i.rows[e]={}),i.rows[e].isHidden=this.hiddenHeaders[i.id].ROW[e]);void 0===i.cols&&(i.cols={});for(let e=0;e<this.getters.getNumberCols(i.id);e++)(t||this.hiddenHeaders[i.id].COL[e])&&(void 0===i.cols[e]&&(i.cols[e]={}),i.cols[e].isHidden=this.hiddenHeaders[i.id].COL[e])}}}vv.getters=["checkElementsIncludeAllVisibleHeaders","getHiddenColsGroups","getHiddenRowsGroups","isRowHiddenByUser","isColHiddenByUser"];class bv extends sv{constructor(){super(...arguments),this.nextId=1,this.merges={},this.mergeCellMap={}}allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;for(const i of Object.values(t).filter(Xe))this.addMerge(e.sheetIdTo,i.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(e.sheetId,t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){const i=t?[t]:Object.keys(this.merges);for(const t of i)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(Xe)}getMerge(e,t,i){var n;const o=this.mergeCellMap[e],s=o?t in o&&(null===(n=o[t])||void 0===n?void 0:n[i]):void 0;return s?this.getMergeById(e,s):void 0}getMergesInZone(e,t){var i;const n=this.mergeCellMap[e];if(!n)return[];const o=new Set;for(const{col:e,row:s}of ji(t)){const t=null===(i=n[e])||void 0===i?void 0:i[s];t&&o.add(t)}return Array.from(o).map((t=>this.getMergeById(e,t))).filter(Xe)}doesIntersectMerge(e,t){const{left:i,right:n,top:o,bottom:s}=t;for(let t=o;t<=s;t++)for(let o=i;o<=n;o++)if(this.getMerge(e,o,t))return!0;return!1}doesColumnsHaveCommonMerges(e,t,i){const n=this.getters.getSheet(e);for(let o=0;o<this.getters.getNumberRows(e);o++)if(this.isInSameMerge(n.id,t,o,i,o))return!0;return!1}doesRowsHaveCommonMerges(e,t,i){const n=this.getters.getSheet(e);for(let o=0;o<=this.getters.getNumberCols(e);o++)if(this.isInSameMerge(n.id,o,t,o,i))return!0;return!1}expandZone(e,t){let{left:i,right:n,top:o,bottom:s}=t,r={left:i,right:n,top:o,bottom:s};for(let t in this.merges[e]){const i=this.getMergeById(e,parseInt(t));i&&zi(i,r)&&(r=Pi(i,r))}return Vi(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,i,n,o){const s=this.getMerge(e,t,i),r=this.getMerge(e,n,o);return!(!s||!r)&&Vi(s,r)}isInMerge(e,t,i){var n;const o=this.mergeCellMap[e];return!!o&&(t in o&&Boolean(null===(n=o[t])||void 0===n?void 0:n[i]))}getMainCellPosition(e,t,i){if(!this.isInMerge(e,t,i))return{col:t,row:i};const n=this.getMerge(e,t,i).topLeft;return{col:n.col,row:n.row}}getBottomLeftCell(e,t,i){if(!this.isInMerge(e,t,i))return{col:t,row:i};const{bottom:n,left:o}=this.getMerge(e,t,i);return{col:o,row:n}}isMergeHidden(e,t){const i=this.getters.getHiddenColsGroups(e),n=this.getters.getHiddenRowsGroups(e);for(let e of i)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of n)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const i=this.getMerge(e,t.left,t.top);if(i)return Vi(t,i);const{width:n,height:o}=qi(t);return 1===n&&1===o}isMergeDestructive(e,t){let{left:i,right:n,top:o,bottom:s}=t;n=Me(n,0,this.getters.getNumberCols(e)-1),s=Me(s,0,this.getters.getNumberRows(e)-1);for(let t=o;t<=s;t++)for(let s=i;s<=n;s++)if(s!==i||t!==o){const i=this.getters.getCell(e,s,t);if(i&&!i.isEmpty())return!0}return!1}getMergeById(e,t){var i;const n=null===(i=this.merges[e])||void 0===i?void 0:i[t];return void 0!==n?Cv(t,n):void 0}checkDestructiveMerge({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;return t.some((t=>this.isMergeDestructive(e,t)))?3:0}checkOverlap({target:e}){for(const t of e)for(const i of e)if(t!==i&&zi(t,i))return 66;return 0}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;const{xSplit:i,ySplit:n}=this.getters.getPaneDivisions(e);for(const e of t)if(e.left<i&&e.right>=i||e.top<n&&e.bottom>=n)return 76;return 0}checkMergedContentUpdate(e){const{col:t,row:i,sheetId:n,content:o}=e;if(void 0===o)return 0;const{col:s,row:r}=this.getMainCellPosition(n,t,i);return s===t&&r===i?0:4}checkMergeExists(e){const{sheetId:t,target:i}=e;for(const e of i){const{left:i,top:n}=e,o=this.getMerge(t,i,n);if(void 0===o||!Vi(e,o))return 5}return 0}addMerge(e,t){let{left:i,right:n,top:o,bottom:s}=t;n=Me(n,0,this.getters.getNumberCols(e)-1),s=Me(s,0,this.getters.getNumberRows(e)-1);if(Vt(i,o)===Vt(n,s))return;const r=this.getters.getCell(e,i,o);let a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,Fi({left:i,top:o,right:n,bottom:s})));let l=new Set;for(let t=o;t<=s;t++)for(let s=i;s<=n;s++){s===i&&t===o||this.dispatch("UPDATE_CELL",{sheetId:e,col:s,row:t,style:r?r.style:null,content:""});const n=this.getMerge(e,s,t);n&&l.add(n.id),this.history.update("mergeCellMap",e,s,t,a)}for(let t of l){const{top:i,bottom:n,left:o,right:s}=this.getMergeById(e,t);for(let t=i;t<=n;t++)for(let i=o;i<=s;i++){const n=this.getMerge(e,i,t);n&&n.id===a||(this.history.update("mergeCellMap",e,i,t,void 0),this.dispatch("CLEAR_CELL",{sheetId:e,col:i,row:t}))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:i,top:n,bottom:o,right:s}=t,r=this.getMerge(e,i,n);if(void 0!==r&&Vi(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=n;t<=o;t++)for(let n=i;n<=s;n++)this.history.update("mergeCellMap",e,n,t,void 0)}}applyRangeChangeOnSheet(e,t){const i=Object.entries(this.merges[e]||{});for(const[n,o]of i)if(o){const i=o.zone,s=t(o);switch(s.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,i);break;default:const{width:t,height:o}=qi(s.range.zone);1===t&&1===o?this.removeMerge(e,i):this.history.update("merges",e,parseInt(n,10),s.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:i,row:n}of ji(t))this.history.update("mergeCellMap",e,i,n,t.id)}import(e){const t=e.sheets||[];for(let e of t)this.history.update("merges",e.id,{}),this.history.update("mergeCellMap",e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let i of t)this.addMerge(e,Mi(i))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...Sv(e))}}exportForExcel(e){this.export(e)}}function Sv(e){return Object.entries(e).map((([e,t])=>t?Cv(parseInt(e,10),t):void 0)).filter(Xe).map((e=>Vt(e.left,e.top)+":"+Vt(e.right,e.bottom)))}function Cv(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}bv.getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge"];class Ev extends sv{constructor(){super(...arguments),this.sheetIdsMapName={},this.orderedSheetIds=[],this.sheets={},this.cellPosition={}}allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZones)(e);if(0!==t)return t;switch(e.type){case"HIDE_SHEET":return 1===this.getVisibleSheetIds().length?9:0;case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"DUPLICATE_SHEET":return this.sheets[e.sheetIdTo]?12:0;case"MOVE_SHEET":const t=this.orderedSheetIds.indexOf(e.sheetId);if("left"===e.direction){return this.orderedSheetIds.slice(0,t).map((e=>!this.isSheetVisible(e))).every((e=>e))?14:0}return this.orderedSheetIds.slice(t+1).map((e=>!this.isSheetVisible(e))).every((e=>e))?14:0;case"RENAME_SHEET":return this.isRenameAllowed(e);case"DELETE_SHEET":return this.getVisibleSheetIds().length>1?0:9;case"ADD_COLUMNS_ROWS":const i="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return e.base<0||e.base>=i?87:e.quantity<=0?88:0;case"REMOVE_COLUMNS_ROWS":{const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return ct(e.elements)<0||lt(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.direction);break;case"RENAME_SHEET":this.renameSheet(this.sheets[e.sheetId],e.name);break;case"HIDE_SHEET":this.hideSheet(e.sheetId);break;case"SHOW_SHEET":this.showSheet(e.sheetId);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case"UPDATE_CELL_POSITION":this.updateCellPosition(e);break;case"FREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,e.quantity,"COL");break;case"FREEZE_ROWS":this.setPaneDivisions(e.sheetId,e.quantity,"ROW");break;case"UNFREEZE_ROWS":this.setPaneDivisions(e.sheetId,0,"ROW");break;case"UNFREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,0,"COL");break;case"UNFREEZE_COLUMNS_ROWS":this.setPaneDivisions(e.sheetId,0,"COL"),this.setPaneDivisions(e.sheetId,0,"ROW")}}import(e){var t,i;for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let n of e.sheets){const e=n.name||o("Sheet")+(Object.keys(this.sheets).length+1),{colNumber:s,rowNumber:r}=this.getImportedSheetSize(n),a={id:n.id,name:e,numberOfCols:s,rows:Ti(r),areGridLinesVisible:void 0===n.areGridLinesVisible||n.areGridLinesVisible,isVisible:n.isVisible,panes:{xSplit:(null===(t=n.panes)||void 0===t?void 0:t.xSplit)||0,ySplit:(null===(i=n.panes)||void 0===i?void 0:i.ySplit)||0}};this.orderedSheetIds.push(a.id),this.sheets[a.id]=a}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(Xe).map((e=>{const t=this.sheets[e],i={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},conditionalFormats:[],figures:[],filterTables:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible};return(t.panes.xSplit||t.panes.ySplit)&&(i.panes=t.panes),i}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}getCellsInZone(e,t){return ji(t).map((({col:t,row:i})=>this.getCell(e,t,i)))}tryGetSheetName(e){var t;return null===(t=this.tryGetSheet(e))||void 0===t?void 0:t.name}getSheetIdByName(e){if(e){const t=Oe(e);for(const e in this.sheetIdsMapName)if(Ai(e,t))return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}getEvaluationSheets(){return this.sheets}doesHeaderExist(e,t,i){return"COL"===t?i>=0&&i<this.getNumberCols(e):i>=0&&i<this.getNumberRows(e)}getRow(e,t){const i=this.getSheet(e).rows[t];if(!i)throw new Error(`Row ${i} not found.`);return i}getCell(e,t,i){var n;const o=this.tryGetSheet(e),s=null===(n=null==o?void 0:o.rows[i])||void 0===n?void 0:n.cells[t];if(void 0!==s)return this.getters.getCellById(s)}getColCells(e,t){return this.getSheet(e).rows.map((e=>e.cells[t])).filter(Xe).map((e=>this.getters.getCellById(e))).filter(Xe)}getColsZone(e,t,i){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:i}}getRowCells(e,t){var i;return Object.values(null===(i=this.getSheet(e).rows[t])||void 0===i?void 0:i.cells).filter(Xe)}getRowsZone(e,t,i){return{top:t,bottom:i,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){let t=1;const i=this.orderedSheetIds.map(this.getSheetName.bind(this));let n=`${e}${t}`;for(;i.includes(n);)n=`${e}${t}`,t++;return n}getSheetSize(e){return{height:this.getNumberRows(e),width:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,i){const n={...this.getPaneDivisions(e)};"COL"===i?n.xSplit=t:"ROW"===i&&(n.ySplit=t),this.history.update("sheets",e,"panes",n)}checkElementsIncludeAllNonFrozenHeaders(e,t,i){const n=this.getters.getPaneDivisions(e),o="ROW"===t?n.ySplit:n.xSplit,s=this.getters.getNumberHeaders(e,t);if(!o)return!1;return st(i,$e(o,s))}isEmpty(e,t){return this.getCellsInZone(e,t).flat().every((e=>!e||e.isEmpty()))}updateCellPosition(e){const{sheetId:t,cellId:i,col:n,row:o}=e;i?this.setNewPosition(i,t,n,o):this.clearPosition(t,n,o)}setNewPosition(e,t,i,n){const o=this.cellPosition[e];o&&this.clearPosition(t,o.col,o.row),this.history.update("cellPosition",e,{row:n,col:i,sheetId:t}),this.history.update("sheets",t,"rows",n,"cells",i,e)}clearPosition(e,t,i){var n;const o=null===(n=this.sheets[e])||void 0===n?void 0:n.rows[i].cells[t];o&&(this.history.update("cellPosition",o,void 0),this.history.update("sheets",e,"rows",i,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}clearZones(e,t){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++){this.sheets[e].rows[n].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:n})}}createSheet(e,t,i,n,o){const s={id:e,name:t,numberOfCols:i,rows:Ti(n),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},r=this.orderedSheetIds.slice();r.splice(o,0,s.id);const a=this.sheets;return this.history.update("orderedSheetIds",r),this.history.update("sheets",Object.assign({},a,{[s.id]:s})),s}moveSheet(e,t){const i=this.orderedSheetIds.slice(),n=i.findIndex((t=>t===e)),o=i.splice(n,1);let s="left"===t?this.findIndexOfPreviousVisibleSheet(n-1,i):this.findIndexOfNextVisibleSheet(n+1,i);void 0===s&&(s=i.length),i.splice(s,0,o[0]),this.history.update("orderedSheetIds",i)}findIndexOfPreviousVisibleSheet(e,t){for(;e>=0&&!this.isSheetVisible(t[e]);)e--;if(-1===e)throw new Error("There is no previous visible sheet");return e}findIndexOfNextVisibleSheet(e,t){for(;e<t.length&&!this.isSheetVisible(t[e]);)e++;if(e!==t.length-1||this.isSheetVisible(t[e-1]))return e}checkSheetName(e){const{orderedSheetIds:t,sheets:i}=this,n=e.name&&e.name.trim().toLowerCase();return t.find((e=>{var t;return Ai(null===(t=i[e])||void 0===t?void 0:t.name,n)}))?11:te.test(n)?13:0}checkSheetPosition(e){const{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?15:0}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?0:75}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?0:75}checkRowFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let i of t)if(i.top<e.quantity&&e.quantity<=i.bottom)return 66;return 0}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let i of t)if(i.left<e.quantity&&e.quantity<=i.right)return 66;return 0}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):10}renameSheet(e,t){const i=e.name;this.history.update("sheets",e.id,"name",t.trim());const n=Object.assign({},this.sheetIdsMapName);n[t]=e.id,delete n[i],this.history.update("sheetIdsMapName",n)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t){const i=this.getSheet(e),n=this.getDuplicateSheetName(i.name),o=Ae(i);o.id=t,o.name=n;for(let e=0;e<=o.numberOfCols;e++)for(let t=0;t<=o.rows.length;t++)o.rows[t]&&(o.rows[t].cells[e]=void 0);const s=this.orderedSheetIds.slice(),r=s.indexOf(e);s.splice(r+1,0,o.id),this.history.update("orderedSheetIds",s),this.history.update("sheets",Object.assign({},this.sheets,{[o.id]:o}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:i}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:o.id,col:e,row:i,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIdsMapName);a[o.name]=o.id,this.history.update("sheetIdsMapName",a)}getDuplicateSheetName(e){let t=1;const i=this.orderedSheetIds.map(this.getSheetName.bind(this)),n=s("Copy of %s",e);let o=n.toString();for(;i.includes(o);)o=`${n} (${t})`,t++;return o}deleteSheet(e){const t=e.name,i=Object.assign({},this.sheets);delete i[e.id],this.history.update("sheets",i);const n=this.orderedSheetIds.slice(),o=n.indexOf(e.id);n.splice(o,1),this.history.update("orderedSheetIds",n);const s=Object.assign({},this.sheetIdsMapName);delete s[t],this.history.update("sheetIdsMapName",s)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(let i of t)this.moveCellOnColumnsDeletion(e,i);const i=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",i-t.length);const n=t.filter((t=>t<e.panes.xSplit)).length;n&&this.setPaneDivisions(e.id,e.panes.xSplit-n,"COL")}removeRows(e,t){t.sort(((e,t)=>t-e));for(let i of Le(t)){const t=i[i.length-1],n=i[0];this.moveCellOnRowsDeletion(e,t,n),this.updateRowsStructureOnDeletion(e,t,n)}const i=t.filter((t=>t<e.panes.ySplit)).length;i&&this.setPaneDivisions(e.id,e.panes.ySplit-i,"ROW")}addColumns(e,t,i,n){const o="before"===i?t:t+1;this.moveCellsOnAddition(e,o,n,"columns");const s=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",s+n),o<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+n,"COL")}addRows(e,t,i,n){const o="before"===i?t:t+1;this.addEmptyRows(e,n),this.moveCellsOnAddition(e,o,n,"rows"),o<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+n,"ROW")}moveCellOnColumnsDeletion(e,t){for(let i=0;i<e.rows.length;i++){const n=e.rows[i];for(let o in n.cells){const s=Number(o),r=n.cells[o];r&&(s===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:s,row:i}),s>t&&this.setNewPosition(r,e.id,s-1,i))}}}moveCellsOnAddition(e,t,i,n){const o=[];for(let s=0;s<e.rows.length;s++){const r=e.rows[s];if("rows"!==n||s>=t)for(let a in r.cells){const l=Number(a),c=r.cells[a];c&&("rows"===n||l>=t)&&o.push({sheetId:e.id,cellId:c,col:l+("columns"===n?i:0),row:s+("rows"===n?i:0),type:"UPDATE_CELL_POSITION"})}}for(let e of o.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,i){const n=i-t+1;for(let o=0;o<e.rows.length;o++){const s=e.rows[o];if(o>=t&&o<=i)for(let t in s.cells){const i=Number(t);s.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:i,row:o})}if(o>i)for(let t in s.cells){const i=Number(t),r=s.cells[t];r&&this.setNewPosition(r,e.id,i,o-n)}}}updateRowsStructureOnDeletion(e,t,i){const n=[],o=e.rows.map((e=>e.cells)).reverse();for(let s in e.rows){const e=Number(s);e>=t&&e<=i||n.push({cells:o.pop()})}this.history.update("sheets",e.id,"rows",n)}addEmptyRows(e,t){const i=e.rows.slice();for(let e=0;e<t;e++)i.push({cells:{}});this.history.update("sheets",e.id,"rows",i)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(Ut);let i=e.rowNumber,n=e.colNumber;for(let{col:e,row:o}of t)i=Math.max(i,o+1),n=Math.max(n,e+1);return{rowNumber:i,colNumber:n}}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?27:"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?12:0}checkZones(e){const t=[];if("zone"in e&&t.push(e.zone),"target"in e&&Array.isArray(e.target)&&t.push(...e.target),"ranges"in e&&Array.isArray(e.ranges)){if(e.ranges.some((e=>!this.getters.tryGetSheet(e._sheetId))))return 27;t.push(...e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone)))}if(!t.every(_i))return 25;if(t.length&&"sheetId"in e){const i=this.getSheetZone(e.sheetId);return t.every((e=>Hi(e,i)))?0:18}return 0}}Ev.getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheetIds","getVisibleSheetIds","isSheetVisible","getEvaluationSheets","doesHeaderExist","getCell","getCellsInZone","getCellPosition","getColCells","getColsZone","getRowCells","getRowsZone","getNumberCols","getNumberRows","getNumberHeaders","getGridLinesVisibility","getNextSheetName","isEmpty","getSheetSize","getSheetZone","getPaneDivisions","checkElementsIncludeAllNonFrozenHeaders"];class wv{constructor(e,t,i){this.index=0,this.cells=e,this.getters=t,this.direction=i}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:i,tooltip:n}=an.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:i,tooltip:n,origin:{col:e.data.col,row:e.data.row}}}}class yv extends Bg{constructor(){super(...arguments),this.lastCellSelected={}}allowDispatch(e){switch(e.type){case"AUTOFILL_SELECT":const t=this.getters.getActiveSheetId();return this.lastCellSelected.col=-1===e.col?this.lastCellSelected.col:Me(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:Me(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?0:46;case"AUTOFILL_AUTO":const i=this.getters.getSelectedZone();return i.top===i.bottom?0:1}return 0}handle(e){switch(e.type){case"AUTOFILL":this.autofill(!0);break;case"AUTOFILL_SELECT":this.select(e.col,e.row);break;case"AUTOFILL_AUTO":this.autofillAuto();break;case"AUTOFILL_CELL":this.autoFillMerge(e.originCol,e.originRow,e.col,e.row);const t=this.getters.getActiveSheetId();this.dispatch("UPDATE_CELL",{sheetId:t,col:e.col,row:e.row,style:e.style||null,content:e.content||"",format:e.format||""}),this.dispatch("SET_BORDER",{sheetId:t,col:e.col,row:e.row,border:e.border})}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),i=this.autofillZone;switch(this.direction){case"down":for(let n=t.left;n<=t.right;n++){const o=[];for(let e=t.top;e<=t.bottom;e++)o.push(Vt(n,e));const s=this.createGenerator(o);for(let t=i.top;t<=i.bottom;t++)this.computeNewCell(s,n,t,e)}break;case"up":for(let n=t.left;n<=t.right;n++){const o=[];for(let e=t.bottom;e>=t.top;e--)o.push(Vt(n,e));const s=this.createGenerator(o);for(let t=i.bottom;t>=i.top;t--)this.computeNewCell(s,n,t,e)}break;case"left":for(let n=t.top;n<=t.bottom;n++){const o=[];for(let e=t.right;e>=t.left;e--)o.push(Vt(e,n));const s=this.createGenerator(o);for(let t=i.right;t>=i.left;t--)this.computeNewCell(s,t,n,e)}break;case"right":for(let n=t.top;n<=t.bottom;n++){const o=[];for(let e=t.left;e<=t.right;e++)o.push(Vt(e,n));const s=this.createGenerator(o);for(let t=i.left;t<=i.right;t++)this.computeNewCell(s,t,n,e)}}e&&(this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0)}select(e,t){const i=this.getters.getSelectedZone();if(Bi(e,t,i))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,i.top-1,i.left,i.right),this.steps=i.top-t;break;case"down":this.saveZone(i.bottom+1,t,i.left,i.right),this.steps=t-i.bottom;break;case"left":this.saveZone(i.top,i.bottom,e,i.left-1),this.steps=i.left-e;break;case"right":this.saveZone(i.top,i.bottom,i.right+1,e),this.steps=e-i.right}this.autofill(!1)}}autofillAuto(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let i=e.left,n=e.bottom;if(i>0){let e=this.getters.getCell(t,i-1,n);for(;e&&!e.isEmpty();)n+=1,e=this.getters.getCell(t,i-1,n)}if(n===e.bottom&&(i=e.right,i<=this.getters.getNumberCols(t))){let e=this.getters.getCell(t,i+1,n);for(;e&&!e.isEmpty();)n+=1,e=this.getters.getCell(t,i+1,n)}n!==e.bottom&&(this.select(e.left,n-1),this.autofill(!0))}computeNewCell(e,t,i,n){const{cellData:o,tooltip:s,origin:r}=e.next(),{content:a,style:l,border:c,format:h}=o;this.tooltip=s,n&&this.dispatch("AUTOFILL_CELL",{originCol:r.col,originRow:r.row,col:t,row:i,content:a,style:l,border:c,format:h})}getRule(e,t){const i=Sn.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((i=>i.condition(e,t)));return i&&this.direction&&i.generateRule(e,t,this.direction)}createGenerator(e){const t=[],i=[],n=this.getters.getActiveSheetId();for(let t of e){const{col:e,row:o}=Ut(t),s=this.getters.getCell(n,e,o);i.push({col:e,row:o,cell:s,sheetId:n})}const o=i.map((e=>e.cell));for(let e of i){let i={type:"COPY_MODIFIER"};if(e&&e.cell){i=this.getRule(e.cell,o)||i}const{sheetId:n,col:s,row:r}=e,a=this.getters.getCellBorder(n,s,r)||void 0;t.push({data:{...e,border:a},rule:i})}return new wv(t,this.getters,this.direction)}saveZone(e,t,i,n){this.autofillZone={top:e,bottom:t,left:i,right:n}}getDirection(e,t){const i=this.getters.getSelectedZone(),n={up:{number:i.top-t,value:"up"},down:{number:t-i.bottom,value:"down"},left:{number:i.left-e,value:"left"},right:{number:e-i.right,value:"right"}};if(1===Object.values(n).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(n).find((e=>e.number>0?1:0)).value;const o=n.up.number>0?"up":"down",s=n.left.number>0?"left":"right";return Math.abs(n[o].number)>=Math.abs(n[s].number)?n[o].value:n[s].value}autoFillMerge(e,t,i,n){const o=this.getters.getActiveSheet();if(this.getters.isInMerge(o.id,i,n)&&!this.getters.isInMerge(o.id,e,t)){const e=this.getters.getMerge(o.id,i,n);e&&this.dispatch("REMOVE_MERGE",{sheetId:o.id,target:[e]})}const s=this.getters.getMerge(o.id,e,t);(null==s?void 0:s.topLeft.col)===e&&(null==s?void 0:s.topLeft.row)===t&&this.dispatch("ADD_MERGE",{sheetId:o.id,target:[{top:n,bottom:n+s.bottom-s.top,left:i,right:i+s.right-s.left}]})}drawGrid(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:i}=e,{x:n,y:o,width:s,height:r}=this.getters.getVisibleRect(this.autofillZone);s>0&&r>0&&(t.strokeStyle="black",t.lineWidth=i,t.setLineDash([3]),t.strokeRect(n,o,s,r),t.setLineDash([]))}}yv.layers=[6],yv.getters=["getAutofillTooltip"];class xv extends Bg{handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:i}=this.getters.getSelection();for(const n of t){const t=this.getAutomaticSums(e,n,i.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,i){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,i):this.sumData(e,t)}sumData(e,t){const i=this.dimensionsToSum(e,t),n=this.sumDimensions(e,t,i).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return i.has("ROW")&&i.has("COL")&&n.push(this.sumTotal(t)),n}sumAdjacentData(e,t,i){const{col:n,row:o}=Bi(i.col,i.row,t)?i:{col:t.left,row:t.top},s=this.findAdjacentData(e,n,o);return s?this.getters.isSingleCellOrMerge(e,t)||Zi(Pi(s,t))?[{position:{col:n,row:o},zone:s}]:this.sumDimensions(e,Pi(s,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,i){const n=this.getters.getSheet(e),o=this.getters.getMainCellPosition(e,t,i),s=this.findSuitableZoneToSum(n,o.col,o.row);if(s)return this.getters.expandZone(e,s)}findSuitableZoneToSum(e,t,i){const n=this.getters.getCell(e.id,t,i-1),o=this.getters.getCell(e.id,t-1,i);if(this.isNumber(o)&&!this.isNumber(n))return this.findHorizontalZone(e,t,i);const s=this.findVerticalZone(e,t,i);if(this.isZoneValid(s))return s;const r=this.findHorizontalZone(e,t,i);return this.isZoneValid(r)?r:void 0}findVerticalZone(e,t,i){const n={top:0,bottom:i-1,left:t,right:t},o=this.reduceZoneStart(e,n,n.bottom);return{...n,top:o}}findHorizontalZone(e,t,i){const n={top:i,bottom:i,left:0,right:t-1},o=this.reduceZoneStart(e,n,n.right);return{...n,left:o}}reduceZoneStart(e,t,i){const n=this.getters.getCellsInZone(e.id,t),o=$e(i,-1,-1),s=lt(o.filter((e=>{var t;return n[e]&&!(null===(t=n[e])||void 0===t?void 0:t.isAutoSummable)}))),r=Le(o.filter((e=>this.isNumber(n[e]))))[0]||[];return lt(r)<s?1/0:ct(r)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){var t;return(null==e?void 0:e.evaluated.type)===ln.number&&!(null===(t=e.evaluated.format)||void 0===t?void 0:t.match(Y))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){const i=new Set;return Zi(t)?(i.add(1===qi(t).width?"COL":"ROW"),i):(this.lastColIsEmpty(e,t)&&i.add("ROW"),this.lastRowIsEmpty(e,t)&&i.add("COL"),0===i.size&&i.add("COL"),i)}sumDimensions(e,t,i){return[...i.has("COL")?this.sumColumns(t,e):[],...i.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:i}=e;return{position:{col:i,row:t},zone:{...e,top:t,right:i-1}}}sumColumns(e,t){const i=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,i.bottom-1)},ji(i).map((t=>({position:t,zone:{...e,right:t.col,left:t.col}})))}sumRows(e,t){const i=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,i.right-1)},ji(i).map((t=>({position:t,zone:{...e,top:t.row,bottom:t.row}})))}dispatchCellUpdates(e,t){for(const i of t){const{col:t,row:n}=i.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,content:`=SUM(${this.getters.zoneToXC(e,i.zone)})`})}}nextEmptyRow(e,t){let i=t.bottom+1;const{left:n,right:o}=t;for(;!this.getters.isEmpty(e,{bottom:i,top:i,left:n,right:o});)i++;return{...t,top:i,bottom:i}}nextEmptyCol(e,t){let i=t.right+1;const{top:n,bottom:o}=t;for(;!this.getters.isEmpty(e,{left:i,right:i,top:n,bottom:o});)i++;return{...t,left:i,right:i}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}xv.getters=["getAutomaticSums"];class Rv extends Bg{allowDispatch(e){if("OPEN_CELL_POPOVER"===e.type){try{Jn.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,type:e.popoverType}}}getCellPopover({col:e,row:t}){var i,n;const o=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(o,this.persistentPopover.col,this.persistentPopover.row)){const e=this.getters.getMainCellPosition(o,this.persistentPopover.col,this.persistentPopover.row),t=null===(n=(i=Jn.get(this.persistentPopover.type)).onOpen)||void 0===n?void 0:n.call(i,e,this.getters);return(null==t?void 0:t.isOpen)?{...t,...this.computePopoverProps(this.persistentPopover,t.cellCorner)}:{isOpen:!1}}if(void 0===e||void 0===t||!this.getters.isVisibleInViewport(o,e,t))return{isOpen:!1};const s=this.getters.getMainCellPosition(o,e,t),r=Jn.getAll().map((e=>{var t;return null===(t=e.onHover)||void 0===t?void 0:t.call(e,s,this.getters)})).find((e=>null==e?void 0:e.isOpen));return(null==r?void 0:r.isOpen)?{...r,...this.computePopoverProps(s,r.cellCorner)}:{isOpen:!1}}getPersistentPopoverTypeAtPosition({col:e,row:t}){if(this.persistentPopover&&this.persistentPopover.col===e&&this.persistentPopover.row===t)return this.persistentPopover.type}computePopoverProps({col:e,row:t},i){const{width:n,height:o}=this.getters.getVisibleRect(Qi({col:e,row:t}));return{coordinates:this.computePopoverPosition({col:e,row:t},i),cellWidth:-n,cellHeight:-o}}computePopoverPosition({col:e,row:t},i){const n=this.getters.getActiveSheetId(),o=this.getters.getMerge(n,e,t);o&&(e="TopRight"===i?o.right:o.left,t="TopRight"===i?o.top:o.bottom);const{x:s,y:r,width:a,height:l}=this.getters.getVisibleRect(Qi({col:e,row:t}));switch(i){case"BottomLeft":return{x:s,y:r+l};case"TopRight":return{x:s+a,y:r}}}}Rv.getters=["getCellPopover","getPersistentPopoverTypeAtPosition"],Rv.modes=["normal"];class Iv{constructor(e,t,i,n){this.getters=t,this.dispatch=i,this.selection=n,this.operation=e,this.sheetId=t.getActiveSheetId()}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0}addMissingDimensions(e,t,i,n){const o=this.getters.getActiveSheetId(),s=t+n-this.getters.getNumberRows(o);s>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(o)-1,sheetId:o,quantity:s,position:"after"});const r=e+i-this.getters.getNumberCols(o);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(o)-1,sheetId:o,quantity:r,position:"after"})}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class Tv extends Iv{constructor(e,t,i,n,o){if(super(t,i,n,o),!e.length)return this.cells=[[]],this.zones=[],void(this.copiedTables=[]);const s=new Set(e.map((e=>e.left))),r=new Set(e.map((e=>e.right))),a=new Set(e.map((e=>e.top))),l=new Set(e.map((e=>e.bottom))),c=1===a.size&&1===l.size||1===s.size&&1===r.size?function(e){return e.reduce(((e,t)=>{const i=e.length;for(let n=0;n<i;n++)if(zi(e[n],t))return e[n]=Pi(e[n],t),e;return e[i]=t,e}),[])}(e):[e[e.length-1]],h=c.map((e=>ji(e))).flat(),d=[...new Set(h.map((e=>e.col)))].sort(((e,t)=>e-t)),u=[...new Set(h.map((e=>e.row)))].sort(((e,t)=>e-t)),g=[],p=i.getActiveSheetId();for(let e of u){let t=[];for(let n of d)t.push({cell:i.getCell(p,n,e),border:i.getCellBorder(p,n,e)||void 0,position:{col:n,row:e,sheetId:p}});g.push(t)}const m=[];for(const t of e)for(const e of this.getters.getFilterTablesInZone(p,t)){const t=[];for(const i of $e(e.zone.left,e.zone.right+1))t.push(this.getters.getFilterValues(p,i,e.zone.top));m.push({filtersValues:t,zone:e.zone})}this.cells=g,this.zones=c,this.copiedTables=m}isCutAllowed(e){return 1!==e.length?19:0}isPasteAllowed(e,t){const i=this.getters.getActiveSheetId();if("CUT"===this.operation&&void 0!==(null==t?void 0:t.pasteOption))return 21;if(e.length>1&&(this.cells.length>1||this.cells[0].length>1))return 20;const n=this.cells.length,o=this.cells[0].length;for(let t of this.getPasteZones(e))if(this.getters.doesIntersectMerge(i,t)&&(e.length>1||!this.getters.isSingleCellOrMerge(i,e[0])||n*o!=1))return 2;const{xSplit:s,ySplit:r}=this.getters.getPaneDivisions(i);for(const t of this.getPasteZones(e))if(t.left<s&&t.right>=s||t.top<r&&t.bottom>=r)return 76;return 0}paste(e,t){"COPY"===this.operation?this.pasteFromCopy(e,t):this.pasteFromCut(e,t);const i=this.cells.length,n=this.cells[0].length,o="CUT"===this.operation;(null==t?void 0:t.selectTarget)&&this.selectPastedZone(n,i,o,e)}pasteFromCopy(e,t){if(1===e.length){const i=this.cells.length,n=this.cells[0].length,o=this.pastedZones(e,n,i);for(const e of o)this.pasteZone(e.left,e.top,t)}else for(const i of e)for(let e=i.left;e<=i.right;e++)for(let n=i.top;n<=i.bottom;n++)this.pasteZone(e,n,t);void 0===(null==t?void 0:t.pasteOption)&&this.pasteCopiedTables(e)}pasteFromCut(e,t){this.clearClippedZones();const i=e[0];this.pasteZone(i.left,i.top,t),this.dispatch("MOVE_RANGES",{target:this.zones,sheetId:this.sheetId,targetSheetId:this.getters.getActiveSheetId(),col:i.left,row:i.top});for(const e of this.copiedTables)this.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.sheetId,target:[e.zone]});this.pasteCopiedTables(e)}pastedZones(e,t,i){const n=e[0],o=Math.max(1,Math.floor((n.right+1-n.left)/t)),s=Math.max(1,Math.floor((n.bottom+1-n.top)/i)),r=[];for(let e=0;e<o;e++)for(let o=0;o<s;o++){const s=n.top+o*i,a=n.left+e*t;r.push({left:a,top:s,bottom:s+i-1,right:a+t-1})}return r}getPasteZones(e){const t=this.cells;if(!t.length||!t[0].length)return e;const i=[],n=t.length,o=t[0].length,s=e[e.length-1],r=s.left,a=s.top,l=Math.max(1,Math.floor((s.right+1-r)/o)),c=Math.max(1,Math.floor((s.bottom+1-a)/n));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)i.push({left:r,top:a,right:r-1+e*o,bottom:a-1+t*n});return i}selectPastedZone(e,t,i,n){const o=n[0],s=o.left,r=o.top;if(t>1||e>1||i){const o=this.pastedZones(n,e,t),a=i?o[0]:Pi(...o);this.selection.selectZone({cell:{col:s,row:r},zone:a})}}clearClippedZones(){for(const e of this.cells)for(const t of e)t.cell&&this.dispatch("CLEAR_CELL",t.position);this.dispatch("CLEAR_FORMATTING",{sheetId:this.sheetId,target:this.zones})}pasteZone(e,t,i){const n=this.cells.length,o=this.cells[0].length,s="onlyValue"!==(null==i?void 0:i.pasteOption)&&(null==i?void 0:i.shouldPasteCF),r=this.getters.getActiveSheetId();this.addMissingDimensions(o,n,e,t);for(let a=0;a<n;a++){const n=this.cells[a];for(let l=0;l<o;l++){const o=n[l],c={col:e+l,row:t+a,sheetId:r};this.pasteMergeIfExist(o.position,c,this.operation),this.pasteCell(o,c,this.operation,i),s&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{origin:o.position,target:c,operation:this.operation})}}}pasteCell(e,t,i,n){const{sheetId:o,col:s,row:r}=t,a=this.getters.getCell(o,s,r);if("onlyValue"!==(null==n?void 0:n.pasteOption)){const t=this.getters.getCellBorder(o,s,r),i=e.border,n={top:(null==t?void 0:t.top)||(null==i?void 0:i.top),bottom:(null==t?void 0:t.bottom)||(null==i?void 0:i.bottom),left:(null==t?void 0:t.left)||(null==i?void 0:i.left),right:(null==t?void 0:t.right)||(null==i?void 0:i.right)};this.dispatch("SET_BORDER",{sheetId:o,col:s,row:r,border:n})}if(e.cell){if("onlyFormat"===(null==n?void 0:n.pasteOption))return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.cell.evaluated.format||e.cell.format});if("onlyValue"===(null==n?void 0:n.pasteOption)){const i=Qt(e.cell.evaluated.value);return void this.dispatch("UPDATE_CELL",{...t,content:i})}let a=e.cell.content;if(e.cell.isFormula()&&"COPY"===i){const t=s-e.position.col,n=r-e.position.row;a=this.getUpdatedContent(o,e.cell,t,n,i)}this.dispatch("UPDATE_CELL",{...t,content:a,style:e.cell.style||null,format:e.cell.format})}else a&&("onlyValue"===(null==n?void 0:n.pasteOption)?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===(null==n?void 0:n.pasteOption)?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,i,n,o){const s=this.getters.createAdaptedRanges(t.dependencies,i,n,e);return this.getters.buildFormulaContent(e,t,s)}pasteMergeIfExist(e,t,i){let{sheetId:n,col:o,row:s}=e;const{col:r,row:a}=this.getters.getMainCellPosition(n,o,s);if(r===o&&a===s){const e=this.getters.getMerge(n,o,s);if(!e)return;"CUT"===i&&this.dispatch("REMOVE_MERGE",{sheetId:n,target:[e]}),({sheetId:n,col:o,row:s}=t),this.dispatch("ADD_MERGE",{sheetId:n,force:!0,target:[{left:o,top:s,right:o+e.right-e.left,bottom:s+e.bottom-e.top}]})}}pasteCopiedTables(e){const t=this.getters.getActiveSheetId(),i=e[0],n=this.zones[0],o=[i.left-n.left,i.top-n.top];for(const e of this.copiedTables){const i=Yi(e.zone,"both","MOVE",o);this.dispatch("CREATE_FILTER_TABLE",{sheetId:t,target:[i]});for(const n of $e(0,e.filtersValues.length))this.dispatch("UPDATE_FILTER",{sheetId:t,col:i.left+n,row:i.top,values:e.filtersValues[n]})}}getClipboardContent(){return this.cells.map((e=>e.map((e=>e.cell?this.getters.getCellText(e.cell,this.getters.shouldShowFormulas()):"")).join("\t"))).join("\n")||"\t"}isColRowDirtyingClipboard(e,t){if(!this.zones)return!1;for(let i of this.zones){if("COL"===t&&e<=i.right)return!0;if("ROW"===t&&e<=i.bottom)return!0}return!1}drawClipboard(e){const{ctx:t,thinLineWidth:i}=e;if(this.sheetId===this.getters.getActiveSheetId()&&this.zones&&this.zones.length){t.setLineDash([8,5]),t.strokeStyle=E,t.lineWidth=3.3*i;for(const e of this.zones){const{x:i,y:n,width:o,height:s}=this.getters.getVisibleRect(e);o>0&&s>0&&t.strokeRect(i,n,o,s)}}}}class Av{constructor(e,t,i){this.getters=t,this.dispatch=i,this.sheetId=t.getActiveSheetId();const n=t.getSelectedFigureId();if(!n)throw new Error("No figure selected");const o=t.getFigure(this.sheetId,n);if(!o)throw new Error(`No figure for the given id: ${n}`);this.copiedFigure={...o};const s=t.getChart(n);if(!s)throw new Error(`No chart for the given id: ${n}`);this.copiedChart=s.copyInSheetId(this.sheetId),this.operation=e}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0===e.length?74:void 0!==(null==t?void 0:t.pasteOption)?22:0}paste(e){const t=this.getters.getActiveSheetId(),i={x:this.getters.getColDimensions(t,e[0].left).start,y:this.getters.getRowDimensions(t,e[0].top).start},n=this.copiedChart.copyInSheetId(t),o=(new Oi).smallUuid();this.dispatch("CREATE_CHART",{id:o,sheetId:t,position:i,size:{height:this.copiedFigure.height,width:this.copiedFigure.width},definition:n.getDefinition()}),"CUT"===this.operation&&this.dispatch("DELETE_FIGURE",{sheetId:this.copiedChart.sheetId,id:this.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{id:o})}getClipboardContent(){return"\t"}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class Ov extends Iv{constructor(e,t,i,n){super("COPY",t,i,n),this.values=e.replace(/\r/g,"").split("\n").map((e=>e.split("\t")))}isPasteAllowed(e,t){const i=this.getters.getActiveSheetId(),n=this.getPasteZone(e);return this.getters.doesIntersectMerge(i,n)?2:0}paste(e){const t=this.values,i=this.getPasteZone(e),{left:n,top:o}=i,{width:s,height:r}=qi(i),a=this.getters.getActiveSheetId();this.addMissingDimensions(s,r,n,o);for(let e=0;e<t.length;e++)for(let i=0;i<t[e].length;i++)this.dispatch("UPDATE_CELL",{row:o+e,col:n+i,content:t[e][i],sheetId:a});const l={left:n,top:o,right:n+s-1,bottom:o+r-1};this.selection.selectZone({cell:{col:n,row:o},zone:l})}getClipboardContent(){return this.values.map((e=>e.join("\t"))).join("\n")}getPasteZone(e){const t=this.values.length,i=Math.max(...this.values.map((e=>e.length))),{left:n,top:o}=e[0];return{top:o,left:n,bottom:o+t-1,right:n+i-1}}}class Nv extends Bg{constructor(){super(...arguments),this.status="invisible",this._isPaintingFormat=!1}allowDispatch(e){switch(e.type){case"CUT":const t=this.getters.getSelectedZones();return this.getClipboardState(t,e.type).isCutAllowed(t);case"PASTE":if(!this.state)return 23;const i=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);return this.state.isPasteAllowed(e.target,{pasteOption:i});case"PASTE_FROM_OS_CLIPBOARD":return new Ov(e.text,this.getters,this.dispatch,this.selection).isPasteAllowed(e.target);case"INSERT_CELL":{const{cut:t,paste:i}=this.getInsertCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(i)}case"DELETE_CELL":{const{cut:t,paste:i}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(i)}}return 0}handle(e){var t,i,n,o;switch(e.type){case"COPY":case"CUT":const s=this.getters.getSelectedZones();this.state=this.getClipboardState(s,e.type),this.status="visible";break;case"PASTE":if(!this.state)break;const r=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);this._isPaintingFormat=!1,this.state.paste(e.target,{pasteOption:r,shouldPasteCF:!0,selectTarget:!0}),"CUT"===this.state.operation&&(this.state=void 0),this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:i}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!_i(t[0])){for(const{col:t,row:i}of ji(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:i,sheetId:this.getters.getActiveSheetId()});break}this.getClipboardStateForCopyCells(t,"CUT").paste(i);break}case"INSERT_CELL":{const{cut:t,paste:i}=this.getInsertCellsTargets(e.zone,e.shiftDimension);this.getClipboardStateForCopyCells(t,"CUT").paste(i);break}case"ADD_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(t=this.state)||void 0===t?void 0:t.operation)||e.sheetId!==(null===(i=this.state)||void 0===i?void 0:i.sheetId))return;this.state.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.state=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(n=this.state)||void 0===n?void 0:n.operation)||e.sheetId!==(null===(o=this.state)||void 0===o?void 0:o.sheetId))return;for(let t of e.elements){if(this.state.isColRowDirtyingClipboard(t,e.dimension)){this.state=void 0;break}}this.status="invisible";break;case"PASTE_FROM_OS_CLIPBOARD":new Ov(e.text,this.getters,this.dispatch,this.selection).paste(e.target),this.status="invisible";break;case"ACTIVATE_PAINT_FORMAT":{const e=this.getters.getSelectedZones();this.state=this.getClipboardStateForCopyCells(e,"COPY"),this._isPaintingFormat=!0,this.status="visible";break}default:gn(e)&&(this.status="invisible")}}getClipboardContent(){var e;return(null===(e=this.state)||void 0===e?void 0:e.getClipboardContent())||"\t"}isCutOperation(){return!!this.state&&"CUT"===this.state.operation}isPaintingFormat(){return this._isPaintingFormat}getDeleteCellsTargets(e,t){const i=this.getters.getActiveSheetId();let n;return n="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(i)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(i)-1},{cut:[n],paste:[e]}}getInsertCellsTargets(e,t){const i=this.getters.getActiveSheetId();let n,o;return"COL"===t?(n={...e,right:this.getters.getNumberCols(i)-1},o={...e,left:e.right+1,right:e.right+1}):(n={...e,bottom:this.getters.getNumberRows(i)-1},o={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(i)-1}),{cut:[n],paste:[o]}}getClipboardStateForCopyCells(e,t){return new Tv(e,t,this.getters,this.dispatch,this.selection)}getClipboardState(e,t){return this.getters.getSelectedFigureId()?new Av(t,this.getters,this.dispatch):new Tv(e,t,this.getters,this.dispatch,this.selection)}drawGrid(e){"visible"===this.status&&this.state&&this.state.drawClipboard(e)}}Nv.layers=[2],Nv.getters=["getClipboardContent","isCutOperation","isPaintingFormat"];class Mv extends Bg{constructor(){super(...arguments),this.customColors=new Set,this.shouldUpdateColors=!1}handle(e){switch(e.type){case"UPDATE_CELL":case"UPDATE_CHART":case"CREATE_CHART":case"ADD_CONDITIONAL_FORMAT":this.shouldUpdateColors=!0}}finalize(){if(this.shouldUpdateColors){this.shouldUpdateColors=!1;for(const e of this.getCustomColors())this.tryToAddColor(e)}}getCustomColors(){let e=[];for(const t of this.getters.getSheetIds()){const i=Object.values(this.getters.getCells(t));e=e.concat(this.getColorsFromCells(i),this.getFormattingColors(t),this.getChartColors(t))}return function(e){const t=[{leadColor:bt(255,0,0),colors:[]},{leadColor:bt(255,128,0),colors:[]},{leadColor:bt(128,128,0),colors:[]},{leadColor:bt(128,255,0),colors:[]},{leadColor:bt(0,255,0),colors:[]},{leadColor:bt(0,255,128),colors:[]},{leadColor:bt(0,255,255),colors:[]},{leadColor:bt(0,127,255),colors:[]},{leadColor:bt(0,0,255),colors:[]},{leadColor:bt(127,0,255),colors:[]},{leadColor:bt(128,0,128),colors:[]},{leadColor:bt(255,0,128),colors:[]}];for(const i of e.map(Et)){let e=500,n=0;t.forEach(((t,o)=>{const s=(r=i,a=t.leadColor,Math.sqrt(Math.pow(r.r-a.r,2)+Math.pow(r.g-a.g,2)+Math.pow(r.b-a.b,2)));var r,a;e>s&&(e=s,n=o)})),t[n].colors.push(i)}return t.map((e=>e.colors.sort(((e,t)=>yt(e).s-yt(t).s)))).flat().map(Ct)}([...new Set([...new Set([...e,...this.customColors])].filter(ft).map(mt))]).filter((e=>!O.includes(e)))}getColorsFromCells(e){var t,i;const n=new Set;for(const o of e)(null===(t=o.style)||void 0===t?void 0:t.textColor)&&n.add(o.style.textColor),(null===(i=o.style)||void 0===i?void 0:i.fillColor)&&n.add(o.style.fillColor);return[...n]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),i=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(i.push(t.style.textColor),i.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(i.push(gt(t.minimum.color)),i.push(t.midpoint?gt(t.midpoint.color):void 0),i.push(gt(t.maximum.color)))}return i.filter(Xe)}getChartColors(e){const t=this.getters.getChartIds(e).map((e=>this.getters.getChart(e)));let i=new Set;for(let e of t){if(void 0===e)continue;const t=e.getDefinition().background;switch(void 0!==t&&i.add(t),e.type){case"gauge":const t=e.sectionRule.colors;i.add(t.lowerColor),i.add(t.middleColor),i.add(t.upperColor);break;case"scorecard":const n=e;i.add(n.baselineColorDown),i.add(n.baselineColorUp)}}return[...i]}tryToAddColor(e){const t=mt(e);e&&!O.includes(t)&&this.customColors.add(t)}}Mv.getters=["getCustomColors"];const _v=qu.mapping;class Fv extends Bg{constructor(e,t,i,n,o){super(e,t,i,n,o),this.isUpToDate=!1,this.evalContext=n.evalContext}handle(e){switch(cn.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()}evaluateFormula(e,t=this.getters.getActiveSheetId()){try{const i=$g(e),n=this.getCompilationParameters((()=>{})),o=[];for(let e of i.dependencies)o.push(this.getters.getRangeFromSheetXC(t,e));return i.execute(o,...n).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.getCellsInZone(t.id,e.zone).map((e=>(null==e?void 0:e.formattedValue)||""))}getRangeValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getCellsInZone(t.id,e.zone).map((e=>null==e?void 0:e.evaluated.value))}*getAllCells(){for(const e of this.getters.getSheetIds()){const t=this.getters.getCells(e);for(const e in t)yield t[e]}}evaluate(){const e=this.getCompilationParameters(i),t={};for(const e of this.getAllCells())i(e);function i(i){if(!i.isFormula())return;const n=i.id,o=tt((()=>{if(e[2].__originCellXC=()=>{const t=e[2].getters.getCellPosition(n);return Vt(t.col,t.row)},n in t)return null===t[n]?new d:i.evaluated;t[n]=null;try{const o=i.compiledFormula.execute(i.dependencies,...e);if(t[n]=!0,Array.isArray(o.value))throw new Error(s("This formula depends on invalid values"));return{value:o.value,format:i.format||o.format}}catch(i){return t[n]=!0,function(t){t instanceof Error||(t=new Error(t));const i=(null==t?void 0:t.errorType)||a.GenericError,n=e[2].__lastFnCalled||"";return new c(i,t.message.replace("[[FUNCTION_NAME]]",n),void 0!==t.logLevel?t.logLevel:l.error)}(i)}}));i.assignEvaluation(o)}this.isUpToDate=!0}getCompilationParameters(e){const t=Object.assign(Object.create(_v),this.evalContext,{getters:this.getters}),i=this.getters;function n(e){if(e.evaluated.type===ln.error)throw new c(e.evaluated.value,e.evaluated.error.message,e.evaluated.error.logLevel);return e.evaluated}const o={};function r(e){if(!_i(e.zone))throw new u;if(e.invalidSheetName)throw new Error(s("Invalid sheet name: %s",e.invalidSheetName))}return[function(e,t,o,a){if(r(e),t)return{value:Fi(e.zone)};if(e.zone.bottom!==e.zone.top||e.zone.left!==e.zone.right)throw new Error(a?s("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",o.toString(),a.toString()):s("Function %s expects its parameters to be single values or single cell references, not ranges.",o.toString()));return function(e){let t;if(!i.tryGetSheet(e.sheetId))throw new Error(s("Invalid sheet name"));return t=i.getCell(e.sheetId,e.zone.left,e.zone.top),!t||t.isEmpty()?{value:null,format:null==t?void 0:t.format}:n(t)}(e)},function(e){r(e);const s=e.sheetId,a=i.getSheetZone(s),l=Ui(e.zone,a);if(!l)return[[]];const{top:c,left:h,bottom:d,right:u}=l,g=`${s}-${c}-${h}-${d}-${u}`;if(g in o)return o[g];const p=new Array(u-h+1);for(let i=h;i<=u;i++){const o=new Array(d-c+1);for(let s=c;s<=d;s++){const r=t.getters.getCell(e.sheetId,i,s);o[s-c]=r?n(r):void 0}p[i-h]=o}return o[g]=p,p},t]}}Fv.getters=["evaluateFormula","getRangeFormattedValues","getRangeValues"];class Dv extends Bg{constructor(){super(...arguments),this.charts={},this.createRuntimeChart=function(e){const t=on.getAll();return function(i){const n=t.find((e=>e.match(i.type)));if(!n)throw new Error("No runtime builder for this chart.");return n.getChartRuntime(i,e)}}(this.getters)}handle(e){if(cn.has(e.type)||hn.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:ys(e)};if(!t)return{background:w,fontColor:ys(w)};const i=t.zone.left,n=t.zone.top,o=t.sheetId,s=this.getters.getCellComputedStyle(o,i,n),r=s.fillColor||w;return{background:r,fontColor:s.textColor||ys(r)}}}Dv.getters=["getChartRuntime","getStyleOfSingleCellChart"];class kv extends Bg{constructor(){super(...arguments),this.isStale=!0,this.computedStyles={},this.computedIcons={},this.uuidGenerator=new Oi,this.rulePredicate={CellIsRule:(e,t)=>{if(e&&e.evaluated.type===ln.error)return!1;const i=t.values.map(Vp);switch(t.operator){case"IsEmpty":return!Xe(e)||""===e.evaluated.value.toString().trim();case"IsNotEmpty":return Xe(e)&&""!==e.evaluated.value.toString().trim();case"BeginsWith":return!(!e&&""===i[0])&&(Xe(e)&&(null==e?void 0:e.evaluated.value.toString().startsWith(i[0].toString())));case"EndsWith":return!(!e&&""===i[0])&&(Xe(e)&&e.evaluated.value.toString().endsWith(i[0].toString()));case"Between":return Xe(e)&&e.evaluated.value>=i[0]&&e.evaluated.value<=i[1];case"NotBetween":return!(Xe(e)&&e.evaluated.value>=i[0]&&e.evaluated.value<=i[1]);case"ContainsText":return Xe(e)&&e.evaluated.value.toString().indexOf(i[0].toString())>-1;case"NotContains":return!Xe(e)||!e.evaluated.value||-1==e.evaluated.value.toString().indexOf(i[0].toString());case"GreaterThan":return Xe(e)&&e.evaluated.value>i[0];case"GreaterThanOrEqual":return Xe(e)&&e.evaluated.value>=i[0];case"LessThan":return Xe(e)&&e.evaluated.value<i[0];case"LessThanOrEqual":return Xe(e)&&e.evaluated.value<=i[0];case"NotEqual":return!(!Xe(e)&&""===i[0])&&(Xe(e)&&e.evaluated.value!==i[0]);case"Equal":return!e&&""===i[0]||Xe(e)&&e.evaluated.value===i[0];default:console.warn(s("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}}}handle(e){switch((hn.has(e.type)||"UPDATE_CELL"===e.type&&"content"in e)&&(this.isStale=!0),e.type){case"ACTIVATE_SHEET":const t=e.sheetIdTo;this.computedStyles[t]=this.computedStyles[t]||{},this.computedIcons[t]=this.computedIcons[t]||{},this.isStale=!0;break;case"AUTOFILL_CELL":const i=this.getters.getActiveSheetId(),n=this.getters.getRulesByCell(i,e.originCol,e.originRow);for(const t of n)this.adaptRules(i,t,[Vt(e.col,e.row)],[]);break;case"PASTE_CONDITIONAL_FORMAT":this.pasteCf(e.origin,e.target,e.operation)}}finalize(){this.isStale&&(this.computeStyles(),this.isStale=!1)}getCellComputedStyle(e,t,i){var n;const o=this.getters.getCell(e,t,i),s=this.computedStyles[e],r=s&&(null===(n=s[t])||void 0===n?void 0:n[i]),a={...null==o?void 0:o.style,...r};return this.getters.isFilterHeader(e,t,i)&&(a.bold=!0),a}getConditionalIcon(e,t){var i;const n=this.getters.getActiveSheetId(),o=this.computedIcons[n];return o&&(null===(i=o[e])||void 0===i?void 0:i[t])}computeStyles(){var e;const t=this.getters.getActiveSheetId();this.computedStyles[t]={},this.computedIcons[t]={};const i=this.computedStyles[t];for(let n of this.getters.getConditionalFormats(t).reverse())switch(n.rule.type){case"ColorScaleRule":for(let e of n.ranges)this.applyColorScale(e,n.rule);break;case"IconSetRule":for(let e of n.ranges)this.applyIcon(e,n.rule);break;default:for(let o of n.ranges){const s=this.getters.getRangeFromSheetXC(t,o).zone;for(let o=s.top;o<=s.bottom;o++)for(let r=s.left;r<=s.right;r++){const s=this.rulePredicate[n.rule.type];let a=this.getters.getCell(t,r,o);s&&s(a,n.rule)&&(i[r]||(i[r]=[]),i[r][o]=Object.assign((null===(e=i[r])||void 0===e?void 0:e[o])||{},n.rule.style))}}}}parsePoint(e,t,i){const n=this.getters.getActiveSheetId(),o=this.getters.getRangeValues(this.getters.getRangeFromSheetXC(n,e)).filter(this.isCellValueNumber);switch(t.type){case"value":return"max"===i?lt(o):ct(o);case"number":return Number(t.value);case"percentage":const e=ct(o);return e+(lt(o)-e)*Number(t.value)/100;case"percentile":return yi(o,Number(t.value)/100,!0);case"formula":const n=t.value&&this.getters.evaluateFormula(t.value);return"number"==typeof n?n:null;default:return null}}applyIcon(e,t){const i=this.parsePoint(e,t.lowerInflectionPoint),n=this.parsePoint(e,t.upperInflectionPoint);if(null===i||null===n||i>n)return;const o=this.getters.getActiveSheetId(),s=this.getters.getRangeFromSheetXC(o,e).zone,r=this.computedIcons[o],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=s.top;e<=s.bottom;e++)for(let l=s.left;l<=s.right;l++){const s=this.getters.getCell(o,l,e);if((null==s?void 0:s.evaluated.type)!==ln.number)continue;const c=this.computeIcon(s.evaluated.value,n,t.upperInflectionPoint.operator,i,t.lowerInflectionPoint.operator,a);r[l]||(r[l]=[]),r[l][e]=c}}computeIcon(e,t,i,n,o,s){return"ge"===i&&e>=t||"gt"===i&&e>t?s[0]:"ge"===o&&e>=n||"gt"===o&&e>n?s[1]:s[2]}applyColorScale(e,t){var i;const n=this.parsePoint(e,t.minimum,"min"),o=t.midpoint?this.parsePoint(e,t.midpoint):null,s=this.parsePoint(e,t.maximum,"max");if(null===n||null===s||n>=s||o&&(n>=o||o>=s))return;const r=this.getters.getActiveSheetId(),a=this.getters.getRangeFromSheetXC(r,e).zone,l=this.computedStyles[r],c=[];t.midpoint&&o?(c.push({minValue:n,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(n,o,t.minimum.color,t.midpoint.color)}),c.push({minValue:o,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(o,s,t.midpoint.color,t.maximum.color)})):c.push({minValue:n,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(n,s,t.minimum.color,t.maximum.color)});for(let e=a.top;e<=a.bottom;e++)for(let t=a.left;t<=a.right;t++){const a=this.getters.getCell(r,t,e);if((null==a?void 0:a.evaluated.type)===ln.number){const r=Me(a.evaluated.value,n,s);let h;h=2===c.length&&o?r<=o?this.colorCell(r,c[0].minValue,c[0].minColor,c[0].colorDiffUnit):this.colorCell(r,c[1].minValue,c[1].minColor,c[1].colorDiffUnit):this.colorCell(r,c[0].minValue,c[0].minColor,c[0].colorDiffUnit),l[t]||(l[t]=[]),l[t][e]=(null===(i=l[t])||void 0===i?void 0:i[e])||{},l[t][e].fillColor=gt(h)}}}computeColorDiffUnits(e,t,i,n){const o=t-e;return[((i>>16)%256-(n>>16)%256)/o,((i>>8)%256-(n>>8)%256)/o,(i%256-n%256)/o]}colorCell(e,t,i,n){const[o,s,r]=n;return Math.round((i>>16)%256-o*(e-t))<<16|Math.round((i>>8)%256-s*(e-t))<<8|Math.round(i%256-r*(e-t))}adaptRules(e,t,i,n){if(0===i.length&&0===n.length)return;const o=this.getters.getConditionalFormats(e),s=o.findIndex((e=>e.id===t.id));let r=[];s>-1&&(r=o[s].ranges),r=r.concat(i);const a=Wi(r,n);0!==a.length?this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:t.id,rule:t.rule,stopIfTrue:t.stopIfTrue},ranges:a.map((t=>this.getters.getRangeDataFromXc(e,t))),sheetId:e}):this.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:t.id,sheetId:e})}pasteCf(e,t,i){const n=Vt(t.col,t.row);for(let o of this.getters.getConditionalFormats(e.sheetId))for(let s of o.ranges)if(Bi(e.col,e.row,this.getters.getRangeFromSheetXC(e.sheetId,s).zone)){const s=o,r=[];if("CUT"===i&&r.push(Vt(e.col,e.row)),e.sheetId===t.sheetId)this.adaptRules(e.sheetId,s,[n],r);else{this.adaptRules(e.sheetId,s,[],r);const i=this.getCFToCopyTo(t.sheetId,s);this.adaptRules(t.sheetId,i,[n],[])}}}isCellValueNumber(e){return"number"==typeof e}getCFToCopyTo(e,t){const i=this.getters.getConditionalFormats(e).find((e=>e.stopIfTrue===t.stopIfTrue&&ot(e.rule,t.rule)));return i||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}}kv.getters=["getConditionalIcon","getCellComputedStyle"];class $v extends Bg{constructor(){super(...arguments),this.filterValues={},this.hiddenRows=new Set,this.isEvaluationDirty=!1}allowDispatch(e){if("UPDATE_FILTER"===e.type)if(!this.getters.getFilterId(e.sheetId,e.col,e.row))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":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":case"ADD_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":this.updateHiddenRows();break;case"UPDATE_FILTER":this.updateFilter(e),this.updateHiddenRows();break;case"DUPLICATE_SHEET":const t={};for(const i of this.getters.getFilters(e.sheetIdTo)){const n=i.zoneWithHeaders;t[i.id]=this.getFilterValues(e.sheetId,n.left,n.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,t,i){let n;for(let o of this.getters.getFilterTables(e)){const s=o.zone;if(Bi(t,i,s)){const o=this.intersectZoneWithViewport(e,s);n={top:i===o.top?j:void 0,bottom:i===o.bottom?j:void 0,left:t===o.left?j:void 0,right:t===o.right?j:void 0}}}const o=this.getters.getCellBorder(e,t,i),s={...n,...rt(o||{})};return Qe(s)?null:s}getFilterHeaders(e){const t=[];for(let i of this.getters.getFilterTables(e)){const n=i.zone;if(!n)continue;const o=n.top;for(let i=n.left;i<=n.right;i++)this.getters.isColHidden(e,i)||this.getters.isRowHidden(e,o)||t.push({col:i,row:o})}return t}getFilterValues(e,t,i){const n=this.getters.getFilterId(e,t,i);return n&&this.filterValues[e]&&this.filterValues[e][n]||[]}isFilterHeader(e,t,i){return this.getFilterHeaders(e).some((e=>e.col===t&&e.row===i))}isFilterActive(e,t,i){var n,o;const s=this.getters.getFilterId(e,t,i);return Boolean(s&&(null===(o=null===(n=this.filterValues[e])||void 0===n?void 0:n[s])||void 0===o?void 0:o.length))}intersectZoneWithViewport(e,t){return{left:this.getters.findVisibleHeader(e,"COL",t.left,t.right),right:this.getters.findVisibleHeader(e,"COL",t.right,t.left),top:this.getters.findVisibleHeader(e,"ROW",t.top,t.bottom),bottom:this.getters.findVisibleHeader(e,"ROW",t.bottom,t.top)}}updateFilter({col:e,row:t,values:i,sheetId:n}){const o=this.getters.getFilterId(n,e,t);o&&(this.filterValues[n]||(this.filterValues[n]={}),this.filterValues[n][o]=i)}updateHiddenRows(){var e,t;const i=this.getters.getActiveSheetId(),n=this.getters.getFilters(i).sort(((e,t)=>e.zoneWithHeaders.top-t.zoneWithHeaders.top)),o=new Set;for(let s of n){if(this.getters.isRowHiddenByUser(i,s.zoneWithHeaders.top))continue;if(o.has(s.zoneWithHeaders.top))continue;const n=null===(t=null===(e=this.filterValues[i])||void 0===e?void 0:e[s.id])||void 0===t?void 0:t.map(at);if(n&&s.filteredZone)for(let e=s.filteredZone.top;e<=s.filteredZone.bottom;e++){const t=this.getCellValueAsString(i,s.col,e);n.includes(t)&&o.add(e)}}this.hiddenRows=o}getCellValueAsString(e,t,i){var n;const o=null===(n=this.getters.getCell(e,t,i))||void 0===n?void 0:n.formattedValue;return(null==o?void 0:o.toLowerCase())||""}exportForExcel(e){var t;for(const i of e.sheets)for(const e of i.filterTables){const n=Mi(e.range),o=[],s=[];for(const e of $e(0,qi(n).width)){const r=this.getFilterValues(i.id,n.left+e,n.top),a=this.getters.getFilter(i.id,n.left+e,n.top);if(!a)continue;const l=a.filteredZone?ji(a.filteredZone).map((e=>{var t;return null===(t=this.getters.getCell(i.id,e.col,e.row))||void 0===t?void 0:t.formattedValue})):[];if(r.length){const t=l.filter(Ke).filter((e=>!r.includes(e)));o.push({colId:e,displayedValues:[...new Set(t)],displayBlanks:!r.includes("")&&l.some((e=>!e))})}const c={col:a.col,row:a.zoneWithHeaders.top},h=null===(t=this.getters.getCell(i.id,c.col,c.row))||void 0===t?void 0:t.formattedValue,d=this.getUniqueColNameForExcel(e,h,s);s.push(d),i.cells[Vt(c.col,c.row)]={...i.cells[Vt(c.col,c.row)],content:d,value:d,isFormula:!1}}e.filters=o}}getUniqueColNameForExcel(e,t,i){t||(t=`Column${e}`);let n=t,o=2;for(;i.includes(n);)n=t+String(o),o++;return n}}$v.getters=["getCellBorderWithFilterBorder","getFilterHeaders","getFilterValues","isFilterHeader","isRowFiltered","isFilterActive"];var Lv;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(Lv||(Lv={}));class Pv extends Bg{constructor(){super(...arguments),this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1},this.toSearch="",this.isSearchDirty=!1}handle(e){switch(e.type){case"UPDATE_SEARCH":this.updateSearch(e.toSearch,e.searchOptions);break;case"CLEAR_SEARCH":this.clearSearch();break;case"SELECT_SEARCH_PREVIOUS_MATCH":this.selectNextCell(Lv.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(Lv.next);break;case"REPLACE_SEARCH":this.replace(e.replaceWith);break;case"REPLACE_ALL_SEARCH":this.replaceAll(e.replaceWith);break;case"EVALUATE_CELLS":case"UPDATE_CELL":case"REMOVE_FILTER_TABLE":case"UPDATE_FILTER":this.isSearchDirty=!0;break;case"UNDO":case"REDO":case"REMOVE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":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(Lv.current)}updateRegex(){let e=Te(this.toSearch);const t=this.searchOptions.matchCase?"":"i";this.searchOptions.exactMatch&&(e=`^${e}$`),this.currentSearchRegex=RegExp(e,t)}findMatches(){const e=this.getters.getActiveSheetId(),t=this.getters.getCells(e),i=[];if(this.toSearch)for(const n of Object.values(t)){const{col:t,row:o}=this.getters.getCellPosition(n.id),s=this.getters.isColHidden(e,t),r=this.getters.isRowHidden(e,o);if(!s&&!r&&(n&&this.currentSearchRegex&&this.currentSearchRegex.test(this.searchOptions.searchFormulas?n.content:String(n.evaluated.value)))){const e=this.getters.getCellPosition(n.id),t={col:e.col,row:e.row,selected:!1};i.push(t)}}return i.sort(this.sortByRowThenColumn)}sortByRowThenColumn(e,t){return e.row===t.row?e.col-t.col:e.row>t.row?1:-1}selectNextCell(e){const t=this.searchMatches;if(!t.length)return void(this.selectedMatchIndex=null);let i;i=null===this.selectedMatchIndex?0:this.selectedMatchIndex+e,i=(i%t.length+t.length)%t.length,null!==this.selectedMatchIndex&&this.selectedMatchIndex===i||(this.selectedMatchIndex=i,this.selection.selectCell(t[i].col,t[i].row));for(let e=0;e<this.searchMatches.length;e++)this.searchMatches[e].selected=e===this.selectedMatchIndex}clearSearch(){this.toSearch="",this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1}}replace(e){if(null===this.selectedMatchIndex||!this.currentSearchRegex)return;const t=this.searchMatches[this.selectedMatchIndex],i=this.getters.getActiveSheetId(),n=this.getters.getCell(i,t.col,t.row),o=this.toReplace(n,i);if(n&&o){const i=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),n=o.toString().replace(i,e);this.dispatch("UPDATE_CELL",{sheetId:this.getters.getActiveSheetId(),col:t.col,row:t.row,content:n}),this.searchMatches.splice(this.selectedMatchIndex,1),this.selectNextCell(Lv.current)}else this.selectNextCell(Lv.next)}replaceAll(e){const t=this.searchMatches.length;for(let i=0;i<t;i++)this.replace(e)}toReplace(e,t){if(e){if(this.searchOptions.searchFormulas&&e.isFormula())return e.content;if(this.searchOptions.searchFormulas||!e.isFormula())return e.evaluated.value.toString()}return null}drawGrid(e){const{ctx:t}=e,i=this.getters.getActiveSheetId();for(const e of this.searchMatches){const n=this.getters.getMerge(i,e.col,e.row),o=n?n.left:e.col,s=n?n.right:e.col,r=n?n.top:e.row,a=n?n.bottom:e.row,{x:l,y:c,width:h,height:d}=this.getters.getVisibleRect({top:r,left:o,right:s,bottom:a});h>0&&d>0&&(t.fillStyle="#8B008B33",t.fillRect(l,c,h,d),e.selected&&(t.strokeStyle="#8B008B",t.strokeRect(l,c,h,d)))}}}Pv.layers=[3],Pv.getters=["getSearchMatches","getCurrentSelectedMatchIndex"];class Uv extends Bg{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,i){const n=this.searchNumberFormat(e,t);if(void 0!==n){const o=function(e,t){const i=Kt(e).map((e=>"NUMBER"===e.type?{...e,format:ci(e.format,t)}:e)),n=gi(i);return Xt[n]=i,n}(n,i);this.dispatch("SET_FORMATTING",{sheetId:e,target:t,format:o})}}searchNumberFormat(e,t){var i;for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let o=n.left;o<=n.right;o++){const n=this.getters.getCell(e,o,t);if((null==n?void 0:n.evaluated.type)===ln.number&&!(null===(i=n.evaluated.format)||void 0===i?void 0:i.match(Y)))return n.evaluated.format||ai(n.evaluated.value)}}}Uv.modes=["normal"];class Vv extends Bg{isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,i){return"COL"===t?this.isColHidden(e,i):this.isRowHidden(e,i)}getNextVisibleCellPosition(e,t,i){return{col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",i,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,i,n){if(i<=n)for(let o=i;o<=n;o++)if(this.getters.doesHeaderExist(e,t,o)&&!this.isHeaderHidden(e,t,o))return o;if(i>n)for(let o=i;o>=n;o--)if(this.getters.doesHeaderExist(e,t,o)&&!this.isHeaderHidden(e,t,o))return o}findLastVisibleColRowIndex(e,t,i){let n;for(n=i.last;n>=i.first;n--)if(!this.isHeaderHidden(e,t,n))return n;return n}findFirstVisibleColRowIndex(e,t){const i=this.getters.getNumberHeaders(e,t);for(let n=0;n<i;n++){if("COL"===t&&!this.isColHidden(e,n))return n;if("ROW"===t&&!this.isRowHidden(e,n))return n}}exportForExcel(e){for(const t of e.sheets)for(const[e,i]of Object.entries(t.rows)){const n=this.isRowHidden(t.id,Number(e));i.isHidden=n}}}Vv.getters=["getNextVisibleCellPosition","findVisibleHeader","findLastVisibleColRowIndex","findFirstVisibleColRowIndex","isRowHidden","isColHidden","isHeaderHidden"];class zv extends Bg{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{height:t,width:i}=qi(e.zone),n=t*i==1?this.getters.expandZone(e.sheetId,e.zone):e.zone;return{...e,zone:n}}))}drawGrid(e){const{ctx:t,thinLineWidth:i}=e,n=this.getters.getActiveSheetId(),o=3*i;t.lineWidth=o;const s=this.getHighlights();for(let e of s.filter(((e,t)=>s.findIndex((t=>Vi(t.zone,e.zone)&&t.sheetId===n))===t))){const{x:i,y:n,width:s,height:r}=this.getters.getVisibleRect(e.zone);s>0&&r>0&&(t.strokeStyle=e.color,t.strokeRect(i+o/2,n+o/2,s-o,r-o),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(i+o,n+o,s-2*o,r-2*o))}}}zv.layers=[1],zv.getters=["getHighlights"];class Bv extends Bg{constructor(){super(...arguments),this.boxes=[]}getColDimensionsInViewport(e,t){const i=Math.min(...this.getters.getSheetViewVisibleCols()),n=this.getters.getColRowOffsetInViewport("COL",i,t),o=this.getters.getColSize(e,t);return{start:n,size:o,end:n+(this.getters.isColHidden(e,t)?0:o)}}getRowDimensionsInViewport(e,t){const i=Math.min(...this.getters.getSheetViewVisibleRows()),n=this.getters.getColRowOffsetInViewport("ROW",i,t),o=this.getters.getRowSize(e,t);return{start:n,size:o,end:n+(this.getters.isRowHidden(e,t)?0:o)}}getHeaderOffset(e,t,i){let n=this.getters.getColRowOffsetInViewport(e,t,i);return this.getters.isDashboard()||(n+="ROW"===e?N:M),n}drawGrid(e,t){switch(t){case 0:this.drawBackground(e);for(const t of this.getters.getAllActiveViewportsZones()){const{ctx:i}=e;i.save(),i.beginPath();const n=this.getters.getVisibleRect(t);i.rect(n.x,n.y,n.width,n.height),i.clip(),this.boxes=this.getGridBoxes(t),this.drawCellBackground(e),this.drawBorders(e),this.drawTexts(e),this.drawIcon(e),i.restore()}this.drawFrozenPanes(e);break;case 7:this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e))}}drawBackground(e){const{ctx:t,thinLineWidth:i}=e,{width:n,height:o}=this.getters.getSheetViewDimensionWithHeaders(),s=this.getters.getActiveSheetId();t.fillStyle="#ffffff",t.fillRect(0,0,n+m,o+m);const r=this.getters.getSheetViewVisibleCols(),a=r[0],l=r[r.length-1],c=this.getters.getSheetViewVisibleRows(),h=c[0],d=c[c.length-1];if(this.getters.getGridLinesVisibility(s)&&!this.getters.isDashboard()){t.lineWidth=2*i,t.strokeStyle="#E2E3E3",t.beginPath();for(const e of r){const i={top:h,bottom:d,left:e,right:e},{x:n,width:s,height:r}=this.getters.getVisibleRect(i);t.moveTo(n+s,0),t.lineTo(n+s,Math.min(o,r+(this.getters.isDashboard()?0:N)))}for(const e of c){const i={left:a,right:l,top:e,bottom:e},{y:o,width:s,height:r}=this.getters.getVisibleRect(i);t.moveTo(0,o+r),t.lineTo(Math.min(n,s+(this.getters.isDashboard()?0:M)),o+r)}t.stroke()}}drawCellBackground(e){const{ctx:t,thinLineWidth:i}=e,n=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId());t.lineWidth=n?.3*i:i;const o=n?.1*i:0;t.strokeStyle="#111";for(let e of this.boxes){let s=e.style;(s.fillColor&&"#ffffff"!==s.fillColor||e.isMerge)&&(t.fillStyle=s.fillColor||"#ffffff",n?(t.fillRect(e.x,e.y,e.width,e.height),t.strokeRect(e.x+o,e.y+o,e.width-2*o,e.height-2*o)):t.fillRect(e.x-i,e.y-i,e.width+2*i,e.height+2*i)),e.error&&(t.fillStyle="red",t.beginPath(),t.moveTo(e.x+e.width-5,e.y),t.lineTo(e.x+e.width,e.y),t.lineTo(e.x+e.width,e.y+5),t.fill())}}drawBorders(e){const{ctx:t,thinLineWidth:i}=e;for(let e of this.boxes){const t=e.border;if(t){const{x:i,y:o,width:s,height:r}=e;t.left&&n(t.left,i,o,i,o+r),t.top&&n(t.top,i,o,i+s,o),t.right&&n(t.right,i+s,o,i+s,o+r),t.bottom&&n(t.bottom,i,o+r,i+s,o+r)}}function n([e,n],o,s,r,a){t.strokeStyle=n,t.lineWidth=("thin"===e?2:3)*i,t.beginPath(),t.moveTo(o,s),t.lineTo(r,a),t.stroke()}}drawTexts(e){const{ctx:t,thinLineWidth:i}=e;let n;t.textBaseline="top";for(let e of this.boxes)if(e.content){const o=e.style||{},s=e.content.align||"left",r=De(o);let a;r!==n&&(n=r,t.font=r),t.fillStyle=o.textColor||"#000";let l=e.y+e.height/2+1;if(a="left"===s?e.x+(e.image?e.image.size+2*L:P):"right"===s?e.x+e.width-P-(e.isFilterHeader?20:0):e.x+e.width/2,t.textAlign=s,e.clipRect){t.save(),t.beginPath();const{x:i,y:n,width:o,height:s}=e.clipRect;t.rect(i,n,o,s),t.clip()}const c=e.content.multiLineText.length,h=ke(o);let d=l-(c*(h+P)-P)/2;for(let n of e.content.multiLineText){if(t.fillText(n,Math.round(a),Math.round(d)),o.strikethrough||o.underline){const e=_e(t,n,o);let r=a;"right"===s?r-=e:"center"===s&&(r-=e/2),o.strikethrough&&t.fillRect(r,d+h/2,e,2.6*i),o.underline&&t.fillRect(r,d+h+1,e,1.3*i)}d+=P+h}e.clipRect&&t.restore()}}drawIcon(e){const{ctx:t}=e;for(const e of this.boxes)if(e.image){const i=e.image.image,n=e.image.size,o=(e.height-n)/2;if(e.image.clipIcon){t.save(),t.beginPath();const{x:i,y:n,width:o,height:s}=e.image.clipIcon;t.rect(i,n,o,s),t.clip()}t.drawImage(i,e.x+L,e.y+o,n,n),e.image.clipIcon&&t.restore()}}drawHeaders(e){const{ctx:t,thinLineWidth:i}=e,n=this.getters.getSheetViewVisibleCols(),o=n[0],s=this.getters.getSheetViewVisibleRows(),r=s[0],{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders(),c=this.getters.getSelectedZones(),h=function(e){const t=new Set;for(let i of e)for(let e of $e(i.left,i.right+1))t.add(e);return t}(c),d=function(e){const t=new Set;for(let i of e)for(let e of $e(i.top,i.bottom+1))t.add(e);return t}(c),u=this.getters.getActiveSheetId(),g=this.getters.getNumberCols(u),p=this.getters.getNumberRows(u),m=this.getters.getActiveCols(),f=this.getters.getActiveRows();t.font=`400 11px ${q}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=i,t.strokeStyle="#333";for(const e of n){const i={left:e,right:e,top:0,bottom:p-1},{x:n,width:o}=this.getters.getVisibleRect(i),s=this.getters.doesZonesContainFilter(u,[i]),r=m.has(e),a=h.has(e);t.fillStyle=r?s?I:S:a?s?A:b:s?T:v,t.fillRect(n,0,o,N)}for(const e of s){const i={top:e,bottom:e,left:0,right:g-1},{y:n,height:o}=this.getters.getVisibleRect(i),s=this.getters.doesZonesContainFilter(u,[i]),r=f.has(e),a=d.has(e);t.fillStyle=r?s?I:S:a?s?A:b:s?T:v,t.fillRect(0,n,M,o)}t.beginPath(),t.moveTo(M,0),t.lineTo(M,l),t.moveTo(0,N),t.lineTo(a,N),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(const e of n){const i=this.getters.getColSize(u,e),n=Lt(e);t.fillStyle=m.has(e)?"#fff":C;let s=this.getHeaderOffset("COL",o,e);t.fillText(n,s+i/2,13),t.moveTo(s+i,0),t.lineTo(s+i,N)}for(const e of s){const i=this.getters.getRowSize(u,e);t.fillStyle=f.has(e)?"#fff":C;let n=this.getHeaderOffset("ROW",r,e);t.fillText(String(e+1),24,n+i/2),t.moveTo(0,n+i),t.lineTo(M,n+i)}t.stroke()}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:i}=e,{x:n,y:o}=this.getters.getMainViewportCoordinates(),s=this.getters.isDashboard()?0:M,r=this.getters.isDashboard()?0:N;t.lineWidth=6*i,t.strokeStyle="#BCBCBC",t.beginPath(),n&&(t.moveTo(s+n,0),t.lineTo(s+n,r)),o&&(t.moveTo(0,r+o),t.lineTo(s,r+o)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:i}=e,{x:n,y:o}=this.getters.getMainViewportCoordinates(),s=this.getters.getSheetViewVisibleCols(),r=s[0],a=s[s.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:r,right:a,top:l[0],bottom:l[l.length-1]},h=this.getters.getVisibleRect(c),d=this.getters.isDashboard()?0:M,u=this.getters.isDashboard()?0:N;t.lineWidth=6*i,t.strokeStyle="#DADFE8",t.beginPath(),n&&(t.moveTo(d+n,u),t.lineTo(d+n,h.height+u)),o&&(t.moveTo(d,u+o),t.lineTo(h.width+d,u+o)),t.stroke()}hasContent(e,t){const i=this.getters.getActiveSheetId(),n=this.getters.getCell(i,e,t);return n&&!n.isEmpty()||this.getters.isInMerge(i,e,t)}findNextEmptyCol(e,t,i){let n=e;for(;n<t&&!this.hasContent(n+1,i);)n++;return n}findPreviousEmptyCol(e,t,i){let n=e;for(;n>t&&!this.hasContent(n-1,i);)n--;return n}computeCellAlignment(e,t){if(e.isFormula()&&this.getters.shouldShowFormulas())return"left";const{align:i}=this.getters.getCellStyle(e);return t&&e.evaluated.type===ln.number?"center"!==i?"left":i:i||e.defaultAlign}createZoneBox(e,t,i){const{left:n,right:o}=i,s=t.left,r=t.top,a=this.getters.getCell(e,s,r),c=this.getters.shouldShowFormulas(),{x:h,y:d,width:u,height:g}=this.getters.getRect(t),p={x:h,y:d,width:u,height:g,border:this.getters.getCellBorderWithFilterBorder(e,s,r)||void 0,style:this.getters.getCellComputedStyle(e,s,r)};if(!a)return p;const m=this.getters.getConditionalIcon(s,r),f=ke(p.style),v=m?2*L+f:0;m&&(p.image={type:"icon",size:f,clipIcon:{x:p.x,y:p.y,width:Math.min(v,u),height:g},image:vr[m].img}),p.isFilterHeader=this.getters.isFilterHeader(e,s,r);const b=p.isFilterHeader?19:0,S=this.getters.getCellText(a,c),C=this.getters.getTextWidth(a),E=this.getters.getCellStyle(a).wrapping||"overflow",w="wrap"===E?this.getters.getCellMultiLineText(a,u-2*P):[S],y=v+C+b,x=this.computeCellAlignment(a,y>u);p.content={multiLineText:w,width:"overflow"===E?C:u,align:x},a.evaluated.type===ln.error&&a.evaluated.error.logLevel>l.silent&&(p.error=a.evaluated.error.message);const R=y>u||f>g;if(m||p.isFilterHeader)p.clipRect={x:p.x+v,y:p.y,width:Math.max(0,u-v-b),height:g};else if(R&&"overflow"===E){let i,a;switch(this.getters.isInMerge(e,s,r)?(i=this.getters.getMerge(e,s,r).right,a=s):(i=this.findNextEmptyCol(s,o,r),a=this.findPreviousEmptyCol(s,n,r)),x){case"left":{const e=Qi({col:i,row:r}),{x:n,y:o,width:s,height:a}=this.getters.getVisibleRect(Pi(t,e));(s<C||f>a)&&(p.clipRect={x:n,y:o,width:s,height:a});break}case"right":{const e=Qi({col:a,row:r}),{x:i,y:n,width:o,height:s}=this.getters.getVisibleRect(Pi(t,e));(o<C||f>s)&&(p.clipRect={x:i,y:n,width:o,height:s});break}case"center":{const e={...t,right:i,left:a},{x:n,y:o,width:r,height:l}=this.getters.getVisibleRect(e);(r<C||a===s||i===s||f>l)&&(p.clipRect={x:n,y:o,width:r,height:l});break}}}else"clip"!==E&&"wrap"!==E||(p.clipRect={x:p.x,y:p.y,width:u,height:g});return p}getGridBoxes(e){const t=[],i=this.getters.getSheetViewVisibleCols().filter((t=>t>=e.left&&t<=e.right)),n=i[0],o=i[i.length-1],s=this.getters.getSheetViewVisibleRows().filter((t=>t>=e.top&&t<=e.bottom)),r={left:n,right:o,top:s[0],bottom:s[s.length-1]},a=this.getters.getActiveSheetId();for(const e of s)for(const n of i)this.getters.isInMerge(a,n,e)||t.push(this.createZoneBox(a,Qi({col:n,row:e}),r));for(const e of this.getters.getMerges(a))if(!this.getters.isMergeHidden(a,e)&&zi(e,r)){const i=this.createZoneBox(a,e,r),n=this.getters.getCellBorder(a,e.right,e.bottom);i.border={...i.border,bottom:n?n.bottom:void 0,right:n?n.right:void 0},i.isMerge=!0,t.push(i)}return t}}Bv.layers=[0,7],Bv.getters=["getColDimensionsInViewport","getRowDimensionsInViewport"];const Hv=[{name:s("Sum"),types:[ln.number],compute:e=>ul.compute([e])},{name:s("Avg"),types:[ln.number],compute:e=>yl.compute([e])},{name:s("Min"),types:[ln.number],compute:e=>Vl.compute([e])},{name:s("Max"),types:[ln.number],compute:e=>$l.compute([e])},{name:s("Count"),types:[ln.number,ln.text,ln.boolean,ln.error],compute:e=>Ml.compute([e])},{name:s("Count Numbers"),types:[ln.number,ln.text,ln.boolean,ln.error],compute:e=>Nl.compute([e])}];class Wv extends Bg{constructor(e,t,i,n,o){super(e,t,i,n,o),this.gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]},this.selectedFigureId=null,this.sheetsData={},this.activeSheet=null,this.moveClient=n.moveClient}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{this.getters.getSheet(e.sheetIdTo);break}catch(e){return 27}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return 0}handleEvent(e){const t=e.anchor;let i=[];switch(e.mode){case"overrideSelection":i=[t.zone];break;case"updateAnchor":i=[...this.gridSelection.zones];const n=i.findIndex((t=>Vi(t,e.previousAnchor.zone)));n>=0&&(i[n]=t.zone);break;case"newAnchor":i=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,i),this.selection.resetDefaultAnchor(this,Ae(this.gridSelection.anchor));const{col:n,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:n,row:o}),this.selectedFigureId=null}handle(e){switch(e.type){case"START_EDITION":case"ACTIVATE_SHEET":this.selectedFigureId=null;break;case"DELETE_FIGURE":this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;case"DELETE_SHEET":this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null)}switch(e.type){case"START":const t=this.getters.getVisibleSheetIds()[0];this.dispatch("ACTIVATE_SHEET",{sheetIdTo:t,sheetIdFrom:t});const{col:i,row:n}=this.getters.getNextVisibleCellPosition(t,0,0);this.selectCell(i,n),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:Ae(this.gridSelection)},e.sheetIdTo in this.sheetsData)Object.assign(this,this.sheetsData[e.sheetIdTo]),this.selection.resetDefaultAnchor(this,Ae(this.gridSelection.anchor));else{const{col:t,row:i}=this.getters.getNextVisibleCellPosition(e.sheetIdTo,0,0);this.selectCell(t,i)}const{col:t,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:t,row:i});break}case"REMOVE_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);const{col:i,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:i,row:n})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:i,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:i,row:n})}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 o=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of o)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:Ae(t)}}this.fallbackToVisibleSheet();const s=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map((e=>this.getters.expandZone(s,e))),this.gridSelection.anchor.zone=this.getters.expandZone(s,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,Ae(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveCell(){const e=this.getters.getActiveSheetId(),{col:t,row:i}=this.gridSelection.anchor.cell,{col:n,row:o}=this.getters.getMainCellPosition(e,t,i);return this.getters.getCell(e,n,o)}getActiveCols(){const e=new Set;for(let t of this.gridSelection.zones)if(0===t.top&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let i=t.left;i<=t.right;i++)e.add(i);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(let i of this.gridSelection.zones)if(0===i.left&&i.right===this.getters.getNumberCols(t)-1)for(let t=i.top;t<=i.bottom;t++)e.add(t);return e}getCurrentStyle(){const e=this.getters.getActiveCell();return e?this.getters.getCellStyle(e):{}}getSelectedZones(){return Ae(this.gridSelection.zones)}getSelectedZone(){return Ae(this.gridSelection.anchor.zone)}getSelection(){return Ae(this.gridSelection)}getSelectedFigureId(){return this.selectedFigureId}getPosition(){return{col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row}}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getPosition();{const t=this.sheetsData[e];return t?{col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition(e,0,0)}}getStatisticFnResults(){const e=this.getters.getActiveSheetId(),t=new Set(this.gridSelection.zones.map((t=>this.getters.getCellsInZone(e,t))).flat().filter((t=>{if(!t)return!1;const{col:i,row:n}=this.getters.getCellPosition(null==t?void 0:t.id);return!this.getters.isRowHidden(e,n)&&!this.getters.isColHidden(e,i)})));let i=new Set,n=[];for(let e of t)i.add(e.evaluated.type),n.push(e.evaluated.value);let o={};for(let e of Hv){let t;e.types.some((e=>i.has(e)))&&(t=e.compute(n)),o[e.name]=t}return o}getAggregate(){let e=0,t=0;const i=this.getters.getActiveSheetId(),n=this.gridSelection.zones.map(ji).flat();for(const{col:o,row:s}of n){const n=this.getters.getCell(i,o,s);(null==n?void 0:n.evaluated.type)===ln.number&&(t++,e+=n.evaluated.value)}return t<2?null:Qt(e)}isSelected(e){return!!this.getters.getSelectedZones().find((t=>Vi(t,e)))}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let i=[];const n="COL"===e?"left":"top",o="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[o]-e[n]+1},((t,i)=>e[n]+i));i=i.concat(t)}return[...new Set(i)].sort()}setSelectionMixin(e,t){const{anchor:i,zones:n}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=i,this.gridSelection.zones=function(e){return e.reverse().filter(((e,t,i)=>t===i.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}(n)}selectCell(e,t){const i=this.getters.getActiveSheetId(),n=this.getters.expandZone(i,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:n,cell:{col:e,row:t}},[n])}setActiveSheet(e){const t=this.getters.getSheet(e);this.activeSheet=t}activateNextSheet(e){const t=this.getters.getSheetIds(),i=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[i]})}onColumnsRemoved(e){const{cell:t,zone:i}=this.gridSelection.anchor,n=$i(i,"left",[...e.elements]);let o={left:t.col,right:t.col,top:t.row,bottom:t.row};o=$i(o,"left",[...e.elements]);const s={cell:{col:o.left,row:o.top},zone:n};this.setSelectionMixin(s,[n])}onRowsRemoved(e){const{cell:t,zone:i}=this.gridSelection.anchor,n=$i(i,"top",[...e.elements]);let o={left:t.col,right:t.col,top:t.row,bottom:t.row};o=$i(o,"top",[...e.elements]);const s={cell:{col:o.left,row:o.top},zone:n};this.setSelectionMixin(s,[n])}onAddElements(e){const t=ki(this.gridSelection.anchor.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),i={cell:{col:t.left,row:t.top},zone:t};this.setSelectionMixin(i,[t])}onMoveElements(e){const t=e.elements.length;this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:e.position});const i="COL"===e.dimension,n=e.elements[0],o=e.elements[t-1],s=e.base<n,r=s&&i?t:0,a=s&&!i?t:0,l=[{left:i?n+r:0,right:i?o+r:this.getters.getNumberCols(e.sheetId)-1,top:i?0:n+a,bottom:i?this.getters.getNumberRows(e.sheetId)-1:o+a}],c=new Tv(l,"CUT",this.getters,this.dispatch,this.selection),h=s?e.base:e.base+1,d=[{left:i?h:0,right:i?h+t-1:this.getters.getNumberCols(e.sheetId)-1,top:i?0:h,bottom:i?this.getters.getNumberRows(e.sheetId)-1:h+t-1}];c.paste(d,{selectTarget:!0});const u=s?e.elements.map((e=>e+t)):e.elements;let g=s?e.base:e.base+1;for(const t of u){const i="COL"===e.dimension?this.getters.getColSize(e.sheetId,t):this.getters.getRowSize(e.sheetId,t);this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:i,elements:[g]}),g+=1}this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,elements:u})}isMoveElementAllowed(e){const t="COL"===e.dimension,i=e.elements[0],n=e.elements[e.elements.length-1],o=e.sheetId,s=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(s(o,i-1,i)||s(o,n,n+1)||s(o,e.base-1,e.base))return 2;const r=[e.base,...e.elements],a=t?this.getters.getNumberCols(o):this.getters.getNumberRows(o);return r.some((e=>e<0||e>=a))?87:0}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){const e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){const{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);const{col:t,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:i})}}clipSelection(e,t){const i=this.getters.getNumberCols(e)-1,n=this.getters.getNumberRows(e)-1;return{zones:t.zones.map((e=>({left:Me(e.left,0,i),right:Me(e.right,0,i),top:Me(e.top,0,n),bottom:Me(e.bottom,0,n)}))),anchor:{cell:{col:Me(t.anchor.cell.col,0,i),row:Me(t.anchor.cell.row,0,n)},zone:{left:Me(t.anchor.zone.left,0,i),right:Me(t.anchor.zone.right,0,i),top:Me(t.anchor.zone.top,0,n),bottom:Me(t.anchor.zone.bottom,0,n)}}}}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:i}=e,n=this.getSelectedZones();t.fillStyle="#f3f7fe";const o=1===n.length&&n[0].left===n[0].right&&n[0].top===n[0].bottom;t.fillStyle=o?"#f3f7fe":"#e9f0ff",t.strokeStyle=E,t.lineWidth=1.5*i,t.globalCompositeOperation="multiply";for(const e of n){const{x:i,y:n,width:o,height:s}=this.getters.getVisibleRect(e);t.fillRect(i,n,o,s),t.strokeRect(i,n,o,s)}t.globalCompositeOperation="source-over";const s=this.getters.getActiveSheetId(),{col:r,row:a}=this.getPosition();let l;t.strokeStyle=E,t.lineWidth=3*i,l=this.getters.isInMerge(s,r,a)?this.getters.getMerge(s,r,a):{top:a,bottom:a,left:r,right:r};const{x:c,y:h,width:d,height:u}=this.getters.getVisibleRect(l);d>0&&u>0&&t.strokeRect(c,h,d,u)}}Wv.layers=[5],Wv.getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getStatisticFnResults","getAggregate","getSelectedFigureId","getSelection","getPosition","getSheetPosition","isSelected","getElementsFromSelection","isGridSelectionActive"];const Gv=new Oi;class qv extends Bg{constructor(e,t,i,n,o,s,r){if(r&&s.length>1)throw new Error("Input with a single range cannot be instantiated with several range references.");super(e,t,i,n,o),this.inputHasSingleRange=r,this.ranges=[],this.focusedRangeIndex=null,this.willAddNewRange=!1,this.insertNewRange(0,s),this.activeSheet=this.getters.getActiveSheetId(),0===this.ranges.length&&(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}handleEvent(e){const t=Fi(e.anchor.zone),i=this.activeSheet,n=this.getters.getActiveSheetId(),o=this.getters.getSheetName(n);this.add([n===i?t:`${Ne(o)}!${t}`])}handle(e){switch(e.type){case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"FOCUS_RANGE":this.focus(this.getIndex(e.rangeId));break;case"CHANGE_RANGE":{const t=this.getIndex(e.rangeId);if(null!==t&&this.focusedRangeIndex!==t&&this.focus(t),null!==t){const i=e.value.split(",").map((e=>e.trim()));this.setRange(t,i)}break}case"ADD_EMPTY_RANGE":this.insertNewRange(this.ranges.length,[""]),this.focusLast();break;case"REMOVE_RANGE":const t=this.getIndex(e.rangeId);null!==t&&this.removeRange(t);break;case"STOP_SELECTION_INPUT":this.willAddNewRange=!1;break;case"PREPARE_SELECTION_INPUT_EXPANSION":{const e=this.focusedRangeIndex;null===e||this.inputHasSingleRange||(this.willAddNewRange=""!==this.ranges[e].xc.trim());break}case"ACTIVATE_SHEET":if(e.sheetIdFrom!==e.sheetIdTo){const{col:t,row:i}=this.getters.getNextVisibleCellPosition(e.sheetIdTo,0,0),n=this.getters.expandZone(e.sheetIdTo,Qi({col:t,row:i}));this.selection.resetAnchor(this,{cell:{col:t,row:i},zone:n})}}}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],id:Gv.smallUuid(),xc:t}}insertNewRange(e,t){this.ranges.splice(e,0,...t.map(((e,t)=>({xc:e,id:(this.ranges.length+t+1).toString(),color:(pt=++pt%ut.length,ut[pt])}))))}setRange(e,t){const[,...i]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,i),i.length&&this.focus(e+i.length)}removeRange(e){this.ranges.splice(e,1),null!==this.focusedRangeIndex&&this.focusLast()}inputToHighlights({xc:e,color:t}){const i=this.cleanInputs([e]).filter((e=>this.getters.isRangeValid(e))).filter((e=>this.shouldBeHighlighted(this.activeSheet,e)));return i.map((e=>{const{sheetName:i}=$t(e);return{zone:this.getters.getRangeFromSheetXC(this.activeSheet,e).zone,sheetId:i&&this.getters.getSheetIdByName(i)||this.activeSheet,color:t}}))}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:i}=$t(t),n=this.getters.getSheetIdByName(i),o=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(n===o||void 0===n&&o===e)}getIndex(e){const t=this.ranges.findIndex((t=>t.id===e));return t>=0?t:null}}qv.layers=[1],qv.getters=[];class Zv extends Bg{get currentInput(){return this.focusedInputId?this.inputs[this.focusedInputId]:null}constructor(e,t,i,n,o){super(e,t,i,n,o),this.state=t,this.config=n,this.inputs={},this.focusedInputId=null}allowDispatch(e){var t,i;switch(e.type){case"FOCUS_RANGE":case"CHANGE_RANGE":case"ADD_EMPTY_RANGE":case"REMOVE_RANGE":if(!this.inputs[e.id])return 31}switch(e.type){case"FOCUS_RANGE":const n=null===(t=this.currentInput)||void 0===t?void 0:t.getIndex(e.rangeId);if(this.focusedInputId===e.id&&(null===(i=this.currentInput)||void 0===i?void 0:i.focusedRangeIndex)===n)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){var t;switch(e.type){case"ENABLE_NEW_SELECTION_INPUT":this.initInput(e.id,e.initialRanges||[],e.hasSingleRange);break;case"DISABLE_SELECTION_INPUT":this.focusedInputId===e.id&&this.unfocus(),delete this.inputs[e.id];break;case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"ADD_EMPTY_RANGE":case"REMOVE_RANGE":case"FOCUS_RANGE":case"CHANGE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id];this.selection.capture(t,{cell:{col:0,row:0},zone:Qi({col:0,row:0})},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}}null===(t=this.currentInput)||void 0===t||t.handle(e)}getSelectionInput(e){return this.inputs[e]?this.inputs[e].ranges.map(((t,i)=>Object.assign({},t,{color:this.focusedInputId===e&&null!==this.inputs[e].focusedRangeIndex&&this.isRangeValid(t.xc)?t.color:null,isFocused:this.focusedInputId===e&&this.inputs[e].focusedRangeIndex===i}))):[]}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:i}=$t(e);return null!==t.match(Nt)&&(!i||void 0!==this.getters.getSheetIdByName(i))}getSelectionInputValue(e){return this.inputs[e].getSelectionInputValue()}getSelectionInputHighlights(){return this.focusedInputId?this.inputs[this.focusedInputId].getSelectionInputHighlights():[]}initInput(e,t,i=!1){if(this.inputs[e]=new qv(this.getters,this.state,this.dispatch,this.config,this.selection,t,i),0===t.length){const t=this.inputs[e],i={zone:Qi({col:0,row:0}),cell:{col:0,row:0}};this.selection.capture(t,i,{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e}}unfocus(){this.selection.release(this.currentInput),this.focusedInputId=null}}Zv.layers=[1],Zv.getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];class jv{constructor(){this.subscriptions={}}on(e,t,i){if(!i)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:i})}trigger(e,t){const i=this.subscriptions[e]||[];for(let e=0,n=i.length;e<n;e++){const n=i[e];n.callback.call(n.owner,t)}}off(e,t){const i=this.subscriptions[e];i&&(this.subscriptions[e]=i.filter((e=>e.owner!==t)))}clear(){this.subscriptions={}}}function Yv(e,t){return{...e,definition:Ls(e.definition,t)}}function Xv(e,t){if(e.sheetId!==t.sheetId)return e;if(("FREEZE_COLUMNS"===e.type?"COL":"ROW")!==t.dimension)return e;let i=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));for(let t of e)i>t&&i--}if("ADD_COLUMNS_ROWS"===t.type){i=i>("before"===t.position?t.base-1:t.base)?i+t.quantity:i}return i>0?{...e,quantity:i}:void 0}ss.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],Yv),ss.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],Yv),ss.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const i=t.sheetId;if(e.targetSheetId===i||e.sheetId===i)return;return e})),ss.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),ss.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){var i;e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`});if(e.name===t.name)return{...e,name:(null===(i=e.name)||void 0===i?void 0:i.match(/\d+/))?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),ss.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE","CREATE_FILTER_TABLE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const i=[];for(const n of e.target)t.target.every((e=>!zi(n,e)))&&i.push(n);if(i.length)return{...e,target:i};return})),ss.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],Xv),ss.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],Xv),ss.addTransformation("CREATE_FILTER_TABLE",["CREATE_FILTER_TABLE","ADD_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;for(const i of e.target)for(const e of t.target)if(zi(e,i))return;return e}));const Kv=[{match:function(e){return"sheetId"in e},fn:eb},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const i=eb(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;const n=[];for(const i of e.target){const e=us(i,t);e&&n.push(e)}if(!n.length)return"IGNORE_COMMAND";return{...e,target:n}}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const i=eb(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const i="COL"===t.dimension?"col":"row";let n=e[i];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(n))return"IGNORE_COMMAND";for(let t of e)n>=t&&n--}"ADD_COLUMNS_ROWS"===t.type&&(n>t.base||n===t.base&&"before"===t.position)&&(n+=t.quantity);return{...e,[i]:n}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const i of t.target){if(!(e.col===i.left&&e.row===i.top)&&Bi(e.col,e.row,i))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e&&"sheetId"in e},fn:function(e,t){const i=eb(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type){if(t.dimension!==e.dimension)return e;const i="ADD_COLUMNS_ROWS"===e.type,n=i?"base":"elements";let o=i?[e[n]]:e[n];if("REMOVE_COLUMNS_ROWS"===t.type&&(o=o.map((e=>{if(t.elements.includes(e))return;const i=t.elements.sort(((e,t)=>t-e));for(let t of i)e>t&&e--;return e})).filter(Xe)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;o=o.map((i=>i>e?i+t.quantity:i))}if(o.length){let t=o;return i&&(t=o[0]),{...e,[n]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}},{match:function(e){return"ranges"in e},fn:function(e,t){const i=[],n="DELETE_SHEET"===t.type&&t.sheetId;for(const o of e.ranges)if(o._sheetId!==t.sheetId)i.push({...o,_zone:o._zone});else{const e=us(o._zone,t);e&&n!==o._sheetId&&i.push({...o,_zone:e})}if(!i.length)return"IGNORE_COMMAND";return{...e,ranges:i}}}];function Qv(e,t){const i=ss.getTransformation(e.type,t.type);return i?i(e,t):function(e,t){for(const{match:i,fn:n}of Kv)if(i(e)){const i=n(e,t);if("SKIP_TRANSFORMATION"===i)continue;if("IGNORE_COMMAND"===i)return;e=i}return e}(e,t)}function Jv(e,t){let i=[...e];for(const e of t)i=i.map((t=>Qv(t,e))).filter(Xe);return i}function eb(e,t){const i="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===i?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class tb{constructor(e,t,i,n){this._commands=[],this._changes=[],this.id=e,this.clientId=t,this._commands=[...i],this._changes=n?[...n]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class ib extends Error{}class nb extends jv{constructor(e,t,i=K){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=i,this.clients={},this.clientId="local",this.pendingMessages=[],this.waitingAck=!1,this.waitingUndoRedoAck=!1,this.isReplayingInitialRevisions=!1,this.processedRevisions=new Set,this.uuidGenerator=new Oi,this.debouncedMove=function(e,t,i){let n;return function(){const o=this,s=arguments,r=i&&!n;clearTimeout(n),n=setTimeout((function(){n=null,i||e.apply(o,s)}),t),r&&e.apply(o,s)}}(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t){if(!e.length||!t.length||!this.canApplyOptimisticUpdate())return;const i=new tb(this.uuidGenerator.uuidv4(),this.clientId,e,t);this.revisions.append(i.id,i),this.trigger("new-local-state-update",{id:i.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:i.id,clientId:i.clientId,commands:i.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_UNDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_REDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:"local",name:"local"},this.clientId="local"),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this))}loadInitialMessages(e){this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1}leave(){delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}snapshot(e){const t=this.uuidGenerator.uuidv4();this.transportService.sendMessage({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){const e=this.clients[this.clientId];if(!e)throw new ib("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(Xe))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}_move(e){var t;if(!this.clients[this.clientId])return;const i=null===(t=this.clients[this.clientId])||void 0===t?void 0:t.position;if((null==i?void 0:i.col)===e.col&&i.row===e.row&&i.sheetId===e.sheetId)return;const n=i?"CLIENT_MOVED":"CLIENT_JOINED",o=this.getClient();this.clients[this.clientId]={...o,position:e},this.transportService.sendMessage({type:n,version:1,client:{...o,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:i}=e,n=new tb(e.nextRevisionId,t,i);if(n.clientId!==this.clientId){this.revisions.insert(n.id,n,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:Jv(i,t)})}break;case"SNAPSHOT_CREATED":{const t=new tb(e.nextRevisionId,"server",[]);this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger("snapshot");break}}this.acknowledge(e),this.trigger("collaborative-event-received")}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;const t=this.clients[this.clientId];if(t){const{position:e}=t;e&&this.transportService.sendMessage({type:"CLIENT_MOVED",version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),this.waitingAck||(this.waitingAck=!0,this.sendPendingMessage())}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if("REMOTE_REVISION"===e.type){let t=this.revisions.get(e.nextRevisionId);0===t.commands.length&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),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"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();break;case"REVISION_UNDONE":{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter((t=>t.nextRevisionId!==e.nextRevisionId));const t=this.pendingMessages.findIndex((e=>"REMOTE_REVISION"===e.type));-1!==t&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}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":case"SNAPSHOT_CREATED":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 ob=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];class sb extends Bg{constructor(){super(...arguments),this.availableColors=new Set(ob),this.colors={}}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}chooseNewColor(){0===this.availableColors.size&&(this.availableColors=new Set(ob));const e=(t=[...this.availableColors.values()])[Math.floor(Math.random()*t.length)];var t;return this.availableColors.delete(e),e}getClientsToDisplay(){try{this.getters.getClient()}catch(e){if(e instanceof ib)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const i of this.getters.getConnectedClients())if(i.id!==this.getters.getClient().id&&i.position&&i.position.sheetId===e&&this.isPositionValid(i.position)){const e=i.position;this.colors[i.id]||(this.colors[i.id]=this.chooseNewColor());const n=this.colors[i.id];t.push({...i,position:e,color:n})}return t}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:i}=e,n=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:o,col:s}=e.position,r=this.getters.expandZone(n,{top:o,bottom:o,left:s,right:s}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);if(c<=0||h<=0)continue;const d=e.color,u=`${d}10`;t.fillStyle=u,t.lineWidth=4*i,t.strokeStyle=d,t.globalCompositeOperation="multiply",t.fillRect(a,l,c,h),t.globalCompositeOperation="source-over",t.strokeRect(a,l,c,h),t.font=`bold ${G+1}px ${q}`}}}sb.getters=["getClientsToDisplay"],sb.layers=[5];class rb{constructor(e,t,i,n,o,s){if(this.getters=e,this.sheetId=t,this.boundaries=i,n.width<0||n.height<0)throw new Error("Viewport size cannot be negative");this.viewportWidth=n.height&&n.width,this.viewportHeight=n.width&&n.height,this.top=i.top,this.bottom=i.bottom,this.left=i.left,this.right=i.right,this.offsetX=s.x,this.offsetY=s.y,this.offsetScrollbarX=s.x,this.offsetScrollbarY=s.y,this.canScrollVertically=o.canScrollVertically,this.canScrollHorizontally=o.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){const e=this.getters.findLastVisibleColRowIndex(this.sheetId,"COL",{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,"ROW",{first:this.boundaries.top,last:this.boundaries.bottom}),{end:i,size:n}=this.getters.getColDimensions(this.sheetId,e),{end:o,size:s}=this.getters.getRowDimensions(this.sheetId,t),r=this.searchHeaderIndex("COL",i-this.viewportWidth,0),a=this.getters.getColSize(this.sheetId,r),l=this.searchHeaderIndex("ROW",o-this.viewportHeight,0),c=this.getters.getRowSize(this.sheetId,l);let h=i-this.offsetCorrectionX;this.canScrollHorizontally&&(h+=Math.max(_,Math.min(a,this.viewportWidth-n)),h=Math.max(h,this.viewportWidth));let d=o-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(F+5,Math.min(c,this.viewportHeight-s)),d=Math.max(d,this.viewportHeight)),{width:h,height:d}}getColIndex(e,t=!1){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex("COL",e-this.offsetCorrectionX,this.left,t)}getRowIndex(e,t=!1){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex("ROW",e-this.offsetCorrectionY,this.top,t)}adjustPosition(e){const t=this.sheetId;e||(e=this.getters.getSheetPosition(t));const i=this.getters.getMainCellPosition(t,e.col,e.row),{col:n,row:o}=this.getters.getNextVisibleCellPosition(t,i.col,i.row);Bi(n,this.boundaries.top,this.boundaries)&&this.adjustPositionX(n),Bi(this.boundaries.left,o,this.boundaries)&&this.adjustPositionY(o)}adjustPositionX(e){const t=this.sheetId,{end:i}=this.getters.getColDimensions(t,e),n=this.getters.getNumberCols(t);if(this.offsetX+this.offsetCorrectionX+this.viewportWidth<i){let i=e;for(;this.getters.isColHidden(t,i)&&e<n;)i++;const o=this.getters.getColDimensions(t,i).end,s=this.searchHeaderIndex("COL",o-this.viewportWidth-this.offsetCorrectionX,this.boundaries.left,!0);this.offsetX=this.getters.getColDimensions(t,s).end-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX()}else if(this.left>e){let i=e;for(;this.getters.isColHidden(t,i)&&e>0;)i--;this.offsetX=this.getters.getColDimensions(t,i).start-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX()}}adjustPositionY(e){const t=this.sheetId,{end:i}=this.getters.getRowDimensions(t,e),n=this.getters.getNumberRows(t);if(this.offsetY+this.viewportHeight+this.offsetCorrectionY<i){let i=e;for(;this.getters.isRowHidden(t,i)&&e<n;)i++;const o=this.getters.getRowDimensions(t,i).end,s=this.searchHeaderIndex("ROW",o-this.viewportHeight-this.offsetCorrectionY,this.boundaries.top,!0);this.offsetY=this.getters.getRowDimensions(t,s).end-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY()}else if(this.top>e){let i=e;for(;this.getters.isRowHidden(t,i)&&e>0;)i--;this.offsetY=this.getters.getRowDimensions(t,i).start-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY()}}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getVisibleRect(e){const t=Ui(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)}}}getFullRect(e){if(Ui(e,this.zone)){return{x:this.getters.getColRowOffset("COL",this.zone.left,e.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset("ROW",this.zone.top,e.top)+this.offsetCorrectionY,width:this.getters.getColRowOffset("COL",e.left,e.right+1),height:this.getters.getColRowOffset("ROW",e.top,e.bottom+1)}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,i=0,n=!1){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;let o=0;const s=this.sheetId,r=this.getters.getNumberHeaders(s,e);for(let a=i;a<=r-1;a++){const i=n||"COL"!==e?a<this.top&&a>this.bottom:a<this.left&&a>this.right;if(!this.getters.isHeaderHidden(s,e,a)&&!i&&(o+="COL"===e?this.getters.getColSize(s,a):this.getters.getRowSize(s,a),o>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)),this.viewportWidth&&(-1===this.left&&(this.left=this.boundaries.left),-1===this.right&&(this.right=this.boundaries.right),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)),this.viewportHeight&&(-1===this.top&&(this.top=this.boundaries.top),-1===this.bottom&&(this.bottom=this.boundaries.bottom),this.offsetY=this.getters.getRowDimensions(e,this.top).start-this.getters.getRowDimensions(e,this.boundaries.top).start)}}class ab extends Bg{constructor(){super(...arguments),this.viewports={},this.sheetViewWidth=1e3,this.sheetViewHeight=1e3,this.gridOffsetX=0,this.gridOffsetY=0,this.sheetsWithDirtyViewports=new Set}allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.checkScrollingDirection(e);case"RESIZE_SHEETVIEW":return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return 0}}handleEvent(e){switch(e.type){case"HeadersSelected":case"AlterZoneCorner":break;case"ZonesSelected":const t=this.getters.getActiveSheetId();let{col:i,row:n}=Xi(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const o=e.previousAnchor.zone,s=e.anchor.zone,{top:r,bottom:a,left:l,right:c}=this.getMainInternalViewport(t);o.left===s.left&&o.right===s.right&&(i=l>i||i>c?l:i),o.top===s.top&&o.bottom===s.bottom&&(n=r>n||n>a?r:n)}i=Math.min(i,this.getters.getNumberCols(t)-1),n=Math.min(n,this.getters.getNumberRows(t)-1),this.refreshViewport(t,{col:i,row:n})}}handle(e){var t;switch(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 i=this.getters.getActiveSheetId(),{top:n,viewportHeight:o,offsetCorrectionY:s}=this.getMainInternalViewport(i),r=this.getters.getRowDimensions(i,n);this.shiftVertically(r.start+o-s);break;case"SHIFT_VIEWPORT_UP":{const e=this.getters.getActiveSheetId(),{top:t,viewportHeight:i,offsetCorrectionY:n}=this.getMainInternalViewport(e),o=this.getters.getRowDimensions(e,t);this.shiftVertically(o.end-n-i);break}case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"UPDATE_FILTER":this.resetViewports(e.sheetId);break;case"UPDATE_CELL":("content"in e||"format"in e||void 0!==(null===(t=e.style)||void 0===t?void 0:t.fontSize))&&this.sheetsWithDirtyViewports.add(e.sheetId);break;case"DELETE_SHEET":this.cleanViewports(),this.sheetsWithDirtyViewports.delete(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"START_EDITION":const{col:a,row:l}=this.getters.getPosition();this.refreshViewport(this.getters.getActiveSheetId(),{col:a,row:l})}}finalize(){for(const e of this.sheetsWithDirtyViewports)this.resetViewports(e);this.sheetsWithDirtyViewports=new Set,this.setViewports()}setViewports(){var e;const t=this.getters.getSheetIds();for(const i of t)(null===(e=this.viewports[i])||void 0===e?void 0:e.bottomRight)||this.resetViewports(i)}getColIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getColIndex(e))))}getRowIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getRowIndex(e))))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getActiveMainViewport(){const e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getActiveSheetDOMScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetScrollbarX,scrollY:t.offsetScrollbarY}}getSheetViewVisibleCols(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>$e(e.left,e.right+1))).flat())].filter((t=>t>=0&&!this.getters.isHeaderHidden(e,"COL",t)))}getSheetViewVisibleRows(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>$e(e.top,e.bottom+1))).flat())].filter((t=>t>=0&&!this.getters.isHeaderHidden(e,"ROW",t)))}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:i,ySplit:n}=this.getters.getPaneDivisions(e);let{width:o,height:s}=t.getMaxSize();return{x:this.getters.getColDimensions(e,i).start,y:this.getters.getRowDimensions(e,n).start,width:o,height:s}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:i}=this.getMainViewportRect(),n=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-n.viewportWidth+1),maxOffsetY:Math.max(0,i-n.viewportHeight+1)}}getColRowOffsetInViewport(e,t,i){if(i<t)return-this.getColRowOffsetInViewport(e,i,t);const n=this.getters.getActiveSheetId(),o="COL"===e?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),s=o.findIndex((e=>t>=e));let r=o.findIndex((e=>i<=e));r=-1===r?o.length:r;const a=o.slice(s,r);let l=0;for(const t of a)l+="COL"===e?this.getters.getColSize(n,t):this.getters.getRowSize(n,t);return l}isVisibleInViewport(e,t,i){return this.getSubViewports(e).some((e=>e.isVisible(t,i)))}getEdgeScrollCol(e,t,i){let n=!1,o=0,s=0;const{xSplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(n=!0,s=Wt(e-a),o=1):e<l&&i>=l&&c>0?(n=!0,s=Wt(l-e),o=-1):r&&t<l&&e>l&&(n=!0,s=Wt(e),o="reset"),{canEdgeScroll:n,direction:o,delay:s}}getEdgeScrollRow(e,t,i){let n=!1,o=0,s=0;const{ySplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(n=!0,s=Wt(e-a),o=1):e<l&&i>=l&&c>0?(n=!0,s=Wt(l-e),o=-1):r&&t<l&&e>l&&(n=!0,s=Wt(e),o="reset"),{canEdgeScroll:n,direction:o,delay:s}}getVisibleRect(e){const t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,(t=>t.getVisibleRect(e)))}getRect(e){const t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,(t=>t.getFullRect(e)))}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,i).start}}getAllActiveViewportsZones(){const e=this.getters.getActiveSheetId();return this.getSubViewports(e)}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(Xe)}checkPositiveDimension(e){return e.width<0||e.height<0?69:0}checkValuesAreDifferent(e){const{height:t,width:i}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===i&&e.height===t?77:0}checkScrollingDirection({offsetX:e,offsetY:t}){const i=this.getMainInternalViewport(this.getters.getActiveSheetId());return!i.canScrollHorizontally&&e>0||!i.canScrollVertically&&t>0?70:0}getMainViewport(e){const t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){const e={};for(const t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resetSheetViews(){this.cleanViewports();for(let e of Object.keys(this.viewports)){const t=this.getters.getSheetPosition(e);this.resetViewports(e);const i=this.getSubViewports(e);Object.values(i).forEach((e=>{e.adjustPosition(t)}))}}resizeSheetView(e,t,i=0,n=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=i,this.gridOffsetY=n,this.recomputeViewports()}recomputeViewports(){for(const e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){const i=this.getters.getActiveSheetId(),{maxOffsetX:n,maxOffsetY:o}=this.getMaximumSheetOffset();this.getSubViewports(i).forEach((i=>i.setViewportOffset(Me(e,0,n),Me(t,0,o))))}getViewportOffset(e){var t,i;return{x:(null===(t=this.viewports[e])||void 0===t?void 0:t.bottomRight.offsetScrollbarX)||0,y:(null===(i=this.viewports[e])||void 0===i?void 0:i.bottomRight.offsetScrollbarY)||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e),n=this.getters.getNumberCols(e),o=this.getters.getNumberRows(e),s=Math.min(this.getters.getColRowOffset("COL",0,t,e),this.sheetViewWidth),r=Math.min(this.getters.getColRowOffset("ROW",0,i,e),this.sheetViewHeight),a=Math.max(this.sheetViewWidth-s,0),l=Math.max(this.sheetViewHeight-r,0),{xRatio:c,yRatio:h}=this.getFrozenSheetViewRatio(e),d=c<1,u=h<1,g=this.getViewportOffset(e),p={topLeft:i&&t&&new rb(this.getters,e,{left:0,right:t-1,top:0,bottom:i-1},{width:s,height:r},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:i&&new rb(this.getters,e,{left:t,right:n-1,top:0,bottom:i-1},{width:a,height:r},{canScrollHorizontally:d,canScrollVertically:!1},{x:d?g.x:0,y:0})||void 0,bottomLeft:t&&new rb(this.getters,e,{left:0,right:t-1,top:i,bottom:o-1},{width:s,height:l},{canScrollHorizontally:!1,canScrollVertically:u},{x:0,y:u?g.y:0})||void 0,bottomRight:new rb(this.getters,e,{left:t,right:n-1,top:i,bottom:o-1},{width:a,height:l},{canScrollHorizontally:d,canScrollVertically:u},{x:d?g.x:0,y:u?g.y:0})};this.viewports[e]=p}refreshViewport(e,t){this.getSubViewports(e).forEach((e=>{e.adjustViewportZone(),e.adjustPosition(t)}))}shiftVertically(e){const t=this.getters.getActiveSheetId(),{top:i}=this.getMainInternalViewport(t),{scrollX:n}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(n,e);const{anchor:o}=this.getters.getSelection();if(o.cell.row>=this.getters.getPaneDivisions(t).ySplit){const e=this.getMainInternalViewport(t).top-i;this.selection.selectCell(o.cell.col,o.cell.row+e)}}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],i=this.getters.getFigures(e),{scrollX:n,scrollY:o}=this.getActiveSheetScrollInfo(),{x:s,y:r}=this.getters.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const e of i)e.x>=s&&(e.x+e.width<=s+n||e.x>=a+n+s)||e.y>=r&&(e.y+e.height<=r+o||e.y>=l+o+r)||t.push(e);return t}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e),n=this.getters.getColDimensions(e,t).start,o=this.getters.getRowDimensions(e,i).start;return{xRatio:n/(this.sheetViewWidth+this.gridOffsetX),yRatio:o/(this.sheetViewHeight+this.gridOffsetY)}}mapViewportsToRect(e,t){let i=1/0,n=1/0,o=0,s=0,r=!1;for(const a of this.getSubViewports(e)){const e=t(a);e&&(r=!0,i=Math.min(i,e.x),n=Math.min(n,e.y),o=Math.max(o,e.x+e.width),s=Math.max(s,e.y+e.height))}return r?{x:i+this.gridOffsetX,y:n+this.gridOffsetY,width:o-i,height:s-n}:{x:0,y:0,width:0,height:0}}}ab.getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getActiveSheetDOMScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio","getAllActiveViewportsZones","getRect"];class lb extends Bg{allowDispatch(e){if("SORT_CELLS"===e.type){if(!Bi(e.col,e.row,e.zone))throw new Error(s("The anchor must be part of the provided zone"));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return 0}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{})}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;for(let i=t.top;i<=t.bottom;i++)for(let n=t.left;n<=t.right;n++)if(!this.getters.isInMerge(e,n,i))return 64;return 0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const i=this.getters.getMerges(e).filter((e=>zi(e,t))),n=qi(i[0]);let[o,s]=[n.width,n.height];return i.every((e=>{let[t,i]=[e.right-e.left+1,e.bottom-e.top+1];return t===o&&i===s}))?0:64}expand(e,t){const{left:i,right:n,top:o,bottom:s}=this.getters.expandZone(e,t);return{left:Math.max(0,i),right:Math.min(this.getters.getNumberCols(e)-1,n),top:Math.max(0,o),bottom:Math.min(this.getters.getNumberRows(e)-1,s)}}checkExpandedValues(e,t){const i=this.expand(e,t);let n;if(this.getters.doesIntersectMerge(e,i)){const{left:t,right:o,top:s,bottom:r}=i;for(let i=t;i<=o;i++)for(let t=s;t<=r;t++){const{col:o,row:s}=this.getters.getMainCellPosition(e,i,t);if(n=this.getters.getCell(e,o,s),null==n?void 0:n.formattedValue)return!0}}else for(let t of this.getters.getCellsInZone(e,i))if(null==t?void 0:t.formattedValue)return!0;return!1}getContiguousZone(e,t){let i,{top:n,bottom:o,left:s,right:r}=t,a=!1;for(;!a;)a=!0,n>0&&(i=this.checkExpandedValues(e,{left:s-1,right:r+1,top:n-1,bottom:n-1}),i&&(a=!1,n--)),s>0&&(i=this.checkExpandedValues(e,{left:s-1,right:s-1,top:n-1,bottom:o+1}),i&&(a=!1,s--)),r<this.getters.getNumberCols(e)-1&&(i=this.checkExpandedValues(e,{left:r+1,right:r+1,top:n-1,bottom:o+1}),i&&(a=!1,r++)),o<this.getters.getNumberRows(e)-1&&(i=this.checkExpandedValues(e,{left:s-1,right:r+1,top:o+1,bottom:o+1}),i&&(a=!1,o++));return{left:s,right:r,top:n,bottom:o}}hasHeader(e){if(1===e[0].length)return!1;let t=e.map((e=>e.map((e=>(null==e?void 0:e.evaluated.type)||ln.empty))));return t[0][0]===ln.empty&&(t=t.slice(1)),!t.some((e=>e[0]===ln.empty))&&!!t.some((e=>e[1]!==ln.empty&&e[0]!==e[1]))}sortZone(e,t,i,n,o){const[s,r]=this.mainCellsSteps(e,i);let a=this.getters.getMainCellPosition(e,t.col,t.row).col,l=Object.assign({},i),c=this.mainCells(e,i);!o.sortHeaders&&this.hasHeader(c)&&(l.top+=r),c=this.mainCells(e,l);const h=function(e,t,i){const n=e.map(ro);let o=n.filter((e=>e.type===ln.empty)),s=n.filter((e=>e.type!==ln.empty));i&&(s.push(...o.map((e=>({...e,type:ln.number,value:0})))),o=[]);const r="descending"===t?-1:1;return s.sort(((e,t)=>{let i=so.indexOf(e.type)-so.indexOf(t.type);return 0===i&&(i=e.type===ln.text||e.type===ln.error?e.value.localeCompare(t.value):e.value-t.value),r*i})).concat(o)}(c[a-l.left],n,Boolean(o.emptyCellAsZero)),d=h.map((e=>e.index)),[u,g]=[c.length,c[0].length],p=[];for(let t=0;t<u;t++)for(let i=0;i<g;i++){let n=c[t][d[i]],o=l.left+t*s,a=l.top+i*r,h={sheetId:e,col:o,row:a,content:""};if(n){let t=n.content;if(n.isFormula()){const i=a-this.getters.getCellPosition(n.id).row,o=this.getters.createAdaptedRanges(n.dependencies,0,i,e);t=this.getters.buildFormulaContent(e,n,o)}h.style=n.style,h.content=t,h.format=n.format}p.push(h)}p.forEach((e=>this.dispatch("UPDATE_CELL",e)))}mainCellsSteps(e,t){const i=this.getters.getMerge(e,t.left,t.top);return[i?i.right-i.left+1:1,i?i.bottom-i.top+1:1]}mainCells(e,t){const[i,n]=this.mainCellsSteps(e,t),o=[],s=$e(t.left,t.right+1,i),r=$e(t.top,t.bottom+1,n);for(const t of s){const i=[];o.push(i);for(const n of r)i.push(this.getters.getCell(e,t,n))}return o}}lb.getters=["getContiguousZone"];class cb extends Bg{constructor(){super(...arguments),this.showFormulas=!1}handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}cb.getters=["shouldShowFormulas"];class hb extends Bg{constructor(){super(...arguments),this.ctx=document.createElement("canvas").getContext("2d")}allowDispatch(e){switch(e.type){case"AUTORESIZE_ROWS":case"AUTORESIZE_COLUMNS":try{this.getters.getSheet(e.sheetId);break}catch(e){return 27}}return 0}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(let t of e.cols){const i=this.getColMaxWidth(e.sheetId,t);0!==i&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:i,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":this.dispatch("RESIZE_COLUMNS_ROWS",{elements:e.rows,dimension:"ROW",size:null,sheetId:e.sheetId})}}getCellWidth(e,{col:t,row:i}){const n=this.getters.getCell(e,t,i);let o=0;n&&(o+=this.getTextWidth(n));this.getters.getConditionalIcon(t,i)&&(o+=ke(this.getters.getCellStyle(n))+2*L);if(this.getters.isFilterHeader(e,t,i)&&(o+=20),o>0&&(o+=2*V,"wrap"===this.getters.getCellStyle(n).wrapping)){const e=Qi({col:t,row:i}),n=this.getters.getColSize(this.getters.getActiveSheetId(),e.left);return Math.min(n,o)}return o}getTextWidth(e){const t=this.getters.getCellText(e,this.getters.shouldShowFormulas()),{sheetId:i,col:n,row:o}=this.getters.getCellPosition(e.id);return _e(this.ctx,t,this.getters.getCellComputedStyle(i,n,o))}getCellText(e,t=!1){return t&&(e.isFormula()||e.evaluated.type===ln.error)?e.content:e.formattedValue}getCellMultiLineText(e,t){const i=this.getters.getCellStyle(e),n=this.getters.getCellText(e).split(" "),o=[];let s="",r=t;for(let e of n){const n=this.splitWordToSpecificWidth(this.ctx,e,t,i),a=n.pop(),l=_e(this.ctx,a,i);if(n.length)""!==s&&(o.push(s),s="",r=t),n.forEach((e=>{o.push(e)})),s=a,r=t-l;else{const e=""===s?a:" "+a,n=_e(this.ctx,e,i);n<=r?(s+=e,r-=n):(o.push(s),s=a,r=t-l)}}return""!==s&&o.push(s),o}getColDimensions(e,t){const i=this.getColRowOffset("COL",0,t,e),n=this.getters.getColSize(e,t);return{start:i,size:n,end:i+(this.getters.isColHidden(e,t)?0:n)}}getRowDimensions(e,t){const i=this.getColRowOffset("ROW",0,t,e),n=this.getters.getRowSize(e,t);return{start:i,size:n,end:i+(this.getters.isRowHidden(e,t)?0:n)}}getColRowOffset(e,t,i,n=this.getters.getActiveSheetId()){if(i<t)return-this.getColRowOffset(e,i,t);let o=0;for(let s=t;s<i;s++)this.getters.isHeaderHidden(n,e,s)||(o+="COL"===e?this.getters.getColSize(n,s):this.getters.getRowSize(n,s));return o}getColMaxWidth(e,t){const i=ji(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth(e,t)));return Math.max(0,lt(i))}splitWordToSpecificWidth(e,t,i,n){if(_e(e,t,n)<=i)return[t];const o=[];let s="";for(let r of t){_e(e,s+r,n)>i?(o.push(s),s=r):s+=r}return o.push(s),o}}hb.getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getColDimensions","getRowDimensions","getColRowOffset"];const db=(new nn).add("sheet",Ev).add("header visibility",vv).add("filters",mv).add("cell",lv).add("merge",bv).add("headerSize",fv).add("borders",rv).add("conditional formatting",dv).add("figures",uv).add("chart",cv),ub=(new nn).add("selection",Wv).add("ui_sheet",hb).add("header_visibility_ui",Vv).add("ui_options",cb).add("evaluation",Fv).add("evaluation_filter",$v).add("evaluation_cf",kv).add("evaluation_chart",Dv).add("clipboard",Nv).add("edition",Wg).add("selectionInputManager",Zv).add("highlight",zv).add("viewport",ab).add("grid renderer",Bv).add("autofill",yv).add("find_and_replace",Pv).add("sort",lb).add("automatic_sum",xv).add("format",Uv).add("cell_popovers",Rv).add("selection_multiuser",sb).add("custom_colors",Mv),gb=new nn;gb.add("link",{condition:e=>e.isLink(),action:(e,t)=>{e.action(t)},sequence:5});class pb{constructor(){this.focusableElement=void 0}setFocusableElement(e){this.focusableElement=e}focus(){var e;null===(e=this.focusableElement)||void 0===e||e.focus()}}wn`
1390
+ `}function Ff(e){return new Hp(e.join("\n"))}function Df(e,...t){let i=[e[0]];for(let n=0;n<t.length;n++){const o=t[n]instanceof Hp?t[n]:Af(t[n]);i.push(o+e[n+1])}return new Hp(et(i))}function kf(e){return e.replace(/[a-z0-9]+:(?=[a-z0-9]+)/gi,"")}function $f(e){return e.replace(/([a-z0-9]+):(?=[a-z0-9]+)/gi,"$1\\:")}class Lf{constructor(e){this.value=e}asString(){return _m(String(this.value))}asBool(){return Boolean(Number(this.value))}asNum(){return Number(this.value)}}class Pf{constructor(e,t,i){this.currentFile=void 0,this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=i,this.areNamespaceIgnored=null!==(new DOMParser).parseFromString("<t:test xmlns:t='a'/>","text/xml").querySelector("test"),this.relationships={},e.rels&&this.extractRelationships(e.rels).map((e=>{this.relationships[e.id]=e}))}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:"Relationship"},(e=>({id:this.extractAttr(e,"Id",{required:!0}).asString(),target:this.extractAttr(e,"Target",{required:!0}).asString(),type:this.extractAttr(e,"Type",{required:!0}).asString()})))}getListOfFiles(){return Object.values(this.xlsxFileStructure).flat().filter(Xe)}mapOnElements(e,t){var i;const n=[],o=this.currentFile;let s;if(e.children){const t=null===(i=this.querySelector(e.parent,e.query))||void 0===i?void 0:i.children;s=t||[]}else s=this.querySelectorAll(e.parent,e.query);if(s)for(let e of s)try{n.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=o,n}catchErrorOnElement(e,t){const i=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([i,e.message].join("\n"))}extractAttr(e,t,i){const n=e.attributes[t];n||this.handleMissingValue(e,`attribute "${t}"`,i);const o=(null==n?void 0:n.value)?n.value:null==i?void 0:i.default;return void 0===o?void 0:new Lf(o)}extractTextContent(e,t){var i;if(void 0!==(null==t?void 0:t.default)&&"string"!=typeof t.default)throw new Error("extractTextContent default value should be a string");const n="preserve"===(null===(i=null==e?void 0:e.attributes["xml:space"])||void 0===i?void 0:i.value);let o=null==e?void 0:e.textContent;return e&&null!==o||this.handleMissingValue(e,"text content",t),o&&(o=n?o:o.trim()),o?_m(o):null==t?void 0:t.default}extractChildAttr(e,t,i,n){var o;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}>`,n);const r=s?null===(o=this.extractAttr(s,i,n))||void 0===o?void 0:o.asString():null==n?void 0:n.default;return void 0!==r?new Lf(r):void 0}extractChildTextContent(e,t,i){if(void 0!==(null==i?void 0:i.default)&&"string"!=typeof i.default)throw new Error("extractTextContent default value should be a string");let n=this.querySelector(e,t);return n||this.handleMissingValue(e,`child <${t}>`,i),n?this.extractTextContent(n,i):null==i?void 0:i.default}handleMissingValue(e,t,i){if(null==i?void 0:i.required){if(!(null==i?void 0:i.default))throw new Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`);this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${i.default}`)}}extractColor(e,t,i){var n,o,s,r,a;if(!e)return i?{rgb:i}:void 0;const l=null===(n=this.extractAttr(e,"theme"))||void 0===n?void 0:n.asString();let c;if(void 0!==l){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");c=this.getThemeColor(l,t.clrScheme)}else c=null===(o=this.extractAttr(e,"rgb"))||void 0===o?void 0:o.asString();return{rgb:c,auto:null===(s=this.extractAttr(e,"auto"))||void 0===s?void 0:s.asBool(),indexed:null===(r=this.extractAttr(e,"indexed"))||void 0===r?void 0:r.asNum(),tint:null===(a=this.extractAttr(e,"tint"))||void 0===a?void 0:a.asNum()}}getTargetXmlFile(e){if(!e)throw new Error("Undefined target file");let t=e.target;t=t.replace("../",""),t=t.replace("./","");const i=this.getListOfFiles().find((e=>e.file.fileName.endsWith(t)));if(!i||!i.file)throw new Error("Cannot find target file");return i}querySelector(e,t){return t=this.areNamespaceIgnored?kf(t):$f(t),e.querySelector(t)}querySelectorAll(e,t){return t=this.areNamespaceIgnored?kf(t):$f(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 Uf extends Pf{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:Gp}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:Gp}).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 Vf extends Pf{constructor(e,t,i,n){super(e,t,i),this.theme=n}extractConditionalFormattings(){const e=this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > conditionalFormatting"},(e=>{var t;return{sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),pivot:null===(t=this.extractAttr(e,"pivot"))||void 0===t?void 0:t.asBool(),cfRules:this.extractCFRules(e,this.theme)}}));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:"extLst x14:conditionalFormatting"},(e=>{var t;return{sqref:this.extractChildTextContent(e,"xm:sqref",{required:!0}).split(" "),pivot:null===(t=this.extractAttr(e,"xm:pivot"))||void 0===t?void 0:t.asBool(),cfRules:this.extractCFRules(e,this.theme)}}))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:"cfRule, x14:cfRule"},(e=>{var i,n,o,s,r,a,l,c,h,d,u;const g=this.extractAttr(e,"type",{required:!0}).asString();if("dataBar"===g)throw new Error("Databars conditional formats are not supported.");return{type:g,priority:this.extractAttr(e,"priority",{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:null===(i=this.extractAttr(e,"dxfId"))||void 0===i?void 0:i.asNum(),stopIfTrue:null===(n=this.extractAttr(e,"stopIfTrue"))||void 0===n?void 0:n.asBool(),aboveAverage:null===(o=this.extractAttr(e,"aboveAverage"))||void 0===o?void 0:o.asBool(),percent:null===(s=this.extractAttr(e,"percent"))||void 0===s?void 0:s.asBool(),bottom:null===(r=this.extractAttr(e,"bottom"))||void 0===r?void 0:r.asBool(),operator:null===(a=this.extractAttr(e,"operator"))||void 0===a?void 0:a.asString(),text:null===(l=this.extractAttr(e,"text"))||void 0===l?void 0:l.asString(),timePeriod:null===(c=this.extractAttr(e,"timePeriod"))||void 0===c?void 0:c.asString(),rank:null===(h=this.extractAttr(e,"rank"))||void 0===h?void 0:h.asNum(),stdDev:null===(d=this.extractAttr(e,"stdDev"))||void 0===d?void 0:d.asNum(),equalAverage:null===(u=this.extractAttr(e,"equalAverage"))||void 0===u?void 0:u.asBool()}}))}extractCfFormula(e){return this.mapOnElements({parent:e,query:"formula"},(e=>this.extractTextContent(e,{required:!0})))}extractCfColorScale(e,t){const i=this.querySelector(e,"colorScale");if(i)return{colors:this.mapOnElements({parent:i,query:"color"},(e=>this.extractColor(e,t,"ffffff"))),cfvos:this.extractCFVos(i)}}extractCfIconSet(e){var t,i;const n=this.querySelector(e,"iconSet, x14:iconSet");if(n)return{iconSet:this.extractAttr(n,"iconSet",{default:"3TrafficLights1"}).asString(),showValue:this.extractAttr(n,"showValue",{default:!0}).asBool(),percent:this.extractAttr(n,"percent",{default:!0}).asBool(),reverse:null===(t=this.extractAttr(n,"reverse"))||void 0===t?void 0:t.asBool(),custom:null===(i=this.extractAttr(n,"custom"))||void 0===i?void 0:i.asBool(),cfvos:this.extractCFVos(n),cfIcons:this.extractCfIcons(n)}}extractCfIcons(e){const t=this.mapOnElements({parent:e,query:"cfIcon, x14:cfIcon"},(e=>({iconSet:this.extractAttr(e,"iconSet",{required:!0}).asString(),iconId:this.extractAttr(e,"iconId",{required:!0}).asNum()})));return 0===t.length?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:"cfvo, x14:cfvo"},(e=>{var t,i;return{type:this.extractAttr(e,"type",{required:!0}).asString(),gte:null===(t=this.extractAttr(e,"gte",{default:!0}))||void 0===t?void 0:t.asBool(),value:e.attributes.val?null===(i=this.extractAttr(e,"val"))||void 0===i?void 0:i.asString():this.extractChildTextContent(e,"f, xm:f")}}))}}class zf extends Pf{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},(e=>{const t=this.getChartType(e);if(!ym[t])throw new Error(`Unsupported chart type ${t}`);const i=this.mapOnElements({parent:e,query:"c:title a:t"},(e=>e.textContent||"")).join(""),n=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString();return{title:i,type:ym[t],dataSets:this.extractChartDatasets(this.querySelector(e,`c:${t}`)),backgroundColor:this.extractChildAttr(e,"c:chartSpace > c:spPr a:srgbClr","val",{default:"ffffff"}).asString(),verticalAxisPosition:"r"===this.extractChildAttr(e,"c:valAx > c:axPos","val",{default:"l"}).asString()?"right":"left",legendPosition:wm[this.extractChildAttr(e,"c:legendPos","val",{default:"none"}).asString()],stacked:"stacked"===n,fontColor:"000000"}}))[0]}extractChartDatasets(e){return this.mapOnElements({parent:e,query:"c:ser"},(e=>({label:this.extractChildTextContent(e,"c:cat c:f"),range:this.extractChildTextContent(e,"c:val c:f",{required:!0})})))}getChartType(e){const t=this.querySelector(e,"c:plotArea");if(!t)throw new Error("Missing plot area in the chart definition.");for(let e of t.children){const t=kf(e.tagName);if(Wp.some((e=>e===t)))return t}throw new Error("Unknown chart type")}}class Bf extends Pf{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},(e=>{if("twoCellAnchor"!==kf(e.tagName))throw new Error("Only twoCellAnchor are supported for xlsx drawings.");const t=this.querySelector(e,"c:chart");if(!t)throw new Error("Only chart figures are currently supported.");return{anchors:[this.extractFigureAnchor("xdr:from",e),this.extractFigureAnchor("xdr:to",e)],data:this.extractChart(t)}}))}extractFigureAnchor(e,t){const i=this.querySelector(t,e);if(!i)throw new Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(i,"xdr:col",{required:!0})),colOffset:Number(this.extractChildTextContent(i,"xdr:colOff",{required:!0})),row:Number(this.extractChildTextContent(i,"xdr:row",{required:!0})),rowOffset:Number(this.extractChildTextContent(i,"xdr:rowOff",{required:!0}))}}extractChart(e){const t=this.extractAttr(e,"r:id",{required:!0}).asString(),i=this.getTargetXmlFile(this.relationships[t]),n=new zf(i,this.xlsxFileStructure,this.warningManager).extractChart();if(!n)throw new Error("Unable to extract chart definition");return n}}class Hf extends Pf{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 Wf extends Pf{getTable(){return this.mapOnElements({query:"table",parent:this.rootFile.file.xml},(e=>{var t;return{displayName:this.extractAttr(e,"displayName",{required:!0}).asString(),name:null===(t=this.extractAttr(e,"name"))||void 0===t?void 0:t.asString(),id:this.extractAttr(e,"id",{required:!0}).asString(),ref:this.extractAttr(e,"ref",{required:!0}).asString(),headerRowCount:this.extractAttr(e,"headerRowCount",{default:1}).asNum(),totalsRowCount:this.extractAttr(e,"totalsRowCount",{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)}}))[0]}extractTableCols(e){return this.mapOnElements({query:"tableColumn",parent:e},(e=>({id:this.extractAttr(e,"id",{required:!0}).asString(),name:this.extractAttr(e,"name",{required:!0}).asString(),colFormula:this.extractChildTextContent(e,"calculatedColumnFormula")})))}extractTableStyleInfo(e){return this.mapOnElements({query:"tableStyleInfo",parent:e},(e=>{var t,i,n,o,s;return{name:null===(t=this.extractAttr(e,"name"))||void 0===t?void 0:t.asString(),showFirstColumn:null===(i=this.extractAttr(e,"showFirstColumn"))||void 0===i?void 0:i.asBool(),showLastColumn:null===(n=this.extractAttr(e,"showLastColumn"))||void 0===n?void 0:n.asBool(),showRowStripes:null===(o=this.extractAttr(e,"showRowStripes"))||void 0===o?void 0:o.asBool(),showColumnStripes:null===(s=this.extractAttr(e,"showColumnStripes"))||void 0===s?void 0:s.asBool()}}))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:"autoFilter",parent:e},(e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,"ref",{required:!0}).asString()})))[0]}extractFilterColumns(e){return this.mapOnElements({query:"tableColumn",parent:e},(t=>({colId:this.extractAttr(e,"colId",{required:!0}).asNum(),hiddenButton:this.extractAttr(e,"hiddenButton",{default:!1}).asBool(),filters:this.extractSimpleFilter(t)})))}extractSimpleFilter(e){return this.mapOnElements({query:"filter",parent:e},(e=>({val:this.extractAttr(e,"val",{required:!0}).asString()})))}}class Gf extends Pf{constructor(e,t,i,n){super(e,t,i),this.theme=n}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=Nm(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=Nm(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id,i=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:"sheet"},(e=>({relationshipId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetId:this.extractAttr(e,"sheetId",{required:!0}).asString(),sheetName:this.extractAttr(e,"name",{required:!0}).asString(),state:this.extractAttr(e,"state",{default:"visible"}).asString()}))).find((e=>e.relationshipId===t));if(!i)throw new Error("Cannot find corresponding workbook sheet");return i}extractConditionalFormats(){return new Vf(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractFigures(e){return this.mapOnElements({parent:e,query:"drawing"},(e=>{var t;const i=null===(t=this.extractAttr(e,"r:id",{required:!0}))||void 0===t?void 0:t.asString(),n=this.getTargetXmlFile(this.relationships[i]);return new Bf(n,this.xlsxFileStructure,this.warningManager).extractFigures()}))[0]||[]}extractTables(e){return this.mapOnElements({query:"tablePart",parent:e},(e=>{var t;const i=null===(t=this.extractAttr(e,"r:id",{required:!0}))||void 0===t?void 0:t.asString(),n=this.getTargetXmlFile(this.relationships[i]);return new Wf(n,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 Hf(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:tm.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:im.toString()}).asNum()}}extractCols(e){return this.mapOnElements({parent:e,query:"cols col"},(e=>{var t,i,n,o,s,r,a;return{width:null===(t=this.extractAttr(e,"width"))||void 0===t?void 0:t.asNum(),customWidth:null===(i=this.extractAttr(e,"customWidth"))||void 0===i?void 0:i.asBool(),bestFit:null===(n=this.extractAttr(e,"bestFit"))||void 0===n?void 0:n.asBool(),hidden:null===(o=this.extractAttr(e,"hidden"))||void 0===o?void 0:o.asBool(),min:null===(s=this.extractAttr(e,"min",{required:!0}))||void 0===s?void 0:s.asNum(),max:null===(r=this.extractAttr(e,"max",{required:!0}))||void 0===r?void 0:r.asNum(),styleIndex:null===(a=this.extractAttr(e,"style"))||void 0===a?void 0:a.asNum()}}))}extractRows(e){return this.mapOnElements({parent:e,query:"sheetData row"},(e=>{var t,i,n,o,s;return{index:null===(t=this.extractAttr(e,"r",{required:!0}))||void 0===t?void 0:t.asNum(),cells:this.extractCells(e),height:null===(i=this.extractAttr(e,"ht"))||void 0===i?void 0:i.asNum(),customHeight:null===(n=this.extractAttr(e,"customHeight"))||void 0===n?void 0:n.asBool(),hidden:null===(o=this.extractAttr(e,"hidden"))||void 0===o?void 0:o.asBool(),styleIndex:null===(s=this.extractAttr(e,"s"))||void 0===s?void 0:s.asNum()}}))}extractCells(e){return this.mapOnElements({parent:e,query:"c"},(e=>{var t,i,n;return{xc:null===(t=this.extractAttr(e,"r",{required:!0}))||void 0===t?void 0:t.asString(),styleIndex:null===(i=this.extractAttr(e,"s"))||void 0===i?void 0:i.asNum(),type:fm[null===(n=this.extractAttr(e,"t",{default:"n"}))||void 0===n?void 0:n.asString()],value:this.extractChildTextContent(e,"v"),formula:this.extractCellFormula(e)}}))}extractCellFormula(e){var t,i;const n=this.querySelector(e,"f");if(n)return{content:this.extractTextContent(n),sharedIndex:null===(t=this.extractAttr(n,"si"))||void 0===t?void 0:t.asNum(),ref:null===(i=this.extractAttr(n,"ref"))||void 0===i?void 0:i.asString()}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:"hyperlink"},(e=>{var t,i,n,o;const s=null===(t=this.extractAttr(e,"r:id"))||void 0===t?void 0:t.asString();return{xc:null===(i=this.extractAttr(e,"ref",{required:!0}))||void 0===i?void 0:i.asString(),location:null===(n=this.extractAttr(e,"location"))||void 0===n?void 0:n.asString(),display:null===(o=this.extractAttr(e,"display"))||void 0===o?void 0:o.asString(),relTarget:s?this.relationships[s].target:void 0}}))}extractSharedFormulas(e){const t=this.querySelectorAll(e,"f[si][ref]"),i={};for(let e of t){const t=this.extractAttr(e,"si",{required:!0}).asNum(),n=this.extractTextContent(e,{required:!0});i[t]=n}const n=[];for(let e=0;e<Object.keys(i).length;e++)i[e]?n.push(i[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),n.push(""));return n}}class qf extends Pf{constructor(e,t,i){super(e.styles,e,t),this.theme=i}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"numFmt"},(e=>this.extractNumFormats(e)))}extractNumFormats(e){return{id:this.extractAttr(e,"numFmtId",{required:!0}).asNum(),format:this.extractAttr(e,"formatCode",{required:!0,default:""}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"font"},(e=>this.extractFont(e)))}extractFont(e){var t,i,n,o;const s=this.extractChildAttr(e,"name","val",{default:"Arial"}).asString(),r=this.extractChildAttr(e,"sz","val",{default:G.toString()}).asNum(),a=this.extractColor(this.querySelector(e,"color"),this.theme),l=this.querySelector(e,"i")||void 0,c=l&&"0"!==(null===(t=l.attributes.val)||void 0===t?void 0:t.value),h=this.querySelector(e,"b")||void 0,d=h&&"0"!==(null===(i=h.attributes.val)||void 0===i?void 0:i.value),u=this.querySelector(e,"strike")||void 0,g=u&&"0"!==(null===(n=u.attributes.val)||void 0===n?void 0:n.value),p=this.querySelector(e,"u")||void 0;return{name:s,size:r,color:a,italic:c,bold:d,underline:p&&"none"!==(null===(o=p.attributes.val)||void 0===o?void 0:o.value),strike:g}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"fill"},(e=>this.extractFill(e)))}extractFill(e){var t;const i=e.children[0];return"patternFill"===i.tagName?{patternType:null===(t=i.attributes.patternType)||void 0===t?void 0:t.value,bgColor:this.extractColor(this.querySelector(i,"bgColor"),this.theme),fgColor:this.extractColor(this.querySelector(i,"fgColor"),this.theme)}:{patternType:"solid",fgColor:this.extractColor(this.querySelectorAll(i,"color")[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"border"},(e=>this.extractBorder(e)))}extractBorder(e){var t,i;const n={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 n.diagonal&&(n.diagonalUp=null===(t=this.extractAttr(e,"diagonalUp"))||void 0===t?void 0:t.asBool(),n.diagonalDown=null===(i=this.extractAttr(e,"diagonalDown"))||void 0===i?void 0:i.asBool()),n}extractSingleBorder(e,t,i){const n=this.querySelector(e,t);if(n&&n.attributes.style)return{style:this.extractAttr(n,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(n.children[0],i,"000000")}}extractAlignment(e){var t,i,n,o,s,r,a;return{horizontal:this.extractAttr(e,"horizontal",{default:"general"}).asString(),vertical:this.extractAttr(e,"vertical",{default:"center"}).asString(),textRotation:null===(t=this.extractAttr(e,"textRotation"))||void 0===t?void 0:t.asNum(),wrapText:null===(i=this.extractAttr(e,"wrapText"))||void 0===i?void 0:i.asBool(),indent:null===(n=this.extractAttr(e,"indent"))||void 0===n?void 0:n.asNum(),relativeIndent:null===(o=this.extractAttr(e,"relativeIndent"))||void 0===o?void 0:o.asNum(),justifyLastLine:null===(s=this.extractAttr(e,"justifyLastLine"))||void 0===s?void 0:s.asBool(),shrinkToFit:null===(r=this.extractAttr(e,"shrinkToFit"))||void 0===r?void 0:r.asBool(),readingOrder:null===(a=this.extractAttr(e,"readingOrder"))||void 0===a?void 0:a.asNum()}}getDxfs(){return this.mapOnElements({query:"dxf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"font"),i=this.querySelector(e,"fill"),n=this.querySelector(e,"border"),o=this.querySelector(e,"numFmt"),s=this.querySelector(e,"alignment");return{font:t?this.extractFont(t):void 0,fill:i?this.extractFill(i):void 0,numFmt:o?this.extractNumFormats(o):void 0,alignment:s?this.extractAlignment(s):void 0,border:n?this.extractBorder(n):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 Zf extends Pf{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"externalBook"},(e=>({rId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:"sheetName"},(e=>this.extractAttr(e,"val",{required:!0}).asString())),datasets:this.extractExternalSheetData(e)})))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:"sheetData"},(e=>{const t=this.mapOnElements({parent:e,query:"cell"},(e=>({xc:this.extractAttr(e,"r",{required:!0}).asString(),value:this.extractChildTextContent(e,"v",{required:!0})}))),i={};for(let e of t)i[e.xc]=e.value;return{sheetId:this.extractAttr(e,"sheetId",{required:!0}).asNum(),data:i}}))}}function jf(e,t){const i=function(e,t){const i=t[lm],n=i.querySelectorAll(`Override[ContentType="${e}"]`),o=[];for(let e of n){const t=null==e?void 0:e.attributes.PartName.value;o.push(t.substring(1))}return o}(e,t);return function(e,t){const i=[];for(let n of e){const e=Yf(n,t);i.push({file:{fileName:n,xml:t[n]},rels:e?{fileName:e,xml:t[e]}:void 0})}return i}(i,t)}function Yf(e,t){if(e===lm)return"_rels/.rels";let i="";const n=e.split("/");for(let e=0;e<n.length-1;e++)i+=n[e]+"/";return i+="_rels/",i+=n[n.length-1]+".rels",t[i]||(i=void 0),i}class Xf{constructor(e){this.warningManager=new hm,this.xmls={};for(let t of Object.keys(e))(t.endsWith(".xml")||t.endsWith(".rels"))&&(this.xmls[t]=Of(new Hp(e[t])))}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new Uf(e.theme,e,this.warningManager).getTheme():void 0,i=e.sharedStrings?new Uf(e.sharedStrings,e,this.warningManager).getSharedStrings():[],n=e.sheets.sort(((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0}))).map((i=>new Gf(i,e,this.warningManager,t).getSheet())),o=e.externalLinks.map((t=>new Zf(t,e,this.warningManager).getExternalBook())),s=new qf(e,this.warningManager,t);return{fonts:s.getFonts(),fills:s.getFills(),borders:s.getBorders(),dxfs:s.getDxfs(),numFmts:s.getNumFormats(),styles:s.getStyles(),sheets:n,sharedStrings:i,externalBooks:o}}buildXlsxFileStructure(){const e={sheets:jf(Xp.sheet,this.xmls),workbook:jf(Xp.workbook,this.xmls)[0],styles:jf(Xp.styles,this.xmls)[0],sharedStrings:jf(Xp.sharedStrings,this.xmls)[0],theme:jf(Xp.themes,this.xmls)[0],charts:jf(Xp.chart,this.xmls),figures:jf(Xp.drawing,this.xmls),tables:jf(Xp.table,this.xmls),pivots:jf(Xp.pivot,this.xmls),externalLinks:jf(Xp.externalLink,this.xmls)};if(!e.workbook.rels)throw Error(s("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:12,sheets:mf(e,this.warningManager),styles:Lm(e,this.warningManager),formats:Um(e,this.warningManager),borders:km(e,this.warningManager),entities:{},revisionId:K};return yf(t,e),Object.keys(e.styles).map((t=>{e.styles[t]=rt(e.styles[t])})),t}}function Kf(e){const t=vg(e);let i=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&xt.test(e.value)){const t=e.value.trim();return i.includes(t)||i.push(t),`${ie}${i.indexOf(t)}${ie}`}return e.value}))),dependencies:i}}const Qf=12.5,Jf="Sheet1";function ev(e,t){if(!e)return sv();if(e["[Content_Types].xml"]){const i=new Xf(e);if(e=i.convertXlsx(),t)for(let e of i.warningManager.warnings.sort())console.warn(e)}return"version"in(e=Ae(e))&&e.version<Qf&&(e=function(e){for(let t=tv.findIndex((t=>t.from===e.version));t<tv.length;t++)e=tv[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,i=new Mi;for(const n of e.sheets||[])for(const e of n.figures||[])t.has(e.id)&&(e.id+=i.smallUuid()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){e=Object.assign(sv(),e,{version:Qf}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(ov(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(ov(Jf,"Sheet1"));return e}(e),e}(e),e}const tv=[{description:"add the `activeSheet` field on data",from:1,to:2,applyMigration:e=>(e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e)},{description:"add an id field in each sheet",from:2,to:3,applyMigration(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}},{description:"activeSheet is now an id, not the name of a sheet",from:3,to:4,applyMigration(e){if(e.sheets&&e.activeSheet){const t=e.sheets.find((t=>t.name===e.activeSheet));e.activeSheet=t.id}return e}},{description:"add figures object in each sheets",from:4,to:5,applyMigration(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}},{description:"normalize the content of the cell if it is a formula to avoid parsing all the formula that vary only by the cells they use",from:5,to:6,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const i=t.cells[e];i.content&&i.content.startsWith("=")&&(i.formula=Kf(i.content))}return e}},{description:"transform chart data structure",from:6,to:7,applyMigration(e){for(let t of e.sheets||[])for(let e in t.figures||[]){const{dataSets:i,...n}=t.figures[e].data,o=[];for(let e of i)if(e.labelCell){const t=Fi(e.dataRange),i=e.labelCell+":"+Vt(t.right,t.bottom);o.push(i)}else o.push(e.dataRange);n.dataSetsHaveTitle=Boolean(i[0].labelCell),n.dataSets=o,t.figures[e].data=n}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){var t;const i=[],n=new RegExp(te,"g");for(let o of e.sheets||[]){if(!o.name)continue;const e=o.name,s=e.replace(n,"_");let r=1,a=s;for(;i.includes(a);)a=`${s}${r}`,r++;o.name=a,i.push(a);const l=t=>{if(void 0===t)return t;let i=t.replace(e,a),n=t;for(;n!==i;)n=i,i=n.replace(e,a);return n};for(let e in o.cells){const t=o.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(l))}for(let e of o.figures||[])if("chart"===e.type){const t=e.data.dataSets.map(l),i=l(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:i}}for(let e of o.conditionalFormats||[]){e.ranges=e.ranges.map(l);for(const i of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===(null===(t=e.rule[i])||void 0===t?void 0:t.type)&&(e.rule[i].value=l(e.rule[i].value))}}return e}},{description:"transform chart data structure with design attributes",from:8,to:9,applyMigration(e){for(const t of e.sheets||[])for(const e of t.figures||[])e.data.background=w,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stacked=!1;return e}},{description:"de-normalize formula to reduce exported json size (~30%)",from:9,to:10,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const i=t.cells[e];if(i.formula){let{text:e,dependencies:t}=i.formula;for(let[i,n]of Object.entries(t)){const t=`\\${ie}${i}\\${ie}`;e=e.replace(new RegExp(t,"g"),n)}i.content=e,delete i.formula}}return e}},{description:"normalize the formats of the cells",from:10,to:11,applyMigration(e){const t={};for(let i of e.sheets||[])for(let e in i.cells||[]){const n=i.cells[e];n.format&&(n.format=Je(n.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 i of t.filterTables||[]){const t=Fi(i.range),n=e.findIndex((e=>Hi(e,t)));-1!==n?e[n]=t:e.push(t)}t.filterTables=e.map((e=>({range:ki(e)})))}return e}}];function iv(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const i=[],n=[],o=e=>{if("CREATE_SHEET"===e.type)i.push(e.sheetId);else if("sheetId"in e&&!i.includes(e.sheetId))return{...e,sheetId:Jf};return e};for(const e of t)"REMOTE_REVISION"===e.type?n.push({...e,commands:e.commands.map(o)}):n.push(e);return n}(e,t),t=nv(t,"SORT_CELLS"),t=function(e,t){var i;const n=[],o={};for(const t of e.sheets||[])null===(i=t.figures)||void 0===i||i.forEach((e=>{"chart"===e.tag&&(o[e.id]=e.data)}));for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const i of e.commands){let e=i;switch(i.type){case"CREATE_CHART":o[i.id]=i.definition;break;case"UPDATE_CHART":if(!o[i.id]){console.log(`Fix chart definition: chart with id ${i.id} not found.`);continue}const t={...o[i.id],...i.definition};e={...i,definition:t},o[i.id]=t}t.push(e)}n.push({...e,commands:t})}else n.push(e);return n}(e,t=nv(t,"SET_DECIMAL")),t=function(e,t){var i;const n={};for(const t of e.sheets||[])n[t.id]=t.name;const o=[];for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const o of e.commands){switch(o.type){case"DUPLICATE_SHEET":o.sheetNameTo=null!==(i=o.sheetNameTo)&&void 0!==i?i:Oi(n[o.sheetId],Object.values(n));break;case"CREATE_SHEET":case"RENAME_SHEET":n[o.sheetId]=o.name||Ni(Object.values(n))}t.push(o)}o.push({...e,commands:t})}else o.push(e);return t}(e,t),t}function nv(e,t){const i=[];for(const n of e)"REMOTE_REVISION"===n.type?i.push({...n,commands:n.commands.filter((e=>e.type!==t))}):i.push(n);return i}function ov(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[],filterTables:[],isVisible:!0}}function sv(e="Sheet1"){return{version:Qf,sheets:[ov(Jf,e)],entities:{},styles:{},formats:{},borders:{},revisionId:K,uniqueFigureIds:!0}}function rv(e,t){return{...ov(e,t),charts:[]}}class av extends Hg{constructor(e,t,i,n,o,s){super(t,n,o),this.dispatch=n,this.range=i,i.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=s}import(e){}export(e){}adaptRanges(e,t){}}class lv extends av{constructor(){super(...arguments),this.borders={}}allowDispatch(e){return"SET_BORDER"===e.type?this.checkBordersUnchanged(e):0}handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":const t=this.borders[e.sheetId];if(t){const i=t.slice().map((e=>null==e?void 0:e.slice().map((e=>({...e})))));this.history.update("borders",e.sheetIdTo,i)}break;case"DELETE_SHEET":const i={...this.borders};delete i[e.sheetId],this.history.update("borders",i);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_FORMATTING":if(e.border){const t=e.target.map((t=>this.getters.expandZone(e.sheetId,t)));this.setBorders(e.sheetId,t,e.border)}break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target);break;case"REMOVE_COLUMNS_ROWS":const n=[...e.elements].sort(((e,t)=>t-e));for(const t of Le(n))if("COL"===e.dimension){if(t[0]>=this.getters.getNumberCols(e.sheetId))for(let i=0;i<this.getters.getNumberRows(e.sheetId);i++)this.history.update("borders",e.sheetId,t[0]+1,i,"vertical",void 0);if(0===t[t.length-1])for(let t=0;t<this.getters.getNumberRows(e.sheetId);t++)this.history.update("borders",e.sheetId,0,t,"vertical",void 0);const i=this.getters.getColsZone(e.sheetId,t[t.length-1]+1,t[0]);this.clearInsideBorders(e.sheetId,[i]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{if(t[0]>=this.getters.getNumberRows(e.sheetId))for(let i=0;i<this.getters.getNumberCols(e.sheetId);i++)this.history.update("borders",e.sheetId,i,t[0]+1,"horizontal",void 0);if(0===t[t.length-1])for(let t=0;t<this.getters.getNumberCols(e.sheetId);t++)this.history.update("borders",e.sheetId,t,0,"horizontal",void 0);const i=this.getters.getRowsZone(e.sheetId,t[t.length-1]+1,t[0]);this.clearInsideBorders(e.sheetId,[i]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumns(e):this.handleAddRows(e)}}handleAddColumns(e){let t,i;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),t=e.base-1,i=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),t=e.base,i=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,i)}handleAddRows(e){let t,i;"before"===e.position?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity,{moveFirstTopBorder:!0}),t=e.base-1,i=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity,{moveFirstTopBorder:!1}),t=e.base,i=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,i)}getCellBorder(e,t,i){var n,o,s,r,a,l,c,h,d,u,g,p;const m={top:null===(s=null===(o=null===(n=this.borders[e])||void 0===n?void 0:n[t])||void 0===o?void 0:o[i])||void 0===s?void 0:s.horizontal,bottom:null===(l=null===(a=null===(r=this.borders[e])||void 0===r?void 0:r[t])||void 0===a?void 0:a[i+1])||void 0===l?void 0:l.horizontal,left:null===(d=null===(h=null===(c=this.borders[e])||void 0===c?void 0:c[t])||void 0===h?void 0:h[i])||void 0===d?void 0:d.vertical,right:null===(p=null===(g=null===(u=this.borders[e])||void 0===u?void 0:u[t+1])||void 0===g?void 0:g[i])||void 0===p?void 0:p.vertical};return m.bottom||m.left||m.right||m.top?m:null}ensureColumnBorderContinuity(e,t,i){const n=$e(t+1,i);for(let o=0;o<this.getters.getNumberRows(e);o++){const s=this.getCellBorder(e,t,o),r=this.getCellBorder(e,i,o);if(s&&r){const t=this.getCommonSides(s,r);for(let i of n)this.addBorder(e,i,o,t)}}}ensureRowBorderContinuity(e,t,i){const n=$e(t+1,i);for(let o=0;o<this.getters.getNumberCols(e);o++){const s=this.getCellBorder(e,o,t),r=this.getCellBorder(e,o,i);if(s&&r){const t=this.getCommonSides(s,r);for(let i of n)this.addBorder(e,o,i,t)}}}getCommonSides(e,t){const i={};for(let n of["top","bottom","left","right"])e[n]&&e[n]===t[n]&&(i[n]=e[n]);return i}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsWithBorders(e){var t;const i=null===(t=this.borders[e])||void 0===t?void 0:t.filter(Xe);if(!i)return[];const n=new Set;for(const e of i)for(const t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?$e(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,i,{moveFirstLeftBorder:n}={}){this.borders[e]&&(i<0&&this.moveBordersOfColumn(e,t,i,"vertical",{destructive:!1}),this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>i<0?e-t:t-e)).forEach((o=>{(o===t&&n||o!==t)&&this.moveBordersOfColumn(e,o,i,"vertical"),this.moveBordersOfColumn(e,o,i,"horizontal")})))}shiftBordersVertically(e,t,i,{moveFirstTopBorder:n}={}){this.borders[e]&&(i<0&&this.moveBordersOfRow(e,t,i,"horizontal",{destructive:!1}),this.getRowsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>i<0?e-t:t-e)).forEach((o=>{(o===t&&n||o!==t)&&this.moveBordersOfRow(e,o,i,"horizontal"),this.moveBordersOfRow(e,o,i,"vertical")})))}moveBordersOfRow(e,t,i,n,{destructive:o}={destructive:!0}){const s=this.borders[e];s&&this.getColumnsWithBorders(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=s[r])||void 0===a?void 0:a[t+i])||void 0===l?void 0:l[n],u=null===(h=null===(c=s[r])||void 0===c?void 0:c[t])||void 0===h?void 0:h[n];this.history.update("borders",e,r,t+i,n,o?u:u||d),this.history.update("borders",e,r,t,n,void 0)}))}moveBordersOfColumn(e,t,i,n,{destructive:o}={destructive:!0}){const s=this.borders[e];s&&this.getRowsRange(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=s[t+i])||void 0===a?void 0:a[r])||void 0===l?void 0:l[n],u=null===(h=null===(c=s[t])||void 0===c?void 0:c[r])||void 0===h?void 0:h[n];this.history.update("borders",e,t+i,r,n,o?u:u||d),this.history.update("borders",e,t,r,n,void 0)}))}setBorder(e,t,i,n,o=!0){var s,r,a,l,c,h,d,u,g,p,m,f,v,b,S,C;!o&&(null===(l=null===(a=null===(r=null===(s=this.borders)||void 0===s?void 0:s[e])||void 0===r?void 0:r[t])||void 0===a?void 0:a[i])||void 0===l?void 0:l.vertical)||this.history.update("borders",e,t,i,"vertical",null==n?void 0:n.left),!o&&(null===(u=null===(d=null===(h=null===(c=this.borders)||void 0===c?void 0:c[e])||void 0===h?void 0:h[t])||void 0===d?void 0:d[i])||void 0===u?void 0:u.horizontal)||this.history.update("borders",e,t,i,"horizontal",null==n?void 0:n.top),!o&&(null===(f=null===(m=null===(p=null===(g=this.borders)||void 0===g?void 0:g[e])||void 0===p?void 0:p[t+1])||void 0===m?void 0:m[i])||void 0===f?void 0:f.vertical)||this.history.update("borders",e,t+1,i,"vertical",null==n?void 0:n.right),!o&&(null===(C=null===(S=null===(b=null===(v=this.borders)||void 0===v?void 0:v[e])||void 0===b?void 0:b[t])||void 0===S?void 0:S[i+1])||void 0===C?void 0:C.horizontal)||this.history.update("borders",e,t,i+1,"horizontal",null==n?void 0:n.bottom)}clearBorders(e,t){for(let i of t){for(let t=i.top;t<=i.bottom;t++){this.history.update("borders",e,i.right+1,t,"vertical",void 0);for(let n=i.left;n<=i.right;n++)this.history.update("borders",e,n,t,void 0)}for(let t=i.left;t<=i.right;t++)this.history.update("borders",e,t,i.bottom+1,"horizontal",void 0)}}clearInsideBorders(e,t){for(let i of t)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.history.update("borders",e,n,t,void 0)}addBorder(e,t,i,n){this.setBorder(e,t,i,{...this.getCellBorder(e,t,i),...n})}setBorders(e,t,i){if("clear"===i)return this.clearBorders(e,t);for(let n of t){if("h"===i||"hv"===i||"all"===i)for(let t=n.top+1;t<=n.bottom;t++)for(let i=n.left;i<=n.right;i++)this.addBorder(e,i,t,{top:Z});if("v"===i||"hv"===i||"all"===i)for(let t=n.top;t<=n.bottom;t++)for(let i=n.left+1;i<=n.right;i++)this.addBorder(e,i,t,{left:Z});if("left"===i||"all"===i||"external"===i)for(let t=n.top;t<=n.bottom;t++)this.addBorder(e,n.left,t,{left:Z});if("right"===i||"all"===i||"external"===i)for(let t=n.top;t<=n.bottom;t++)this.addBorder(e,n.right+1,t,{left:Z});if("top"===i||"all"===i||"external"===i)for(let t=n.left;t<=n.right;t++)this.addBorder(e,t,n.top,{top:Z});if("bottom"===i||"all"===i||"external"===i)for(let t=n.left;t<=n.right;t++)this.addBorder(e,t,n.bottom+1,{top:Z})}}addBordersToMerge(e,t){const{left:i,right:n,top:o,bottom:s}=t,r=this.getCellBorder(e,i,o),a=this.getCellBorder(e,n,s);this.clearBorders(e,[t]),(null==r?void 0:r.top)&&this.setBorders(e,[{...t,bottom:o}],"top"),(null==r?void 0:r.left)&&this.setBorders(e,[{...t,right:i}],"left"),((null==a?void 0:a.bottom)||(null==r?void 0:r.bottom))&&this.setBorders(e,[{...t,top:s}],"bottom"),((null==a?void 0:a.right)||(null==r?void 0:r.right))&&this.setBorders(e,[{...t,left:n}],"right")}checkBordersUnchanged(e){var t,i,n,o;const s=this.getCellBorder(e.sheetId,e.col,e.row),r=!((null===(t=e.border)||void 0===t?void 0:t.bottom)||(null===(i=e.border)||void 0===i?void 0:i.left)||(null===(n=e.border)||void 0===n?void 0:n.right)||(null===(o=e.border)||void 0===o?void 0:o.top));return!s&&r||ot(s,e.border)?89:0}import(e){if(e.borders)for(let t of e.sheets)for(let[i,n]of Object.entries(t.cells))if(null==n?void 0:n.border){const o=e.borders[n.border],{col:s,row:r}=Ut(i);this.setBorder(t.id,s,r,o,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Fi(e))}export(e){let t=0;const i={};function n(e){for(let[t,n]of Object.entries(i))if(ot(n,e))return parseInt(t,10);return i[++t]=e,t}for(let t of e.sheets)for(let e=0;e<t.colNumber;e++)for(let i=0;i<t.rowNumber;i++){const o=this.getCellBorder(t.id,e,i);if(o){const s=Vt(e,i),r=t.cells[s],a=n(o);r?r.border=a:t.cells[s]={border:a}}}e.borders=i}exportForExcel(e){this.export(e)}}lv.getters=["getCellBorder"];const cv={textColor:R};class hv extends av{constructor(){super(...arguments),this.nextId=1,this.cells={},this.createCell=function(e){const t=io.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(i,n,o,s){const r=t.find((e=>e.match(n,o.format)));if(!r)return new kp(i,n,o);try{return r.createCell(i,n,o,s,e)}catch(e){return new zp(i,n,e instanceof c?e:new h(e.message||ne),o)}}}(this.getters)}adaptRanges(e,t){for(const i of Object.keys(this.cells))for(const n of Object.values(this.cells[i]||{}))if(n.isFormula())for(const o of n.dependencies)if(!t||o.sheetId===t){const t=e(o);"NONE"!==t.changeType&&this.history.update("cells",i,n.id,"dependencies",n.dependencies.indexOf(o),t.range)}}allowDispatch(e){var t;switch(e.type){case"UPDATE_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case"CLEAR_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case"UPDATE_CELL_POSITION":return!e.cellId||(null===(t=this.cells[e.sheetId])||void 0===t?void 0:t[e.cellId])?0:28;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:""});break;case"DELETE_SHEET":this.history.update("cells",e.sheetId,void 0)}}setFormatter(e,t,i){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let o=n.left;o<=n.right;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:o,row:t,format:i})}clearFormatting(e,t){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,style:null,format:""})}handleAddColumnsRows(e,t){let i,n;"before"===e.position?(i=$e(e.base,e.base+e.quantity),n=e.base+e.quantity):(i=$e(e.base+1,e.base+e.quantity+1),n=e.base),t(e.sheetId,n,i)}import(e){for(let t of e.sheets)for(let i in t.cells){const n=t.cells[i],{col:o,row:s}=Ut(i);if((null==n?void 0:n.content)||(null==n?void 0:n.format)||(null==n?void 0:n.style)){const i=this.importCell(t.id,n,e.styles,e.formats);this.history.update("cells",t.id,i.id,i),this.dispatch("UPDATE_CELL_POSITION",{cellId:i.id,col:o,row:s,sheetId:t.id})}}}export(e){const t={},i={};for(let n of e.sheets){const e={},o=Object.keys(this.cells[n.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const{col:s,row:r}of o){const o=this.getters.getCell(n.id,s,r);e[Vt(s,r)]={style:o.style?Je(o.style,t):void 0,format:o.format?Je(o.format,i):void 0,content:o.content||void 0}}n.cells=e}e.styles=t,e.formats=i}importCell(e,t,i,n){const o=t.style&&i[t.style]||void 0,s=t.format&&n[t.format]||void 0,r=this.getNextUid(),a={format:s,style:o};return this.createCell(r,(null==t?void 0:t.content)||"",a,e)}exportForExcel(e){this.export(e);for(let t of e.sheets)for(const e in t.cells){const{col:i,row:n}=Ut(e),o=this.getters.getCell(t.id,i,n),s=t.cells[e];s.value=o.evaluated.value,s.isFormula=o.isFormula(),o.isFormula()&&(s.content=this.buildFormulaContent(t.id,o,o.dependencies,!0)),o.format!==o.evaluated.format&&(s.computedFormat=o.evaluated.format)}}getCells(e){return this.cells[e]||{}}getCellById(e){const t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}buildFormulaContent(e,t,i,n=!1){const o=i||t.dependencies;let s=0;return et(t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=o[s++];return this.getters.getRangeString(t,e,n)}return t.value})))}getFormulaCellContent(e,t){return this.buildFormulaContent(e,t)}getCellStyle(e){if(!e)return{};return{...e.isLink()?cv:{},...e.style}}zoneToXC(e,t,i=[{colFixed:!1,rowFixed:!1}]){const n=Vt((t=this.getters.expandZone(e,t)).left,t.top,i[0]),o=Vt(t.right,t.bottom,i.length>1?i[1]:i[0]),s=this.getters.getMainCellPosition(e,t.left,t.top),r=this.getters.getMainCellPosition(e,t.right,t.bottom),a=s.col===r.col&&s.row===r.row;return n==o||a?n:n+":"+o}setStyle(e,t,i){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let o=n.top;o<=n.bottom;o++){const n=this.getters.getCell(e,t,o);this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,style:i?{...null==n?void 0:n.style,...i}:void 0})}}copyColumnStyle(e,t,i){for(let n=0;n<this.getters.getNumberRows(e);n++){const o=this.getFormat(e,t,n);if(o.style||o.format)for(let t of i)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,...o})}}copyRowStyle(e,t,i){for(let n=0;n<this.getters.getNumberCols(e);n++){const o=this.getFormat(e,n,t);if(o.style||o.format)for(let t of i)this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,...o})}}getFormat(e,t,i){const n={},{col:o,row:s}=this.getters.getMainCellPosition(e,t,i),r=this.getters.getCell(e,o,s);return r&&(r.style&&(n.style=r.style),r.format&&(n.format=r.format)),n}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,i,n){const o=this.getters.getCell(e,t,i),s="content"in n||"formula"in n,r=(s?n.content:null==o?void 0:o.content)||"";let a;a=void 0!==n.style?n.style||void 0:o?o.style:void 0;let l=("format"in n?n.format:o&&o.format)||undefined;if((s&&!r&&!n.formula||!s&&(!o||o.isEmpty()))&&!a&&!l)return void(o&&(this.history.update("cells",e,o.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:i,sheetId:e})));const c=(null==o?void 0:o.id)||this.getNextUid(),h=s,d={format:l,style:a},u=this.createCell(c,r,d,e);o&&!h&&u.isFormula()&&u.assignEvaluation(tt(o.evaluated)),this.history.update("cells",e,u.id,u),this.dispatch("UPDATE_CELL_POSITION",{cellId:u.id,col:t,row:i,sheetId:e})}checkCellOutOfSheet(e){const{sheetId:t,col:i,row:n}=e;if(!this.getters.tryGetSheet(t))return 27;return Wi(i,n,this.getters.getSheetZone(t))?0:18}checkUselessClearCell(e){const t=this.getters.getCell(e.sheetId,e.col,e.row);return t&&(t.content||t.style||t.format)?0:89}checkUselessUpdateCell(e){const t=this.getters.getCell(e.sheetId,e.col,e.row),i="style"in e,n="format"in e;return("content"in e||"formula"in e)&&(null==t?void 0:t.content)!==e.content||i&&!ot(null==t?void 0:t.style,e.style)||n&&(null==t?void 0:t.format)!==e.format?0:89}}hv.getters=["zoneToXC","getCells","getFormulaCellContent","getCellStyle","buildFormulaContent","getCellById"];class dv extends av{constructor(){super(...arguments),this.charts={},this.createChart=function(e){const t=rn.getAll();return function(i,n,o){const s=t.find((e=>e.match(n.type)));if(!s)throw new Error(`No builder for this chart: ${n.type}`);return s.createChart(n,o,e)}}(this.getters),this.validateChartDefinition=e=>function(e,t){const i=rn.getAll().find((e=>e.match(t.type)));if(!i)throw new Error("Unknown chart type.");return i.validateChartDefinition(e,t)}(this,e.definition)}adaptRanges(e){for(const[t,i]of Object.entries(this.charts))this.history.update("charts",t,null==i?void 0:i.updateRanges(e))}allowDispatch(e){switch(e.type){case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists));default:return 0}}handle(e){var t;switch(e.type){case"CREATE_CHART":this.addFigure(e.id,e.sheetId,e.position,e.size),this.addChart(e.id,e.definition);break;case"UPDATE_CHART":this.addChart(e.id,e.definition);break;case"DUPLICATE_SHEET":{const i=this.getters.getFigures(e.sheetId);for(const n of i)if("chart"===n.tag){const i=n.id.split("??").pop(),o=`${e.sheetIdTo}??${i}`,s=null===(t=this.charts[n.id])||void 0===t?void 0:t.copyForSheetId(e.sheetIdTo);s&&this.dispatch("CREATE_CHART",{id:o,position:{x:n.x,y:n.y},size:{width:n.width,height:n.height},definition:s.getDefinition(),sheetId:e.sheetIdTo})}break}case"DELETE_FIGURE":this.history.update("charts",e.id,void 0);break;case"DELETE_SHEET":for(let t of this.getChartIds(e.sheetId))this.history.update("charts",t,void 0)}}getContextCreationChart(e){var t;return null===(t=this.charts[e])||void 0===t?void 0:t.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){var t;const i=null===(t=this.charts[e])||void 0===t?void 0:t.type;if(!i)throw new Error("Chart not defined.");return i}isChartDefined(e){return e in this.charts&&void 0!==this.charts}getChartIds(e){return Object.entries(this.charts).filter((([,t])=>(null==t?void 0:t.sheetId)===e)).map((([e])=>e))}getChartDefinition(e){var t;const i=null===(t=this.charts[e])||void 0===t?void 0:t.getDefinition();if(!i)throw new Error(`There is no chart with the given figureId: ${e}`);return i}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)"chart"===e.tag&&(this.charts[e.id]=this.createChart(e.id,e.data,t.id))}export(e){var t;if(e.sheets)for(let i of e.sheets){const e=this.getters.getFigures(i.id),n=[];for(let i of e){const e=i;if(e&&"chart"===e.tag){const i=null===(t=this.charts[e.id])||void 0===t?void 0:t.getDefinition();i&&(e.data=i,n.push(e))}else n.push(e)}i.figures=n}}exportForExcel(e){var t;for(let i of e.sheets){const e=this.getters.getFigures(i.id),n=[];for(let i of e)if(i&&"chart"===i.tag){const e=null===(t=this.charts[i.id])||void 0===t?void 0:t.getDefinitionForExcel();e&&n.push({...i,data:e})}i.charts=n}}addFigure(e,t,i={x:0,y:0},n={width:536,height:335}){if(this.getters.getFigure(t,e))return;const o={id:e,x:i.x,y:i.y,width:n.width,height:n.height,tag:"chart"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:o})}addChart(e,t){const i=this.getters.getFigureSheetId(e);i&&this.history.update("charts",e,this.createChart(e,t,i))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.id)?85:0}checkChartExists(e){return this.isChartDefined(e.id)?0:86}}function uv(e){return""===e?NaN:Number(e)}dv.getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];class gv extends av{constructor(){super(...arguments),this.cfRules={}}loopThroughRangesOfSheet(e,t){for(const i of this.cfRules[e])for(const n of i.ranges){const o=t(n);switch(o.changeType){case"REMOVE":let t=i.ranges.slice();t.splice(i.ranges.indexOf(n),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(i),"ranges",t):this.removeConditionalFormatting(i.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(i),"ranges",i.ranges.indexOf(n),o.range)}}}adaptRanges(e,t){if(t)this.loopThroughRangesOfSheet(t,e);else for(const t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,e)}allowDispatch(e){switch(e.type){case"ADD_CONDITIONAL_FORMAT":return this.checkValidations(e,this.checkCFRule,this.checkEmptyRange);case"MOVE_CONDITIONAL_FORMAT":return this.checkValidReordering(e.cfId,e.direction,e.sheetId)}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const i={...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))};this.addConditionalFormatting(i,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId);break;case"MOVE_CONDITIONAL_FORMAT":this.reorderConditionalFormatting(e.cfId,e.direction,e.sheetId)}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map((e=>this.mapToConditionalFormatInternal(t.id,e)))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map((e=>this.mapToConditionalFormat(t.id,e))))}exportForExcel(e){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){var t;return(null===(t=this.cfRules[e])||void 0===t?void 0:t.map((t=>this.mapToConditionalFormat(e,t))))||[]}getRulesSelection(e,t){const i=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{i.add(e)}))})),Array.from(i)}getRulesByZone(e,t){const i=new Set;for(let n=t.top;n<=t.bottom;n++)for(let o=t.left;o<=t.right;o++){this.getRulesByCell(e,o,n).forEach((e=>{i.add(e.id)}))}return i}getRulesByCell(e,t,i){const n=[];for(let o of this.cfRules[e])for(let e of o.ranges)Wi(t,i,e.zone)&&n.push(o);return new Set(n.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t,i={useFixedReference:!1}){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e,i.useFixedReference)))}}mapToConditionalFormatInternal(e,t){const i={...t,ranges:t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)))};return i}addConditionalFormatting(e,t){const i=this.cfRules[t].slice(),n=i.findIndex((t=>t.id===e.id)),o=this.mapToConditionalFormatInternal(t,e);n>-1?i.splice(n,1,o):i.push(o),this.history.update("cfRules",t,i)}checkValidReordering(e,t,i){if(!this.cfRules[i])return 27;const n=this.cfRules[i].findIndex((t=>t.id===e));if(-1===n)return 72;const o="up"===t?n-1:n+1;return o<0||o>=this.cfRules[i].length?72:0}checkEmptyRange(e){return e.ranges.length?0:24}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber(2,["Between","NotBetween"]),this.checkOperatorArgsNumber(1,["BeginsWith","ContainsText","EndsWith","GreaterThan","GreaterThanOrEqual","LessThan","LessThanOrEqual","NotContains"]),this.checkOperatorArgsNumber(0,["IsEmpty","IsNotEmpty"]));case"ColorScaleRule":return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case"IconSetRule":return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)))}return 0}checkOperatorArgsNumber(e,t){if(e>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");return i=>{if(t.includes(i.operator)){const t=[],n=e=>void 0===e||""===e;return e>=1&&n(i.values[0])&&t.push(52),e>=2&&n(i.values[1])&&t.push(53),t.length?t:0}return 0}}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return 54;case"max":return 56;case"mid":return 55;case"upperInflectionPoint":return 57;case"lowerInflectionPoint":return 58}return 0}checkFormulaCompilation(e,t){if("formula"!==e.type)return 0;try{Pg(e.value||"")}catch(e){switch(t){case"min":return 59;case"max":return 61;case"mid":return 60;case"upperInflectionPoint":return 62;case"lowerInflectionPoint":return 63}}return 0}checkThresholds(e){return this.batchValidations((t=>e(t.minimum,"min")),(t=>e(t.maximum,"max")),(t=>t.midpoint?e(t.midpoint,"mid"):0))}checkInflectionPoints(e){return this.batchValidations((t=>e(t.lowerInflectionPoint,"lowerInflectionPoint")),(t=>e(t.upperInflectionPoint,"upperInflectionPoint")))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,i=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(i)?49:0}checkMinBiggerThanMax(e){const t=e.minimum.value,i=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&uv(t)>=uv(i)?48:0}checkMidBiggerThanMax(e){var t;const i=null===(t=e.midpoint)||void 0===t?void 0:t.value,n=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&uv(i)>=uv(n)?50:0}checkMinBiggerThanMid(e){var t;const i=e.minimum.value,n=null===(t=e.midpoint)||void 0===t?void 0:t.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&uv(i)>=uv(n)?51:0}removeConditionalFormatting(e,t){const i=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==i){const e=this.cfRules[t].slice();e.splice(i,1),this.history.update("cfRules",t,e)}}reorderConditionalFormatting(e,t,i){const n=this.cfRules[i].findIndex((t=>t.id===e)),o="up"===t?n-1:n+1;if(!(o<0||o>=this.cfRules[i].length)&&-1!==n&&-1!==o){const e=[...this.cfRules[i]],t=e[n];e[n]=e[o],e[o]=t,this.history.update("cfRules",i,e)}}}gv.getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];class pv extends av{constructor(){super(...arguments),this.figures={}}allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkFigureDuplicate(e.figure.id);case"UPDATE_FIGURE":case"DELETE_FIGURE":return this.checkFigureExists(e.sheetId,e.id);default:return 0}}beforeHandle(e){if("DELETE_SHEET"===e.type)this.getters.getFigures(e.sheetId).forEach((t=>{this.dispatch("DELETE_FIGURE",{id:t.id,sheetId:e.sheetId})}))}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":this.addFigure(e.figure,e.sheetId);break;case"UPDATE_FIGURE":const{type:t,sheetId:i,...n}=e,o=n;this.updateFigure(i,o);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId)}}updateFigure(e,t){if("id"in t)for(const[i,n]of Object.entries(t))switch(i){case"x":case"y":void 0!==n&&this.history.update("figures",e,t.id,i,Math.max(n,0));break;case"width":case"height":void 0!==n&&this.history.update("figures",e,t.id,i,n)}}addFigure(e,t){this.history.update("figures",t,e.id,e)}deleteSheet(e){this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){var i;return void 0===(null===(i=this.figures[e])||void 0===i?void 0:i[t])?71:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>null==t?void 0:t[e]))?83:0}getFigures(e){return Object.values(this.figures[e]||{}).filter(Xe)}getFigure(e,t){var i;return null===(i=this.figures[e])||void 0===i?void 0:i[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>{var i;return void 0!==(null===(i=this.figures[t])||void 0===i?void 0:i[e])}))}import(e){for(let t of e.sheets){const e={};t.figures.forEach((t=>{e[t.id]=t})),this.figures[t.id]=e}}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const i=void 0;t.figures.push({...e,data:i})}}exportForExcel(e){this.export(e)}}pv.getters=["getFigures","getFigure","getFigureSheetId"];class mv{constructor(e){this.filters=[],this.zone=e;const t=new Mi;this.id=t.smallUuid();for(const i of $e(e.left,e.right+1)){const e={...this.zone,left:i,right:i};this.filters.push(new fv(t.smallUuid(),e))}}get contentZone(){if(this.zone.bottom!==this.zone.top)return{...this.zone,top:this.zone.top+1}}getFilterId(e){var t;return null===(t=this.filters.find((t=>t.col===e)))||void 0===t?void 0:t.id}clone(){return new mv(this.zone)}}class fv{constructor(e,t){if(t.left!==t.right)throw new Error("Can only define a filter on a single column");this.id=e,this.zoneWithHeaders=t}get col(){return this.zoneWithHeaders.left}get filteredZone(){const e=this.zoneWithHeaders;if(e.bottom!==e.top)return{...e,top:e.top+1}}}class vv extends av{constructor(){super(...arguments),this.tables={}}allowDispatch(e){switch(e.type){case"CREATE_FILTER_TABLE":if(!on(...e.target))return 82;const t=Vi(...e.target),i=()=>this.getFilterTables(e.sheetId).some((e=>Hi(e.zone,t)))?79:0,n=()=>{const i=this.getters.getMergesInZone(e.sheetId,t);for(let e of i)if(Hi(t,e))return 81;return 0};return this.checkValidations(e,i,n);case"ADD_MERGE":for(let t of e.target)for(let i of this.getFilterTables(e.sheetId))if(Hi(i.zone,t))return 81}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break;case"DUPLICATE_SHEET":const i={};for(const t of Object.values(this.tables[e.sheetId]||{}))if(t){const e=Ae(t);i[e.id]=e}this.history.update("tables",e.sheetIdTo,i);break;case"ADD_COLUMNS_ROWS":this.onAddColumnsRows(e);break;case"REMOVE_COLUMNS_ROWS":this.onDeleteColumnsRows(e);break;case"CREATE_FILTER_TABLE":{const t=Vi(...e.target),i=this.createFilterTable(t);this.history.update("tables",e.sheetId,i.id,i);break}case"REMOVE_FILTER_TABLE":{const t={};for(const i of this.getFilterTables(e.sheetId))e.target.every((e=>!zi(e,i.zone)))&&(t[i.id]=i);this.history.update("tables",e.sheetId,t);break}case"UPDATE_CELL":{const t=e.sheetId;for(let i of this.getFilterTables(t))this.canUpdateCellCmdExtendTable(e,i)&&this.extendTableDown(t,i);break}}}getFilters(e){return this.getFilterTables(e).map((e=>e.filters)).flat()}getFilterTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(Xe):[]}getFilter(e,t,i){var n;return null===(n=this.getFilterTable(e,t,i))||void 0===n?void 0:n.filters.find((e=>e.col===t))}getFilterId(e,t,i){var n;return null===(n=this.getFilter(e,t,i))||void 0===n?void 0:n.id}getFilterTable(e,t,i){return this.getFilterTables(e).find((e=>Wi(t,i,e.zone)))}getFilterTablesInZone(e,t){return this.getFilterTables(e).filter((e=>Gi(e.zone,t)))}doesZonesContainFilter(e,t){for(const i of t)for(const t of this.getFilterTables(e))if(zi(i,t.zone))return!0;return!1}onAddColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const i=$i(t.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),n=[];for(const i of t.filters){const t=$i(i.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);n.push(new fv(i.id,t))}if(n.length<ji(i).width){for(let e=i.left;e<=i.right;e++)n.find((t=>t.col===e))||n.push(new fv(this.uuidGenerator.smallUuid(),{...i,left:e,right:e}));n.sort(((e,t)=>e.col-t.col))}this.history.update("tables",e.sheetId,t.id,"zone",i),this.history.update("tables",e.sheetId,t.id,"filters",n)}}onDeleteColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){if("ROW"===e.dimension&&e.elements.includes(t.zone.top)){const i={...this.tables[e.sheetId]};delete i[t.id],this.history.update("tables",e.sheetId,i);continue}const i=Ui(t.zone,"COL"===e.dimension?"left":"top",e.elements);if(i){if(ki(i)!==ki(t.zone)){const n=[];for(const i of t.filters){const t=Ui(i.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.elements);t&&n.push(new fv(i.id,t))}this.history.update("tables",e.sheetId,t.id,"zone",i),this.history.update("tables",e.sheetId,t.id,"filters",n)}}else{const i={...this.tables[e.sheetId]};delete i[t.id],this.history.update("tables",e.sheetId,i)}}}createFilterTable(e){return new mv(e)}extendTableDown(e,t){const i={...t.zone,bottom:t.zone.bottom+1};this.history.update("tables",e,t.id,"zone",i);for(let i=0;i<t.filters.length;i++){const n=t.filters[i],o={...n.zoneWithHeaders,bottom:n.zoneWithHeaders.bottom+1};this.history.update("tables",e,t.id,"filters",i,"zoneWithHeaders",o)}}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:i,row:n},o){var s;if(!e)return;const r=o.zone;if(!(r.bottom+1===n&&i>=r.left&&i<=r.right))return!1;for(const e of $e(r.left,r.right+1)){if(null===(s=this.getters.getCell(t,e,n))||void 0===s?void 0:s.content)return!1;if(this.getters.getFilter(t,e,n))return!1;if(this.getters.isInMerge(t,e,n))return!1}return!0}import(e){for(const t of e.sheets)for(const e of t.filterTables||[]){const i=this.createFilterTable(Fi(e.range));this.history.update("tables",t.id,i.id,i)}}export(e){for(const t of e.sheets)for(const e of this.getFilterTables(t.id))t.filterTables.push({range:ki(e.zone)})}exportForExcel(e){for(const t of e.sheets)for(const e of this.getFilterTables(t.id))1!==ji(e.zone).height&&t.filterTables.push({range:ki(e.zone),filters:[]})}}vv.getters=["doesZonesContainFilter","getFilter","getFilters","getFilterTable","getFilterTables","getFilterTablesInZone","getFilterId"];class bv extends av{constructor(){super(...arguments),this.sizes={}}handle(e){var t,i;switch(e.type){case"CREATE_SHEET":{const t=this.computeSheetSizes(e.sheetId),i={COL:t.COL.map((e=>({manualSize:void 0,computedSize:tt(e)}))),ROW:t.ROW.map((e=>({manualSize:void 0,computedSize:tt(e)})))};this.history.update("sizes",e.sheetId,i);break}case"DUPLICATE_SHEET":for(const t of this.sizes[e.sheetId].ROW)t.computedSize();for(const t of this.sizes[e.sheetId].COL)t.computedSize();this.history.update("sizes",e.sheetIdTo,Ae(this.sizes[e.sheetId]));break;case"DELETE_SHEET":const n={...this.sizes};delete n[e.sheetId],this.history.update("sizes",n);break;case"REMOVE_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];for(let i of[...e.elements].sort(((e,t)=>t-e)))t.splice(i,1);const i=ct(e.elements);t=t.map(((t,n)=>"ROW"===e.dimension&&n>=i?{manualSize:t.manualSize,computedSize:tt((()=>this.getRowTallestCellSize(e.sheetId,n)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];const i=nt(e.position,e.base),n=t[e.base],o=$e(0,e.quantity).map((()=>({manualSize:n.manualSize,computedSize:tt(n.computedSize())})));t.splice(i,0,...o),t=t.map(((t,i)=>"ROW"===e.dimension&&i>e.base+e.quantity?{manualSize:t.manualSize,computedSize:tt((()=>this.getRowTallestCellSize(e.sheetId,i)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"RESIZE_COLUMNS_ROWS":for(let t of e.elements)if("ROW"===e.dimension){const i=this.getRowTallestCellSize(e.sheetId,t);this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:tt(i)})}else this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:tt(e.size||_)});break;case"UPDATE_CELL":const o=null===(i=null===(t=this.sizes[e.sheetId])||void 0===t?void 0:t.ROW)||void 0===i?void 0:i[e.row];if(o&&!o.manualSize){const{sheetId:t,row:i}=e;this.history.update("sizes",t,"ROW",i,"computedSize",tt((()=>this.getRowTallestCellSize(t,i))))}break;case"ADD_MERGE":case"REMOVE_MERGE":for(let t of e.target)for(let i of $e(t.top,t.bottom+1)){const t=this.getRowTallestCellSize(e.sheetId,i);t!==this.getRowSize(e.sheetId,i)&&this.history.update("sizes",e.sheetId,"ROW",i,"computedSize",tt(t))}}}getColSize(e,t){return this.getHeaderSize(e,"COL",t)}getRowSize(e,t){return this.getHeaderSize(e,"ROW",t)}getHeaderSize(e,t,i){var n,o,s,r;return Math.round((null===(o=null===(n=this.sizes[e])||void 0===n?void 0:n[t][i])||void 0===o?void 0:o.manualSize)||(null===(r=null===(s=this.sizes[e])||void 0===s?void 0:s[t][i])||void 0===r?void 0:r.computedSize())||this.getDefaultHeaderSize(t))}computeSheetSizes(e){var t,i;const n={COL:[],ROW:[]};for(let t of $e(0,this.getters.getNumberCols(e)))n.COL.push(this.getHeaderSize(e,"COL",t));for(let o of $e(0,this.getters.getNumberRows(e))){let s=null===(i=null===(t=this.sizes[e])||void 0===t?void 0:t.ROW)||void 0===i?void 0:i[o].manualSize;if(!s){s=this.getRowTallestCellSize(e,o)}n.ROW.push(s)}return n}getDefaultHeaderSize(e){return"COL"===e?_:F}getCellHeight(e,t,i){const n=this.getters.getMerge(e,t,i);if(n&&n.bottom!==n.top)return F;const o=this.getters.getCell(e,t,i);return(null==(s=null==o?void 0:o.style)?void 0:s.fontSize)?(r||1)*(ke(s)+P)-P+2*U:F;var s,r}getRowTallestCellSize(e,t){const i=this.getters.getRowCells(e,t);let n=0;for(let t=0;t<i.length;t++){const o=this.getters.getCellById(i[t]);if(!o)continue;const{col:s,row:r}=this.getters.getCellPosition(o.id),a=this.getCellHeight(e,s,r);a>n&&a>F&&(n=a)}return n<=F?F:n}import(e){for(let t of e.sheets){const e={COL:[],ROW:[]};for(let[i,n]of Object.entries(t.rows))n.size&&(e.ROW[i]=n.size);for(let[i,n]of Object.entries(t.cols))n.size&&(e.COL[i]=n.size);const i=this.computeSheetSizes(t.id);this.sizes[t.id]={COL:i.COL.map(((t,i)=>({manualSize:e.COL[i],computedSize:tt(t)}))),ROW:i.ROW.map(((t,i)=>({manualSize:e.ROW[i],computedSize:tt(t)})))}}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){var i,n;for(let o of e.sheets){void 0===o.rows&&(o.rows={});for(let e of $e(0,this.getters.getNumberRows(o.id)))(t||(null===(i=this.sizes[o.id].ROW[e])||void 0===i?void 0:i.manualSize))&&(o.rows[e]={...o.rows[e],size:this.getRowSize(o.id,e)});void 0===o.cols&&(o.cols={});for(let e of $e(0,this.getters.getNumberCols(o.id)))(t||(null===(n=this.sizes[o.id].COL[e])||void 0===n?void 0:n.manualSize))&&(o.cols[e]={...o.cols[e],size:this.getColSize(o.id,e)})}}}bv.getters=["getRowSize","getColSize"];class Sv extends av{constructor(){super(...arguments),this.hiddenHeaders={}}allowDispatch(e){switch(e.type){case"HIDE_COLUMNS_ROWS":{if(!this.getters.tryGetSheet(e.sheetId))return 27;const t="COL"===e.dimension?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),i="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=i?67:ct(e.elements)<0||lt(e.elements)>i?87:0}case"REMOVE_COLUMNS_ROWS":return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?8:0:27}return 0}handle(e){switch(e.type){case"CREATE_SHEET":const t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update("hiddenHeaders",e.sheetId,t);break;case"DUPLICATE_SHEET":this.history.update("hiddenHeaders",e.sheetIdTo,Ae(this.hiddenHeaders[e.sheetId]));break;case"DELETE_SHEET":this.history.update("hiddenHeaders",e.sheetId,void 0);break;case"REMOVE_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let i of[...e.elements].sort(((e,t)=>t-e)))t.splice(i,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]],i=nt(e.position,e.base);t.splice(i,0,...Array(e.quantity).fill(!1)),this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"HIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!0);break;case"UNHIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!1)}}checkElementsIncludeAllVisibleHeaders(e,t,i){return st(i,this.getAllVisibleHeaders(e,t))}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]}getHiddenColsGroups(e){const t=[[]],i=this.hiddenHeaders[e].COL;for(let e=0;e<i.length;e++){i[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getHiddenRowsGroups(e){const t=[[]],i=this.hiddenHeaders[e].ROW;for(let e=0;e<i.length;e++){i[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getAllVisibleHeaders(e,t){return $e(0,this.hiddenHeaders[e][t].length).filter((i=>!this.hiddenHeaders[e][t][i]))}import(e){var t,i;for(let n of e.sheets){this.hiddenHeaders[n.id]={COL:[],ROW:[]};for(let e=0;e<n.rowNumber;e++)this.hiddenHeaders[n.id].ROW[e]=Boolean(null===(t=n.rows[e])||void 0===t?void 0:t.isHidden);for(let e=0;e<n.colNumber;e++)this.hiddenHeaders[n.id].COL[e]=Boolean(null===(i=n.cols[e])||void 0===i?void 0:i.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let i of e.sheets){void 0===i.rows&&(i.rows={});for(let e=0;e<this.getters.getNumberRows(i.id);e++)(t||this.hiddenHeaders[i.id].ROW[e])&&(void 0===i.rows[e]&&(i.rows[e]={}),i.rows[e].isHidden=this.hiddenHeaders[i.id].ROW[e]);void 0===i.cols&&(i.cols={});for(let e=0;e<this.getters.getNumberCols(i.id);e++)(t||this.hiddenHeaders[i.id].COL[e])&&(void 0===i.cols[e]&&(i.cols[e]={}),i.cols[e].isHidden=this.hiddenHeaders[i.id].COL[e])}}}Sv.getters=["checkElementsIncludeAllVisibleHeaders","getHiddenColsGroups","getHiddenRowsGroups","isRowHiddenByUser","isColHiddenByUser"];class Cv extends av{constructor(){super(...arguments),this.nextId=1,this.merges={},this.mergeCellMap={}}allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;for(const i of Object.values(t).filter(Xe))this.addMerge(e.sheetIdTo,i.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(e.sheetId,t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){const i=t?[t]:Object.keys(this.merges);for(const t of i)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(Xe)}getMerge(e,t,i){var n;const o=this.mergeCellMap[e],s=o?t in o&&(null===(n=o[t])||void 0===n?void 0:n[i]):void 0;return s?this.getMergeById(e,s):void 0}getMergesInZone(e,t){var i;const n=this.mergeCellMap[e];if(!n)return[];const o=new Set;for(const{col:e,row:s}of Xi(t)){const t=null===(i=n[e])||void 0===i?void 0:i[s];t&&o.add(t)}return Array.from(o).map((t=>this.getMergeById(e,t))).filter(Xe)}doesIntersectMerge(e,t){const{left:i,right:n,top:o,bottom:s}=t;for(let t=o;t<=s;t++)for(let o=i;o<=n;o++)if(this.getMerge(e,o,t))return!0;return!1}doesColumnsHaveCommonMerges(e,t,i){const n=this.getters.getSheet(e);for(let o=0;o<this.getters.getNumberRows(e);o++)if(this.isInSameMerge(n.id,t,o,i,o))return!0;return!1}doesRowsHaveCommonMerges(e,t,i){const n=this.getters.getSheet(e);for(let o=0;o<=this.getters.getNumberCols(e);o++)if(this.isInSameMerge(n.id,o,t,o,i))return!0;return!1}expandZone(e,t){let{left:i,right:n,top:o,bottom:s}=t,r={left:i,right:n,top:o,bottom:s};for(let t in this.merges[e]){const i=this.getMergeById(e,parseInt(t));i&&Hi(i,r)&&(r=Vi(i,r))}return Bi(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,i,n,o){const s=this.getMerge(e,t,i),r=this.getMerge(e,n,o);return!(!s||!r)&&Bi(s,r)}isInMerge(e,t,i){var n;const o=this.mergeCellMap[e];return!!o&&(t in o&&Boolean(null===(n=o[t])||void 0===n?void 0:n[i]))}getMainCellPosition(e,t,i){if(!this.isInMerge(e,t,i))return{col:t,row:i};const n=this.getMerge(e,t,i).topLeft;return{col:n.col,row:n.row}}getBottomLeftCell(e,t,i){if(!this.isInMerge(e,t,i))return{col:t,row:i};const{bottom:n,left:o}=this.getMerge(e,t,i);return{col:o,row:n}}isMergeHidden(e,t){const i=this.getters.getHiddenColsGroups(e),n=this.getters.getHiddenRowsGroups(e);for(let e of i)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of n)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const i=this.getMerge(e,t.left,t.top);if(i)return Bi(t,i);const{width:n,height:o}=ji(t);return 1===n&&1===o}isMergeDestructive(e,t){let{left:i,right:n,top:o,bottom:s}=t;n=Me(n,0,this.getters.getNumberCols(e)-1),s=Me(s,0,this.getters.getNumberRows(e)-1);for(let t=o;t<=s;t++)for(let s=i;s<=n;s++)if(s!==i||t!==o){const i=this.getters.getCell(e,s,t);if(i&&!i.isEmpty())return!0}return!1}getMergeById(e,t){var i;const n=null===(i=this.merges[e])||void 0===i?void 0:i[t];return void 0!==n?wv(t,n):void 0}checkDestructiveMerge({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;return t.some((t=>this.isMergeDestructive(e,t)))?3:0}checkOverlap({target:e}){for(const t of e)for(const i of e)if(t!==i&&Hi(t,i))return 66;return 0}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;const{xSplit:i,ySplit:n}=this.getters.getPaneDivisions(e);for(const e of t)if(e.left<i&&e.right>=i||e.top<n&&e.bottom>=n)return 76;return 0}checkMergedContentUpdate(e){const{col:t,row:i,sheetId:n,content:o}=e;if(void 0===o)return 0;const{col:s,row:r}=this.getMainCellPosition(n,t,i);return s===t&&r===i?0:4}checkMergeExists(e){const{sheetId:t,target:i}=e;for(const e of i){const{left:i,top:n}=e,o=this.getMerge(t,i,n);if(void 0===o||!Bi(e,o))return 5}return 0}addMerge(e,t){let{left:i,right:n,top:o,bottom:s}=t;n=Me(n,0,this.getters.getNumberCols(e)-1),s=Me(s,0,this.getters.getNumberRows(e)-1);if(Vt(i,o)===Vt(n,s))return;const r=this.getters.getCell(e,i,o);let a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,ki({left:i,top:o,right:n,bottom:s})));let l=new Set;for(let t=o;t<=s;t++)for(let s=i;s<=n;s++){s===i&&t===o||this.dispatch("UPDATE_CELL",{sheetId:e,col:s,row:t,style:r?r.style:null,content:""});const n=this.getMerge(e,s,t);n&&l.add(n.id),this.history.update("mergeCellMap",e,s,t,a)}for(let t of l){const{top:i,bottom:n,left:o,right:s}=this.getMergeById(e,t);for(let t=i;t<=n;t++)for(let i=o;i<=s;i++){const n=this.getMerge(e,i,t);n&&n.id===a||(this.history.update("mergeCellMap",e,i,t,void 0),this.dispatch("CLEAR_CELL",{sheetId:e,col:i,row:t}))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:i,top:n,bottom:o,right:s}=t,r=this.getMerge(e,i,n);if(void 0!==r&&Bi(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=n;t<=o;t++)for(let n=i;n<=s;n++)this.history.update("mergeCellMap",e,n,t,void 0)}}applyRangeChangeOnSheet(e,t){const i=Object.entries(this.merges[e]||{});for(const[n,o]of i)if(o){const i=o.zone,s=t(o);switch(s.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,i);break;default:const{width:t,height:o}=ji(s.range.zone);1===t&&1===o?this.removeMerge(e,i):this.history.update("merges",e,parseInt(n,10),s.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:i,row:n}of Xi(t))this.history.update("mergeCellMap",e,i,n,t.id)}import(e){const t=e.sheets||[];for(let e of t)this.history.update("merges",e.id,{}),this.history.update("mergeCellMap",e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let i of t)this.addMerge(e,Fi(i))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...Ev(e))}}exportForExcel(e){this.export(e)}}function Ev(e){return Object.entries(e).map((([e,t])=>t?wv(parseInt(e,10),t):void 0)).filter(Xe).map((e=>Vt(e.left,e.top)+":"+Vt(e.right,e.bottom)))}function wv(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}Cv.getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge"];class yv extends av{constructor(){super(...arguments),this.sheetIdsMapName={},this.orderedSheetIds=[],this.sheets={},this.cellPosition={}}allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZones)(e);if(0!==t)return t;switch(e.type){case"HIDE_SHEET":return 1===this.getVisibleSheetIds().length?9:0;case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"DUPLICATE_SHEET":return this.sheets[e.sheetIdTo]?12:this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?11:0;case"MOVE_SHEET":const t=this.orderedSheetIds.indexOf(e.sheetId);if("left"===e.direction){return this.orderedSheetIds.slice(0,t).map((e=>!this.isSheetVisible(e))).every((e=>e))?14:0}return this.orderedSheetIds.slice(t+1).map((e=>!this.isSheetVisible(e))).every((e=>e))?14:0;case"RENAME_SHEET":return this.isRenameAllowed(e);case"DELETE_SHEET":return this.getVisibleSheetIds().length>1?0:9;case"ADD_COLUMNS_ROWS":const i="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return e.base<0||e.base>=i?87:e.quantity<=0?88:0;case"REMOVE_COLUMNS_ROWS":{const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return ct(e.elements)<0||lt(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.direction);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,e.sheetNameTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case"UPDATE_CELL_POSITION":this.updateCellPosition(e);break;case"FREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,e.quantity,"COL");break;case"FREEZE_ROWS":this.setPaneDivisions(e.sheetId,e.quantity,"ROW");break;case"UNFREEZE_ROWS":this.setPaneDivisions(e.sheetId,0,"ROW");break;case"UNFREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,0,"COL");break;case"UNFREEZE_COLUMNS_ROWS":this.setPaneDivisions(e.sheetId,0,"COL"),this.setPaneDivisions(e.sheetId,0,"ROW")}}import(e){var t,i;for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let n of e.sheets){const e=n.name||o("Sheet")+(Object.keys(this.sheets).length+1),{colNumber:s,rowNumber:r}=this.getImportedSheetSize(n),a={id:n.id,name:e,numberOfCols:s,rows:Ti(r),areGridLinesVisible:void 0===n.areGridLinesVisible||n.areGridLinesVisible,isVisible:n.isVisible,panes:{xSplit:(null===(t=n.panes)||void 0===t?void 0:t.xSplit)||0,ySplit:(null===(i=n.panes)||void 0===i?void 0:i.ySplit)||0}};this.orderedSheetIds.push(a.id),this.sheets[a.id]=a}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(Xe).map((e=>{const t=this.sheets[e],i={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},conditionalFormats:[],figures:[],filterTables:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible};return(t.panes.xSplit||t.panes.ySplit)&&(i.panes=t.panes),i}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}getCellsInZone(e,t){return Xi(t).map((({col:t,row:i})=>this.getCell(e,t,i)))}tryGetSheetName(e){var t;return null===(t=this.tryGetSheet(e))||void 0===t?void 0:t.name}getSheetIdByName(e){if(e){const t=Ne(e);for(const e in this.sheetIdsMapName)if(Ai(e,t))return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}getEvaluationSheets(){return this.sheets}doesHeaderExist(e,t,i){return"COL"===t?i>=0&&i<this.getNumberCols(e):i>=0&&i<this.getNumberRows(e)}getRow(e,t){const i=this.getSheet(e).rows[t];if(!i)throw new Error(`Row ${i} not found.`);return i}getCell(e,t,i){var n;const o=this.tryGetSheet(e),s=null===(n=null==o?void 0:o.rows[i])||void 0===n?void 0:n.cells[t];if(void 0!==s)return this.getters.getCellById(s)}getColCells(e,t){return this.getSheet(e).rows.map((e=>e.cells[t])).filter(Xe).map((e=>this.getters.getCellById(e))).filter(Xe)}getColsZone(e,t,i){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:i}}getRowCells(e,t){var i;return Object.values(null===(i=this.getSheet(e).rows[t])||void 0===i?void 0:i.cells).filter(Xe)}getRowsZone(e,t,i){return{top:t,bottom:i,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){return Ni(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{height:this.getNumberRows(e),width:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,i){const n={...this.getPaneDivisions(e)};"COL"===i?n.xSplit=t:"ROW"===i&&(n.ySplit=t),this.history.update("sheets",e,"panes",n)}checkElementsIncludeAllNonFrozenHeaders(e,t,i){const n=this.getters.getPaneDivisions(e),o="ROW"===t?n.ySplit:n.xSplit,s=this.getters.getNumberHeaders(e,t);if(!o)return!1;return st(i,$e(o,s))}isEmpty(e,t){return this.getCellsInZone(e,t).flat().every((e=>!e||e.isEmpty()))}updateCellPosition(e){const{sheetId:t,cellId:i,col:n,row:o}=e;i?this.setNewPosition(i,t,n,o):this.clearPosition(t,n,o)}setNewPosition(e,t,i,n){const o=this.cellPosition[e];o&&this.clearPosition(t,o.col,o.row),this.history.update("cellPosition",e,{row:n,col:i,sheetId:t}),this.history.update("sheets",t,"rows",n,"cells",i,e)}clearPosition(e,t,i){var n;const o=null===(n=this.sheets[e])||void 0===n?void 0:n.rows[i].cells[t];o&&(this.history.update("cellPosition",o,void 0),this.history.update("sheets",e,"rows",i,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}clearZones(e,t){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++){this.sheets[e].rows[n].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:n})}}createSheet(e,t,i,n,o){const s={id:e,name:t,numberOfCols:i,rows:Ti(n),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},r=this.orderedSheetIds.slice();r.splice(o,0,s.id);const a=this.sheets;return this.history.update("orderedSheetIds",r),this.history.update("sheets",Object.assign({},a,{[s.id]:s})),s}moveSheet(e,t){const i=this.orderedSheetIds.slice(),n=i.findIndex((t=>t===e)),o=i.splice(n,1);let s="left"===t?this.findIndexOfPreviousVisibleSheet(n-1,i):this.findIndexOfNextVisibleSheet(n+1,i);void 0===s&&(s=i.length),i.splice(s,0,o[0]),this.history.update("orderedSheetIds",i)}findIndexOfPreviousVisibleSheet(e,t){for(;e>=0&&!this.isSheetVisible(t[e]);)e--;if(-1===e)throw new Error("There is no previous visible sheet");return e}findIndexOfNextVisibleSheet(e,t){for(;e<t.length&&!this.isSheetVisible(t[e]);)e++;if(e!==t.length-1||this.isSheetVisible(t[e-1]))return e}checkSheetName(e){const{orderedSheetIds:t,sheets:i}=this,n=e.name&&e.name.trim().toLowerCase();return t.find((e=>{var t;return Ai(null===(t=i[e])||void 0===t?void 0:t.name,n)}))?11:te.test(n)?13:0}checkSheetPosition(e){const{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?15:0}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?0:75}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?0:75}checkRowFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let i of t)if(i.top<e.quantity&&e.quantity<=i.bottom)return 66;return 0}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let i of t)if(i.left<e.quantity&&e.quantity<=i.right)return 66;return 0}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):10}renameSheet(e,t){const i=e.name;this.history.update("sheets",e.id,"name",t.trim());const n=Object.assign({},this.sheetIdsMapName);n[t]=e.id,delete n[i],this.history.update("sheetIdsMapName",n)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t,i){const n=Ae(this.getSheet(e));n.id=t,n.name=i;for(let e=0;e<=n.numberOfCols;e++)for(let t=0;t<=n.rows.length;t++)n.rows[t]&&(n.rows[t].cells[e]=void 0);const o=this.orderedSheetIds.slice(),s=o.indexOf(e);o.splice(s+1,0,n.id),this.history.update("orderedSheetIds",o),this.history.update("sheets",Object.assign({},this.sheets,{[n.id]:n}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:i}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:n.id,col:e,row:i,content:t.content,format:t.format,style:t.style})}const r=Object.assign({},this.sheetIdsMapName);r[n.name]=n.id,this.history.update("sheetIdsMapName",r)}getDuplicateSheetName(e){return Oi(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){const t=e.name,i=Object.assign({},this.sheets);delete i[e.id],this.history.update("sheets",i);const n=this.orderedSheetIds.slice(),o=n.indexOf(e.id);n.splice(o,1),this.history.update("orderedSheetIds",n);const s=Object.assign({},this.sheetIdsMapName);delete s[t],this.history.update("sheetIdsMapName",s)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(let i of t)this.moveCellOnColumnsDeletion(e,i);const i=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",i-t.length);const n=t.filter((t=>t<e.panes.xSplit)).length;n&&this.setPaneDivisions(e.id,e.panes.xSplit-n,"COL")}removeRows(e,t){t.sort(((e,t)=>t-e));for(let i of Le(t)){const t=i[i.length-1],n=i[0];this.moveCellOnRowsDeletion(e,t,n),this.updateRowsStructureOnDeletion(e,t,n)}const i=t.filter((t=>t<e.panes.ySplit)).length;i&&this.setPaneDivisions(e.id,e.panes.ySplit-i,"ROW")}addColumns(e,t,i,n){const o="before"===i?t:t+1;this.moveCellsOnAddition(e,o,n,"columns");const s=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",s+n),o<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+n,"COL")}addRows(e,t,i,n){const o="before"===i?t:t+1;this.addEmptyRows(e,n),this.moveCellsOnAddition(e,o,n,"rows"),o<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+n,"ROW")}moveCellOnColumnsDeletion(e,t){for(let i=0;i<e.rows.length;i++){const n=e.rows[i];for(let o in n.cells){const s=Number(o),r=n.cells[o];r&&(s===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:s,row:i}),s>t&&this.setNewPosition(r,e.id,s-1,i))}}}moveCellsOnAddition(e,t,i,n){const o=[];for(let s=0;s<e.rows.length;s++){const r=e.rows[s];if("rows"!==n||s>=t)for(let a in r.cells){const l=Number(a),c=r.cells[a];c&&("rows"===n||l>=t)&&o.push({sheetId:e.id,cellId:c,col:l+("columns"===n?i:0),row:s+("rows"===n?i:0),type:"UPDATE_CELL_POSITION"})}}for(let e of o.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,i){const n=i-t+1;for(let o=0;o<e.rows.length;o++){const s=e.rows[o];if(o>=t&&o<=i)for(let t in s.cells){const i=Number(t);s.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:i,row:o})}if(o>i)for(let t in s.cells){const i=Number(t),r=s.cells[t];r&&this.setNewPosition(r,e.id,i,o-n)}}}updateRowsStructureOnDeletion(e,t,i){const n=[],o=e.rows.map((e=>e.cells)).reverse();for(let s in e.rows){const e=Number(s);e>=t&&e<=i||n.push({cells:o.pop()})}this.history.update("sheets",e.id,"rows",n)}addEmptyRows(e,t){const i=e.rows.slice();for(let e=0;e<t;e++)i.push({cells:{}});this.history.update("sheets",e.id,"rows",i)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(Ut);let i=e.rowNumber,n=e.colNumber;for(let{col:e,row:o}of t)i=Math.max(i,o+1),n=Math.max(n,e+1);return{rowNumber:i,colNumber:n}}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?27:"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?12:0}checkZones(e){const t=[];if("zone"in e&&t.push(e.zone),"target"in e&&Array.isArray(e.target)&&t.push(...e.target),"ranges"in e&&Array.isArray(e.ranges)){if(e.ranges.some((e=>!this.getters.tryGetSheet(e._sheetId))))return 27;t.push(...e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone)))}if(!t.every(Di))return 25;if(t.length&&"sheetId"in e){const i=this.getSheetZone(e.sheetId);return t.every((e=>Gi(e,i)))?0:18}return 0}}yv.getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheetIds","getVisibleSheetIds","isSheetVisible","getEvaluationSheets","doesHeaderExist","getCell","getCellsInZone","getCellPosition","getColCells","getColsZone","getRowCells","getRowsZone","getNumberCols","getNumberRows","getNumberHeaders","getGridLinesVisibility","getNextSheetName","isEmpty","getSheetSize","getSheetZone","getPaneDivisions","checkElementsIncludeAllNonFrozenHeaders","getDuplicateSheetName"];class xv{constructor(e,t,i){this.index=0,this.cells=e,this.getters=t,this.direction=i}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:i,tooltip:n}=cn.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:i,tooltip:n,origin:{col:e.data.col,row:e.data.row}}}}class Rv extends Wg{constructor(){super(...arguments),this.lastCellSelected={}}allowDispatch(e){switch(e.type){case"AUTOFILL_SELECT":const t=this.getters.getActiveSheetId();return this.lastCellSelected.col=-1===e.col?this.lastCellSelected.col:Me(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:Me(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?0:46;case"AUTOFILL_AUTO":const i=this.getters.getSelectedZone();return i.top===i.bottom?0:1}return 0}handle(e){switch(e.type){case"AUTOFILL":this.autofill(!0);break;case"AUTOFILL_SELECT":this.select(e.col,e.row);break;case"AUTOFILL_AUTO":this.autofillAuto();break;case"AUTOFILL_CELL":this.autoFillMerge(e.originCol,e.originRow,e.col,e.row);const t=this.getters.getActiveSheetId();this.dispatch("UPDATE_CELL",{sheetId:t,col:e.col,row:e.row,style:e.style||null,content:e.content||"",format:e.format||""}),this.dispatch("SET_BORDER",{sheetId:t,col:e.col,row:e.row,border:e.border})}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),i=this.autofillZone;switch(this.direction){case"down":for(let n=t.left;n<=t.right;n++){const o=[];for(let e=t.top;e<=t.bottom;e++)o.push(Vt(n,e));const s=this.createGenerator(o);for(let t=i.top;t<=i.bottom;t++)this.computeNewCell(s,n,t,e)}break;case"up":for(let n=t.left;n<=t.right;n++){const o=[];for(let e=t.bottom;e>=t.top;e--)o.push(Vt(n,e));const s=this.createGenerator(o);for(let t=i.bottom;t>=i.top;t--)this.computeNewCell(s,n,t,e)}break;case"left":for(let n=t.top;n<=t.bottom;n++){const o=[];for(let e=t.right;e>=t.left;e--)o.push(Vt(e,n));const s=this.createGenerator(o);for(let t=i.right;t>=i.left;t--)this.computeNewCell(s,t,n,e)}break;case"right":for(let n=t.top;n<=t.bottom;n++){const o=[];for(let e=t.left;e<=t.right;e++)o.push(Vt(e,n));const s=this.createGenerator(o);for(let t=i.left;t<=i.right;t++)this.computeNewCell(s,t,n,e)}}e&&(this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0)}select(e,t){const i=this.getters.getSelectedZone();if(Wi(e,t,i))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,i.top-1,i.left,i.right),this.steps=i.top-t;break;case"down":this.saveZone(i.bottom+1,t,i.left,i.right),this.steps=t-i.bottom;break;case"left":this.saveZone(i.top,i.bottom,e,i.left-1),this.steps=i.left-e;break;case"right":this.saveZone(i.top,i.bottom,i.right+1,e),this.steps=e-i.right}this.autofill(!1)}}autofillAuto(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let i=e.left,n=e.bottom;if(i>0){let e=this.getters.getCell(t,i-1,n);for(;e&&!e.isEmpty();)n+=1,e=this.getters.getCell(t,i-1,n)}if(n===e.bottom&&(i=e.right,i<=this.getters.getNumberCols(t))){let e=this.getters.getCell(t,i+1,n);for(;e&&!e.isEmpty();)n+=1,e=this.getters.getCell(t,i+1,n)}n!==e.bottom&&(this.select(e.left,n-1),this.autofill(!0))}computeNewCell(e,t,i,n){const{cellData:o,tooltip:s,origin:r}=e.next(),{content:a,style:l,border:c,format:h}=o;this.tooltip=s,n&&this.dispatch("AUTOFILL_CELL",{originCol:r.col,originRow:r.row,col:t,row:i,content:a,style:l,border:c,format:h})}getRule(e,t){const i=En.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((i=>i.condition(e,t)));return i&&this.direction&&i.generateRule(e,t,this.direction)}createGenerator(e){const t=[],i=[],n=this.getters.getActiveSheetId();for(let t of e){const{col:e,row:o}=Ut(t),s=this.getters.getCell(n,e,o);i.push({col:e,row:o,cell:s,sheetId:n})}const o=i.map((e=>e.cell));for(let e of i){let i={type:"COPY_MODIFIER"};if(e&&e.cell){i=this.getRule(e.cell,o)||i}const{sheetId:n,col:s,row:r}=e,a=this.getters.getCellBorder(n,s,r)||void 0;t.push({data:{...e,border:a},rule:i})}return new xv(t,this.getters,this.direction)}saveZone(e,t,i,n){this.autofillZone={top:e,bottom:t,left:i,right:n}}getDirection(e,t){const i=this.getters.getSelectedZone(),n={up:{number:i.top-t,value:"up"},down:{number:t-i.bottom,value:"down"},left:{number:i.left-e,value:"left"},right:{number:e-i.right,value:"right"}};if(1===Object.values(n).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(n).find((e=>e.number>0?1:0)).value;const o=n.up.number>0?"up":"down",s=n.left.number>0?"left":"right";return Math.abs(n[o].number)>=Math.abs(n[s].number)?n[o].value:n[s].value}autoFillMerge(e,t,i,n){const o=this.getters.getActiveSheet();if(this.getters.isInMerge(o.id,i,n)&&!this.getters.isInMerge(o.id,e,t)){const e=this.getters.getMerge(o.id,i,n);e&&this.dispatch("REMOVE_MERGE",{sheetId:o.id,target:[e]})}const s=this.getters.getMerge(o.id,e,t);(null==s?void 0:s.topLeft.col)===e&&(null==s?void 0:s.topLeft.row)===t&&this.dispatch("ADD_MERGE",{sheetId:o.id,target:[{top:n,bottom:n+s.bottom-s.top,left:i,right:i+s.right-s.left}]})}drawGrid(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:i}=e,{x:n,y:o,width:s,height:r}=this.getters.getVisibleRect(this.autofillZone);s>0&&r>0&&(t.strokeStyle="black",t.lineWidth=i,t.setLineDash([3]),t.strokeRect(n,o,s,r),t.setLineDash([]))}}Rv.layers=[6],Rv.getters=["getAutofillTooltip"];class Iv extends Wg{handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:i}=this.getters.getSelection();for(const n of t){const t=this.getAutomaticSums(e,n,i.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,i){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,i):this.sumData(e,t)}sumData(e,t){const i=this.dimensionsToSum(e,t),n=this.sumDimensions(e,t,i).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return i.has("ROW")&&i.has("COL")&&n.push(this.sumTotal(t)),n}sumAdjacentData(e,t,i){const{col:n,row:o}=Wi(i.col,i.row,t)?i:{col:t.left,row:t.top},s=this.findAdjacentData(e,n,o);return s?this.getters.isSingleCellOrMerge(e,t)||Yi(Vi(s,t))?[{position:{col:n,row:o},zone:s}]:this.sumDimensions(e,Vi(s,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,i){const n=this.getters.getSheet(e),o=this.getters.getMainCellPosition(e,t,i),s=this.findSuitableZoneToSum(n,o.col,o.row);if(s)return this.getters.expandZone(e,s)}findSuitableZoneToSum(e,t,i){const n=this.getters.getCell(e.id,t,i-1),o=this.getters.getCell(e.id,t-1,i);if(this.isNumber(o)&&!this.isNumber(n))return this.findHorizontalZone(e,t,i);const s=this.findVerticalZone(e,t,i);if(this.isZoneValid(s))return s;const r=this.findHorizontalZone(e,t,i);return this.isZoneValid(r)?r:void 0}findVerticalZone(e,t,i){const n={top:0,bottom:i-1,left:t,right:t},o=this.reduceZoneStart(e,n,n.bottom);return{...n,top:o}}findHorizontalZone(e,t,i){const n={top:i,bottom:i,left:0,right:t-1},o=this.reduceZoneStart(e,n,n.right);return{...n,left:o}}reduceZoneStart(e,t,i){const n=this.getters.getCellsInZone(e.id,t),o=$e(i,-1,-1),s=lt(o.filter((e=>{var t;return n[e]&&!(null===(t=n[e])||void 0===t?void 0:t.isAutoSummable)}))),r=Le(o.filter((e=>this.isNumber(n[e]))))[0]||[];return lt(r)<s?1/0:ct(r)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){var t;return(null==e?void 0:e.evaluated.type)===hn.number&&!(null===(t=e.evaluated.format)||void 0===t?void 0:t.match(Y))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){const i=new Set;return Yi(t)?(i.add(1===ji(t).width?"COL":"ROW"),i):(this.lastColIsEmpty(e,t)&&i.add("ROW"),this.lastRowIsEmpty(e,t)&&i.add("COL"),0===i.size&&i.add("COL"),i)}sumDimensions(e,t,i){return[...i.has("COL")?this.sumColumns(t,e):[],...i.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:i}=e;return{position:{col:i,row:t},zone:{...e,top:t,right:i-1}}}sumColumns(e,t){const i=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,i.bottom-1)},Xi(i).map((t=>({position:t,zone:{...e,right:t.col,left:t.col}})))}sumRows(e,t){const i=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,i.right-1)},Xi(i).map((t=>({position:t,zone:{...e,top:t.row,bottom:t.row}})))}dispatchCellUpdates(e,t){for(const i of t){const{col:t,row:n}=i.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,content:`=SUM(${this.getters.zoneToXC(e,i.zone)})`})}}nextEmptyRow(e,t){let i=t.bottom+1;const{left:n,right:o}=t;for(;!this.getters.isEmpty(e,{bottom:i,top:i,left:n,right:o});)i++;return{...t,top:i,bottom:i}}nextEmptyCol(e,t){let i=t.right+1;const{top:n,bottom:o}=t;for(;!this.getters.isEmpty(e,{left:i,right:i,top:n,bottom:o});)i++;return{...t,left:i,right:i}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}Iv.getters=["getAutomaticSums"];class Tv extends Wg{allowDispatch(e){if("OPEN_CELL_POPOVER"===e.type){try{to.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,type:e.popoverType}}}getCellPopover({col:e,row:t}){var i,n;const o=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(o,this.persistentPopover.col,this.persistentPopover.row)){const e=this.getters.getMainCellPosition(o,this.persistentPopover.col,this.persistentPopover.row),t=null===(n=(i=to.get(this.persistentPopover.type)).onOpen)||void 0===n?void 0:n.call(i,e,this.getters);return(null==t?void 0:t.isOpen)?{...t,...this.computePopoverProps(this.persistentPopover,t.cellCorner)}:{isOpen:!1}}if(void 0===e||void 0===t||!this.getters.isVisibleInViewport(o,e,t))return{isOpen:!1};const s=this.getters.getMainCellPosition(o,e,t),r=to.getAll().map((e=>{var t;return null===(t=e.onHover)||void 0===t?void 0:t.call(e,s,this.getters)})).find((e=>null==e?void 0:e.isOpen));return(null==r?void 0:r.isOpen)?{...r,...this.computePopoverProps(s,r.cellCorner)}:{isOpen:!1}}getPersistentPopoverTypeAtPosition({col:e,row:t}){if(this.persistentPopover&&this.persistentPopover.col===e&&this.persistentPopover.row===t)return this.persistentPopover.type}computePopoverProps({col:e,row:t},i){const{width:n,height:o}=this.getters.getVisibleRect(en({col:e,row:t}));return{coordinates:this.computePopoverPosition({col:e,row:t},i),cellWidth:-n,cellHeight:-o}}computePopoverPosition({col:e,row:t},i){const n=this.getters.getActiveSheetId(),o=this.getters.getMerge(n,e,t);o&&(e="TopRight"===i?o.right:o.left,t="TopRight"===i?o.top:o.bottom);const{x:s,y:r,width:a,height:l}=this.getters.getVisibleRect(en({col:e,row:t}));switch(i){case"BottomLeft":return{x:s,y:r+l};case"TopRight":return{x:s+a,y:r}}}}Tv.getters=["getCellPopover","getPersistentPopoverTypeAtPosition"],Tv.modes=["normal"];class Av{constructor(e,t,i,n){this.getters=t,this.dispatch=i,this.selection=n,this.operation=e,this.sheetId=t.getActiveSheetId()}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0}addMissingDimensions(e,t,i,n){const o=this.getters.getActiveSheetId(),s=t+n-this.getters.getNumberRows(o);s>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(o)-1,sheetId:o,quantity:s,position:"after"});const r=e+i-this.getters.getNumberCols(o);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(o)-1,sheetId:o,quantity:r,position:"after"})}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class Nv extends Av{constructor(e,t,i,n,o){if(super(t,i,n,o),!e.length)return this.cells=[[]],this.zones=[],void(this.copiedTables=[]);const s=new Set(e.map((e=>e.left))),r=new Set(e.map((e=>e.right))),a=new Set(e.map((e=>e.top))),l=new Set(e.map((e=>e.bottom))),c=1===a.size&&1===l.size||1===s.size&&1===r.size?function(e){return e.reduce(((e,t)=>{const i=e.length;for(let n=0;n<i;n++)if(Hi(e[n],t))return e[n]=Vi(e[n],t),e;return e[i]=t,e}),[])}(e):[e[e.length-1]],h=c.map((e=>Xi(e))).flat(),d=[...new Set(h.map((e=>e.col)))].sort(((e,t)=>e-t)),u=[...new Set(h.map((e=>e.row)))].sort(((e,t)=>e-t)),g=[],p=i.getActiveSheetId();for(let e of u){let t=[];for(let n of d)t.push({cell:i.getCell(p,n,e),border:i.getCellBorder(p,n,e)||void 0,position:{col:n,row:e,sheetId:p}});g.push(t)}const m=[];for(const t of e)for(const e of this.getters.getFilterTablesInZone(p,t)){const t=[];for(const i of $e(e.zone.left,e.zone.right+1))t.push(this.getters.getFilterValues(p,i,e.zone.top));m.push({filtersValues:t,zone:e.zone})}this.cells=g,this.zones=c,this.copiedTables=m}isCutAllowed(e){return 1!==e.length?19:0}isPasteAllowed(e,t){const i=this.getters.getActiveSheetId();if("CUT"===this.operation&&void 0!==(null==t?void 0:t.pasteOption))return 21;if(e.length>1&&(this.cells.length>1||this.cells[0].length>1))return 20;const n=this.cells.length,o=this.cells[0].length;for(let t of this.getPasteZones(e))if(this.getters.doesIntersectMerge(i,t)&&(e.length>1||!this.getters.isSingleCellOrMerge(i,e[0])||n*o!=1))return 2;const{xSplit:s,ySplit:r}=this.getters.getPaneDivisions(i);for(const t of this.getPasteZones(e))if(t.left<s&&t.right>=s||t.top<r&&t.bottom>=r)return 76;return 0}paste(e,t){"COPY"===this.operation?this.pasteFromCopy(e,t):this.pasteFromCut(e,t);const i=this.cells.length,n=this.cells[0].length,o="CUT"===this.operation;(null==t?void 0:t.selectTarget)&&this.selectPastedZone(n,i,o,e)}pasteFromCopy(e,t){if(1===e.length){const i=this.cells.length,n=this.cells[0].length,o=this.pastedZones(e,n,i);for(const e of o)this.pasteZone(e.left,e.top,t)}else for(const i of e)for(let e=i.left;e<=i.right;e++)for(let n=i.top;n<=i.bottom;n++)this.pasteZone(e,n,t);void 0===(null==t?void 0:t.pasteOption)&&this.pasteCopiedTables(e)}pasteFromCut(e,t){this.clearClippedZones();const i=e[0];this.pasteZone(i.left,i.top,t),this.dispatch("MOVE_RANGES",{target:this.zones,sheetId:this.sheetId,targetSheetId:this.getters.getActiveSheetId(),col:i.left,row:i.top});for(const e of this.copiedTables)this.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.sheetId,target:[e.zone]});this.pasteCopiedTables(e)}pastedZones(e,t,i){const n=e[0],o=Math.max(1,Math.floor((n.right+1-n.left)/t)),s=Math.max(1,Math.floor((n.bottom+1-n.top)/i)),r=[];for(let e=0;e<o;e++)for(let o=0;o<s;o++){const s=n.top+o*i,a=n.left+e*t;r.push({left:a,top:s,bottom:s+i-1,right:a+t-1})}return r}getPasteZones(e){const t=this.cells;if(!t.length||!t[0].length)return e;const i=[],n=t.length,o=t[0].length,s=e[e.length-1],r=s.left,a=s.top,l=Math.max(1,Math.floor((s.right+1-r)/o)),c=Math.max(1,Math.floor((s.bottom+1-a)/n));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)i.push({left:r,top:a,right:r-1+e*o,bottom:a-1+t*n});return i}selectPastedZone(e,t,i,n){const o=n[0],s=o.left,r=o.top;if(t>1||e>1||i){const o=this.pastedZones(n,e,t),a=i?o[0]:Vi(...o);this.selection.selectZone({cell:{col:s,row:r},zone:a})}}clearClippedZones(){for(const e of this.cells)for(const t of e)t.cell&&this.dispatch("CLEAR_CELL",t.position);this.dispatch("CLEAR_FORMATTING",{sheetId:this.sheetId,target:this.zones})}pasteZone(e,t,i){const n=this.cells.length,o=this.cells[0].length,s="onlyValue"!==(null==i?void 0:i.pasteOption)&&(null==i?void 0:i.shouldPasteCF),r=this.getters.getActiveSheetId();this.addMissingDimensions(o,n,e,t);for(let a=0;a<n;a++){const n=this.cells[a];for(let l=0;l<o;l++){const o=n[l],c={col:e+l,row:t+a,sheetId:r};this.pasteMergeIfExist(o.position,c,this.operation),this.pasteCell(o,c,this.operation,i),s&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{origin:o.position,target:c,operation:this.operation})}}}pasteCell(e,t,i,n){const{sheetId:o,col:s,row:r}=t,a=this.getters.getCell(o,s,r);if("onlyValue"!==(null==n?void 0:n.pasteOption)){const t=this.getters.getCellBorder(o,s,r),i=e.border,n={top:(null==t?void 0:t.top)||(null==i?void 0:i.top),bottom:(null==t?void 0:t.bottom)||(null==i?void 0:i.bottom),left:(null==t?void 0:t.left)||(null==i?void 0:i.left),right:(null==t?void 0:t.right)||(null==i?void 0:i.right)};this.dispatch("SET_BORDER",{sheetId:o,col:s,row:r,border:n})}if(e.cell){if("onlyFormat"===(null==n?void 0:n.pasteOption))return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.cell.evaluated.format||e.cell.format});if("onlyValue"===(null==n?void 0:n.pasteOption)){const i=Qt(e.cell.evaluated.value);return void this.dispatch("UPDATE_CELL",{...t,content:i})}let a=e.cell.content;if(e.cell.isFormula()&&"COPY"===i){const t=s-e.position.col,n=r-e.position.row;a=this.getUpdatedContent(o,e.cell,t,n,i)}this.dispatch("UPDATE_CELL",{...t,content:a,style:e.cell.style||null,format:e.cell.format})}else a&&("onlyValue"===(null==n?void 0:n.pasteOption)?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===(null==n?void 0:n.pasteOption)?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,i,n,o){const s=this.getters.createAdaptedRanges(t.dependencies,i,n,e);return this.getters.buildFormulaContent(e,t,s)}pasteMergeIfExist(e,t,i){let{sheetId:n,col:o,row:s}=e;const{col:r,row:a}=this.getters.getMainCellPosition(n,o,s);if(r===o&&a===s){const e=this.getters.getMerge(n,o,s);if(!e)return;"CUT"===i&&this.dispatch("REMOVE_MERGE",{sheetId:n,target:[e]}),({sheetId:n,col:o,row:s}=t),this.dispatch("ADD_MERGE",{sheetId:n,force:!0,target:[{left:o,top:s,right:o+e.right-e.left,bottom:s+e.bottom-e.top}]})}}pasteCopiedTables(e){const t=this.getters.getActiveSheetId(),i=e[0],n=this.zones[0],o=[i.left-n.left,i.top-n.top];for(const e of this.copiedTables){const i=Ki(e.zone,"both","MOVE",o);this.dispatch("CREATE_FILTER_TABLE",{sheetId:t,target:[i]});for(const n of $e(0,e.filtersValues.length))this.dispatch("UPDATE_FILTER",{sheetId:t,col:i.left+n,row:i.top,values:e.filtersValues[n]})}}getClipboardContent(){return this.cells.map((e=>e.map((e=>e.cell?this.getters.getCellText(e.cell,this.getters.shouldShowFormulas()):"")).join("\t"))).join("\n")||"\t"}isColRowDirtyingClipboard(e,t){if(!this.zones)return!1;for(let i of this.zones){if("COL"===t&&e<=i.right)return!0;if("ROW"===t&&e<=i.bottom)return!0}return!1}drawClipboard(e){const{ctx:t,thinLineWidth:i}=e;if(this.sheetId===this.getters.getActiveSheetId()&&this.zones&&this.zones.length){t.setLineDash([8,5]),t.strokeStyle=E,t.lineWidth=3.3*i;for(const e of this.zones){const{x:i,y:n,width:o,height:s}=this.getters.getVisibleRect(e);o>0&&s>0&&t.strokeRect(i,n,o,s)}}}}class Ov{constructor(e,t,i){this.getters=t,this.dispatch=i,this.sheetId=t.getActiveSheetId();const n=t.getSelectedFigureId();if(!n)throw new Error("No figure selected");const o=t.getFigure(this.sheetId,n);if(!o)throw new Error(`No figure for the given id: ${n}`);this.copiedFigure={...o};const s=t.getChart(n);if(!s)throw new Error(`No chart for the given id: ${n}`);this.copiedChart=s.copyInSheetId(this.sheetId),this.operation=e}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0===e.length?74:void 0!==(null==t?void 0:t.pasteOption)?22:0}paste(e){const t=this.getters.getActiveSheetId(),i={x:this.getters.getColDimensions(t,e[0].left).start,y:this.getters.getRowDimensions(t,e[0].top).start},n=this.copiedChart.copyInSheetId(t),o=(new Mi).smallUuid();this.dispatch("CREATE_CHART",{id:o,sheetId:t,position:i,size:{height:this.copiedFigure.height,width:this.copiedFigure.width},definition:n.getDefinition()}),"CUT"===this.operation&&this.dispatch("DELETE_FIGURE",{sheetId:this.copiedChart.sheetId,id:this.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{id:o})}getClipboardContent(){return"\t"}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class Mv extends Av{constructor(e,t,i,n){super("COPY",t,i,n),this.values=e.replace(/\r/g,"").split("\n").map((e=>e.split("\t")))}isPasteAllowed(e,t){const i=this.getters.getActiveSheetId(),n=this.getPasteZone(e);return this.getters.doesIntersectMerge(i,n)?2:0}paste(e){const t=this.values,i=this.getPasteZone(e),{left:n,top:o}=i,{width:s,height:r}=ji(i),a=this.getters.getActiveSheetId();this.addMissingDimensions(s,r,n,o);for(let e=0;e<t.length;e++)for(let i=0;i<t[e].length;i++)this.dispatch("UPDATE_CELL",{row:o+e,col:n+i,content:t[e][i],sheetId:a});const l={left:n,top:o,right:n+s-1,bottom:o+r-1};this.selection.selectZone({cell:{col:n,row:o},zone:l})}getClipboardContent(){return this.values.map((e=>e.join("\t"))).join("\n")}getPasteZone(e){const t=this.values.length,i=Math.max(...this.values.map((e=>e.length))),{left:n,top:o}=e[0];return{top:o,left:n,bottom:o+t-1,right:n+i-1}}}class _v extends Wg{constructor(){super(...arguments),this.status="invisible",this._isPaintingFormat=!1}allowDispatch(e){switch(e.type){case"CUT":const t=this.getters.getSelectedZones();return this.getClipboardState(t,e.type).isCutAllowed(t);case"PASTE":if(!this.state)return 23;const i=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);return this.state.isPasteAllowed(e.target,{pasteOption:i});case"PASTE_FROM_OS_CLIPBOARD":return new Mv(e.text,this.getters,this.dispatch,this.selection).isPasteAllowed(e.target);case"INSERT_CELL":{const{cut:t,paste:i}=this.getInsertCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(i)}case"DELETE_CELL":{const{cut:t,paste:i}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(i)}}return 0}handle(e){var t,i,n,o;switch(e.type){case"COPY":case"CUT":const s=this.getters.getSelectedZones();this.state=this.getClipboardState(s,e.type),this.status="visible";break;case"PASTE":if(!this.state)break;const r=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);this._isPaintingFormat=!1,this.state.paste(e.target,{pasteOption:r,shouldPasteCF:!0,selectTarget:!0}),"CUT"===this.state.operation&&(this.state=void 0),this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:i}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!Di(t[0])){for(const{col:t,row:i}of Xi(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:i,sheetId:this.getters.getActiveSheetId()});break}this.getClipboardStateForCopyCells(t,"CUT").paste(i);break}case"INSERT_CELL":{const{cut:t,paste:i}=this.getInsertCellsTargets(e.zone,e.shiftDimension);this.getClipboardStateForCopyCells(t,"CUT").paste(i);break}case"ADD_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(t=this.state)||void 0===t?void 0:t.operation)||e.sheetId!==(null===(i=this.state)||void 0===i?void 0:i.sheetId))return;this.state.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.state=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(n=this.state)||void 0===n?void 0:n.operation)||e.sheetId!==(null===(o=this.state)||void 0===o?void 0:o.sheetId))return;for(let t of e.elements){if(this.state.isColRowDirtyingClipboard(t,e.dimension)){this.state=void 0;break}}this.status="invisible";break;case"PASTE_FROM_OS_CLIPBOARD":new Mv(e.text,this.getters,this.dispatch,this.selection).paste(e.target),this.status="invisible";break;case"ACTIVATE_PAINT_FORMAT":{const e=this.getters.getSelectedZones();this.state=this.getClipboardStateForCopyCells(e,"COPY"),this._isPaintingFormat=!0,this.status="visible";break}default:mn(e)&&(this.status="invisible")}}getClipboardContent(){var e;return(null===(e=this.state)||void 0===e?void 0:e.getClipboardContent())||"\t"}isCutOperation(){return!!this.state&&"CUT"===this.state.operation}isPaintingFormat(){return this._isPaintingFormat}getDeleteCellsTargets(e,t){const i=this.getters.getActiveSheetId();let n;return n="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(i)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(i)-1},{cut:[n],paste:[e]}}getInsertCellsTargets(e,t){const i=this.getters.getActiveSheetId();let n,o;return"COL"===t?(n={...e,right:this.getters.getNumberCols(i)-1},o={...e,left:e.right+1,right:e.right+1}):(n={...e,bottom:this.getters.getNumberRows(i)-1},o={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(i)-1}),{cut:[n],paste:[o]}}getClipboardStateForCopyCells(e,t){return new Nv(e,t,this.getters,this.dispatch,this.selection)}getClipboardState(e,t){return this.getters.getSelectedFigureId()?new Ov(t,this.getters,this.dispatch):new Nv(e,t,this.getters,this.dispatch,this.selection)}drawGrid(e){"visible"===this.status&&this.state&&this.state.drawClipboard(e)}}_v.layers=[2],_v.getters=["getClipboardContent","isCutOperation","isPaintingFormat"];class Fv extends Wg{constructor(){super(...arguments),this.customColors=new Set,this.shouldUpdateColors=!1}handle(e){switch(e.type){case"UPDATE_CELL":case"UPDATE_CHART":case"CREATE_CHART":case"ADD_CONDITIONAL_FORMAT":this.shouldUpdateColors=!0}}finalize(){if(this.shouldUpdateColors){this.shouldUpdateColors=!1;for(const e of this.getCustomColors())this.tryToAddColor(e)}}getCustomColors(){let e=[];for(const t of this.getters.getSheetIds()){const i=Object.values(this.getters.getCells(t));e=e.concat(this.getColorsFromCells(i),this.getFormattingColors(t),this.getChartColors(t))}return function(e){const t=[{leadColor:bt(255,0,0),colors:[]},{leadColor:bt(255,128,0),colors:[]},{leadColor:bt(128,128,0),colors:[]},{leadColor:bt(128,255,0),colors:[]},{leadColor:bt(0,255,0),colors:[]},{leadColor:bt(0,255,128),colors:[]},{leadColor:bt(0,255,255),colors:[]},{leadColor:bt(0,127,255),colors:[]},{leadColor:bt(0,0,255),colors:[]},{leadColor:bt(127,0,255),colors:[]},{leadColor:bt(128,0,128),colors:[]},{leadColor:bt(255,0,128),colors:[]}];for(const i of e.map(Et)){let e=500,n=0;t.forEach(((t,o)=>{const s=(r=i,a=t.leadColor,Math.sqrt(Math.pow(r.r-a.r,2)+Math.pow(r.g-a.g,2)+Math.pow(r.b-a.b,2)));var r,a;e>s&&(e=s,n=o)})),t[n].colors.push(i)}return t.map((e=>e.colors.sort(((e,t)=>yt(e).s-yt(t).s)))).flat().map(Ct)}([...new Set([...new Set([...e,...this.customColors])].filter(ft).map(mt))]).filter((e=>!N.includes(e)))}getColorsFromCells(e){var t,i;const n=new Set;for(const o of e)(null===(t=o.style)||void 0===t?void 0:t.textColor)&&n.add(o.style.textColor),(null===(i=o.style)||void 0===i?void 0:i.fillColor)&&n.add(o.style.fillColor);return[...n]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),i=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(i.push(t.style.textColor),i.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(i.push(gt(t.minimum.color)),i.push(t.midpoint?gt(t.midpoint.color):void 0),i.push(gt(t.maximum.color)))}return i.filter(Xe)}getChartColors(e){const t=this.getters.getChartIds(e).map((e=>this.getters.getChart(e)));let i=new Set;for(let e of t){if(void 0===e)continue;const t=e.getDefinition().background;switch(void 0!==t&&i.add(t),e.type){case"gauge":const t=e.sectionRule.colors;i.add(t.lowerColor),i.add(t.middleColor),i.add(t.upperColor);break;case"scorecard":const n=e;i.add(n.baselineColorDown),i.add(n.baselineColorUp)}}return[...i]}tryToAddColor(e){const t=mt(e);e&&!N.includes(t)&&this.customColors.add(t)}}Fv.getters=["getCustomColors"];const Dv=ju.mapping;class kv extends Wg{constructor(e,t,i,n,o){super(e,t,i,n,o),this.isUpToDate=!1,this.evalContext=n.evalContext}handle(e){switch(dn.has(e.type)&&(this.isUpToDate=!1),e.type){case"UPDATE_CELL":("content"in e||"format"in e)&&(this.isUpToDate=!1);break;case"EVALUATE_CELLS":this.evaluate()}}finalize(){this.isUpToDate||this.evaluate()}evaluateFormula(e,t=this.getters.getActiveSheetId()){try{const i=Pg(e),n=this.getCompilationParameters((()=>{})),o=[];for(let e of i.dependencies)o.push(this.getters.getRangeFromSheetXC(t,e));return i.execute(o,...n).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.getCellsInZone(t.id,e.zone).map((e=>(null==e?void 0:e.formattedValue)||""))}getRangeValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getCellsInZone(t.id,e.zone).map((e=>null==e?void 0:e.evaluated.value))}*getAllCells(){for(const e of this.getters.getSheetIds()){const t=this.getters.getCells(e);for(const e in t)yield t[e]}}evaluate(){const e=this.getCompilationParameters(i),t={};for(const e of this.getAllCells())i(e);function i(i){if(!i.isFormula())return;const n=i.id,o=tt((()=>{if(e[2].__originCellXC=()=>{const t=e[2].getters.getCellPosition(n);return Vt(t.col,t.row)},n in t)return null===t[n]?new d:i.evaluated;t[n]=null;try{const o=i.compiledFormula.execute(i.dependencies,...e);if(t[n]=!0,Array.isArray(o.value))throw new Error(s("This formula depends on invalid values"));return{value:o.value,format:i.format||o.format}}catch(i){return t[n]=!0,function(t){t instanceof Error||(t=new Error(t));const i=(null==t?void 0:t.errorType)||a.GenericError,n=e[2].__lastFnCalled||"";return new c(i,t.message.replace("[[FUNCTION_NAME]]",n),void 0!==t.logLevel?t.logLevel:l.error)}(i)}}));i.assignEvaluation(o)}this.isUpToDate=!0}getCompilationParameters(e){const t=Object.assign(Object.create(Dv),this.evalContext,{getters:this.getters}),i=this.getters;function n(e){if(e.evaluated.type===hn.error)throw new c(e.evaluated.value,e.evaluated.error.message,e.evaluated.error.logLevel);return e.evaluated}const o={};function r(e){if(!Di(e.zone))throw new u;if(e.invalidSheetName)throw new Error(s("Invalid sheet name: %s",e.invalidSheetName))}return[function(e,t,o,a){if(r(e),t)return{value:ki(e.zone)};if(e.zone.bottom!==e.zone.top||e.zone.left!==e.zone.right)throw new Error(a?s("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",o.toString(),a.toString()):s("Function %s expects its parameters to be single values or single cell references, not ranges.",o.toString()));return function(e){let t;if(!i.tryGetSheet(e.sheetId))throw new Error(s("Invalid sheet name"));return t=i.getCell(e.sheetId,e.zone.left,e.zone.top),!t||t.isEmpty()?{value:null,format:null==t?void 0:t.format}:n(t)}(e)},function(e){r(e);const s=e.sheetId,a=i.getSheetZone(s),l=zi(e.zone,a);if(!l)return[[]];const{top:c,left:h,bottom:d,right:u}=l,g=`${s}-${c}-${h}-${d}-${u}`;if(g in o)return o[g];const p=new Array(u-h+1);for(let i=h;i<=u;i++){const o=new Array(d-c+1);for(let s=c;s<=d;s++){const r=t.getters.getCell(e.sheetId,i,s);o[s-c]=r?n(r):void 0}p[i-h]=o}return o[g]=p,p},t]}}kv.getters=["evaluateFormula","getRangeFormattedValues","getRangeValues"];class $v extends Wg{constructor(){super(...arguments),this.charts={},this.createRuntimeChart=function(e){const t=rn.getAll();return function(i){const n=t.find((e=>e.match(i.type)));if(!n)throw new Error("No runtime builder for this chart.");return n.getChartRuntime(i,e)}}(this.getters)}handle(e){if(dn.has(e.type)||un.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type)for(const e in this.charts)this.charts[e]=void 0;switch(e.type){case"UPDATE_CHART":case"CREATE_CHART":case"DELETE_FIGURE":this.charts[e.id]=void 0;break;case"DELETE_SHEET":for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0)}}getChartRuntime(e){if(!this.charts[e]){const t=this.getters.getChart(e);if(!t)throw new Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:Rs(e)};if(!t)return{background:w,fontColor:Rs(w)};const i=t.zone.left,n=t.zone.top,o=t.sheetId,s=this.getters.getCellComputedStyle(o,i,n),r=s.fillColor||w;return{background:r,fontColor:s.textColor||Rs(r)}}}$v.getters=["getChartRuntime","getStyleOfSingleCellChart"];class Lv extends Wg{constructor(){super(...arguments),this.isStale=!0,this.computedStyles={},this.computedIcons={},this.uuidGenerator=new Mi,this.rulePredicate={CellIsRule:(e,t)=>{if(e&&e.evaluated.type===hn.error)return!1;const i=t.values.map(Bp);switch(t.operator){case"IsEmpty":return!Xe(e)||""===e.evaluated.value.toString().trim();case"IsNotEmpty":return Xe(e)&&""!==e.evaluated.value.toString().trim();case"BeginsWith":return!(!e&&""===i[0])&&(Xe(e)&&(null==e?void 0:e.evaluated.value.toString().startsWith(i[0].toString())));case"EndsWith":return!(!e&&""===i[0])&&(Xe(e)&&e.evaluated.value.toString().endsWith(i[0].toString()));case"Between":return Xe(e)&&e.evaluated.value>=i[0]&&e.evaluated.value<=i[1];case"NotBetween":return!(Xe(e)&&e.evaluated.value>=i[0]&&e.evaluated.value<=i[1]);case"ContainsText":return Xe(e)&&e.evaluated.value.toString().indexOf(i[0].toString())>-1;case"NotContains":return!Xe(e)||!e.evaluated.value||-1==e.evaluated.value.toString().indexOf(i[0].toString());case"GreaterThan":return Xe(e)&&e.evaluated.value>i[0];case"GreaterThanOrEqual":return Xe(e)&&e.evaluated.value>=i[0];case"LessThan":return Xe(e)&&e.evaluated.value<i[0];case"LessThanOrEqual":return Xe(e)&&e.evaluated.value<=i[0];case"NotEqual":return!(!Xe(e)&&""===i[0])&&(Xe(e)&&e.evaluated.value!==i[0]);case"Equal":return!e&&""===i[0]||Xe(e)&&e.evaluated.value===i[0];default:console.warn(s("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}}}handle(e){switch((un.has(e.type)||"UPDATE_CELL"===e.type&&"content"in e)&&(this.isStale=!0),e.type){case"ACTIVATE_SHEET":const t=e.sheetIdTo;this.computedStyles[t]=this.computedStyles[t]||{},this.computedIcons[t]=this.computedIcons[t]||{},this.isStale=!0;break;case"AUTOFILL_CELL":const i=this.getters.getActiveSheetId(),n=this.getters.getRulesByCell(i,e.originCol,e.originRow);for(const t of n)this.adaptRules(i,t,[Vt(e.col,e.row)],[]);break;case"PASTE_CONDITIONAL_FORMAT":this.pasteCf(e.origin,e.target,e.operation)}}finalize(){this.isStale&&(this.computeStyles(),this.isStale=!1)}getCellComputedStyle(e,t,i){var n;const o=this.getters.getCell(e,t,i),s=this.computedStyles[e],r=s&&(null===(n=s[t])||void 0===n?void 0:n[i]),a={...null==o?void 0:o.style,...r};return this.getters.isFilterHeader(e,t,i)&&(a.bold=!0),a}getConditionalIcon(e,t){var i;const n=this.getters.getActiveSheetId(),o=this.computedIcons[n];return o&&(null===(i=o[e])||void 0===i?void 0:i[t])}computeStyles(){var e;const t=this.getters.getActiveSheetId();this.computedStyles[t]={},this.computedIcons[t]={};const i=this.computedStyles[t];for(let n of this.getters.getConditionalFormats(t).reverse())switch(n.rule.type){case"ColorScaleRule":for(let e of n.ranges)this.applyColorScale(e,n.rule);break;case"IconSetRule":for(let e of n.ranges)this.applyIcon(e,n.rule);break;default:for(let o of n.ranges){const s=this.getters.getRangeFromSheetXC(t,o).zone;for(let o=s.top;o<=s.bottom;o++)for(let r=s.left;r<=s.right;r++){const s=this.rulePredicate[n.rule.type];let a=this.getters.getCell(t,r,o);s&&s(a,n.rule)&&(i[r]||(i[r]=[]),i[r][o]=Object.assign((null===(e=i[r])||void 0===e?void 0:e[o])||{},n.rule.style))}}}}parsePoint(e,t,i){const n=this.getters.getActiveSheetId(),o=this.getters.getRangeValues(this.getters.getRangeFromSheetXC(n,e)).filter(this.isCellValueNumber);switch(t.type){case"value":return"max"===i?lt(o):ct(o);case"number":return Number(t.value);case"percentage":const e=ct(o);return e+(lt(o)-e)*Number(t.value)/100;case"percentile":return yi(o,Number(t.value)/100,!0);case"formula":const n=t.value&&this.getters.evaluateFormula(t.value);return"number"==typeof n?n:null;default:return null}}applyIcon(e,t){const i=this.parsePoint(e,t.lowerInflectionPoint),n=this.parsePoint(e,t.upperInflectionPoint);if(null===i||null===n||i>n)return;const o=this.getters.getActiveSheetId(),s=this.getters.getRangeFromSheetXC(o,e).zone,r=this.computedIcons[o],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=s.top;e<=s.bottom;e++)for(let l=s.left;l<=s.right;l++){const s=this.getters.getCell(o,l,e);if((null==s?void 0:s.evaluated.type)!==hn.number)continue;const c=this.computeIcon(s.evaluated.value,n,t.upperInflectionPoint.operator,i,t.lowerInflectionPoint.operator,a);r[l]||(r[l]=[]),r[l][e]=c}}computeIcon(e,t,i,n,o,s){return"ge"===i&&e>=t||"gt"===i&&e>t?s[0]:"ge"===o&&e>=n||"gt"===o&&e>n?s[1]:s[2]}applyColorScale(e,t){var i;const n=this.parsePoint(e,t.minimum,"min"),o=t.midpoint?this.parsePoint(e,t.midpoint):null,s=this.parsePoint(e,t.maximum,"max");if(null===n||null===s||n>=s||o&&(n>=o||o>=s))return;const r=this.getters.getActiveSheetId(),a=this.getters.getRangeFromSheetXC(r,e).zone,l=this.computedStyles[r],c=[];t.midpoint&&o?(c.push({minValue:n,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(n,o,t.minimum.color,t.midpoint.color)}),c.push({minValue:o,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(o,s,t.midpoint.color,t.maximum.color)})):c.push({minValue:n,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(n,s,t.minimum.color,t.maximum.color)});for(let e=a.top;e<=a.bottom;e++)for(let t=a.left;t<=a.right;t++){const a=this.getters.getCell(r,t,e);if((null==a?void 0:a.evaluated.type)===hn.number){const r=Me(a.evaluated.value,n,s);let h;h=2===c.length&&o?r<=o?this.colorCell(r,c[0].minValue,c[0].minColor,c[0].colorDiffUnit):this.colorCell(r,c[1].minValue,c[1].minColor,c[1].colorDiffUnit):this.colorCell(r,c[0].minValue,c[0].minColor,c[0].colorDiffUnit),l[t]||(l[t]=[]),l[t][e]=(null===(i=l[t])||void 0===i?void 0:i[e])||{},l[t][e].fillColor=gt(h)}}}computeColorDiffUnits(e,t,i,n){const o=t-e;return[((i>>16)%256-(n>>16)%256)/o,((i>>8)%256-(n>>8)%256)/o,(i%256-n%256)/o]}colorCell(e,t,i,n){const[o,s,r]=n;return Math.round((i>>16)%256-o*(e-t))<<16|Math.round((i>>8)%256-s*(e-t))<<8|Math.round(i%256-r*(e-t))}adaptRules(e,t,i,n){if(0===i.length&&0===n.length)return;const o=this.getters.getConditionalFormats(e),s=o.findIndex((e=>e.id===t.id));let r=[];s>-1&&(r=o[s].ranges),r=r.concat(i);const a=qi(r,n);0!==a.length?this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:t.id,rule:t.rule,stopIfTrue:t.stopIfTrue},ranges:a.map((t=>this.getters.getRangeDataFromXc(e,t))),sheetId:e}):this.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:t.id,sheetId:e})}pasteCf(e,t,i){const n=Vt(t.col,t.row);for(let o of this.getters.getConditionalFormats(e.sheetId))for(let s of o.ranges)if(Wi(e.col,e.row,this.getters.getRangeFromSheetXC(e.sheetId,s).zone)){const s=o,r=[];if("CUT"===i&&r.push(Vt(e.col,e.row)),e.sheetId===t.sheetId)this.adaptRules(e.sheetId,s,[n],r);else{this.adaptRules(e.sheetId,s,[],r);const i=this.getCFToCopyTo(t.sheetId,s);this.adaptRules(t.sheetId,i,[n],[])}}}isCellValueNumber(e){return"number"==typeof e}getCFToCopyTo(e,t){const i=this.getters.getConditionalFormats(e).find((e=>e.stopIfTrue===t.stopIfTrue&&ot(e.rule,t.rule)));return i||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}}Lv.getters=["getConditionalIcon","getCellComputedStyle"];class Pv extends Wg{constructor(){super(...arguments),this.filterValues={},this.hiddenRows=new Set,this.isEvaluationDirty=!1}allowDispatch(e){if("UPDATE_FILTER"===e.type)if(!this.getters.getFilterId(e.sheetId,e.col,e.row))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":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":case"ADD_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":this.updateHiddenRows();break;case"UPDATE_FILTER":this.updateFilter(e),this.updateHiddenRows();break;case"DUPLICATE_SHEET":const t={};for(const i of this.getters.getFilters(e.sheetIdTo)){const n=i.zoneWithHeaders;t[i.id]=this.getFilterValues(e.sheetId,n.left,n.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,t,i){let n;for(let o of this.getters.getFilterTables(e)){const s=o.zone;if(Wi(t,i,s)){const o=this.intersectZoneWithViewport(e,s);n={top:i===o.top?j:void 0,bottom:i===o.bottom?j:void 0,left:t===o.left?j:void 0,right:t===o.right?j:void 0}}}const o=this.getters.getCellBorder(e,t,i),s={...n,...rt(o||{})};return Qe(s)?null:s}getFilterHeaders(e){const t=[];for(let i of this.getters.getFilterTables(e)){const n=i.zone;if(!n)continue;const o=n.top;for(let i=n.left;i<=n.right;i++)this.getters.isColHidden(e,i)||this.getters.isRowHidden(e,o)||t.push({col:i,row:o})}return t}getFilterValues(e,t,i){const n=this.getters.getFilterId(e,t,i);return n&&this.filterValues[e]&&this.filterValues[e][n]||[]}isFilterHeader(e,t,i){return this.getFilterHeaders(e).some((e=>e.col===t&&e.row===i))}isFilterActive(e,t,i){var n,o;const s=this.getters.getFilterId(e,t,i);return Boolean(s&&(null===(o=null===(n=this.filterValues[e])||void 0===n?void 0:n[s])||void 0===o?void 0:o.length))}intersectZoneWithViewport(e,t){return{left:this.getters.findVisibleHeader(e,"COL",t.left,t.right),right:this.getters.findVisibleHeader(e,"COL",t.right,t.left),top:this.getters.findVisibleHeader(e,"ROW",t.top,t.bottom),bottom:this.getters.findVisibleHeader(e,"ROW",t.bottom,t.top)}}updateFilter({col:e,row:t,values:i,sheetId:n}){const o=this.getters.getFilterId(n,e,t);o&&(this.filterValues[n]||(this.filterValues[n]={}),this.filterValues[n][o]=i)}updateHiddenRows(){var e,t;const i=this.getters.getActiveSheetId(),n=this.getters.getFilters(i).sort(((e,t)=>e.zoneWithHeaders.top-t.zoneWithHeaders.top)),o=new Set;for(let s of n){if(this.getters.isRowHiddenByUser(i,s.zoneWithHeaders.top))continue;if(o.has(s.zoneWithHeaders.top))continue;const n=null===(t=null===(e=this.filterValues[i])||void 0===e?void 0:e[s.id])||void 0===t?void 0:t.map(at);if(n&&s.filteredZone)for(let e=s.filteredZone.top;e<=s.filteredZone.bottom;e++){const t=this.getCellValueAsString(i,s.col,e);n.includes(t)&&o.add(e)}}this.hiddenRows=o}getCellValueAsString(e,t,i){var n;const o=null===(n=this.getters.getCell(e,t,i))||void 0===n?void 0:n.formattedValue;return(null==o?void 0:o.toLowerCase())||""}exportForExcel(e){var t;for(const i of e.sheets)for(const e of i.filterTables){const n=Fi(e.range),o=[],s=[];for(const e of $e(0,ji(n).width)){const r=this.getFilterValues(i.id,n.left+e,n.top),a=this.getters.getFilter(i.id,n.left+e,n.top);if(!a)continue;const l=a.filteredZone?Xi(a.filteredZone).map((e=>{var t;return null===(t=this.getters.getCell(i.id,e.col,e.row))||void 0===t?void 0:t.formattedValue})):[];if(r.length){const t=l.filter(Ke).filter((e=>!r.includes(e)));o.push({colId:e,displayedValues:[...new Set(t)],displayBlanks:!r.includes("")&&l.some((e=>!e))})}const c={col:a.col,row:a.zoneWithHeaders.top},h=null===(t=this.getters.getCell(i.id,c.col,c.row))||void 0===t?void 0:t.formattedValue,d=this.getUniqueColNameForExcel(e,h,s);s.push(d),i.cells[Vt(c.col,c.row)]={...i.cells[Vt(c.col,c.row)],content:d,value:d,isFormula:!1}}e.filters=o}}getUniqueColNameForExcel(e,t,i){t||(t=`Column${e}`);let n=t,o=2;for(;i.includes(n);)n=t+String(o),o++;return n}}Pv.getters=["getCellBorderWithFilterBorder","getFilterHeaders","getFilterValues","isFilterHeader","isRowFiltered","isFilterActive"];var Uv;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(Uv||(Uv={}));class Vv extends Wg{constructor(){super(...arguments),this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1},this.toSearch="",this.isSearchDirty=!1}handle(e){switch(e.type){case"UPDATE_SEARCH":this.updateSearch(e.toSearch,e.searchOptions);break;case"CLEAR_SEARCH":this.clearSearch();break;case"SELECT_SEARCH_PREVIOUS_MATCH":this.selectNextCell(Uv.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(Uv.next);break;case"REPLACE_SEARCH":this.replace(e.replaceWith);break;case"REPLACE_ALL_SEARCH":this.replaceAll(e.replaceWith);break;case"EVALUATE_CELLS":case"UPDATE_CELL":case"REMOVE_FILTER_TABLE":case"UPDATE_FILTER":this.isSearchDirty=!0;break;case"UNDO":case"REDO":case"REMOVE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":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(Uv.current)}updateRegex(){let e=Te(this.toSearch);const t=this.searchOptions.matchCase?"":"i";this.searchOptions.exactMatch&&(e=`^${e}$`),this.currentSearchRegex=RegExp(e,t)}findMatches(){const e=this.getters.getActiveSheetId(),t=this.getters.getCells(e),i=[];if(this.toSearch)for(const n of Object.values(t)){const{col:t,row:o}=this.getters.getCellPosition(n.id),s=this.getters.isColHidden(e,t),r=this.getters.isRowHidden(e,o);if(!s&&!r&&(n&&this.currentSearchRegex&&this.currentSearchRegex.test(this.searchOptions.searchFormulas?n.content:String(n.evaluated.value)))){const e=this.getters.getCellPosition(n.id),t={col:e.col,row:e.row,selected:!1};i.push(t)}}return i.sort(this.sortByRowThenColumn)}sortByRowThenColumn(e,t){return e.row===t.row?e.col-t.col:e.row>t.row?1:-1}selectNextCell(e){const t=this.searchMatches;if(!t.length)return void(this.selectedMatchIndex=null);let i;i=null===this.selectedMatchIndex?0:this.selectedMatchIndex+e,i=(i%t.length+t.length)%t.length,null!==this.selectedMatchIndex&&this.selectedMatchIndex===i||(this.selectedMatchIndex=i,this.selection.selectCell(t[i].col,t[i].row));for(let e=0;e<this.searchMatches.length;e++)this.searchMatches[e].selected=e===this.selectedMatchIndex}clearSearch(){this.toSearch="",this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1}}replace(e){if(null===this.selectedMatchIndex||!this.currentSearchRegex)return;const t=this.searchMatches[this.selectedMatchIndex],i=this.getters.getActiveSheetId(),n=this.getters.getCell(i,t.col,t.row),o=this.toReplace(n,i);if(n&&o){const i=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),n=o.toString().replace(i,e);this.dispatch("UPDATE_CELL",{sheetId:this.getters.getActiveSheetId(),col:t.col,row:t.row,content:n}),this.searchMatches.splice(this.selectedMatchIndex,1),this.selectNextCell(Uv.current)}else this.selectNextCell(Uv.next)}replaceAll(e){const t=this.searchMatches.length;for(let i=0;i<t;i++)this.replace(e)}toReplace(e,t){if(e){if(this.searchOptions.searchFormulas&&e.isFormula())return e.content;if(this.searchOptions.searchFormulas||!e.isFormula())return e.evaluated.value.toString()}return null}drawGrid(e){const{ctx:t}=e,i=this.getters.getActiveSheetId();for(const e of this.searchMatches){const n=this.getters.getMerge(i,e.col,e.row),o=n?n.left:e.col,s=n?n.right:e.col,r=n?n.top:e.row,a=n?n.bottom:e.row,{x:l,y:c,width:h,height:d}=this.getters.getVisibleRect({top:r,left:o,right:s,bottom:a});h>0&&d>0&&(t.fillStyle="#8B008B33",t.fillRect(l,c,h,d),e.selected&&(t.strokeStyle="#8B008B",t.strokeRect(l,c,h,d)))}}}Vv.layers=[3],Vv.getters=["getSearchMatches","getCurrentSelectedMatchIndex"];class zv extends Wg{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,i){const n=this.searchNumberFormat(e,t);if(void 0!==n){const o=function(e,t){const i=Kt(e).map((e=>"NUMBER"===e.type?{...e,format:ci(e.format,t)}:e)),n=gi(i);return Xt[n]=i,n}(n,i);this.dispatch("SET_FORMATTING",{sheetId:e,target:t,format:o})}}searchNumberFormat(e,t){var i;for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let o=n.left;o<=n.right;o++){const n=this.getters.getCell(e,o,t);if((null==n?void 0:n.evaluated.type)===hn.number&&!(null===(i=n.evaluated.format)||void 0===i?void 0:i.match(Y)))return n.evaluated.format||ai(n.evaluated.value)}}}zv.modes=["normal"];class Bv extends Wg{isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,i){return"COL"===t?this.isColHidden(e,i):this.isRowHidden(e,i)}getNextVisibleCellPosition(e,t,i){return{col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",i,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,i,n){if(i<=n)for(let o=i;o<=n;o++)if(this.getters.doesHeaderExist(e,t,o)&&!this.isHeaderHidden(e,t,o))return o;if(i>n)for(let o=i;o>=n;o--)if(this.getters.doesHeaderExist(e,t,o)&&!this.isHeaderHidden(e,t,o))return o}findLastVisibleColRowIndex(e,t,i){let n;for(n=i.last;n>=i.first;n--)if(!this.isHeaderHidden(e,t,n))return n;return n}findFirstVisibleColRowIndex(e,t){const i=this.getters.getNumberHeaders(e,t);for(let n=0;n<i;n++){if("COL"===t&&!this.isColHidden(e,n))return n;if("ROW"===t&&!this.isRowHidden(e,n))return n}}exportForExcel(e){for(const t of e.sheets)for(const[e,i]of Object.entries(t.rows)){const n=this.isRowHidden(t.id,Number(e));i.isHidden=n}}}Bv.getters=["getNextVisibleCellPosition","findVisibleHeader","findLastVisibleColRowIndex","findFirstVisibleColRowIndex","isRowHidden","isColHidden","isHeaderHidden"];class Hv extends Wg{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{height:t,width:i}=ji(e.zone),n=t*i==1?this.getters.expandZone(e.sheetId,e.zone):e.zone;return{...e,zone:n}}))}drawGrid(e){const{ctx:t,thinLineWidth:i}=e,n=this.getters.getActiveSheetId(),o=3*i;t.lineWidth=o;const s=this.getHighlights();for(let e of s.filter(((e,t)=>s.findIndex((t=>Bi(t.zone,e.zone)&&t.sheetId===n))===t))){const{x:i,y:n,width:s,height:r}=this.getters.getVisibleRect(e.zone);s>0&&r>0&&(t.strokeStyle=e.color,t.strokeRect(i+o/2,n+o/2,s-o,r-o),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(i+o,n+o,s-2*o,r-2*o))}}}Hv.layers=[1],Hv.getters=["getHighlights"];class Wv extends Wg{constructor(){super(...arguments),this.boxes=[]}getColDimensionsInViewport(e,t){const i=Math.min(...this.getters.getSheetViewVisibleCols()),n=this.getters.getColRowOffsetInViewport("COL",i,t),o=this.getters.getColSize(e,t);return{start:n,size:o,end:n+(this.getters.isColHidden(e,t)?0:o)}}getRowDimensionsInViewport(e,t){const i=Math.min(...this.getters.getSheetViewVisibleRows()),n=this.getters.getColRowOffsetInViewport("ROW",i,t),o=this.getters.getRowSize(e,t);return{start:n,size:o,end:n+(this.getters.isRowHidden(e,t)?0:o)}}getHeaderOffset(e,t,i){let n=this.getters.getColRowOffsetInViewport(e,t,i);return this.getters.isDashboard()||(n+="ROW"===e?O:M),n}drawGrid(e,t){switch(t){case 0:this.drawBackground(e);for(const t of this.getters.getAllActiveViewportsZones()){const{ctx:i}=e;i.save(),i.beginPath();const n=this.getters.getVisibleRect(t);i.rect(n.x,n.y,n.width,n.height),i.clip(),this.boxes=this.getGridBoxes(t),this.drawCellBackground(e),this.drawBorders(e),this.drawTexts(e),this.drawIcon(e),i.restore()}this.drawFrozenPanes(e);break;case 7:this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e))}}drawBackground(e){const{ctx:t,thinLineWidth:i}=e,{width:n,height:o}=this.getters.getSheetViewDimensionWithHeaders(),s=this.getters.getActiveSheetId();t.fillStyle="#ffffff",t.fillRect(0,0,n+m,o+m);const r=this.getters.getSheetViewVisibleCols(),a=r[0],l=r[r.length-1],c=this.getters.getSheetViewVisibleRows(),h=c[0],d=c[c.length-1];if(this.getters.getGridLinesVisibility(s)&&!this.getters.isDashboard()){t.lineWidth=2*i,t.strokeStyle="#E2E3E3",t.beginPath();for(const e of r){const i={top:h,bottom:d,left:e,right:e},{x:n,width:s,height:r}=this.getters.getVisibleRect(i);t.moveTo(n+s,0),t.lineTo(n+s,Math.min(o,r+(this.getters.isDashboard()?0:O)))}for(const e of c){const i={left:a,right:l,top:e,bottom:e},{y:o,width:s,height:r}=this.getters.getVisibleRect(i);t.moveTo(0,o+r),t.lineTo(Math.min(n,s+(this.getters.isDashboard()?0:M)),o+r)}t.stroke()}}drawCellBackground(e){const{ctx:t,thinLineWidth:i}=e,n=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId());t.lineWidth=n?.3*i:i;const o=n?.1*i:0;t.strokeStyle="#111";for(let e of this.boxes){let s=e.style;(s.fillColor&&"#ffffff"!==s.fillColor||e.isMerge)&&(t.fillStyle=s.fillColor||"#ffffff",n?(t.fillRect(e.x,e.y,e.width,e.height),t.strokeRect(e.x+o,e.y+o,e.width-2*o,e.height-2*o)):t.fillRect(e.x-i,e.y-i,e.width+2*i,e.height+2*i)),e.error&&(t.fillStyle="red",t.beginPath(),t.moveTo(e.x+e.width-5,e.y),t.lineTo(e.x+e.width,e.y),t.lineTo(e.x+e.width,e.y+5),t.fill())}}drawBorders(e){const{ctx:t,thinLineWidth:i}=e;for(let e of this.boxes){const t=e.border;if(t){const{x:i,y:o,width:s,height:r}=e;t.left&&n(t.left,i,o,i,o+r),t.top&&n(t.top,i,o,i+s,o),t.right&&n(t.right,i+s,o,i+s,o+r),t.bottom&&n(t.bottom,i,o+r,i+s,o+r)}}function n([e,n],o,s,r,a){t.strokeStyle=n,t.lineWidth=("thin"===e?2:3)*i,t.beginPath(),t.moveTo(o,s),t.lineTo(r,a),t.stroke()}}drawTexts(e){const{ctx:t,thinLineWidth:i}=e;let n;t.textBaseline="top";for(let e of this.boxes)if(e.content){const o=e.style||{},s=e.content.align||"left",r=De(o);let a;r!==n&&(n=r,t.font=r),t.fillStyle=o.textColor||"#000";let l=e.y+e.height/2+1;if(a="left"===s?e.x+(e.image?e.image.size+2*L:P):"right"===s?e.x+e.width-P-(e.isFilterHeader?20:0):e.x+e.width/2,t.textAlign=s,e.clipRect){t.save(),t.beginPath();const{x:i,y:n,width:o,height:s}=e.clipRect;t.rect(i,n,o,s),t.clip()}const c=e.content.multiLineText.length,h=ke(o);let d=l-(c*(h+P)-P)/2;for(let n of e.content.multiLineText){if(t.fillText(n,Math.round(a),Math.round(d)),o.strikethrough||o.underline){const e=_e(t,n,o);let r=a;"right"===s?r-=e:"center"===s&&(r-=e/2),o.strikethrough&&t.fillRect(r,d+h/2,e,2.6*i),o.underline&&t.fillRect(r,d+h+1,e,1.3*i)}d+=P+h}e.clipRect&&t.restore()}}drawIcon(e){const{ctx:t}=e;for(const e of this.boxes)if(e.image){const i=e.image.image,n=e.image.size,o=(e.height-n)/2;if(e.image.clipIcon){t.save(),t.beginPath();const{x:i,y:n,width:o,height:s}=e.image.clipIcon;t.rect(i,n,o,s),t.clip()}t.drawImage(i,e.x+L,e.y+o,n,n),e.image.clipIcon&&t.restore()}}drawHeaders(e){const{ctx:t,thinLineWidth:i}=e,n=this.getters.getSheetViewVisibleCols(),o=n[0],s=this.getters.getSheetViewVisibleRows(),r=s[0],{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders(),c=this.getters.getSelectedZones(),h=function(e){const t=new Set;for(let i of e)for(let e of $e(i.left,i.right+1))t.add(e);return t}(c),d=function(e){const t=new Set;for(let i of e)for(let e of $e(i.top,i.bottom+1))t.add(e);return t}(c),u=this.getters.getActiveSheetId(),g=this.getters.getNumberCols(u),p=this.getters.getNumberRows(u),m=this.getters.getActiveCols(),f=this.getters.getActiveRows();t.font=`400 11px ${q}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=i,t.strokeStyle="#333";for(const e of n){const i={left:e,right:e,top:0,bottom:p-1},{x:n,width:o}=this.getters.getVisibleRect(i),s=this.getters.doesZonesContainFilter(u,[i]),r=m.has(e),a=h.has(e);t.fillStyle=r?s?I:S:a?s?A:b:s?T:v,t.fillRect(n,0,o,O)}for(const e of s){const i={top:e,bottom:e,left:0,right:g-1},{y:n,height:o}=this.getters.getVisibleRect(i),s=this.getters.doesZonesContainFilter(u,[i]),r=f.has(e),a=d.has(e);t.fillStyle=r?s?I:S:a?s?A:b:s?T:v,t.fillRect(0,n,M,o)}t.beginPath(),t.moveTo(M,0),t.lineTo(M,l),t.moveTo(0,O),t.lineTo(a,O),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(const e of n){const i=this.getters.getColSize(u,e),n=Lt(e);t.fillStyle=m.has(e)?"#fff":C;let s=this.getHeaderOffset("COL",o,e);t.fillText(n,s+i/2,13),t.moveTo(s+i,0),t.lineTo(s+i,O)}for(const e of s){const i=this.getters.getRowSize(u,e);t.fillStyle=f.has(e)?"#fff":C;let n=this.getHeaderOffset("ROW",r,e);t.fillText(String(e+1),24,n+i/2),t.moveTo(0,n+i),t.lineTo(M,n+i)}t.stroke()}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:i}=e,{x:n,y:o}=this.getters.getMainViewportCoordinates(),s=this.getters.isDashboard()?0:M,r=this.getters.isDashboard()?0:O;t.lineWidth=6*i,t.strokeStyle="#BCBCBC",t.beginPath(),n&&(t.moveTo(s+n,0),t.lineTo(s+n,r)),o&&(t.moveTo(0,r+o),t.lineTo(s,r+o)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:i}=e,{x:n,y:o}=this.getters.getMainViewportCoordinates(),s=this.getters.getSheetViewVisibleCols(),r=s[0],a=s[s.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:r,right:a,top:l[0],bottom:l[l.length-1]},h=this.getters.getVisibleRect(c),d=this.getters.isDashboard()?0:M,u=this.getters.isDashboard()?0:O;t.lineWidth=6*i,t.strokeStyle="#DADFE8",t.beginPath(),n&&(t.moveTo(d+n,u),t.lineTo(d+n,h.height+u)),o&&(t.moveTo(d,u+o),t.lineTo(h.width+d,u+o)),t.stroke()}hasContent(e,t){const i=this.getters.getActiveSheetId(),n=this.getters.getCell(i,e,t);return n&&!n.isEmpty()||this.getters.isInMerge(i,e,t)}findNextEmptyCol(e,t,i){let n=e;for(;n<t&&!this.hasContent(n+1,i);)n++;return n}findPreviousEmptyCol(e,t,i){let n=e;for(;n>t&&!this.hasContent(n-1,i);)n--;return n}computeCellAlignment(e,t){if(e.isFormula()&&this.getters.shouldShowFormulas())return"left";const{align:i}=this.getters.getCellStyle(e);return t&&e.evaluated.type===hn.number?"center"!==i?"left":i:i||e.defaultAlign}createZoneBox(e,t,i){const{left:n,right:o}=i,s=t.left,r=t.top,a=this.getters.getCell(e,s,r),c=this.getters.shouldShowFormulas(),{x:h,y:d,width:u,height:g}=this.getters.getRect(t),p={x:h,y:d,width:u,height:g,border:this.getters.getCellBorderWithFilterBorder(e,s,r)||void 0,style:this.getters.getCellComputedStyle(e,s,r)};if(!a)return p;const m=this.getters.getConditionalIcon(s,r),f=ke(p.style),v=m?2*L+f:0;m&&(p.image={type:"icon",size:f,clipIcon:{x:p.x,y:p.y,width:Math.min(v,u),height:g},image:Sr[m].img}),p.isFilterHeader=this.getters.isFilterHeader(e,s,r);const b=p.isFilterHeader?19:0,S=this.getters.getCellText(a,c),C=this.getters.getTextWidth(a),E=this.getters.getCellStyle(a).wrapping||"overflow",w="wrap"===E?this.getters.getCellMultiLineText(a,u-2*P):[S],y=v+C+b,x=this.computeCellAlignment(a,y>u);p.content={multiLineText:w,width:"overflow"===E?C:u,align:x},a.evaluated.type===hn.error&&a.evaluated.error.logLevel>l.silent&&(p.error=a.evaluated.error.message);const R=y>u||f>g;if(m||p.isFilterHeader)p.clipRect={x:p.x+v,y:p.y,width:Math.max(0,u-v-b),height:g};else if(R&&"overflow"===E){let i,a;switch(this.getters.isInMerge(e,s,r)?(i=this.getters.getMerge(e,s,r).right,a=s):(i=this.findNextEmptyCol(s,o,r),a=this.findPreviousEmptyCol(s,n,r)),x){case"left":{const e=en({col:i,row:r}),{x:n,y:o,width:s,height:a}=this.getters.getVisibleRect(Vi(t,e));(s<C||f>a)&&(p.clipRect={x:n,y:o,width:s,height:a});break}case"right":{const e=en({col:a,row:r}),{x:i,y:n,width:o,height:s}=this.getters.getVisibleRect(Vi(t,e));(o<C||f>s)&&(p.clipRect={x:i,y:n,width:o,height:s});break}case"center":{const e={...t,right:i,left:a},{x:n,y:o,width:r,height:l}=this.getters.getVisibleRect(e);(r<C||a===s||i===s||f>l)&&(p.clipRect={x:n,y:o,width:r,height:l});break}}}else"clip"!==E&&"wrap"!==E||(p.clipRect={x:p.x,y:p.y,width:u,height:g});return p}getGridBoxes(e){const t=[],i=this.getters.getSheetViewVisibleCols().filter((t=>t>=e.left&&t<=e.right)),n=i[0],o=i[i.length-1],s=this.getters.getSheetViewVisibleRows().filter((t=>t>=e.top&&t<=e.bottom)),r={left:n,right:o,top:s[0],bottom:s[s.length-1]},a=this.getters.getActiveSheetId();for(const e of s)for(const n of i)this.getters.isInMerge(a,n,e)||t.push(this.createZoneBox(a,en({col:n,row:e}),r));for(const e of this.getters.getMerges(a))if(!this.getters.isMergeHidden(a,e)&&Hi(e,r)){const i=this.createZoneBox(a,e,r),n=this.getters.getCellBorder(a,e.right,e.bottom);i.border={...i.border,bottom:n?n.bottom:void 0,right:n?n.right:void 0},i.isMerge=!0,t.push(i)}return t}}Wv.layers=[0,7],Wv.getters=["getColDimensionsInViewport","getRowDimensionsInViewport"];const Gv=[{name:s("Sum"),types:[hn.number],compute:e=>pl.compute([e])},{name:s("Avg"),types:[hn.number],compute:e=>Rl.compute([e])},{name:s("Min"),types:[hn.number],compute:e=>Bl.compute([e])},{name:s("Max"),types:[hn.number],compute:e=>Pl.compute([e])},{name:s("Count"),types:[hn.number,hn.text,hn.boolean,hn.error],compute:e=>Fl.compute([e])},{name:s("Count Numbers"),types:[hn.number,hn.text,hn.boolean,hn.error],compute:e=>_l.compute([e])}];class qv extends Wg{constructor(e,t,i,n,o){super(e,t,i,n,o),this.gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]},this.selectedFigureId=null,this.sheetsData={},this.activeSheet=null,this.moveClient=n.moveClient}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{this.getters.getSheet(e.sheetIdTo);break}catch(e){return 27}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return 0}handleEvent(e){const t=e.anchor;let i=[];switch(e.mode){case"overrideSelection":i=[t.zone];break;case"updateAnchor":i=[...this.gridSelection.zones];const n=i.findIndex((t=>Bi(t,e.previousAnchor.zone)));n>=0&&(i[n]=t.zone);break;case"newAnchor":i=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,i),this.selection.resetDefaultAnchor(this,Ae(this.gridSelection.anchor));const{col:n,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:n,row:o}),this.selectedFigureId=null}handle(e){switch(e.type){case"START_EDITION":case"ACTIVATE_SHEET":this.selectedFigureId=null;break;case"DELETE_FIGURE":this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;case"DELETE_SHEET":this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null)}switch(e.type){case"START":const t=this.getters.getVisibleSheetIds()[0];this.dispatch("ACTIVATE_SHEET",{sheetIdTo:t,sheetIdFrom:t});const{col:i,row:n}=this.getters.getNextVisibleCellPosition(t,0,0);this.selectCell(i,n),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:Ae(this.gridSelection)},e.sheetIdTo in this.sheetsData)Object.assign(this,this.sheetsData[e.sheetIdTo]),this.selection.resetDefaultAnchor(this,Ae(this.gridSelection.anchor));else{const{col:t,row:i}=this.getters.getNextVisibleCellPosition(e.sheetIdTo,0,0);this.selectCell(t,i)}const{col:t,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:t,row:i});break}case"REMOVE_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);const{col:i,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:i,row:n})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:i,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:i,row:n})}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 o=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of o)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:Ae(t)}}this.fallbackToVisibleSheet();const s=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map((e=>this.getters.expandZone(s,e))),this.gridSelection.anchor.zone=this.getters.expandZone(s,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,Ae(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveCell(){const e=this.getters.getActiveSheetId(),{col:t,row:i}=this.gridSelection.anchor.cell,{col:n,row:o}=this.getters.getMainCellPosition(e,t,i);return this.getters.getCell(e,n,o)}getActiveCols(){const e=new Set;for(let t of this.gridSelection.zones)if(0===t.top&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let i=t.left;i<=t.right;i++)e.add(i);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(let i of this.gridSelection.zones)if(0===i.left&&i.right===this.getters.getNumberCols(t)-1)for(let t=i.top;t<=i.bottom;t++)e.add(t);return e}getCurrentStyle(){const e=this.getters.getActiveCell();return e?this.getters.getCellStyle(e):{}}getSelectedZones(){return Ae(this.gridSelection.zones)}getSelectedZone(){return Ae(this.gridSelection.anchor.zone)}getSelection(){return Ae(this.gridSelection)}getSelectedFigureId(){return this.selectedFigureId}getPosition(){return{col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row}}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getPosition();{const t=this.sheetsData[e];return t?{col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition(e,0,0)}}getStatisticFnResults(){const e=this.getters.getActiveSheetId(),t=new Set(this.gridSelection.zones.map((t=>this.getters.getCellsInZone(e,t))).flat().filter((t=>{if(!t)return!1;const{col:i,row:n}=this.getters.getCellPosition(null==t?void 0:t.id);return!this.getters.isRowHidden(e,n)&&!this.getters.isColHidden(e,i)})));let i=new Set,n=[];for(let e of t)i.add(e.evaluated.type),n.push(e.evaluated.value);let o={};for(let e of Gv){let t;e.types.some((e=>i.has(e)))&&(t=e.compute(n)),o[e.name]=t}return o}getAggregate(){let e=0,t=0;const i=this.getters.getActiveSheetId(),n=this.gridSelection.zones.map(Xi).flat();for(const{col:o,row:s}of n){const n=this.getters.getCell(i,o,s);(null==n?void 0:n.evaluated.type)===hn.number&&(t++,e+=n.evaluated.value)}return t<2?null:Qt(e)}isSelected(e){return!!this.getters.getSelectedZones().find((t=>Bi(t,e)))}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let i=[];const n="COL"===e?"left":"top",o="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[o]-e[n]+1},((t,i)=>e[n]+i));i=i.concat(t)}return[...new Set(i)].sort()}setSelectionMixin(e,t){const{anchor:i,zones:n}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=i,this.gridSelection.zones=function(e){return e.reverse().filter(((e,t,i)=>t===i.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}(n)}selectCell(e,t){const i=this.getters.getActiveSheetId(),n=this.getters.expandZone(i,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:n,cell:{col:e,row:t}},[n])}setActiveSheet(e){const t=this.getters.getSheet(e);this.activeSheet=t}activateNextSheet(e){const t=this.getters.getSheetIds(),i=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[i]})}onColumnsRemoved(e){const{cell:t,zone:i}=this.gridSelection.anchor,n=Pi(i,"left",[...e.elements]);let o={left:t.col,right:t.col,top:t.row,bottom:t.row};o=Pi(o,"left",[...e.elements]);const s={cell:{col:o.left,row:o.top},zone:n};this.setSelectionMixin(s,[n])}onRowsRemoved(e){const{cell:t,zone:i}=this.gridSelection.anchor,n=Pi(i,"top",[...e.elements]);let o={left:t.col,right:t.col,top:t.row,bottom:t.row};o=Pi(o,"top",[...e.elements]);const s={cell:{col:o.left,row:o.top},zone:n};this.setSelectionMixin(s,[n])}onAddElements(e){const t=Li(this.gridSelection.anchor.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),i={cell:{col:t.left,row:t.top},zone:t};this.setSelectionMixin(i,[t])}onMoveElements(e){const t=e.elements.length;this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:e.position});const i="COL"===e.dimension,n=e.elements[0],o=e.elements[t-1],s=e.base<n,r=s&&i?t:0,a=s&&!i?t:0,l=[{left:i?n+r:0,right:i?o+r:this.getters.getNumberCols(e.sheetId)-1,top:i?0:n+a,bottom:i?this.getters.getNumberRows(e.sheetId)-1:o+a}],c=new Nv(l,"CUT",this.getters,this.dispatch,this.selection),h=s?e.base:e.base+1,d=[{left:i?h:0,right:i?h+t-1:this.getters.getNumberCols(e.sheetId)-1,top:i?0:h,bottom:i?this.getters.getNumberRows(e.sheetId)-1:h+t-1}];c.paste(d,{selectTarget:!0});const u=s?e.elements.map((e=>e+t)):e.elements;let g=s?e.base:e.base+1;for(const t of u){const i="COL"===e.dimension?this.getters.getColSize(e.sheetId,t):this.getters.getRowSize(e.sheetId,t);this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:i,elements:[g]}),g+=1}this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,elements:u})}isMoveElementAllowed(e){const t="COL"===e.dimension,i=e.elements[0],n=e.elements[e.elements.length-1],o=e.sheetId,s=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(s(o,i-1,i)||s(o,n,n+1)||s(o,e.base-1,e.base))return 2;const r=[e.base,...e.elements],a=t?this.getters.getNumberCols(o):this.getters.getNumberRows(o);return r.some((e=>e<0||e>=a))?87:0}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){const e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){const{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);const{col:t,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:i})}}clipSelection(e,t){const i=this.getters.getNumberCols(e)-1,n=this.getters.getNumberRows(e)-1;return{zones:t.zones.map((e=>({left:Me(e.left,0,i),right:Me(e.right,0,i),top:Me(e.top,0,n),bottom:Me(e.bottom,0,n)}))),anchor:{cell:{col:Me(t.anchor.cell.col,0,i),row:Me(t.anchor.cell.row,0,n)},zone:{left:Me(t.anchor.zone.left,0,i),right:Me(t.anchor.zone.right,0,i),top:Me(t.anchor.zone.top,0,n),bottom:Me(t.anchor.zone.bottom,0,n)}}}}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:i}=e,n=this.getSelectedZones();t.fillStyle="#f3f7fe";const o=1===n.length&&n[0].left===n[0].right&&n[0].top===n[0].bottom;t.fillStyle=o?"#f3f7fe":"#e9f0ff",t.strokeStyle=E,t.lineWidth=1.5*i,t.globalCompositeOperation="multiply";for(const e of n){const{x:i,y:n,width:o,height:s}=this.getters.getVisibleRect(e);t.fillRect(i,n,o,s),t.strokeRect(i,n,o,s)}t.globalCompositeOperation="source-over";const s=this.getters.getActiveSheetId(),{col:r,row:a}=this.getPosition();let l;t.strokeStyle=E,t.lineWidth=3*i,l=this.getters.isInMerge(s,r,a)?this.getters.getMerge(s,r,a):{top:a,bottom:a,left:r,right:r};const{x:c,y:h,width:d,height:u}=this.getters.getVisibleRect(l);d>0&&u>0&&t.strokeRect(c,h,d,u)}}qv.layers=[5],qv.getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getStatisticFnResults","getAggregate","getSelectedFigureId","getSelection","getPosition","getSheetPosition","isSelected","getElementsFromSelection","isGridSelectionActive"];const Zv=new Mi;class jv extends Wg{constructor(e,t,i,n,o,s,r){if(r&&s.length>1)throw new Error("Input with a single range cannot be instantiated with several range references.");super(e,t,i,n,o),this.inputHasSingleRange=r,this.ranges=[],this.focusedRangeIndex=null,this.willAddNewRange=!1,this.insertNewRange(0,s),this.activeSheet=this.getters.getActiveSheetId(),0===this.ranges.length&&(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}handleEvent(e){const t=ki(e.anchor.zone),i=this.activeSheet,n=this.getters.getActiveSheetId(),o=this.getters.getSheetName(n);this.add([n===i?t:`${Oe(o)}!${t}`])}handle(e){switch(e.type){case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"FOCUS_RANGE":this.focus(this.getIndex(e.rangeId));break;case"CHANGE_RANGE":{const t=this.getIndex(e.rangeId);if(null!==t&&this.focusedRangeIndex!==t&&this.focus(t),null!==t){const i=e.value.split(",").map((e=>e.trim()));this.setRange(t,i)}break}case"ADD_EMPTY_RANGE":this.insertNewRange(this.ranges.length,[""]),this.focusLast();break;case"REMOVE_RANGE":const t=this.getIndex(e.rangeId);null!==t&&this.removeRange(t);break;case"STOP_SELECTION_INPUT":this.willAddNewRange=!1;break;case"PREPARE_SELECTION_INPUT_EXPANSION":{const e=this.focusedRangeIndex;null===e||this.inputHasSingleRange||(this.willAddNewRange=""!==this.ranges[e].xc.trim());break}case"ACTIVATE_SHEET":if(e.sheetIdFrom!==e.sheetIdTo){const{col:t,row:i}=this.getters.getNextVisibleCellPosition(e.sheetIdTo,0,0),n=this.getters.expandZone(e.sheetIdTo,en({col:t,row:i}));this.selection.resetAnchor(this,{cell:{col:t,row:i},zone:n})}}}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],id:Zv.smallUuid(),xc:t}}insertNewRange(e,t){this.ranges.splice(e,0,...t.map(((e,t)=>({xc:e,id:(this.ranges.length+t+1).toString(),color:(pt=++pt%ut.length,ut[pt])}))))}setRange(e,t){const[,...i]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,i),i.length&&this.focus(e+i.length)}removeRange(e){this.ranges.splice(e,1),null!==this.focusedRangeIndex&&this.focusLast()}inputToHighlights({xc:e,color:t}){const i=this.cleanInputs([e]).filter((e=>this.getters.isRangeValid(e))).filter((e=>this.shouldBeHighlighted(this.activeSheet,e)));return i.map((e=>{const{sheetName:i}=$t(e);return{zone:this.getters.getRangeFromSheetXC(this.activeSheet,e).zone,sheetId:i&&this.getters.getSheetIdByName(i)||this.activeSheet,color:t}}))}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:i}=$t(t),n=this.getters.getSheetIdByName(i),o=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(n===o||void 0===n&&o===e)}getIndex(e){const t=this.ranges.findIndex((t=>t.id===e));return t>=0?t:null}}jv.layers=[1],jv.getters=[];class Yv extends Wg{get currentInput(){return this.focusedInputId?this.inputs[this.focusedInputId]:null}constructor(e,t,i,n,o){super(e,t,i,n,o),this.state=t,this.config=n,this.inputs={},this.focusedInputId=null}allowDispatch(e){var t,i;switch(e.type){case"FOCUS_RANGE":case"CHANGE_RANGE":case"ADD_EMPTY_RANGE":case"REMOVE_RANGE":if(!this.inputs[e.id])return 31}switch(e.type){case"FOCUS_RANGE":const n=null===(t=this.currentInput)||void 0===t?void 0:t.getIndex(e.rangeId);if(this.focusedInputId===e.id&&(null===(i=this.currentInput)||void 0===i?void 0:i.focusedRangeIndex)===n)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){var t;switch(e.type){case"ENABLE_NEW_SELECTION_INPUT":this.initInput(e.id,e.initialRanges||[],e.hasSingleRange);break;case"DISABLE_SELECTION_INPUT":this.focusedInputId===e.id&&this.unfocus(),delete this.inputs[e.id];break;case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"ADD_EMPTY_RANGE":case"REMOVE_RANGE":case"FOCUS_RANGE":case"CHANGE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id];this.selection.capture(t,{cell:{col:0,row:0},zone:en({col:0,row:0})},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}}null===(t=this.currentInput)||void 0===t||t.handle(e)}getSelectionInput(e){return this.inputs[e]?this.inputs[e].ranges.map(((t,i)=>Object.assign({},t,{color:this.focusedInputId===e&&null!==this.inputs[e].focusedRangeIndex&&this.isRangeValid(t.xc)?t.color:null,isFocused:this.focusedInputId===e&&this.inputs[e].focusedRangeIndex===i}))):[]}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:i}=$t(e);return null!==t.match(Ot)&&(!i||void 0!==this.getters.getSheetIdByName(i))}getSelectionInputValue(e){return this.inputs[e].getSelectionInputValue()}getSelectionInputHighlights(){return this.focusedInputId?this.inputs[this.focusedInputId].getSelectionInputHighlights():[]}initInput(e,t,i=!1){if(this.inputs[e]=new jv(this.getters,this.state,this.dispatch,this.config,this.selection,t,i),0===t.length){const t=this.inputs[e],i={zone:en({col:0,row:0}),cell:{col:0,row:0}};this.selection.capture(t,i,{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e}}unfocus(){this.selection.release(this.currentInput),this.focusedInputId=null}}Yv.layers=[1],Yv.getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];class Xv{constructor(){this.subscriptions={}}on(e,t,i){if(!i)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:i})}trigger(e,t){const i=this.subscriptions[e]||[];for(let e=0,n=i.length;e<n;e++){const n=i[e];n.callback.call(n.owner,t)}}off(e,t){const i=this.subscriptions[e];i&&(this.subscriptions[e]=i.filter((e=>e.owner!==t)))}clear(){this.subscriptions={}}}function Kv(e,t){return{...e,definition:Us(e.definition,t)}}function Qv(e,t){if(e.sheetId!==t.sheetId)return e;if(("FREEZE_COLUMNS"===e.type?"COL":"ROW")!==t.dimension)return e;let i=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));for(let t of e)i>t&&i--}if("ADD_COLUMNS_ROWS"===t.type){i=i>("before"===t.position?t.base-1:t.base)?i+t.quantity:i}return i>0?{...e,quantity:i}:void 0}as.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],Kv),as.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],Kv),as.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const i=t.sheetId;if(e.targetSheetId===i||e.sheetId===i)return;return e})),as.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),as.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){var i;e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`});if(e.name===t.name)return{...e,name:(null===(i=e.name)||void 0===i?void 0:i.match(/\d+/))?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),as.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE","CREATE_FILTER_TABLE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const i=[];for(const n of e.target)t.target.every((e=>!Hi(n,e)))&&i.push(n);if(i.length)return{...e,target:i};return})),as.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],Qv),as.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],Qv),as.addTransformation("CREATE_FILTER_TABLE",["CREATE_FILTER_TABLE","ADD_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;for(const i of e.target)for(const e of t.target)if(Hi(e,i))return;return e}));const Jv=[{match:function(e){return"sheetId"in e},fn:ib},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const i=ib(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;const n=[];for(const i of e.target){const e=ps(i,t);e&&n.push(e)}if(!n.length)return"IGNORE_COMMAND";return{...e,target:n}}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const i=ib(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const i="COL"===t.dimension?"col":"row";let n=e[i];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(n))return"IGNORE_COMMAND";for(let t of e)n>=t&&n--}"ADD_COLUMNS_ROWS"===t.type&&(n>t.base||n===t.base&&"before"===t.position)&&(n+=t.quantity);return{...e,[i]:n}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const i of t.target){if(!(e.col===i.left&&e.row===i.top)&&Wi(e.col,e.row,i))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e&&"sheetId"in e},fn:function(e,t){const i=ib(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type){if(t.dimension!==e.dimension)return e;const i="ADD_COLUMNS_ROWS"===e.type,n=i?"base":"elements";let o=i?[e[n]]:e[n];if("REMOVE_COLUMNS_ROWS"===t.type&&(o=o.map((e=>{if(t.elements.includes(e))return;const i=t.elements.sort(((e,t)=>t-e));for(let t of i)e>t&&e--;return e})).filter(Xe)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;o=o.map((i=>i>e?i+t.quantity:i))}if(o.length){let t=o;return i&&(t=o[0]),{...e,[n]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}},{match:function(e){return"ranges"in e},fn:function(e,t){const i=[],n="DELETE_SHEET"===t.type&&t.sheetId;for(const o of e.ranges)if(o._sheetId!==t.sheetId)i.push({...o,_zone:o._zone});else{const e=ps(o._zone,t);e&&n!==o._sheetId&&i.push({...o,_zone:e})}if(!i.length)return"IGNORE_COMMAND";return{...e,ranges:i}}}];function eb(e,t){const i=as.getTransformation(e.type,t.type);return i?i(e,t):function(e,t){for(const{match:i,fn:n}of Jv)if(i(e)){const i=n(e,t);if("SKIP_TRANSFORMATION"===i)continue;if("IGNORE_COMMAND"===i)return;e=i}return e}(e,t)}function tb(e,t){let i=[...e];for(const e of t)i=i.map((t=>eb(t,e))).filter(Xe);return i}function ib(e,t){const i="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===i?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class nb{constructor(e,t,i,n){this._commands=[],this._changes=[],this.id=e,this.clientId=t,this._commands=[...i],this._changes=n?[...n]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class ob extends Error{}class sb extends Xv{constructor(e,t,i=K){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=i,this.clients={},this.clientId="local",this.pendingMessages=[],this.waitingAck=!1,this.waitingUndoRedoAck=!1,this.isReplayingInitialRevisions=!1,this.processedRevisions=new Set,this.uuidGenerator=new Mi,this.debouncedMove=function(e,t,i){let n;return function(){const o=this,s=arguments,r=i&&!n;clearTimeout(n),n=setTimeout((function(){n=null,i||e.apply(o,s)}),t),r&&e.apply(o,s)}}(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t){if(!e.length||!t.length||!this.canApplyOptimisticUpdate())return;const i=new nb(this.uuidGenerator.uuidv4(),this.clientId,e,t);this.revisions.append(i.id,i),this.trigger("new-local-state-update",{id:i.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:i.id,clientId:i.clientId,commands:i.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_UNDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_REDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:"local",name:"local"},this.clientId="local"),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this))}loadInitialMessages(e){this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1}leave(){delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}snapshot(e){const t=this.uuidGenerator.uuidv4();this.transportService.sendMessage({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){const e=this.clients[this.clientId];if(!e)throw new ob("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(Xe))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}_move(e){var t;if(!this.clients[this.clientId])return;const i=null===(t=this.clients[this.clientId])||void 0===t?void 0:t.position;if((null==i?void 0:i.col)===e.col&&i.row===e.row&&i.sheetId===e.sheetId)return;const n=i?"CLIENT_MOVED":"CLIENT_JOINED",o=this.getClient();this.clients[this.clientId]={...o,position:e},this.transportService.sendMessage({type:n,version:1,client:{...o,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:i}=e,n=new nb(e.nextRevisionId,t,i);if(n.clientId!==this.clientId){this.revisions.insert(n.id,n,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:tb(i,t)})}break;case"SNAPSHOT_CREATED":{const t=new nb(e.nextRevisionId,"server",[]);this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger("snapshot");break}}this.acknowledge(e),this.trigger("collaborative-event-received")}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;const t=this.clients[this.clientId];if(t){const{position:e}=t;e&&this.transportService.sendMessage({type:"CLIENT_MOVED",version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),this.waitingAck||(this.waitingAck=!0,this.sendPendingMessage())}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if("REMOTE_REVISION"===e.type){let t=this.revisions.get(e.nextRevisionId);0===t.commands.length&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),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"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();break;case"REVISION_UNDONE":{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter((t=>t.nextRevisionId!==e.nextRevisionId));const t=this.pendingMessages.findIndex((e=>"REMOTE_REVISION"===e.type));-1!==t&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}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":case"SNAPSHOT_CREATED":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 rb=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];class ab extends Wg{constructor(){super(...arguments),this.availableColors=new Set(rb),this.colors={}}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}chooseNewColor(){0===this.availableColors.size&&(this.availableColors=new Set(rb));const e=(t=[...this.availableColors.values()])[Math.floor(Math.random()*t.length)];var t;return this.availableColors.delete(e),e}getClientsToDisplay(){try{this.getters.getClient()}catch(e){if(e instanceof ob)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const i of this.getters.getConnectedClients())if(i.id!==this.getters.getClient().id&&i.position&&i.position.sheetId===e&&this.isPositionValid(i.position)){const e=i.position;this.colors[i.id]||(this.colors[i.id]=this.chooseNewColor());const n=this.colors[i.id];t.push({...i,position:e,color:n})}return t}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:i}=e,n=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:o,col:s}=e.position,r=this.getters.expandZone(n,{top:o,bottom:o,left:s,right:s}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);if(c<=0||h<=0)continue;const d=e.color,u=`${d}10`;t.fillStyle=u,t.lineWidth=4*i,t.strokeStyle=d,t.globalCompositeOperation="multiply",t.fillRect(a,l,c,h),t.globalCompositeOperation="source-over",t.strokeRect(a,l,c,h),t.font=`bold ${G+1}px ${q}`}}}ab.getters=["getClientsToDisplay"],ab.layers=[5];class lb{constructor(e,t,i,n,o,s){if(this.getters=e,this.sheetId=t,this.boundaries=i,n.width<0||n.height<0)throw new Error("Viewport size cannot be negative");this.viewportWidth=n.height&&n.width,this.viewportHeight=n.width&&n.height,this.top=i.top,this.bottom=i.bottom,this.left=i.left,this.right=i.right,this.offsetX=s.x,this.offsetY=s.y,this.offsetScrollbarX=s.x,this.offsetScrollbarY=s.y,this.canScrollVertically=o.canScrollVertically,this.canScrollHorizontally=o.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){const e=this.getters.findLastVisibleColRowIndex(this.sheetId,"COL",{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,"ROW",{first:this.boundaries.top,last:this.boundaries.bottom}),{end:i,size:n}=this.getters.getColDimensions(this.sheetId,e),{end:o,size:s}=this.getters.getRowDimensions(this.sheetId,t),r=this.searchHeaderIndex("COL",i-this.viewportWidth,0),a=this.getters.getColSize(this.sheetId,r),l=this.searchHeaderIndex("ROW",o-this.viewportHeight,0),c=this.getters.getRowSize(this.sheetId,l);let h=i-this.offsetCorrectionX;this.canScrollHorizontally&&(h+=Math.max(_,Math.min(a,this.viewportWidth-n)),h=Math.max(h,this.viewportWidth));let d=o-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(F+5,Math.min(c,this.viewportHeight-s)),d=Math.max(d,this.viewportHeight)),{width:h,height:d}}getColIndex(e,t=!1){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex("COL",e-this.offsetCorrectionX,this.left,t)}getRowIndex(e,t=!1){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex("ROW",e-this.offsetCorrectionY,this.top,t)}adjustPosition(e){const t=this.sheetId;e||(e=this.getters.getSheetPosition(t));const i=this.getters.getMainCellPosition(t,e.col,e.row),{col:n,row:o}=this.getters.getNextVisibleCellPosition(t,i.col,i.row);Wi(n,this.boundaries.top,this.boundaries)&&this.adjustPositionX(n),Wi(this.boundaries.left,o,this.boundaries)&&this.adjustPositionY(o)}adjustPositionX(e){const t=this.sheetId,{end:i}=this.getters.getColDimensions(t,e),n=this.getters.getNumberCols(t);if(this.offsetX+this.offsetCorrectionX+this.viewportWidth<i){let i=e;for(;this.getters.isColHidden(t,i)&&e<n;)i++;const o=this.getters.getColDimensions(t,i).end,s=this.searchHeaderIndex("COL",o-this.viewportWidth-this.offsetCorrectionX,this.boundaries.left,!0);this.offsetX=this.getters.getColDimensions(t,s).end-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX()}else if(this.left>e){let i=e;for(;this.getters.isColHidden(t,i)&&e>0;)i--;this.offsetX=this.getters.getColDimensions(t,i).start-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX()}}adjustPositionY(e){const t=this.sheetId,{end:i}=this.getters.getRowDimensions(t,e),n=this.getters.getNumberRows(t);if(this.offsetY+this.viewportHeight+this.offsetCorrectionY<i){let i=e;for(;this.getters.isRowHidden(t,i)&&e<n;)i++;const o=this.getters.getRowDimensions(t,i).end,s=this.searchHeaderIndex("ROW",o-this.viewportHeight-this.offsetCorrectionY,this.boundaries.top,!0);this.offsetY=this.getters.getRowDimensions(t,s).end-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY()}else if(this.top>e){let i=e;for(;this.getters.isRowHidden(t,i)&&e>0;)i--;this.offsetY=this.getters.getRowDimensions(t,i).start-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY()}}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getVisibleRect(e){const t=zi(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)}}}getFullRect(e){if(zi(e,this.zone)){return{x:this.getters.getColRowOffset("COL",this.zone.left,e.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset("ROW",this.zone.top,e.top)+this.offsetCorrectionY,width:this.getters.getColRowOffset("COL",e.left,e.right+1),height:this.getters.getColRowOffset("ROW",e.top,e.bottom+1)}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,i=0,n=!1){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;let o=0;const s=this.sheetId,r=this.getters.getNumberHeaders(s,e);for(let a=i;a<=r-1;a++){const i=n||"COL"!==e?a<this.top&&a>this.bottom:a<this.left&&a>this.right;if(!this.getters.isHeaderHidden(s,e,a)&&!i&&(o+="COL"===e?this.getters.getColSize(s,a):this.getters.getRowSize(s,a),o>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)),this.viewportWidth&&(-1===this.left&&(this.left=this.boundaries.left),-1===this.right&&(this.right=this.boundaries.right),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)),this.viewportHeight&&(-1===this.top&&(this.top=this.boundaries.top),-1===this.bottom&&(this.bottom=this.boundaries.bottom),this.offsetY=this.getters.getRowDimensions(e,this.top).start-this.getters.getRowDimensions(e,this.boundaries.top).start)}}class cb extends Wg{constructor(){super(...arguments),this.viewports={},this.sheetViewWidth=1e3,this.sheetViewHeight=1e3,this.gridOffsetX=0,this.gridOffsetY=0,this.sheetsWithDirtyViewports=new Set}allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.checkScrollingDirection(e);case"RESIZE_SHEETVIEW":return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return 0}}handleEvent(e){switch(e.type){case"HeadersSelected":case"AlterZoneCorner":break;case"ZonesSelected":const t=this.getters.getActiveSheetId();let{col:i,row:n}=Qi(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const o=e.previousAnchor.zone,s=e.anchor.zone,{top:r,bottom:a,left:l,right:c}=this.getMainInternalViewport(t);o.left===s.left&&o.right===s.right&&(i=l>i||i>c?l:i),o.top===s.top&&o.bottom===s.bottom&&(n=r>n||n>a?r:n)}i=Math.min(i,this.getters.getNumberCols(t)-1),n=Math.min(n,this.getters.getNumberRows(t)-1),this.refreshViewport(t,{col:i,row:n})}}handle(e){var t;switch(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 i=this.getters.getActiveSheetId(),{top:n,viewportHeight:o,offsetCorrectionY:s}=this.getMainInternalViewport(i),r=this.getters.getRowDimensions(i,n);this.shiftVertically(r.start+o-s);break;case"SHIFT_VIEWPORT_UP":{const e=this.getters.getActiveSheetId(),{top:t,viewportHeight:i,offsetCorrectionY:n}=this.getMainInternalViewport(e),o=this.getters.getRowDimensions(e,t);this.shiftVertically(o.end-n-i);break}case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"UPDATE_FILTER":this.resetViewports(e.sheetId);break;case"UPDATE_CELL":("content"in e||"format"in e||void 0!==(null===(t=e.style)||void 0===t?void 0:t.fontSize))&&this.sheetsWithDirtyViewports.add(e.sheetId);break;case"DELETE_SHEET":this.cleanViewports(),this.sheetsWithDirtyViewports.delete(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"START_EDITION":const{col:a,row:l}=this.getters.getPosition();this.refreshViewport(this.getters.getActiveSheetId(),{col:a,row:l})}}finalize(){for(const e of this.sheetsWithDirtyViewports)this.resetViewports(e);this.sheetsWithDirtyViewports=new Set,this.setViewports()}setViewports(){var e;const t=this.getters.getSheetIds();for(const i of t)(null===(e=this.viewports[i])||void 0===e?void 0:e.bottomRight)||this.resetViewports(i)}getColIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getColIndex(e))))}getRowIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getRowIndex(e))))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getActiveMainViewport(){const e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getActiveSheetDOMScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetScrollbarX,scrollY:t.offsetScrollbarY}}getSheetViewVisibleCols(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>$e(e.left,e.right+1))).flat())].filter((t=>t>=0&&!this.getters.isHeaderHidden(e,"COL",t)))}getSheetViewVisibleRows(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>$e(e.top,e.bottom+1))).flat())].filter((t=>t>=0&&!this.getters.isHeaderHidden(e,"ROW",t)))}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:i,ySplit:n}=this.getters.getPaneDivisions(e);let{width:o,height:s}=t.getMaxSize();return{x:this.getters.getColDimensions(e,i).start,y:this.getters.getRowDimensions(e,n).start,width:o,height:s}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:i}=this.getMainViewportRect(),n=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-n.viewportWidth+1),maxOffsetY:Math.max(0,i-n.viewportHeight+1)}}getColRowOffsetInViewport(e,t,i){if(i<t)return-this.getColRowOffsetInViewport(e,i,t);const n=this.getters.getActiveSheetId(),o="COL"===e?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),s=o.findIndex((e=>t>=e));let r=o.findIndex((e=>i<=e));r=-1===r?o.length:r;const a=o.slice(s,r);let l=0;for(const t of a)l+="COL"===e?this.getters.getColSize(n,t):this.getters.getRowSize(n,t);return l}isVisibleInViewport(e,t,i){return this.getSubViewports(e).some((e=>e.isVisible(t,i)))}getEdgeScrollCol(e,t,i){let n=!1,o=0,s=0;const{xSplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(n=!0,s=Wt(e-a),o=1):e<l&&i>=l&&c>0?(n=!0,s=Wt(l-e),o=-1):r&&t<l&&e>l&&(n=!0,s=Wt(e),o="reset"),{canEdgeScroll:n,direction:o,delay:s}}getEdgeScrollRow(e,t,i){let n=!1,o=0,s=0;const{ySplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(n=!0,s=Wt(e-a),o=1):e<l&&i>=l&&c>0?(n=!0,s=Wt(l-e),o=-1):r&&t<l&&e>l&&(n=!0,s=Wt(e),o="reset"),{canEdgeScroll:n,direction:o,delay:s}}getVisibleRect(e){const t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,(t=>t.getVisibleRect(e)))}getRect(e){const t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,(t=>t.getFullRect(e)))}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,i).start}}getAllActiveViewportsZones(){const e=this.getters.getActiveSheetId();return this.getSubViewports(e)}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(Xe)}checkPositiveDimension(e){return e.width<0||e.height<0?69:0}checkValuesAreDifferent(e){const{height:t,width:i}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===i&&e.height===t?77:0}checkScrollingDirection({offsetX:e,offsetY:t}){const i=this.getMainInternalViewport(this.getters.getActiveSheetId());return!i.canScrollHorizontally&&e>0||!i.canScrollVertically&&t>0?70:0}getMainViewport(e){const t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){const e={};for(const t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resetSheetViews(){this.cleanViewports();for(let e of Object.keys(this.viewports)){const t=this.getters.getSheetPosition(e);this.resetViewports(e);const i=this.getSubViewports(e);Object.values(i).forEach((e=>{e.adjustPosition(t)}))}}resizeSheetView(e,t,i=0,n=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=i,this.gridOffsetY=n,this.recomputeViewports()}recomputeViewports(){for(const e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){const i=this.getters.getActiveSheetId(),{maxOffsetX:n,maxOffsetY:o}=this.getMaximumSheetOffset();this.getSubViewports(i).forEach((i=>i.setViewportOffset(Me(e,0,n),Me(t,0,o))))}getViewportOffset(e){var t,i;return{x:(null===(t=this.viewports[e])||void 0===t?void 0:t.bottomRight.offsetScrollbarX)||0,y:(null===(i=this.viewports[e])||void 0===i?void 0:i.bottomRight.offsetScrollbarY)||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e),n=this.getters.getNumberCols(e),o=this.getters.getNumberRows(e),s=Math.min(this.getters.getColRowOffset("COL",0,t,e),this.sheetViewWidth),r=Math.min(this.getters.getColRowOffset("ROW",0,i,e),this.sheetViewHeight),a=Math.max(this.sheetViewWidth-s,0),l=Math.max(this.sheetViewHeight-r,0),{xRatio:c,yRatio:h}=this.getFrozenSheetViewRatio(e),d=c<1,u=h<1,g=this.getViewportOffset(e),p={topLeft:i&&t&&new lb(this.getters,e,{left:0,right:t-1,top:0,bottom:i-1},{width:s,height:r},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:i&&new lb(this.getters,e,{left:t,right:n-1,top:0,bottom:i-1},{width:a,height:r},{canScrollHorizontally:d,canScrollVertically:!1},{x:d?g.x:0,y:0})||void 0,bottomLeft:t&&new lb(this.getters,e,{left:0,right:t-1,top:i,bottom:o-1},{width:s,height:l},{canScrollHorizontally:!1,canScrollVertically:u},{x:0,y:u?g.y:0})||void 0,bottomRight:new lb(this.getters,e,{left:t,right:n-1,top:i,bottom:o-1},{width:a,height:l},{canScrollHorizontally:d,canScrollVertically:u},{x:d?g.x:0,y:u?g.y:0})};this.viewports[e]=p}refreshViewport(e,t){this.getSubViewports(e).forEach((e=>{e.adjustViewportZone(),e.adjustPosition(t)}))}shiftVertically(e){const t=this.getters.getActiveSheetId(),{top:i}=this.getMainInternalViewport(t),{scrollX:n}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(n,e);const{anchor:o}=this.getters.getSelection();if(o.cell.row>=this.getters.getPaneDivisions(t).ySplit){const e=this.getMainInternalViewport(t).top-i;this.selection.selectCell(o.cell.col,o.cell.row+e)}}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],i=this.getters.getFigures(e),{scrollX:n,scrollY:o}=this.getActiveSheetScrollInfo(),{x:s,y:r}=this.getters.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const e of i)e.x>=s&&(e.x+e.width<=s+n||e.x>=a+n+s)||e.y>=r&&(e.y+e.height<=r+o||e.y>=l+o+r)||t.push(e);return t}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e),n=this.getters.getColDimensions(e,t).start,o=this.getters.getRowDimensions(e,i).start;return{xRatio:n/(this.sheetViewWidth+this.gridOffsetX),yRatio:o/(this.sheetViewHeight+this.gridOffsetY)}}mapViewportsToRect(e,t){let i=1/0,n=1/0,o=0,s=0,r=!1;for(const a of this.getSubViewports(e)){const e=t(a);e&&(r=!0,i=Math.min(i,e.x),n=Math.min(n,e.y),o=Math.max(o,e.x+e.width),s=Math.max(s,e.y+e.height))}return r?{x:i+this.gridOffsetX,y:n+this.gridOffsetY,width:o-i,height:s-n}:{x:0,y:0,width:0,height:0}}}cb.getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getActiveSheetDOMScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio","getAllActiveViewportsZones","getRect"];class hb extends Wg{allowDispatch(e){if("SORT_CELLS"===e.type){if(!Wi(e.col,e.row,e.zone))throw new Error(s("The anchor must be part of the provided zone"));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return 0}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{})}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;for(let i=t.top;i<=t.bottom;i++)for(let n=t.left;n<=t.right;n++)if(!this.getters.isInMerge(e,n,i))return 64;return 0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const i=this.getters.getMerges(e).filter((e=>Hi(e,t))),n=ji(i[0]);let[o,s]=[n.width,n.height];return i.every((e=>{let[t,i]=[e.right-e.left+1,e.bottom-e.top+1];return t===o&&i===s}))?0:64}expand(e,t){const{left:i,right:n,top:o,bottom:s}=this.getters.expandZone(e,t);return{left:Math.max(0,i),right:Math.min(this.getters.getNumberCols(e)-1,n),top:Math.max(0,o),bottom:Math.min(this.getters.getNumberRows(e)-1,s)}}checkExpandedValues(e,t){const i=this.expand(e,t);let n;if(this.getters.doesIntersectMerge(e,i)){const{left:t,right:o,top:s,bottom:r}=i;for(let i=t;i<=o;i++)for(let t=s;t<=r;t++){const{col:o,row:s}=this.getters.getMainCellPosition(e,i,t);if(n=this.getters.getCell(e,o,s),null==n?void 0:n.formattedValue)return!0}}else for(let t of this.getters.getCellsInZone(e,i))if(null==t?void 0:t.formattedValue)return!0;return!1}getContiguousZone(e,t){let i,{top:n,bottom:o,left:s,right:r}=t,a=!1;for(;!a;)a=!0,n>0&&(i=this.checkExpandedValues(e,{left:s-1,right:r+1,top:n-1,bottom:n-1}),i&&(a=!1,n--)),s>0&&(i=this.checkExpandedValues(e,{left:s-1,right:s-1,top:n-1,bottom:o+1}),i&&(a=!1,s--)),r<this.getters.getNumberCols(e)-1&&(i=this.checkExpandedValues(e,{left:r+1,right:r+1,top:n-1,bottom:o+1}),i&&(a=!1,r++)),o<this.getters.getNumberRows(e)-1&&(i=this.checkExpandedValues(e,{left:s-1,right:r+1,top:o+1,bottom:o+1}),i&&(a=!1,o++));return{left:s,right:r,top:n,bottom:o}}hasHeader(e){if(1===e[0].length)return!1;let t=e.map((e=>e.map((e=>(null==e?void 0:e.evaluated.type)||hn.empty))));return t[0][0]===hn.empty&&(t=t.slice(1)),!t.some((e=>e[0]===hn.empty))&&!!t.some((e=>e[1]!==hn.empty&&e[0]!==e[1]))}sortZone(e,t,i,n,o){const[s,r]=this.mainCellsSteps(e,i);let a=this.getters.getMainCellPosition(e,t.col,t.row).col,l=Object.assign({},i),c=this.mainCells(e,i);!o.sortHeaders&&this.hasHeader(c)&&(l.top+=r),c=this.mainCells(e,l);const h=function(e,t,i){const n=e.map(lo);let o=n.filter((e=>e.type===hn.empty)),s=n.filter((e=>e.type!==hn.empty));i&&(s.push(...o.map((e=>({...e,type:hn.number,value:0})))),o=[]);const r="descending"===t?-1:1;return s.sort(((e,t)=>{let i=ao.indexOf(e.type)-ao.indexOf(t.type);return 0===i&&(i=e.type===hn.text||e.type===hn.error?e.value.localeCompare(t.value):e.value-t.value),r*i})).concat(o)}(c[a-l.left],n,Boolean(o.emptyCellAsZero)),d=h.map((e=>e.index)),[u,g]=[c.length,c[0].length],p=[];for(let t=0;t<u;t++)for(let i=0;i<g;i++){let n=c[t][d[i]],o=l.left+t*s,a=l.top+i*r,h={sheetId:e,col:o,row:a,content:""};if(n){let t=n.content;if(n.isFormula()){const i=a-this.getters.getCellPosition(n.id).row,o=this.getters.createAdaptedRanges(n.dependencies,0,i,e);t=this.getters.buildFormulaContent(e,n,o)}h.style=n.style,h.content=t,h.format=n.format}p.push(h)}p.forEach((e=>this.dispatch("UPDATE_CELL",e)))}mainCellsSteps(e,t){const i=this.getters.getMerge(e,t.left,t.top);return[i?i.right-i.left+1:1,i?i.bottom-i.top+1:1]}mainCells(e,t){const[i,n]=this.mainCellsSteps(e,t),o=[],s=$e(t.left,t.right+1,i),r=$e(t.top,t.bottom+1,n);for(const t of s){const i=[];o.push(i);for(const n of r)i.push(this.getters.getCell(e,t,n))}return o}}hb.getters=["getContiguousZone"];class db extends Wg{constructor(){super(...arguments),this.showFormulas=!1}handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}db.getters=["shouldShowFormulas"];class ub extends Wg{constructor(){super(...arguments),this.ctx=document.createElement("canvas").getContext("2d")}allowDispatch(e){switch(e.type){case"AUTORESIZE_ROWS":case"AUTORESIZE_COLUMNS":try{this.getters.getSheet(e.sheetId);break}catch(e){return 27}}return 0}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(let t of e.cols){const i=this.getColMaxWidth(e.sheetId,t);0!==i&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:i,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":this.dispatch("RESIZE_COLUMNS_ROWS",{elements:e.rows,dimension:"ROW",size:null,sheetId:e.sheetId})}}getCellWidth(e,{col:t,row:i}){const n=this.getters.getCell(e,t,i);let o=0;n&&(o+=this.getTextWidth(n));this.getters.getConditionalIcon(t,i)&&(o+=ke(this.getters.getCellStyle(n))+2*L);if(this.getters.isFilterHeader(e,t,i)&&(o+=20),o>0&&(o+=2*V,"wrap"===this.getters.getCellStyle(n).wrapping)){const e=en({col:t,row:i}),n=this.getters.getColSize(this.getters.getActiveSheetId(),e.left);return Math.min(n,o)}return o}getTextWidth(e){const t=this.getters.getCellText(e,this.getters.shouldShowFormulas()),{sheetId:i,col:n,row:o}=this.getters.getCellPosition(e.id);return _e(this.ctx,t,this.getters.getCellComputedStyle(i,n,o))}getCellText(e,t=!1){return t&&(e.isFormula()||e.evaluated.type===hn.error)?e.content:e.formattedValue}getCellMultiLineText(e,t){const i=this.getters.getCellStyle(e),n=this.getters.getCellText(e).split(" "),o=[];let s="",r=t;for(let e of n){const n=this.splitWordToSpecificWidth(this.ctx,e,t,i),a=n.pop(),l=_e(this.ctx,a,i);if(n.length)""!==s&&(o.push(s),s="",r=t),n.forEach((e=>{o.push(e)})),s=a,r=t-l;else{const e=""===s?a:" "+a,n=_e(this.ctx,e,i);n<=r?(s+=e,r-=n):(o.push(s),s=a,r=t-l)}}return""!==s&&o.push(s),o}getColDimensions(e,t){const i=this.getColRowOffset("COL",0,t,e),n=this.getters.getColSize(e,t);return{start:i,size:n,end:i+(this.getters.isColHidden(e,t)?0:n)}}getRowDimensions(e,t){const i=this.getColRowOffset("ROW",0,t,e),n=this.getters.getRowSize(e,t);return{start:i,size:n,end:i+(this.getters.isRowHidden(e,t)?0:n)}}getColRowOffset(e,t,i,n=this.getters.getActiveSheetId()){if(i<t)return-this.getColRowOffset(e,i,t);let o=0;for(let s=t;s<i;s++)this.getters.isHeaderHidden(n,e,s)||(o+="COL"===e?this.getters.getColSize(n,s):this.getters.getRowSize(n,s));return o}getColMaxWidth(e,t){const i=Xi(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth(e,t)));return Math.max(0,lt(i))}splitWordToSpecificWidth(e,t,i,n){if(_e(e,t,n)<=i)return[t];const o=[];let s="";for(let r of t){_e(e,s+r,n)>i?(o.push(s),s=r):s+=r}return o.push(s),o}}ub.getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getColDimensions","getRowDimensions","getColRowOffset"];const gb=(new sn).add("sheet",yv).add("header visibility",Sv).add("filters",vv).add("cell",hv).add("merge",Cv).add("headerSize",bv).add("borders",lv).add("conditional formatting",gv).add("figures",pv).add("chart",dv),pb=(new sn).add("selection",qv).add("ui_sheet",ub).add("header_visibility_ui",Bv).add("ui_options",db).add("evaluation",kv).add("evaluation_filter",Pv).add("evaluation_cf",Lv).add("evaluation_chart",$v).add("clipboard",_v).add("edition",qg).add("selectionInputManager",Yv).add("highlight",Hv).add("viewport",cb).add("grid renderer",Wv).add("autofill",Rv).add("find_and_replace",Vv).add("sort",hb).add("automatic_sum",Iv).add("format",zv).add("cell_popovers",Tv).add("selection_multiuser",ab).add("custom_colors",Fv),mb=new sn;mb.add("link",{condition:e=>e.isLink(),action:(e,t)=>{e.action(t)},sequence:5});class fb{constructor(){this.focusableElement=void 0}setFocusableElement(e){this.focusableElement=e}focus(){var e;null===(e=this.focusableElement)||void 0===e||e.focus()}}xn`
1392
1391
  .o-spreadsheet-bottom-bar {
1393
1392
  background-color: ${f};
1394
1393
  padding-left: ${M}px;
@@ -1477,12 +1476,12 @@
1477
1476
  opacity: 0;
1478
1477
  }
1479
1478
  }
1480
- `;class mb extends t.Component{constructor(){super(...arguments),this.bottomBarRef=t.useRef("bottomBar"),this.menuState=t.useState({isOpen:!1,menuId:void 0,position:null,menuItems:[]}),this.selectedStatisticFn=""}setup(){t.onMounted((()=>this.focusSheet())),t.onPatched((()=>this.focusSheet()))}focusSheet(){const e=this.bottomBarRef.el.querySelector(`[data-id="${this.env.model.getters.getActiveSheetId()}"]`);e&&e.scrollIntoView&&e.scrollIntoView()}addSheet(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSheetIds().findIndex((t=>t===e))+1,i=this.env.model.uuidGenerator.smallUuid(),n=this.env.model.getters.getNextSheetName(this.env._t("Sheet"));this.env.model.dispatch("CREATE_SHEET",{sheetId:i,position:t,name:n}),this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:i})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map((e=>this.env.model.getters.getSheet(e)))}listSheets(e){const t=new Yn,i=this.env.model.getters.getActiveSheetId();let n=0;for(const e of this.env.model.getters.getSheetIds()){const o=this.env.model.getters.getSheet(e);t.add(e,{name:o.name,sequence:n,isReadonlyAllowed:!0,textColor:o.isVisible?void 0:"grey",action:t=>{t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:i,sheetIdTo:e})}}),n++}const o=e.currentTarget,{top:s,left:r}=o.getBoundingClientRect();this.openContextMenu(r,s,t)}activateSheet(e){this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:e})}onDblClick(e){Yo(this.env,e)}openContextMenu(e,t,i,n){this.menuState.isOpen=!0,this.menuState.menuItems=i.getAll(),this.menuState.position={x:e,y:t},this.menuState.menuId=n}onIconClick(e,t){if(this.env.model.getters.getActiveSheetId()!==e&&this.activateSheet(e),t.closedMenuId===e)this.menuState.isOpen=!1,this.menuState.menuId=void 0;else{const i=t.currentTarget.parentElement,{top:n,left:o}=i.getBoundingClientRect();this.openContextMenu(o,n,Xo,e)}}onContextMenu(e,t){this.env.model.getters.getActiveSheetId()!==e&&this.activateSheet(e);const i=t.currentTarget,{top:n,left:o}=i.getBoundingClientRect();this.openContextMenu(o,n,Xo,e)}getSelectedStatistic(){const e=this.env.model.getters.getStatisticFnResults();if(!Object.values(e).every((e=>void 0===e)))return""===this.selectedStatisticFn&&(this.selectedStatisticFn=Object.keys(e)[0]),this.getComposedFnName(this.selectedStatisticFn,e[this.selectedStatisticFn])}listSelectionStatistics(e){const t=new Yn;let i=0;for(let[e,n]of Object.entries(this.env.model.getters.getStatisticFnResults()))t.add(e,{name:this.getComposedFnName(e,n),sequence:i,isReadonlyAllowed:!0,action:()=>{this.selectedStatisticFn=e}}),i++;const n=e.currentTarget,{top:o,left:s,width:r}=n.getBoundingClientRect();this.openContextMenu(s+r,o,t)}getComposedFnName(e,t){return e+": "+(void 0!==t?Qt(t):"__")}}mb.template="o-spreadsheet-BottomBar",mb.components={Menu:Hn},wn`
1479
+ `;class vb extends t.Component{constructor(){super(...arguments),this.bottomBarRef=t.useRef("bottomBar"),this.menuState=t.useState({isOpen:!1,menuId:void 0,position:null,menuItems:[]}),this.selectedStatisticFn=""}setup(){t.onMounted((()=>this.focusSheet())),t.onPatched((()=>this.focusSheet()))}focusSheet(){const e=this.bottomBarRef.el.querySelector(`[data-id="${this.env.model.getters.getActiveSheetId()}"]`);e&&e.scrollIntoView&&e.scrollIntoView()}addSheet(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSheetIds().findIndex((t=>t===e))+1,i=this.env.model.uuidGenerator.smallUuid(),n=this.env.model.getters.getNextSheetName(this.env._t("Sheet"));this.env.model.dispatch("CREATE_SHEET",{sheetId:i,position:t,name:n}),this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:i})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map((e=>this.env.model.getters.getSheet(e)))}listSheets(e){const t=new Kn,i=this.env.model.getters.getActiveSheetId();let n=0;for(const e of this.env.model.getters.getSheetIds()){const o=this.env.model.getters.getSheet(e);t.add(e,{name:o.name,sequence:n,isReadonlyAllowed:!0,textColor:o.isVisible?void 0:"grey",action:t=>{t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:i,sheetIdTo:e})}}),n++}const o=e.currentTarget,{top:s,left:r}=o.getBoundingClientRect();this.openContextMenu(r,s,t)}activateSheet(e){this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:e})}onDblClick(e){Ko(this.env,e)}openContextMenu(e,t,i,n){this.menuState.isOpen=!0,this.menuState.menuItems=i.getAll(),this.menuState.position={x:e,y:t},this.menuState.menuId=n}onIconClick(e,t){if(this.env.model.getters.getActiveSheetId()!==e&&this.activateSheet(e),t.closedMenuId===e)this.menuState.isOpen=!1,this.menuState.menuId=void 0;else{const i=t.currentTarget.parentElement,{top:n,left:o}=i.getBoundingClientRect();this.openContextMenu(o,n,Qo,e)}}onContextMenu(e,t){this.env.model.getters.getActiveSheetId()!==e&&this.activateSheet(e);const i=t.currentTarget,{top:n,left:o}=i.getBoundingClientRect();this.openContextMenu(o,n,Qo,e)}getSelectedStatistic(){const e=this.env.model.getters.getStatisticFnResults();if(!Object.values(e).every((e=>void 0===e)))return""===this.selectedStatisticFn&&(this.selectedStatisticFn=Object.keys(e)[0]),this.getComposedFnName(this.selectedStatisticFn,e[this.selectedStatisticFn])}listSelectionStatistics(e){const t=new Kn;let i=0;for(let[e,n]of Object.entries(this.env.model.getters.getStatisticFnResults()))t.add(e,{name:this.getComposedFnName(e,n),sequence:i,isReadonlyAllowed:!0,action:()=>{this.selectedStatisticFn=e}}),i++;const n=e.currentTarget,{top:o,left:s,width:r}=n.getBoundingClientRect();this.openContextMenu(s+r,o,t)}getComposedFnName(e,t){return e+": "+(void 0!==t?Qt(t):"__")}}vb.template="o-spreadsheet-BottomBar",vb.components={Menu:Gn},xn`
1481
1480
  .o-dashboard-clickable-cell {
1482
1481
  position: absolute;
1483
1482
  cursor: pointer;
1484
1483
  }
1485
- `;class fb extends t.Component{setup(){const e=t.useRef("grid");this.canvasPosition=zn(e),this.hoveredCell=t.useState({col:void 0,row:void 0}),bp("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimension())),this.onMouseWheel=Sp(((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:i}=this.env.model.getters.getColDimensions(e,t);return`\n max-width: ${i}px;\n `}get gridOverlayDimensions(){return"\n height: 100%;\n width: 100%\n "}getCellClickableStyle(e){return`\n top: ${e.y}px;\n left: ${e.x}px;\n width: ${e.width}px;\n height: ${e.height}px;\n `}getClickableCells(){const e=[],t=this.env.model.getters.getActiveSheetId();for(const i of this.env.model.getters.getSheetViewVisibleCols())for(const n of this.env.model.getters.getSheetViewVisibleRows()){const o=this.env.model.getters.getCell(t,i,n);if(o){const s=this.getClickableAction(o);if(!s)continue;let r;r=this.env.model.getters.isInMerge(t,i,n)?this.env.model.getters.getMerge(t,i,n):Qi({col:i,row:n});const a=this.env.model.getters.getVisibleRect(r);e.push({coordinates:a,cell:o,action:s})}}return e}getClickableAction(e){for(const t of gb.getAll().sort(((e,t)=>e.sequence-t.sequence)))if(t.condition(e,this.env))return t.action;return!1}selectClickableCell(e){const{cell:t,action:i}=e;i(t,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:i,scrollY:n}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:i+e,offsetY:n+t})}}fb.template="o-spreadsheet-SpreadsheetDashboard",fb.components={GridOverlay:up,GridPopover:gp,Popover:Bn,VerticalScrollBar:Ip,HorizontalScrollBar:Rp,FilterIconsOverlay:lp},wn`
1484
+ `;class bb extends t.Component{setup(){const e=t.useRef("grid");this.canvasPosition=Hn(e),this.hoveredCell=t.useState({col:void 0,row:void 0}),Cp("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimension())),this.onMouseWheel=Ep(((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:i}=this.env.model.getters.getColDimensions(e,t);return`\n max-width: ${i}px;\n `}get gridOverlayDimensions(){return"\n height: 100%;\n width: 100%\n "}getCellClickableStyle(e){return`\n top: ${e.y}px;\n left: ${e.x}px;\n width: ${e.width}px;\n height: ${e.height}px;\n `}getClickableCells(){const e=[],t=this.env.model.getters.getActiveSheetId();for(const i of this.env.model.getters.getSheetViewVisibleCols())for(const n of this.env.model.getters.getSheetViewVisibleRows()){const o=this.env.model.getters.getCell(t,i,n);if(o){const s=this.getClickableAction(o);if(!s)continue;let r;r=this.env.model.getters.isInMerge(t,i,n)?this.env.model.getters.getMerge(t,i,n):en({col:i,row:n});const a=this.env.model.getters.getVisibleRect(r);e.push({coordinates:a,cell:o,action:s})}}return e}getClickableAction(e){for(const t of mb.getAll().sort(((e,t)=>e.sequence-t.sequence)))if(t.condition(e,this.env))return t.action;return!1}selectClickableCell(e){const{cell:t,action:i}=e;i(t,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:i,scrollY:n}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:i+e,offsetY:n+t})}}bb.template="o-spreadsheet-SpreadsheetDashboard",bb.components={GridOverlay:pp,GridPopover:mp,Popover:Wn,VerticalScrollBar:Ap,HorizontalScrollBar:Tp,FilterIconsOverlay:hp},xn`
1486
1485
  .o-sidePanel {
1487
1486
  display: flex;
1488
1487
  flex-direction: column;
@@ -1725,7 +1724,7 @@
1725
1724
  }
1726
1725
  }
1727
1726
  }
1728
- `;class vb extends t.Component{setup(){this.state=t.useState({panel:yr.get(this.props.component)}),t.onWillUpdateProps((e=>this.state.panel=yr.get(e.component)))}getTitle(){return"function"==typeof this.state.panel.title?this.state.panel.title(this.env):this.state.panel.title}}vb.template="o-spreadsheet-SidePanel";const bb={MergeIsDestructive:s("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),MergeInFilter:s("You can't merge cells inside of an existing filter.")};const Sb=[{name:"automatic",text:es.Automatic},{name:"number",text:es.Number,description:"1,000.12",value:"#,##0.00"},{name:"percent",text:es.Percent,description:"10.12%",value:"0.00%"},{name:"currency",text:es.Currency,description:"$1,000.12",value:"[$$]#,##0.00"},{name:"currency_rounded",text:es.CurrencyRounded,description:"$1,000",value:"[$$]#,##0"},{name:"date",text:es.Date,description:"9/26/2008",value:"m/d/yyyy"},{name:"time",text:es.Time,description:"10:43:00 PM",value:"hh:mm:ss a"},{name:"datetime",text:es.DateTime,description:"9/26/2008 22:43:00",value:"m/d/yyyy hh:mm:ss"},{name:"duration",text:es.Duration,description:"27:51:38",value:"hhhh:mm:ss"}],Cb=[{name:"custom_currency",text:es.CustomCurrency,sidePanel:"CustomCurrency"}];wn`
1727
+ `;class Sb extends t.Component{setup(){this.state=t.useState({panel:Rr.get(this.props.component)}),t.onWillUpdateProps((e=>this.state.panel=Rr.get(e.component)))}getTitle(){return"function"==typeof this.state.panel.title?this.state.panel.title(this.env):this.state.panel.title}}Sb.template="o-spreadsheet-SidePanel";const Cb={MergeIsDestructive:s("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),MergeInFilter:s("You can't merge cells inside of an existing filter.")};const Eb=[{name:"automatic",text:is.Automatic},{name:"number",text:is.Number,description:"1,000.12",value:"#,##0.00"},{name:"percent",text:is.Percent,description:"10.12%",value:"0.00%"},{name:"currency",text:is.Currency,description:"$1,000.12",value:"[$$]#,##0.00"},{name:"currency_rounded",text:is.CurrencyRounded,description:"$1,000",value:"[$$]#,##0"},{name:"date",text:is.Date,description:"9/26/2008",value:"m/d/yyyy"},{name:"time",text:is.Time,description:"10:43:00 PM",value:"hh:mm:ss a"},{name:"datetime",text:is.DateTime,description:"9/26/2008 22:43:00",value:"m/d/yyyy hh:mm:ss"},{name:"duration",text:is.Duration,description:"27:51:38",value:"hhhh:mm:ss"}],wb=[{name:"custom_currency",text:is.CustomCurrency,sidePanel:"CustomCurrency"}];xn`
1729
1728
  .o-spreadsheet-topbar {
1730
1729
  background-color: white;
1731
1730
  line-height: 1.2;
@@ -1919,7 +1918,7 @@
1919
1918
  }
1920
1919
  }
1921
1920
  }
1922
- `;class Eb extends t.Component{constructor(){super(...arguments),this.DEFAULT_FONT_SIZE=G,this.commonFormats=Sb,this.customFormats=Cb,this.currentFormatName="automatic",this.fontSizes=se,this.style={},this.state=t.useState({menuState:{isOpen:!1,position:null,menuItems:[]},activeTool:""}),this.isSelectingMenu=!1,this.openedEl=null,this.inMerge=!1,this.cannotMerge=!1,this.undoTool=!1,this.redoTool=!1,this.paintFormatTool=!1,this.fillColor="#ffffff",this.textColor="#000000",this.menus=[],this.composerStyle="\n line-height: 34px;\n padding-left: 8px;\n height: 34px;\n background-color: white;\n "}get dropdownStyle(){return`max-height:${this.props.dropdownMaxHeight}px`}setup(){t.useExternalListener(window,"click",this.onClick),t.onWillStart((()=>this.updateCellState())),t.onWillUpdateProps((()=>this.updateCellState()))}get topbarComponents(){return xr.getAll().filter((e=>!e.isVisible||e.isVisible(this.env)))}onClick(e){this.openedEl&&kn(this.openedEl,e)||this.closeMenus()}toogleStyle(e){So(this.env,{[e]:!this.style[e]})}toogleFormat(e){const t=Sb.find((t=>t.name===e)),i=t&&t.value||"";bo(this.env,i)}toggleAlign(e){So(this.env,{align:e})}onMenuMouseOver(e,t){this.isSelectingMenu&&this.toggleContextMenu(e,t)}toggleDropdownTool(e,t){const i=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=i?"":e,this.openedEl=i?null:t.target}toggleContextMenu(e,t){this.closeMenus();const{left:i,top:n,height:o}=t.target.getBoundingClientRect();this.state.menuState.isOpen=!0,this.state.menuState.position={x:i,y:n+o},this.state.menuState.menuItems=Mn(e,this.env),this.state.menuState.parentMenu=e,this.isSelectingMenu=!0,this.openedEl=t.target,this.env.model.dispatch("STOP_EDITION")}closeMenus(){this.state.activeTool="",this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){const e=this.env.model.getters.getSelectedZones(),t=this.env.model.getters.getActiveSheetId();this.inMerge=!1;const{top:i,left:n,right:o,bottom:s}=this.env.model.getters.getSelectedZone(),{xSplit:r,ySplit:a}=this.env.model.getters.getPaneDivisions(t);if(this.cannotMerge=e.length>1||i===s&&n===o||n<r&&r<=o||i<a&&a<=s,!this.cannotMerge){const{col:i,row:n}=this.env.model.getters.getPosition(),o=this.env.model.getters.expandZone(t,{left:i,right:i,top:n,bottom:n});this.inMerge=Vi(e[0],o)}this.undoTool=this.env.model.getters.canUndo(),this.redoTool=this.env.model.getters.canRedo(),this.paintFormatTool=this.env.model.getters.isPaintingFormat();const l=this.env.model.getters.getActiveCell();if(l&&l.format){const e=this.commonFormats.find((e=>e.value===l.format));this.currentFormatName=e?e.name:""}else this.currentFormatName="automatic";this.style={...this.env.model.getters.getCurrentStyle()},this.style.align=this.style.align||(null==l?void 0:l.defaultAlign),this.fillColor=this.style.fillColor||"#ffffff",this.textColor=this.style.textColor||"#000000",this.menus=os.getAll()}getMenuName(e){return _n(e,this.env)}toggleMerge(){if(this.cannotMerge)return;const e=this.env.model.getters.getSelectedZones(),t=[e[e.length-1]],i=this.env.model.getters.getActiveSheetId();this.inMerge?this.env.model.dispatch("REMOVE_MERGE",{sheetId:i,target:t}):function(e,t,i){const n=e.model.dispatch("ADD_MERGE",{sheetId:t,target:i});n.isCancelledBecause(81)?e.raiseError(bb.MergeInFilter):n.isCancelledBecause(3)&&e.askConfirmation(bb.MergeIsDestructive,(()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:i,force:!0})}))}(this.env,i,t)}setColor(e,t){So(this.env,{[e]:t})}setBorder(e){this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),border:e})}setFormat(e){const t=e.target.dataset.format;if(t)return void this.toogleFormat(t);const i=e.target.dataset.custom;i&&this.openCustomFormatSidePanel(i)}openCustomFormatSidePanel(e){const t=Cb.find((t=>t.name===e)),i=t&&t.sidePanel||"";this.env.openSidePanel(i)}setDecimal(e){this.env.model.dispatch("SET_DECIMAL",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),step:e})}paintFormat(){this.env.model.dispatch("ACTIVATE_PAINT_FORMAT",{target:this.env.model.getters.getSelectedZones()})}clearFormatting(){this.env.model.dispatch("CLEAR_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setSize(e){const t=parseFloat(e.target.dataset.size);So(this.env,{fontSize:t})}doAction(e){e(this.env),this.closeMenus()}undo(){this.env.model.dispatch("REQUEST_UNDO")}redo(){this.env.model.dispatch("REQUEST_REDO")}get selectionContainsFilter(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones();return this.env.model.getters.doesZonesContainFilter(e,t)}get cannotCreateFilter(){return!tn(...this.env.model.getters.getSelectedZones())}createFilter(){if(this.cannotCreateFilter)return;const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones();ho(this.env,e,t)}removeFilter(){this.env.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}}Eb.template="o-spreadsheet-TopBar",Eb.components={ColorPicker:sr,Menu:Hn,Composer:ip},wn`
1921
+ `;class yb extends t.Component{constructor(){super(...arguments),this.DEFAULT_FONT_SIZE=G,this.commonFormats=Eb,this.customFormats=wb,this.currentFormatName="automatic",this.fontSizes=se,this.style={},this.state=t.useState({menuState:{isOpen:!1,position:null,menuItems:[]},activeTool:""}),this.isSelectingMenu=!1,this.openedEl=null,this.inMerge=!1,this.cannotMerge=!1,this.undoTool=!1,this.redoTool=!1,this.paintFormatTool=!1,this.fillColor="#ffffff",this.textColor="#000000",this.menus=[],this.composerStyle="\n line-height: 34px;\n padding-left: 8px;\n height: 34px;\n background-color: white;\n "}get dropdownStyle(){return`max-height:${this.props.dropdownMaxHeight}px`}setup(){t.useExternalListener(window,"click",this.onClick),t.onWillStart((()=>this.updateCellState())),t.onWillUpdateProps((()=>this.updateCellState()))}get topbarComponents(){return Ir.getAll().filter((e=>!e.isVisible||e.isVisible(this.env)))}onClick(e){this.openedEl&&Ln(this.openedEl,e)||this.closeMenus()}toogleStyle(e){Eo(this.env,{[e]:!this.style[e]})}toogleFormat(e){const t=Eb.find((t=>t.name===e)),i=t&&t.value||"";Co(this.env,i)}toggleAlign(e){Eo(this.env,{align:e})}onMenuMouseOver(e,t){this.isSelectingMenu&&this.toggleContextMenu(e,t)}toggleDropdownTool(e,t){const i=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=i?"":e,this.openedEl=i?null:t.target}toggleContextMenu(e,t){this.closeMenus();const{left:i,top:n,height:o}=t.target.getBoundingClientRect();this.state.menuState.isOpen=!0,this.state.menuState.position={x:i,y:n+o},this.state.menuState.menuItems=Fn(e,this.env),this.state.menuState.parentMenu=e,this.isSelectingMenu=!0,this.openedEl=t.target,this.env.model.dispatch("STOP_EDITION")}closeMenus(){this.state.activeTool="",this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){const e=this.env.model.getters.getSelectedZones(),t=this.env.model.getters.getActiveSheetId();this.inMerge=!1;const{top:i,left:n,right:o,bottom:s}=this.env.model.getters.getSelectedZone(),{xSplit:r,ySplit:a}=this.env.model.getters.getPaneDivisions(t);if(this.cannotMerge=e.length>1||i===s&&n===o||n<r&&r<=o||i<a&&a<=s,!this.cannotMerge){const{col:i,row:n}=this.env.model.getters.getPosition(),o=this.env.model.getters.expandZone(t,{left:i,right:i,top:n,bottom:n});this.inMerge=Bi(e[0],o)}this.undoTool=this.env.model.getters.canUndo(),this.redoTool=this.env.model.getters.canRedo(),this.paintFormatTool=this.env.model.getters.isPaintingFormat();const l=this.env.model.getters.getActiveCell();if(l&&l.format){const e=this.commonFormats.find((e=>e.value===l.format));this.currentFormatName=e?e.name:""}else this.currentFormatName="automatic";this.style={...this.env.model.getters.getCurrentStyle()},this.style.align=this.style.align||(null==l?void 0:l.defaultAlign),this.fillColor=this.style.fillColor||"#ffffff",this.textColor=this.style.textColor||"#000000",this.menus=rs.getAll()}getMenuName(e){return Dn(e,this.env)}toggleMerge(){if(this.cannotMerge)return;const e=this.env.model.getters.getSelectedZones(),t=[e[e.length-1]],i=this.env.model.getters.getActiveSheetId();this.inMerge?this.env.model.dispatch("REMOVE_MERGE",{sheetId:i,target:t}):function(e,t,i){const n=e.model.dispatch("ADD_MERGE",{sheetId:t,target:i});n.isCancelledBecause(81)?e.raiseError(Cb.MergeInFilter):n.isCancelledBecause(3)&&e.askConfirmation(Cb.MergeIsDestructive,(()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:i,force:!0})}))}(this.env,i,t)}setColor(e,t){Eo(this.env,{[e]:t})}setBorder(e){this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),border:e})}setFormat(e){const t=e.target.dataset.format;if(t)return void this.toogleFormat(t);const i=e.target.dataset.custom;i&&this.openCustomFormatSidePanel(i)}openCustomFormatSidePanel(e){const t=wb.find((t=>t.name===e)),i=t&&t.sidePanel||"";this.env.openSidePanel(i)}setDecimal(e){this.env.model.dispatch("SET_DECIMAL",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),step:e})}paintFormat(){this.env.model.dispatch("ACTIVATE_PAINT_FORMAT",{target:this.env.model.getters.getSelectedZones()})}clearFormatting(){this.env.model.dispatch("CLEAR_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setSize(e){const t=parseFloat(e.target.dataset.size);Eo(this.env,{fontSize:t})}doAction(e){e(this.env),this.closeMenus()}undo(){this.env.model.dispatch("REQUEST_UNDO")}redo(){this.env.model.dispatch("REQUEST_REDO")}get selectionContainsFilter(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones();return this.env.model.getters.doesZonesContainFilter(e,t)}get cannotCreateFilter(){return!on(...this.env.model.getters.getSelectedZones())}createFilter(){if(this.cannotCreateFilter)return;const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones();go(this.env,e,t)}removeFilter(){this.env.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}}yb.template="o-spreadsheet-TopBar",yb.components={ColorPicker:ar,Menu:Gn,Composer:op},xn`
1923
1922
  .o-spreadsheet {
1924
1923
  position: relative;
1925
1924
  display: grid;
@@ -1964,7 +1963,7 @@
1964
1963
  height: ${15}px;
1965
1964
  vertical-align: sub;
1966
1965
  }
1967
- `,wn`
1966
+ `,xn`
1968
1967
  .o-grid {
1969
1968
  position: relative;
1970
1969
  overflow: hidden;
@@ -1993,23 +1992,23 @@
1993
1992
  outline: none;
1994
1993
  }
1995
1994
  }
1996
- `;class wb extends t.Component{constructor(){super(...arguments),this.isViewportTooSmall=!1}getStyle(){return this.env.isDashboard()?"grid-template-rows: auto;":"grid-template-rows: 63px auto 37px"}setup(){var e,i;null===(i=(e=this.props).exposeSpreadsheet)||void 0===i||i.call(e,this),this.model=this.props.model,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",{})},t.useSubEnv({model:this.model,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.openSidePanel.bind(this),toggleSidePanel:this.toggleSidePanel.bind(this),_t:wb._t,clipboard:navigator.clipboard,focusableElement:new pb}),t.useExternalListener(window,"resize",(()=>this.render(!0))),t.useExternalListener(window,"beforeunload",this.unbindModelEvents.bind(this)),t.useExternalListener(document.body,"wheel",(()=>{})),this.bindModelEvents(),t.onMounted((()=>{this.checkViewportSize()})),t.onWillUnmount((()=>this.unbindModelEvents())),t.onPatched((()=>{this.checkViewportSize()}))}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}bindModelEvents(){this.model.on("update",this,(()=>this.render(!0))),this.model.on("notify-ui",this,this.onNotifyUI)}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.env.notifyUser({text:s("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),tag:"viewportTooSmall"}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}onNotifyUI(e){if("ERROR"===e.type)this.env.raiseError(e.text)}openSidePanel(e,t){this.sidePanel.component=e,this.sidePanel.panelProps=t,this.sidePanel.isOpen=!0}closeSidePanel(){this.sidePanel.isOpen=!1,this.focusGrid()}toggleSidePanel(e,t){this.sidePanel.isOpen&&e===this.sidePanel.component?(this.sidePanel.isOpen=!1,this.focusGrid()):this.openSidePanel(e,t)}focusGrid(){if(!this._focusGrid)throw new Error("_focusGrid should be exposed by the grid component");this._focusGrid()}save(){var e,t;null===(t=(e=this.props).onContentSaved)||void 0===t||t.call(e,this.model.exportData())}onKeydown(e){let t="";Un(e)&&(t+="CTRL+"),t+=e.key.toUpperCase();let i=this.keyDownMapping[t];if(i)return e.preventDefault(),e.stopPropagation(),void i()}onTopBarComposerFocused(e){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="contentFocus",this.composer.gridFocusMode="inactive",this.setComposerContent({selection:e}))}onGridComposerContentFocused(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}}wb.template="o-spreadsheet-Spreadsheet",wb.components={TopBar:Eb,Grid:Ap,BottomBar:mb,SidePanel:vb,SpreadsheetDashboard:fb},wb._t=e=>e;class yb{constructor(){this.listeners=[]}sendMessage(e){for(const{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter((t=>t.id!==e))}}function xb(e){return no.get(e.type)(e)}function Rb(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class Ib{constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find((t=>t.id===e));if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){var e;return null===(e=this.operations[this.operations.length-1])||void 0===e?void 0:e.id}getFirstOperationAmong(e,t){for(const i of this.operations){if(i.id===e)return e;if(i.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const i=this.buildTransformation.with(e.data),{before:n,operation:o,after:s}=this.locateOperation(t);this.operations=[...n,o,e,...s.map((e=>e.transformed(i)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new Ib(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:i}=this.locateOperation(e);this.operations=t.concat([i])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class Tb{constructor(e,t){this.id=e,this.data=t}transformed(e){return new Ab(this.id,tt((()=>e(this.data))))}}class Ab{constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new Ab(this.id,this.lazyData.map(e))}}class Ob{constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new Ob(function*(e,t){for(const i of e)if(yield i,i.operation.id===t)return}(this.operations,e))}stopBefore(e){return new Ob(function*(e,t){for(const i of e){if(i.operation.id===t)return;yield i}}(this.operations,e))}startAfter(e){return new Ob(function*(e,t){let i=!0;for(const n of e)i||(yield n),n.operation.id===t&&(i=!1)}(this.operations,e))}}class Nb{constructor(e,t){this.buildTransformation=e,this.branchingOperationIds=new Map,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new Ob(Pe(this._execution(e),this._execution(e)))}revertedExecution(e){return new Ob(Pe(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){var i;const n=e.getLastOperationId()||(null===(i=this.previousBranch(e))||void 0===i?void 0:i.getLastOperationId());e.append(t),n&&this.insertPrevious(e,t,n)}insertOperationAfter(e,t,i){e.insert(t,i),this.updateNextWith(e,t,i),this.insertPrevious(e,t,i)}undo(e,t){const i=this.buildTransformation.without(t.data),n=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const o=e.fork(t.id);n&&this.branchingOperationIds.set(o,n),this.insertBranchAfter(e,o),this.transform(o,i)}redo(e){const t=this.nextBranch(e);if(!t)return;const i=this.nextBranch(t);this.removeBranchFromTree(t);const n=this.branchingOperationIds.get(t);n?this.branchingOperationIds.set(e,n):this.branchingOperationIds.delete(e),i&&this.rebaseUp(i)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const i of this.revertedExecution(e))if(i.operation.id===t)return i;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!t||!i)return;const n=this.buildTransformation.without(i.data),o=t.fork(i.id);this.branchingOperationIds.set(o,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,o),o.transform(n);const s=this.nextBranch(o);s&&this.rebaseUp(s)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const i=this.branches.findIndex((t=>t===e));this.branches.splice(i+1,0,t)}updateNextWith(e,t,i){const n=this.branchingOperationIds.get(e),o=this.nextBranch(e);if(n&&o)if(e.getFirstOperationAmong(i,n)===n){const s=this.addToNextBranch(e,o,n,t,i);this.updateNextWith(o,s,i)}else{const e=this.buildTransformation.with(t.data);this.transform(o,e)}}addToNextBranch(e,t,i,n,o){let s=n;return o===i?(s=this.getTransformedOperation(e,i,n),t.prepend(s)):t.contains(o)?(s=this.getTransformedOperation(e,i,n),t.insert(s,o)):t.append(n),s}getTransformedOperation(e,t,i){const n=e.getOperation(t),o=this.buildTransformation.without(n.data);return i.transformed(o)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const i=this.nextBranch(e);i&&this.transform(i,t)}insertPrevious(e,t,i){const{previousBranch:n,branchingOperation:o}=this.findPreviousBranchingOperation(e);if(!n||!o)return;const s=this.buildTransformation.with(o.data),r=e.fork(i);r.transform(s),n.cutAfter(i),n.appendBranch(r);const a=t.transformed(s);this.insertPrevious(n,a,i)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const i=this.branchingOperationIds.get(t);return i?{previousBranch:t,branchingOperation:t.getOperation(i)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let i=!!t;const n=e.getOperations();for(let o=n.length-1;o>=0;o--){const s=n[o];s.id===t&&(i=!1),i||(yield{operation:s,branch:e,isCancelled:!this.shouldExecute(e,s)})}const o=this.previousBranch(e);yield*o?this._revertedExecution(o):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class Mb{constructor(e,t,i,n,o){this.applyOperation=t,this.revertOperation=i,this.buildEmpty=n,this.buildTransformation=o,this.HEAD_BRANCH=new Ib(this.buildTransformation),this.tree=new Nb(o,this.HEAD_BRANCH);const s=new Tb(e,n(e));this.tree.insertOperationLast(this.HEAD_BRANCH,s),this.HEAD_OPERATION=s}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const i=new Tb(e,t),n=this.tree.getLastBranch();this.tree.insertOperationLast(n,i),this.HEAD_BRANCH=n,this.HEAD_OPERATION=i}insert(e,t,i){const n=new Tb(e,t);this.revertTo(i),this.tree.insertOperationAfter(this.HEAD_BRANCH,n,i),this.fastForward()}undo(e,t,i){const{branch:n,operation:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(n,o),this.fastForward(),this.insert(t,this.buildEmpty(t),i)}redo(e,t,i){const{branch:n}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(n),this.fastForward(),this.insert(t,this.buildEmpty(t),i)}rebase(e){const t=this.get(e),i=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);const n=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,n);for(const{operation:e}of i)this.insert(e.id,e.data,this.HEAD_OPERATION.id)}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:i,isCancelled:n}of e)n||this.revertOperation(i.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:i,isCancelled:n}of e)n||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=i}}function _b(e,t,i){return new Mb(e,(e=>{const n=e.commands.slice(),{changes:o}=t((()=>{for(const e of n)i(e)}));e.setChanges(o)}),(e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){Fb(t.changes[e],"before")}}([e])),(e=>new tb(e,"empty",[],[])),{with:e=>t=>new tb(t.id,t.clientId,Jv(t.commands,e.commands)),without:e=>t=>new tb(t.id,t.clientId,Jv(t.commands,e.commands.map(xb).flat()))})}function Fb(e,t){let i=e.path[0];const n=e.path[e.path.length-1];for(let t=1;t<e.path.slice(0,-1).length;t++){const n=e.path[t];if(void 0===i[n]){const o=e.path[t+1];i[n]=Rb(o)}i=i[n]}void 0===e[t]?delete i[n]:i[n]=e[t]}class Db extends t.EventBus{constructor(e,t){super(),this.dispatch=e,this.session=t,this.undoStack=[],this.redoStack=[],this.session.on("new-local-state-update",this,this.onNewLocalStateUpdate),this.session.on("revision-undone",this,(({commands:e})=>this.selectiveUndo(e))),this.session.on("revision-redone",this,(({commands:e})=>this.selectiveRedo(e))),this.session.on("snapshot",this,(()=>{this.undoStack=[],this.redoStack=[]}))}allowDispatch(e){switch(e.type){case"REQUEST_UNDO":if(!this.canUndo())return 6;break;case"REQUEST_REDO":if(!this.canRedo())return 7}return 0}beforeHandle(e){}handle(e){switch(e.type){case"REQUEST_UNDO":case"REQUEST_REDO":this.requestHistoryChange("REQUEST_UNDO"===e.type?"UNDO":"REDO")}}finalize(){}requestHistoryChange(e){const t="UNDO"===e?this.undoStack.pop():this.redoStack.pop();t&&("UNDO"===e?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t)))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}selectiveUndo(e){this.dispatch("UNDO",{commands:e})}selectiveRedo(e){this.dispatch("REDO",{commands:e})}}class kb{constructor(e){this.providers=[],this.getters=e}allowDispatch(e){return"MOVE_RANGES"===e.type?1===e.target.length?0:26:0}beforeHandle(e){}handle(e){switch(e.type){case"REMOVE_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",i="COL"===e.dimension?"right":"bottom",n="COL"===e.dimension?"columns":"rows";const o=[...e.elements];o.sort(((e,t)=>t-e));const s=Le(o);this.executeOnAllRanges((o=>{if(o.sheetId!==e.sheetId)return{changeType:"NONE"};let r=o,a="NONE";for(let e of s){const s=ct(e),l=lt(e);if(o.zone[t]<=s&&s<=o.zone[i]){const e=Math.min(o.zone[i],l)-s+1;a="RESIZE",r=this.createAdaptedRange(r,n,a,-e)}else if(o.zone[t]>=s&&o.zone[i]<=l)a="REMOVE",r=o.clone({...this.getInvalidRange()});else if(o.zone[t]<=l&&o.zone[i]>=l){const e=l-o.zone[t]+1;a="RESIZE",r=this.createAdaptedRange(r,n,a,-e),r=this.createAdaptedRange(r,n,"MOVE",-(o.zone[t]-s))}else s<o.zone[t]&&(a="MOVE",r=this.createAdaptedRange(r,n,a,-(l-s+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",i="COL"===e.dimension?"right":"bottom",n="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((o=>{if(o.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(o.zone[t]<=e.base&&e.base<o.zone[i])return{changeType:"RESIZE",range:this.createAdaptedRange(o,n,"RESIZE",e.quantity)};if(e.base<o.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(o,n,"MOVE",e.quantity)}}else{if(o.zone[t]<e.base&&e.base<=o.zone[i])return{changeType:"RESIZE",range:this.createAdaptedRange(o,n,"RESIZE",e.quantity)};if(e.base<=o.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(o,n,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId!==e.sheetId)return{changeType:"NONE"};const i=this.getters.getSheetName(e.sheetId);return{changeType:"REMOVE",range:t=t.clone({...this.getInvalidRange(),invalidSheetName:i})}}),e.sheetId);break;case"RENAME_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(Ai(t.invalidSheetName,e.name)){const i=void 0,n=e.sheetId;return{changeType:"CHANGE",range:t.clone({sheetId:n,invalidSheetName:i})}}return{changeType:"NONE"}}));break;case"MOVE_RANGES":{const t=e.target[0];this.executeOnAllRanges((i=>{if(i.sheetId!==e.sheetId||!Hi(i.zone,t))return{changeType:"NONE"};const n=e.targetSheetId,o=e.col-t.left,s=e.row-t.top,r=this.createAdaptedRange(i,"both","MOVE",[o,s]),a=e.sheetId!==n||r.prefixSheet;return{changeType:"MOVE",range:r.clone({sheetId:n,prefixSheet:a})}}));break}}}finalize(){}verifyRangeRemoved(e){return t=>{const i=e(t);return"NONE"===i.changeType||_i(i.range.zone)?i:{range:i.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,i,n){const o=Yi(e.unboundedZone,t,i,n);return e.clone({zone:o})}executeOnAllRanges(e,t){const i=this.verifyRangeRemoved(e);for(const e of this.providers)e(i,t)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,i,n){const o=e.map((e=>xi.fromRange(e,this.getters)));return o.map((e=>{if(!_i(e.zone))return e;const o=e.prefixSheet?e.sheetId:n,s={...e.unboundedZone,left:e.isFullRow&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:e.isFullRow?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.isFullCol&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:i),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:i)};return(e=e.clone({sheetId:o,zone:s})).orderZone(),e}))}getRangeFromSheetXC(e,t){if(!Nt.test(t)||!this.getters.tryGetSheet(e))return new xi({sheetId:"",zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let i,n=t,o=!1;t.includes("!")&&(({xc:n,sheetName:i}=$t(t)),i&&(o=!0));const s=Ni(n),r=xi.getRangeParts(n,s),a=i&&!this.getters.getSheetIdByName(i)?i:void 0,l=this.getters.getSheetIdByName(i)||e,c=new xi({prefixSheet:o,zone:s,sheetId:l,invalidSheetName:a,parts:r},this.getters.getSheetSize);return c.orderZone(),c}getSelectionRangeString(e,t){const i=xi.fromRange(e,this.getters),n=this.getters.expandZone(i.sheetId,i.zone),o=i.clone({zone:{...n,bottom:i.isFullCol?void 0:n.bottom,right:i.isFullRow?void 0:n.right}});return this.getRangeString(o,t)}getRangeString(e,t,i=!1){if(!e)return X;if(e.invalidXc)return e.invalidXc;if(!this.getters.tryGetSheet(e.sheetId))return X;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return X;if(e.zone.left<0||e.zone.top<0)return X;const n=xi.fromRange(e,this.getters);let o=n.sheetId!==t||n.invalidSheetName||n.prefixSheet,s="";if(o&&(s=n.invalidSheetName?n.invalidSheetName:Ne(this.getters.getSheetName(n.sheetId))),o&&!s)return X;let r=this.getRangePartString(n,0,i);return n.parts&&2===n.parts.length&&(n.zone.top!==n.zone.bottom||n.zone.left!==n.zone.right||n.parts[0].rowFixed||n.parts[0].colFixed||n.parts[1].rowFixed||n.parts[1].colFixed)&&(r+=":",r+=this.getRangePartString(n,1,i)),`${o?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 xi(t,this.getters.getSheetSize)}getRangePartString(e,t,i=!1){var n,o;const s=e.parts&&(null===(n=e.parts[t])||void 0===n?void 0:n.colFixed)?"$":"",r=Lt(0===t?e.zone.left:e.zone.right),a=e.parts&&(null===(o=e.parts[t])||void 0===o?void 0:o.rowFixed)?"$":"",l=String(0===t?e.zone.top+1:e.zone.bottom+1);let c="";return c=e.isFullCol&&!i?0===t&&e.unboundedZone.hasHeader?s+r+a+l:s+r:e.isFullRow&&!i?0===t&&e.unboundedZone.hasHeader?s+r+a+l:a+l:s+r+a+l,c}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:X}}}kb.getters=["getRangeString","getSelectionRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData"];class $b{constructor(){this.observers=[]}registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||(this.mainSubscription=this.defaultSubscription)}observe(e,t){this.observers.push({owner:e,callbacks:t})}capture(e,t){var i,n,o;if(this.observers.find((t=>t.owner===e)))throw new Error("You are already subscribed forever");(null===(i=this.mainSubscription)||void 0===i?void 0:i.owner)&&this.mainSubscription.owner!==e&&(null===(o=(n=this.mainSubscription.callbacks).release)||void 0===o||o.call(n)),this.mainSubscription={owner:e,callbacks:t}}release(e){var t;(null===(t=this.mainSubscription)||void 0===t?void 0:t.owner)!==e||this.observers.find((t=>t.owner===e))||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){var e,t,i;this.mainSubscription!==this.defaultSubscription&&(null===(i=null===(e=this.mainSubscription)||void 0===e?void 0:(t=e.callbacks).release)||void 0===i||i.call(t),this.mainSubscription=this.defaultSubscription)}isListening(e){var t;return(null===(t=this.mainSubscription)||void 0===t?void 0:t.owner)===e}send(e){var t;null===(t=this.mainSubscription)||void 0===t||t.callbacks.handleEvent(e),[...this.observers].forEach((t=>t.callbacks.handleEvent(e)))}}class Lb{constructor(e){this.getters=e,this.stream=new $b,this.anchor={cell:{col:0,row:0},zone:Qi({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,i){this.stream.capture(e,i),this.anchor=t}registerAsDefault(e,t,i){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,i),this.defaultAnchor=t,this.capture(e,t,i)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}selectZone(e){const t=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(t,e.zone)},this.processEvent({type:"ZonesSelected",anchor:e,mode:"overrideSelection"})}selectCell(e,t){const i=Qi({col:e,row:t});return this.selectZone({zone:i,cell:{col:e,row:t}})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new pn(84);const{col:i,row:n}=this.getNextAvailablePosition(e,t);return this.selectCell(i,n)}setAnchorCorner(e,t){const i=this.getters.getActiveSheetId(),{col:n,row:o}=this.anchor.cell,s={left:Math.min(n,e),top:Math.min(o,t),right:Math.max(n,e),bottom:Math.max(o,t)},r={zone:this.getters.expandZone(i,s),cell:{col:n,row:o}};return this.processEvent({type:"AlterZoneCorner",mode:"updateAnchor",anchor:r})}addCellToSelection(e,t){const i=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition(i,e,t));const n=this.getters.expandZone(i,Qi({col:e,row:t}));return this.processEvent({type:"ZonesSelected",anchor:{zone:n,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new pn(84);const i=this.getters.getActiveSheetId(),n=this.anchor,{col:o,row:s}=n.cell,{left:r,right:a,top:l,bottom:c}=n.zone,h=this.getStartingPosition(e);let[d,u]=this.deltaToTarget(h,e,t);if(0===d&&0===u)return pn.Success;let g=n.zone;const p=e=>{e=Ki(e);const{left:t,right:n,top:o,bottom:s}=this.getters.expandZone(i,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(i)-1,n),top:Math.max(0,o),bottom:Math.min(this.getters.getNumberRows(i)-1,s)}},{col:m,row:f}=this.getReferencePosition();let v=0;for(;null!==g;){if(v++,d<0){const e=this.getNextAvailableCol(d,a-(v-1),f);g=m<=a-v?p({top:l,left:r,bottom:c,right:e}):null}if(d>0){const e=this.getNextAvailableCol(d,r+(v-1),f);g=r+v<=m?p({top:l,left:e,bottom:c,right:a}):null}if(u<0){const e=this.getNextAvailableRow(u,m,c-(v-1));g=f<=c-v?p({top:l,left:r,bottom:e,right:a}):null}if(u>0){const e=this.getNextAvailableRow(u,m,l+(v-1));g=l+v<=f?p({top:e,left:r,bottom:c,right:a}):null}if(g=g?Ki(g):g,g&&!Vi(g,n.zone))return this.processEvent({type:"ZonesSelected",mode:"updateAnchor",anchor:{zone:g,cell:{col:o,row:s}}})}g=p(Pi({top:s,bottom:s,left:o,right:o},Ki({top:this.getNextAvailableRow(u,m,l),left:this.getNextAvailableCol(d,r,f),bottom:this.getNextAvailableRow(u,m,c),right:this.getNextAvailableCol(d,a,f)})));const b={zone:g,cell:{col:o,row:s}};return this.processEvent({type:"ZonesSelected",anchor:b,mode:"updateAnchor"})}selectColumn(e,t){const i=this.getters.getActiveSheetId(),n=this.getters.getNumberRows(i)-1;let o={left:e,right:e,top:0,bottom:n};const s=this.getters.findFirstVisibleColRowIndex(i,"ROW");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=e,a=s;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),o=Pi(o,{left:r,right:r,top:s,bottom:n})}return this.processEvent({type:"HeadersSelected",anchor:{zone:o,cell:{col:r,row:a}},mode:t})}selectRow(e,t){const i=this.getters.getActiveSheetId(),n=this.getters.getNumberCols(i)-1;let o={top:e,bottom:e,left:0,right:n};const s=this.getters.findFirstVisibleColRowIndex(i,"COL");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=s,a=e;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),o=Pi(o,{left:s,right:n,top:a,bottom:a})}return this.processEvent({type:"HeadersSelected",anchor:{zone:o,cell:{col:r,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor,i=e=>{for(const t of $e(e.left,e.right+1)){if(!this.isCellEmpty({col:t,row:e.top-1}))return{...e,top:e.top-1};if(!this.isCellEmpty({col:t,row:e.bottom+1}))return{...e,bottom:e.bottom+1}}for(const t of $e(e.top,e.bottom+1)){if(!this.isCellEmpty({col:e.left-1,row:t}))return{...e,left:e.left-1};if(!this.isCellEmpty({col:e.right+1,row:t}))return{...e,right:e.right+1}}return e};if(Vi(this.anchor.zone,this.getters.getSheetZone(e)))return this.selectZone({...t,zone:Qi(t.cell)});let n=!1,o=!1,s=t.zone;do{o=o||n,n=!1;const e=i(s);Vi(s,e)||(n=!0,s=e)}while(n);return o?this.selectZone({...t,zone:s}):this.selectAll()}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:Ae(this.anchor)},i=this.checkEventAnchorZone(t);return 0!==i?new pn(i):(this.anchor=t.anchor,this.stream.send(t),pn.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:i}=e;if(!Bi(t.col,t.row,i))return 16;const{left:n,right:o,top:s,bottom:r}=i,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",n,o);return void 0===this.getters.findVisibleHeader(a,"ROW",s,r)||void 0===l?17:0}checkAnchorZoneOrThrow(e){if(16===this.checkAnchorZone(e))throw new Error(o("The provided anchor is invalid. The cell must be part of the zone."))}getNextAvailablePosition(e,t=1){const{col:i,row:n}=this.anchor.cell,o=this.deltaToTarget({col:i,row:n},e,t);return{col:this.getNextAvailableCol(o[0],i,n),row:this.getNextAvailableRow(o[1],i,n)}}getNextAvailableCol(e,t,i){const n=this.getters.getActiveSheetId(),o={col:t,row:i};return this.getNextAvailableHeader(e,"COL",t,o,(e=>this.getters.isInSameMerge(n,t,i,e,i)))}getNextAvailableRow(e,t,i){const n=this.getters.getActiveSheetId(),o={col:t,row:i};return this.getNextAvailableHeader(e,"ROW",i,o,(e=>this.getters.isInSameMerge(n,t,i,t,e)))}getNextAvailableHeader(e,t,i,n,o){const s=this.getters.getActiveSheetId();if(0===e)return i;const r=Math.sign(e);let a=i+e;for(;o(a);)a+=r;for(;this.getters.isHeaderHidden(s,t,a);)a+=r;return a<0||a>this.getters.getNumberHeaders(s,t)-1?this.getters.isHeaderHidden(s,t,i)?this.getNextAvailableHeader(-r,t,i,n,o):i:a}getReferencePosition(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:i,right:n,top:o,bottom:s}=t.zone,{col:r,row:a}=t.cell;return{col:this.getters.isColHidden(e,r)&&this.getters.findVisibleHeader(e,"COL",i,n)||r,row:this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",o,s)||a}}deltaToTarget(e,t,i){switch(t){case"up":return"end"!==i?[0,-i]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==i?[0,i]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==i?[-i,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==i?[i,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:i}=this.getPosition();const n=this.anchor.zone;switch(e){case"down":case"up":i=i===n.top?n.bottom:n.top;break;case"left":case"right":t=t===n.right?n.left:n.right}return{col:t,row:i}}getEndOfCluster(e,t,i){const n=this.getters.getActiveSheet();let o=e;const s=this.getNextCellPosition(e,t,i);let r=this.isCellEmpty(o,n.id)||this.isCellEmpty(s,n.id)?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(o,t,i);if(o.col===e.col&&o.row===e.row)break;const s=this.isCellEmpty(e,n.id);if("endOfCluster"===r&&s)break;if("nextCluster"===r&&!s){o=e;break}o=e}return"cols"===t?o.col:o.row}isCellEmpty({col:e,row:t},i=this.getters.getActiveSheetId()){const n=this.getters.getMainCellPosition(i,e,t),o=this.getters.getCell(i,n.col,n.row);return!o||o.isEmpty()}getNextCellPosition(e,t,i){const n="cols"===t?"col":"row",o={...e},s="cols"===t?this.getNextAvailableCol(i,o.col,o.row):this.getNextAvailableRow(i,o.col,o.row);return o[n]=s,{col:o.col,row:o.row}}getPosition(){return{...this.anchor.cell}}}class Pb{constructor(){this.changes=[],this.commands=[]}recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop();let i=e[0],n=e[e.length-1];const o=e.length-2;for(let t=1;t<=o;t++){const n=e[t];if(void 0===i[n]){const o=e[t+1];i[n]=Rb(o)}i=i[n]}i[n]!==t&&(this.changes.push({path:e,before:i[n],after:t}),void 0===t?delete i[n]:i[n]=t)}}const Ub=17781237,Vb=88853993;function zb(e,t,i){const n=[["xmlns:r",Xp],["xmlns:a",qp],["xmlns:c",Zp]],o=Bb({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let s=_f``;e.data.title&&(s=_f`
1995
+ `;class xb extends t.Component{constructor(){super(...arguments),this.isViewportTooSmall=!1}getStyle(){return this.env.isDashboard()?"grid-template-rows: auto;":"grid-template-rows: 63px auto 37px"}setup(){var e,i;null===(i=(e=this.props).exposeSpreadsheet)||void 0===i||i.call(e,this),this.model=this.props.model,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",{})},t.useSubEnv({model:this.model,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.openSidePanel.bind(this),toggleSidePanel:this.toggleSidePanel.bind(this),_t:xb._t,clipboard:navigator.clipboard,focusableElement:new fb}),t.useExternalListener(window,"resize",(()=>this.render(!0))),t.useExternalListener(window,"beforeunload",this.unbindModelEvents.bind(this)),t.useExternalListener(document.body,"wheel",(()=>{})),this.bindModelEvents(),t.onMounted((()=>{this.checkViewportSize()})),t.onWillUnmount((()=>this.unbindModelEvents())),t.onPatched((()=>{this.checkViewportSize()}))}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}bindModelEvents(){this.model.on("update",this,(()=>this.render(!0))),this.model.on("notify-ui",this,this.onNotifyUI)}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.env.notifyUser({text:s("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),tag:"viewportTooSmall"}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}onNotifyUI(e){if("ERROR"===e.type)this.env.raiseError(e.text)}openSidePanel(e,t){this.sidePanel.component=e,this.sidePanel.panelProps=t,this.sidePanel.isOpen=!0}closeSidePanel(){this.sidePanel.isOpen=!1,this.focusGrid()}toggleSidePanel(e,t){this.sidePanel.isOpen&&e===this.sidePanel.component?(this.sidePanel.isOpen=!1,this.focusGrid()):this.openSidePanel(e,t)}focusGrid(){if(!this._focusGrid)throw new Error("_focusGrid should be exposed by the grid component");this._focusGrid()}save(){var e,t;null===(t=(e=this.props).onContentSaved)||void 0===t||t.call(e,this.model.exportData())}onKeydown(e){let t="";zn(e)&&(t+="CTRL+"),t+=e.key.toUpperCase();let i=this.keyDownMapping[t];if(i)return e.preventDefault(),e.stopPropagation(),void i()}onTopBarComposerFocused(e){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="contentFocus",this.composer.gridFocusMode="inactive",this.setComposerContent({selection:e}))}onGridComposerContentFocused(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}}xb.template="o-spreadsheet-Spreadsheet",xb.components={TopBar:yb,Grid:Op,BottomBar:vb,SidePanel:Sb,SpreadsheetDashboard:bb},xb._t=e=>e;class Rb{constructor(){this.listeners=[]}sendMessage(e){for(const{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter((t=>t.id!==e))}}function Ib(e){return so.get(e.type)(e)}function Tb(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class Ab{constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find((t=>t.id===e));if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){var e;return null===(e=this.operations[this.operations.length-1])||void 0===e?void 0:e.id}getFirstOperationAmong(e,t){for(const i of this.operations){if(i.id===e)return e;if(i.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const i=this.buildTransformation.with(e.data),{before:n,operation:o,after:s}=this.locateOperation(t);this.operations=[...n,o,e,...s.map((e=>e.transformed(i)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new Ab(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:i}=this.locateOperation(e);this.operations=t.concat([i])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class Nb{constructor(e,t){this.id=e,this.data=t}transformed(e){return new Ob(this.id,tt((()=>e(this.data))))}}class Ob{constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new Ob(this.id,this.lazyData.map(e))}}class Mb{constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new Mb(function*(e,t){for(const i of e)if(yield i,i.operation.id===t)return}(this.operations,e))}stopBefore(e){return new Mb(function*(e,t){for(const i of e){if(i.operation.id===t)return;yield i}}(this.operations,e))}startAfter(e){return new Mb(function*(e,t){let i=!0;for(const n of e)i||(yield n),n.operation.id===t&&(i=!1)}(this.operations,e))}}class _b{constructor(e,t){this.buildTransformation=e,this.branchingOperationIds=new Map,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new Mb(Pe(this._execution(e),this._execution(e)))}revertedExecution(e){return new Mb(Pe(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){var i;const n=e.getLastOperationId()||(null===(i=this.previousBranch(e))||void 0===i?void 0:i.getLastOperationId());e.append(t),n&&this.insertPrevious(e,t,n)}insertOperationAfter(e,t,i){e.insert(t,i),this.updateNextWith(e,t,i),this.insertPrevious(e,t,i)}undo(e,t){const i=this.buildTransformation.without(t.data),n=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const o=e.fork(t.id);n&&this.branchingOperationIds.set(o,n),this.insertBranchAfter(e,o),this.transform(o,i)}redo(e){const t=this.nextBranch(e);if(!t)return;const i=this.nextBranch(t);this.removeBranchFromTree(t);const n=this.branchingOperationIds.get(t);n?this.branchingOperationIds.set(e,n):this.branchingOperationIds.delete(e),i&&this.rebaseUp(i)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const i of this.revertedExecution(e))if(i.operation.id===t)return i;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!t||!i)return;const n=this.buildTransformation.without(i.data),o=t.fork(i.id);this.branchingOperationIds.set(o,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,o),o.transform(n);const s=this.nextBranch(o);s&&this.rebaseUp(s)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const i=this.branches.findIndex((t=>t===e));this.branches.splice(i+1,0,t)}updateNextWith(e,t,i){const n=this.branchingOperationIds.get(e),o=this.nextBranch(e);if(n&&o)if(e.getFirstOperationAmong(i,n)===n){const s=this.addToNextBranch(e,o,n,t,i);this.updateNextWith(o,s,i)}else{const e=this.buildTransformation.with(t.data);this.transform(o,e)}}addToNextBranch(e,t,i,n,o){let s=n;return o===i?(s=this.getTransformedOperation(e,i,n),t.prepend(s)):t.contains(o)?(s=this.getTransformedOperation(e,i,n),t.insert(s,o)):t.append(n),s}getTransformedOperation(e,t,i){const n=e.getOperation(t),o=this.buildTransformation.without(n.data);return i.transformed(o)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const i=this.nextBranch(e);i&&this.transform(i,t)}insertPrevious(e,t,i){const{previousBranch:n,branchingOperation:o}=this.findPreviousBranchingOperation(e);if(!n||!o)return;const s=this.buildTransformation.with(o.data),r=e.fork(i);r.transform(s),n.cutAfter(i),n.appendBranch(r);const a=t.transformed(s);this.insertPrevious(n,a,i)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const i=this.branchingOperationIds.get(t);return i?{previousBranch:t,branchingOperation:t.getOperation(i)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let i=!!t;const n=e.getOperations();for(let o=n.length-1;o>=0;o--){const s=n[o];s.id===t&&(i=!1),i||(yield{operation:s,branch:e,isCancelled:!this.shouldExecute(e,s)})}const o=this.previousBranch(e);yield*o?this._revertedExecution(o):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class Fb{constructor(e,t,i,n,o){this.applyOperation=t,this.revertOperation=i,this.buildEmpty=n,this.buildTransformation=o,this.HEAD_BRANCH=new Ab(this.buildTransformation),this.tree=new _b(o,this.HEAD_BRANCH);const s=new Nb(e,n(e));this.tree.insertOperationLast(this.HEAD_BRANCH,s),this.HEAD_OPERATION=s}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const i=new Nb(e,t),n=this.tree.getLastBranch();this.tree.insertOperationLast(n,i),this.HEAD_BRANCH=n,this.HEAD_OPERATION=i}insert(e,t,i){const n=new Nb(e,t);this.revertTo(i),this.tree.insertOperationAfter(this.HEAD_BRANCH,n,i),this.fastForward()}undo(e,t,i){const{branch:n,operation:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(n,o),this.fastForward(),this.insert(t,this.buildEmpty(t),i)}redo(e,t,i){const{branch:n}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(n),this.fastForward(),this.insert(t,this.buildEmpty(t),i)}rebase(e){const t=this.get(e),i=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);const n=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,n);for(const{operation:e}of i)this.insert(e.id,e.data,this.HEAD_OPERATION.id)}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:i,isCancelled:n}of e)n||this.revertOperation(i.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:i,isCancelled:n}of e)n||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=i}}function Db(e,t,i){return new Fb(e,(e=>{const n=e.commands.slice(),{changes:o}=t((()=>{for(const e of n)i(e)}));e.setChanges(o)}),(e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){kb(t.changes[e],"before")}}([e])),(e=>new nb(e,"empty",[],[])),{with:e=>t=>new nb(t.id,t.clientId,tb(t.commands,e.commands)),without:e=>t=>new nb(t.id,t.clientId,tb(t.commands,e.commands.map(Ib).flat()))})}function kb(e,t){let i=e.path[0];const n=e.path[e.path.length-1];for(let t=1;t<e.path.slice(0,-1).length;t++){const n=e.path[t];if(void 0===i[n]){const o=e.path[t+1];i[n]=Tb(o)}i=i[n]}void 0===e[t]?delete i[n]:i[n]=e[t]}class $b extends t.EventBus{constructor(e,t){super(),this.dispatch=e,this.session=t,this.undoStack=[],this.redoStack=[],this.session.on("new-local-state-update",this,this.onNewLocalStateUpdate),this.session.on("revision-undone",this,(({commands:e})=>this.selectiveUndo(e))),this.session.on("revision-redone",this,(({commands:e})=>this.selectiveRedo(e))),this.session.on("snapshot",this,(()=>{this.undoStack=[],this.redoStack=[]}))}allowDispatch(e){switch(e.type){case"REQUEST_UNDO":if(!this.canUndo())return 6;break;case"REQUEST_REDO":if(!this.canRedo())return 7}return 0}beforeHandle(e){}handle(e){switch(e.type){case"REQUEST_UNDO":case"REQUEST_REDO":this.requestHistoryChange("REQUEST_UNDO"===e.type?"UNDO":"REDO")}}finalize(){}requestHistoryChange(e){const t="UNDO"===e?this.undoStack.pop():this.redoStack.pop();t&&("UNDO"===e?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t)))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}selectiveUndo(e){this.dispatch("UNDO",{commands:e})}selectiveRedo(e){this.dispatch("REDO",{commands:e})}}class Lb{constructor(e){this.providers=[],this.getters=e}allowDispatch(e){return"MOVE_RANGES"===e.type?1===e.target.length?0:26:0}beforeHandle(e){}handle(e){switch(e.type){case"REMOVE_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",i="COL"===e.dimension?"right":"bottom",n="COL"===e.dimension?"columns":"rows";const o=[...e.elements];o.sort(((e,t)=>t-e));const s=Le(o);this.executeOnAllRanges((o=>{if(o.sheetId!==e.sheetId)return{changeType:"NONE"};let r=o,a="NONE";for(let e of s){const s=ct(e),l=lt(e);if(o.zone[t]<=s&&s<=o.zone[i]){const e=Math.min(o.zone[i],l)-s+1;a="RESIZE",r=this.createAdaptedRange(r,n,a,-e)}else if(o.zone[t]>=s&&o.zone[i]<=l)a="REMOVE",r=o.clone({...this.getInvalidRange()});else if(o.zone[t]<=l&&o.zone[i]>=l){const e=l-o.zone[t]+1;a="RESIZE",r=this.createAdaptedRange(r,n,a,-e),r=this.createAdaptedRange(r,n,"MOVE",-(o.zone[t]-s))}else s<o.zone[t]&&(a="MOVE",r=this.createAdaptedRange(r,n,a,-(l-s+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",i="COL"===e.dimension?"right":"bottom",n="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((o=>{if(o.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(o.zone[t]<=e.base&&e.base<o.zone[i])return{changeType:"RESIZE",range:this.createAdaptedRange(o,n,"RESIZE",e.quantity)};if(e.base<o.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(o,n,"MOVE",e.quantity)}}else{if(o.zone[t]<e.base&&e.base<=o.zone[i])return{changeType:"RESIZE",range:this.createAdaptedRange(o,n,"RESIZE",e.quantity)};if(e.base<=o.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(o,n,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId!==e.sheetId)return{changeType:"NONE"};const i=this.getters.getSheetName(e.sheetId);return{changeType:"REMOVE",range:t=t.clone({...this.getInvalidRange(),invalidSheetName:i})}}),e.sheetId);break;case"RENAME_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(Ai(t.invalidSheetName,e.name)){const i=void 0,n=e.sheetId;return{changeType:"CHANGE",range:t.clone({sheetId:n,invalidSheetName:i})}}return{changeType:"NONE"}}));break;case"MOVE_RANGES":{const t=e.target[0];this.executeOnAllRanges((i=>{if(i.sheetId!==e.sheetId||!Gi(i.zone,t))return{changeType:"NONE"};const n=e.targetSheetId,o=e.col-t.left,s=e.row-t.top,r=this.createAdaptedRange(i,"both","MOVE",[o,s]),a=e.sheetId!==n||r.prefixSheet;return{changeType:"MOVE",range:r.clone({sheetId:n,prefixSheet:a})}}));break}}}finalize(){}verifyRangeRemoved(e){return t=>{const i=e(t);return"NONE"===i.changeType||Di(i.range.zone)?i:{range:i.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,i,n){const o=Ki(e.unboundedZone,t,i,n);return e.clone({zone:o})}executeOnAllRanges(e,t){const i=this.verifyRangeRemoved(e);for(const e of this.providers)e(i,t)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,i,n){const o=e.map((e=>xi.fromRange(e,this.getters)));return o.map((e=>{if(!Di(e.zone))return e;const o=e.prefixSheet?e.sheetId:n,s={...e.unboundedZone,left:e.isFullRow&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:e.isFullRow?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.isFullCol&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:i),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:i)};return(e=e.clone({sheetId:o,zone:s})).orderZone(),e}))}getRangeFromSheetXC(e,t){if(!Ot.test(t)||!this.getters.tryGetSheet(e))return new xi({sheetId:"",zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let i,n=t,o=!1;t.includes("!")&&(({xc:n,sheetName:i}=$t(t)),i&&(o=!0));const s=_i(n),r=xi.getRangeParts(n,s),a=i&&!this.getters.getSheetIdByName(i)?i:void 0,l=this.getters.getSheetIdByName(i)||e,c=new xi({prefixSheet:o,zone:s,sheetId:l,invalidSheetName:a,parts:r},this.getters.getSheetSize);return c.orderZone(),c}getSelectionRangeString(e,t){const i=xi.fromRange(e,this.getters),n=this.getters.expandZone(i.sheetId,i.zone),o=i.clone({zone:{...n,bottom:i.isFullCol?void 0:n.bottom,right:i.isFullRow?void 0:n.right}});return this.getRangeString(o,t)}getRangeString(e,t,i=!1){if(!e)return X;if(e.invalidXc)return e.invalidXc;if(!this.getters.tryGetSheet(e.sheetId))return X;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return X;if(e.zone.left<0||e.zone.top<0)return X;const n=xi.fromRange(e,this.getters);let o=n.sheetId!==t||n.invalidSheetName||n.prefixSheet,s="";if(o&&(s=n.invalidSheetName?n.invalidSheetName:Oe(this.getters.getSheetName(n.sheetId))),o&&!s)return X;let r=this.getRangePartString(n,0,i);return n.parts&&2===n.parts.length&&(n.zone.top!==n.zone.bottom||n.zone.left!==n.zone.right||n.parts[0].rowFixed||n.parts[0].colFixed||n.parts[1].rowFixed||n.parts[1].colFixed)&&(r+=":",r+=this.getRangePartString(n,1,i)),`${o?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 xi(t,this.getters.getSheetSize)}getRangePartString(e,t,i=!1){var n,o;const s=e.parts&&(null===(n=e.parts[t])||void 0===n?void 0:n.colFixed)?"$":"",r=Lt(0===t?e.zone.left:e.zone.right),a=e.parts&&(null===(o=e.parts[t])||void 0===o?void 0:o.rowFixed)?"$":"",l=String(0===t?e.zone.top+1:e.zone.bottom+1);let c="";return c=e.isFullCol&&!i?0===t&&e.unboundedZone.hasHeader?s+r+a+l:s+r:e.isFullRow&&!i?0===t&&e.unboundedZone.hasHeader?s+r+a+l:a+l:s+r+a+l,c}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:X}}}Lb.getters=["getRangeString","getSelectionRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData"];class Pb{constructor(){this.observers=[]}registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||(this.mainSubscription=this.defaultSubscription)}observe(e,t){this.observers.push({owner:e,callbacks:t})}capture(e,t){var i,n,o;if(this.observers.find((t=>t.owner===e)))throw new Error("You are already subscribed forever");(null===(i=this.mainSubscription)||void 0===i?void 0:i.owner)&&this.mainSubscription.owner!==e&&(null===(o=(n=this.mainSubscription.callbacks).release)||void 0===o||o.call(n)),this.mainSubscription={owner:e,callbacks:t}}release(e){var t;(null===(t=this.mainSubscription)||void 0===t?void 0:t.owner)!==e||this.observers.find((t=>t.owner===e))||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){var e,t,i;this.mainSubscription!==this.defaultSubscription&&(null===(i=null===(e=this.mainSubscription)||void 0===e?void 0:(t=e.callbacks).release)||void 0===i||i.call(t),this.mainSubscription=this.defaultSubscription)}isListening(e){var t;return(null===(t=this.mainSubscription)||void 0===t?void 0:t.owner)===e}send(e){var t;null===(t=this.mainSubscription)||void 0===t||t.callbacks.handleEvent(e),[...this.observers].forEach((t=>t.callbacks.handleEvent(e)))}}class Ub{constructor(e){this.getters=e,this.stream=new Pb,this.anchor={cell:{col:0,row:0},zone:en({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,i){this.stream.capture(e,i),this.anchor=t}registerAsDefault(e,t,i){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,i),this.defaultAnchor=t,this.capture(e,t,i)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}selectZone(e){const t=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(t,e.zone)},this.processEvent({type:"ZonesSelected",anchor:e,mode:"overrideSelection"})}selectCell(e,t){const i=en({col:e,row:t});return this.selectZone({zone:i,cell:{col:e,row:t}})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new fn(84);const{col:i,row:n}=this.getNextAvailablePosition(e,t);return this.selectCell(i,n)}setAnchorCorner(e,t){const i=this.getters.getActiveSheetId(),{col:n,row:o}=this.anchor.cell,s={left:Math.min(n,e),top:Math.min(o,t),right:Math.max(n,e),bottom:Math.max(o,t)},r={zone:this.getters.expandZone(i,s),cell:{col:n,row:o}};return this.processEvent({type:"AlterZoneCorner",mode:"updateAnchor",anchor:r})}addCellToSelection(e,t){const i=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition(i,e,t));const n=this.getters.expandZone(i,en({col:e,row:t}));return this.processEvent({type:"ZonesSelected",anchor:{zone:n,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new fn(84);const i=this.getters.getActiveSheetId(),n=this.anchor,{col:o,row:s}=n.cell,{left:r,right:a,top:l,bottom:c}=n.zone,h=this.getStartingPosition(e);let[d,u]=this.deltaToTarget(h,e,t);if(0===d&&0===u)return fn.Success;let g=n.zone;const p=e=>{e=Ji(e);const{left:t,right:n,top:o,bottom:s}=this.getters.expandZone(i,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(i)-1,n),top:Math.max(0,o),bottom:Math.min(this.getters.getNumberRows(i)-1,s)}},{col:m,row:f}=this.getReferencePosition();let v=0;for(;null!==g;){if(v++,d<0){const e=this.getNextAvailableCol(d,a-(v-1),f);g=m<=a-v?p({top:l,left:r,bottom:c,right:e}):null}if(d>0){const e=this.getNextAvailableCol(d,r+(v-1),f);g=r+v<=m?p({top:l,left:e,bottom:c,right:a}):null}if(u<0){const e=this.getNextAvailableRow(u,m,c-(v-1));g=f<=c-v?p({top:l,left:r,bottom:e,right:a}):null}if(u>0){const e=this.getNextAvailableRow(u,m,l+(v-1));g=l+v<=f?p({top:e,left:r,bottom:c,right:a}):null}if(g=g?Ji(g):g,g&&!Bi(g,n.zone))return this.processEvent({type:"ZonesSelected",mode:"updateAnchor",anchor:{zone:g,cell:{col:o,row:s}}})}g=p(Vi({top:s,bottom:s,left:o,right:o},Ji({top:this.getNextAvailableRow(u,m,l),left:this.getNextAvailableCol(d,r,f),bottom:this.getNextAvailableRow(u,m,c),right:this.getNextAvailableCol(d,a,f)})));const b={zone:g,cell:{col:o,row:s}};return this.processEvent({type:"ZonesSelected",anchor:b,mode:"updateAnchor"})}selectColumn(e,t){const i=this.getters.getActiveSheetId(),n=this.getters.getNumberRows(i)-1;let o={left:e,right:e,top:0,bottom:n};const s=this.getters.findFirstVisibleColRowIndex(i,"ROW");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=e,a=s;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),o=Vi(o,{left:r,right:r,top:s,bottom:n})}return this.processEvent({type:"HeadersSelected",anchor:{zone:o,cell:{col:r,row:a}},mode:t})}selectRow(e,t){const i=this.getters.getActiveSheetId(),n=this.getters.getNumberCols(i)-1;let o={top:e,bottom:e,left:0,right:n};const s=this.getters.findFirstVisibleColRowIndex(i,"COL");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=s,a=e;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),o=Vi(o,{left:s,right:n,top:a,bottom:a})}return this.processEvent({type:"HeadersSelected",anchor:{zone:o,cell:{col:r,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor,i=e=>{for(const t of $e(e.left,e.right+1)){if(!this.isCellEmpty({col:t,row:e.top-1}))return{...e,top:e.top-1};if(!this.isCellEmpty({col:t,row:e.bottom+1}))return{...e,bottom:e.bottom+1}}for(const t of $e(e.top,e.bottom+1)){if(!this.isCellEmpty({col:e.left-1,row:t}))return{...e,left:e.left-1};if(!this.isCellEmpty({col:e.right+1,row:t}))return{...e,right:e.right+1}}return e};if(Bi(this.anchor.zone,this.getters.getSheetZone(e)))return this.selectZone({...t,zone:en(t.cell)});let n=!1,o=!1,s=t.zone;do{o=o||n,n=!1;const e=i(s);Bi(s,e)||(n=!0,s=e)}while(n);return o?this.selectZone({...t,zone:s}):this.selectAll()}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:Ae(this.anchor)},i=this.checkEventAnchorZone(t);return 0!==i?new fn(i):(this.anchor=t.anchor,this.stream.send(t),fn.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:i}=e;if(!Wi(t.col,t.row,i))return 16;const{left:n,right:o,top:s,bottom:r}=i,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",n,o);return void 0===this.getters.findVisibleHeader(a,"ROW",s,r)||void 0===l?17:0}checkAnchorZoneOrThrow(e){if(16===this.checkAnchorZone(e))throw new Error(o("The provided anchor is invalid. The cell must be part of the zone."))}getNextAvailablePosition(e,t=1){const{col:i,row:n}=this.anchor.cell,o=this.deltaToTarget({col:i,row:n},e,t);return{col:this.getNextAvailableCol(o[0],i,n),row:this.getNextAvailableRow(o[1],i,n)}}getNextAvailableCol(e,t,i){const n=this.getters.getActiveSheetId(),o={col:t,row:i};return this.getNextAvailableHeader(e,"COL",t,o,(e=>this.getters.isInSameMerge(n,t,i,e,i)))}getNextAvailableRow(e,t,i){const n=this.getters.getActiveSheetId(),o={col:t,row:i};return this.getNextAvailableHeader(e,"ROW",i,o,(e=>this.getters.isInSameMerge(n,t,i,t,e)))}getNextAvailableHeader(e,t,i,n,o){const s=this.getters.getActiveSheetId();if(0===e)return i;const r=Math.sign(e);let a=i+e;for(;o(a);)a+=r;for(;this.getters.isHeaderHidden(s,t,a);)a+=r;return a<0||a>this.getters.getNumberHeaders(s,t)-1?this.getters.isHeaderHidden(s,t,i)?this.getNextAvailableHeader(-r,t,i,n,o):i:a}getReferencePosition(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:i,right:n,top:o,bottom:s}=t.zone,{col:r,row:a}=t.cell;return{col:this.getters.isColHidden(e,r)&&this.getters.findVisibleHeader(e,"COL",i,n)||r,row:this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",o,s)||a}}deltaToTarget(e,t,i){switch(t){case"up":return"end"!==i?[0,-i]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==i?[0,i]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==i?[-i,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==i?[i,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:i}=this.getPosition();const n=this.anchor.zone;switch(e){case"down":case"up":i=i===n.top?n.bottom:n.top;break;case"left":case"right":t=t===n.right?n.left:n.right}return{col:t,row:i}}getEndOfCluster(e,t,i){const n=this.getters.getActiveSheet();let o=e;const s=this.getNextCellPosition(e,t,i);let r=this.isCellEmpty(o,n.id)||this.isCellEmpty(s,n.id)?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(o,t,i);if(o.col===e.col&&o.row===e.row)break;const s=this.isCellEmpty(e,n.id);if("endOfCluster"===r&&s)break;if("nextCluster"===r&&!s){o=e;break}o=e}return"cols"===t?o.col:o.row}isCellEmpty({col:e,row:t},i=this.getters.getActiveSheetId()){const n=this.getters.getMainCellPosition(i,e,t),o=this.getters.getCell(i,n.col,n.row);return!o||o.isEmpty()}getNextCellPosition(e,t,i){const n="cols"===t?"col":"row",o={...e},s="cols"===t?this.getNextAvailableCol(i,o.col,o.row):this.getNextAvailableRow(i,o.col,o.row);return o[n]=s,{col:o.col,row:o.row}}getPosition(){return{...this.anchor.cell}}}class Vb{constructor(){this.changes=[],this.commands=[]}recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop();let i=e[0],n=e[e.length-1];const o=e.length-2;for(let t=1;t<=o;t++){const n=e[t];if(void 0===i[n]){const o=e[t+1];i[n]=Tb(o)}i=i[n]}i[n]!==t&&(this.changes.push({path:e,before:i[n],after:t}),void 0===t?delete i[n]:i[n]=t)}}const zb=17781237,Bb=88853993;function Hb(e,t,i){const n=[["xmlns:r",Qp],["xmlns:a",jp],["xmlns:c",Yp]],o=Wb({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let s=Df``;e.data.title&&(s=Df`
1997
1996
  <c:title>
1998
- ${Wb(e.data.title,e.data.fontColor)}
1997
+ ${qb(e.data.title,e.data.fontColor)}
1999
1998
  <c:overlay val="0" />
2000
1999
  </c:title>
2001
- `);let r=_f``;switch(e.data.type){case"bar":r=function(e){const t=new ws,i=[];for(const[n,o]of Object.entries(e.dataSets)){const s=ds(t.next()),r=Bb({backgroundColor:s,line:{color:s}});i.push(_f`
2000
+ `);let r=Df``;switch(e.data.type){case"bar":r=function(e){const t=new xs,i=[];for(const[n,o]of Object.entries(e.dataSets)){const s=gs(t.next()),r=Wb({backgroundColor:s,line:{color:s}});i.push(Df`
2002
2001
  <c:ser>
2003
2002
  <c:idx val="${n}"/>
2004
2003
  <c:order val="${n}"/>
2005
- ${o.label?_f`<c:tx>${jb(o.label)}</c:tx>`:""}
2004
+ ${o.label?Df`<c:tx>${Xb(o.label)}</c:tx>`:""}
2006
2005
  ${r}
2007
- ${e.labelRange?_f`<c:cat>${jb(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
2006
+ ${e.labelRange?Df`<c:cat>${Xb(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
2008
2007
  <c:val> <!-- x-coordinate values -->
2009
- ${Yb(o.range)}
2008
+ ${Kb(o.range)}
2010
2009
  </c:val>
2011
2010
  </c:ser>
2012
- `)}const n="left"===e.verticalAxisPosition?"l":"r",o=e.stacked?"stacked":"clustered",s=e.stacked?100:-20;return _f`
2011
+ `)}const n="left"===e.verticalAxisPosition?"l":"r",o=e.stacked?"stacked":"clustered",s=e.stacked?100:-20;return Df`
2013
2012
  <c:barChart>
2014
2013
  <c:barDir val="col"/>
2015
2014
  <c:grouping val="${o}"/>
@@ -2017,13 +2016,13 @@
2017
2016
  <c:gapWidth val="70"/>
2018
2017
  <!-- each data marker in the series does not have a different color -->
2019
2018
  <c:varyColors val="0"/>
2020
- ${Mf(i)}
2021
- <c:axId val="${Ub}" />
2022
- <c:axId val="${Vb}" />
2019
+ ${Ff(i)}
2020
+ <c:axId val="${zb}" />
2021
+ <c:axId val="${Bb}" />
2023
2022
  </c:barChart>
2024
- ${Zb("b","c:catAx",Ub,Vb,{fontColor:e.fontColor})}
2025
- ${Zb(n,"c:valAx",Vb,Ub,{fontColor:e.fontColor})}
2026
- `}(e.data);break;case"line":r=function(e){const t=new ws,i=[];for(const[n,o]of Object.entries(e.dataSets)){const s=Bb({line:{width:2.5,style:"solid",color:ds(t.next())}});i.push(_f`
2023
+ ${Yb("b","c:catAx",zb,Bb,{fontColor:e.fontColor})}
2024
+ ${Yb(n,"c:valAx",Bb,zb,{fontColor:e.fontColor})}
2025
+ `}(e.data);break;case"line":r=function(e){const t=new xs,i=[];for(const[n,o]of Object.entries(e.dataSets)){const s=Wb({line:{width:2.5,style:"solid",color:gs(t.next())}});i.push(Df`
2027
2026
  <c:ser>
2028
2027
  <c:idx val="${n}"/>
2029
2028
  <c:order val="${n}"/>
@@ -2032,50 +2031,50 @@
2032
2031
  <c:symbol val="circle" />
2033
2032
  <c:size val="5"/>
2034
2033
  </c:marker>
2035
- ${o.label?_f`<c:tx>${jb(o.label)}</c:tx>`:""}
2034
+ ${o.label?Df`<c:tx>${Xb(o.label)}</c:tx>`:""}
2036
2035
  ${s}
2037
- ${e.labelRange?_f`<c:cat>${jb(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
2036
+ ${e.labelRange?Df`<c:cat>${Xb(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
2038
2037
  <c:val> <!-- x-coordinate values -->
2039
- ${Yb(o.range)}
2038
+ ${Kb(o.range)}
2040
2039
  </c:val>
2041
2040
  </c:ser>
2042
- `)}const n="left"===e.verticalAxisPosition?"l":"r",o=e.stacked?"stacked":"standard";return _f`
2041
+ `)}const n="left"===e.verticalAxisPosition?"l":"r",o=e.stacked?"stacked":"standard";return Df`
2043
2042
  <c:lineChart>
2044
2043
  <c:grouping val="${o}"/>
2045
2044
  <!-- each data marker in the series does not have a different color -->
2046
2045
  <c:varyColors val="0"/>
2047
- ${Mf(i)}
2048
- <c:axId val="${Ub}" />
2049
- <c:axId val="${Vb}" />
2046
+ ${Ff(i)}
2047
+ <c:axId val="${zb}" />
2048
+ <c:axId val="${Bb}" />
2050
2049
  </c:lineChart>
2051
- ${Zb("b","c:catAx",Ub,Vb,{fontColor:e.fontColor})}
2052
- ${Zb(n,"c:valAx",Vb,Ub,{fontColor:e.fontColor})}
2053
- `}(e.data);break;case"pie":r=function(e,t,i,{holeSize:n}={holeSize:50}){const o=new ws,s=lt(e.dataSets.map((e=>ef(e.range,t,i)))),r=$e(0,s).map((()=>ds(o.next()))),a=[];for(const[n,o]of Object.entries(e.dataSets).reverse()){const s=ef(o.range,t,i),l=[];for(const e of $e(0,s)){const t=Bb({backgroundColor:r[e],line:{color:"FFFFFF",width:1.5}});l.push(_f`
2050
+ ${Yb("b","c:catAx",zb,Bb,{fontColor:e.fontColor})}
2051
+ ${Yb(n,"c:valAx",Bb,zb,{fontColor:e.fontColor})}
2052
+ `}(e.data);break;case"pie":r=function(e,t,i,{holeSize:n}={holeSize:50}){const o=new xs,s=lt(e.dataSets.map((e=>nf(e.range,t,i)))),r=$e(0,s).map((()=>gs(o.next()))),a=[];for(const[n,o]of Object.entries(e.dataSets).reverse()){const s=nf(o.range,t,i),l=[];for(const e of $e(0,s)){const t=Wb({backgroundColor:r[e],line:{color:"FFFFFF",width:1.5}});l.push(Df`
2054
2053
  <c:dPt>
2055
2054
  <c:idx val="${e}"/>
2056
2055
  ${t}
2057
2056
  </c:dPt>
2058
- `)}a.push(_f`
2057
+ `)}a.push(Df`
2059
2058
  <c:ser>
2060
2059
  <c:idx val="${n}"/>
2061
2060
  <c:order val="${n}"/>
2062
- ${o.label?_f`<c:tx>${jb(o.label)}</c:tx>`:""}
2063
- ${Mf(l)}
2064
- ${qb({showLeaderLines:!0})}
2065
- ${e.labelRange?_f`<c:cat>${jb(e.labelRange)}</c:cat>`:""}
2061
+ ${o.label?Df`<c:tx>${Xb(o.label)}</c:tx>`:""}
2062
+ ${Ff(l)}
2063
+ ${jb({showLeaderLines:!0})}
2064
+ ${e.labelRange?Df`<c:cat>${Xb(e.labelRange)}</c:cat>`:""}
2066
2065
  <c:val>
2067
- ${Yb(o.range)}
2066
+ ${Kb(o.range)}
2068
2067
  </c:val>
2069
2068
  </c:ser>
2070
- `)}return _f`
2069
+ `)}return Df`
2071
2070
  <c:doughnutChart>
2072
2071
  <c:varyColors val="1" />
2073
2072
  <c:holeSize val="${n}" />
2074
- ${qb()}
2075
- ${Mf(a)}
2073
+ ${jb()}
2074
+ ${Ff(a)}
2076
2075
  </c:doughnutChart>
2077
- `}(e.data,t,i,{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=_f`
2078
- <c:chartSpace ${Tf(n)}>
2076
+ `}(e.data,t,i,{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=Df`
2077
+ <c:chartSpace ${Nf(n)}>
2079
2078
  <c:roundedCorners val="0" />
2080
2079
  <!-- <manualLayout/> to manually position the chart in the figure container -->
2081
2080
  ${o}
@@ -2086,32 +2085,32 @@
2086
2085
  <!-- how the chart element is placed on the chart -->
2087
2086
  <c:layout />
2088
2087
  ${r}
2089
- ${Bb({backgroundColor:e.data.backgroundColor})}
2088
+ ${Wb({backgroundColor:e.data.backgroundColor})}
2090
2089
  </c:plotArea>
2091
- ${function(e,t){return _f`
2090
+ ${function(e,t){return Df`
2092
2091
  <c:legend>
2093
2092
  <c:legendPos val="${e}"/>
2094
2093
  <c:overlay val="0"/>
2095
- ${Gb(10,t)}
2094
+ ${Zb(10,t)}
2096
2095
  </c:legend>
2097
2096
  `}(a,l)}
2098
2097
  </c:chart>
2099
2098
  </c:chartSpace>
2100
- `;return Af(c)}function Bb(e){return _f`
2099
+ `;return Of(c)}function Wb(e){return Df`
2101
2100
  <c:spPr>
2102
- ${e.backgroundColor?Hb(e.backgroundColor):""}
2103
- ${e.line?function(e){const t=[["cmpd","sng"]];e.width&&t.push(["w",Jm(e.width)]);const i=e.style?_f`<a:prstDash val="${e.style}"/>`:"";return _f`
2104
- <a:ln ${Tf(t)}>
2105
- ${Hb(e.color)}
2101
+ ${e.backgroundColor?Gb(e.backgroundColor):""}
2102
+ ${e.line?function(e){const t=[["cmpd","sng"]];e.width&&t.push(["w",tf(e.width)]);const i=e.style?Df`<a:prstDash val="${e.style}"/>`:"";return Df`
2103
+ <a:ln ${Nf(t)}>
2104
+ ${Gb(e.color)}
2106
2105
  ${i}
2107
2106
  </a:ln>
2108
2107
  `}(e.line):""}
2109
2108
  </c:spPr>
2110
- `}function Hb(e){return _f`
2109
+ `}function Gb(e){return Df`
2111
2110
  <a:solidFill>
2112
2111
  <a:srgbClr val="${e}"/>
2113
2112
  </a:solidFill>
2114
- `}function Wb(e,t="000000",i=22){return _f`
2113
+ `}function qb(e,t="000000",i=22){return Df`
2115
2114
  <c:tx>
2116
2115
  <c:rich>
2117
2116
  <a:bodyPr />
@@ -2119,7 +2118,7 @@
2119
2118
  <a:p>
2120
2119
  <a:pPr lvl="0">
2121
2120
  <a:defRPr b="0">
2122
- ${Hb(t)}
2121
+ ${Gb(t)}
2123
2122
  <a:latin typeface="+mn-lt"/>
2124
2123
  </a:defRPr>
2125
2124
  </a:pPr>
@@ -2130,20 +2129,20 @@
2130
2129
  </a:p>
2131
2130
  </c:rich>
2132
2131
  </c:tx>
2133
- `}function Gb(e=12,t="000000",i=!1,n=!1){return _f`
2132
+ `}function Zb(e=12,t="000000",i=!1,n=!1){return Df`
2134
2133
  <c:txPr>
2135
2134
  <a:bodyPr/>
2136
2135
  <a:lstStyle/>
2137
2136
  <a:p>
2138
2137
  <a:pPr lvl="0">
2139
- <a:defRPr ${Tf([["b",i?"1":"0"],["i",n?"1":"0"],["sz",100*e]])}>
2140
- ${Hb(t)}
2138
+ <a:defRPr ${Nf([["b",i?"1":"0"],["i",n?"1":"0"],["sz",100*e]])}>
2139
+ ${Gb(t)}
2141
2140
  <a:latin typeface="+mn-lt"/>
2142
2141
  </a:defRPr>
2143
2142
  </a:pPr>
2144
2143
  </a:p>
2145
2144
  </c:txPr>
2146
- `}function qb({showLeaderLines:e}={showLeaderLines:!1}){return _f`
2145
+ `}function jb({showLeaderLines:e}={showLeaderLines:!1}){return Df`
2147
2146
  <dLbls>
2148
2147
  <c:showLegendKey val="0"/>
2149
2148
  <c:showVal val="0"/>
@@ -2153,7 +2152,7 @@
2153
2152
  <c:showBubbleSize val="0"/>
2154
2153
  <c:showLeaderLines val="${e?"1":"0"}"/>
2155
2154
  </dLbls>
2156
- `}function Zb(e,t,i,n,{fontColor:o}){return _f`
2155
+ `}function Yb(e,t,i,n,{fontColor:o}){return Df`
2157
2156
  <${t}>
2158
2157
  <c:axId val="${i}"/>
2159
2158
  <c:crossAx val="${n}"/> <!-- reference to the other axe of the chart -->
@@ -2162,58 +2161,58 @@
2162
2161
  <c:orientation val="minMax" />
2163
2162
  </c:scaling>
2164
2163
  <c:axPos val="${e}" />
2165
- ${function(e="B7B7B7"){return _f`
2164
+ ${function(e="B7B7B7"){return Df`
2166
2165
  <c:majorGridlines>
2167
- ${Bb({line:{color:e}})}
2166
+ ${Wb({line:{color:e}})}
2168
2167
  </c:majorGridlines>
2169
2168
  `}()}
2170
2169
  <c:majorTickMark val="out" />
2171
2170
  <c:minorTickMark val="none" />
2172
2171
  <c:numFmt formatCode="General" sourceLinked="1" />
2173
2172
  <c:title>
2174
- ${Wb("")}
2173
+ ${qb("")}
2175
2174
  </c:title>
2176
- ${Gb(10,o)}
2175
+ ${Zb(10,o)}
2177
2176
  </${t}>
2178
2177
  <!-- <tickLblPos/> omitted -->
2179
- `}function jb(e){return _f`
2178
+ `}function Xb(e){return Df`
2180
2179
  <c:strRef>
2181
2180
  <c:f>${e}</c:f>
2182
2181
  </c:strRef>
2183
- `}function Yb(e){return _f`
2182
+ `}function Kb(e){return Df`
2184
2183
  <c:numRef>
2185
2184
  <c:f>${e}</c:f>
2186
2185
  <c:numCache />
2187
2186
  </c:numRef>
2188
- `}function Xb(e){const t=e.content,i=qu.content,n=[];let o=_f``;const s=Xu(t).filter((e=>"FUNCTION"===e.type)).every((e=>i[e.value.toUpperCase()].isExported)),r=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n"}}(e.value),l=(c=e.value)===a.InvalidReference?"#REF!":c;var c;if(s){return o=_f`
2187
+ `}function Qb(e){const t=e.content,i=ju.content,n=[];let o=Df``;const s=Qu(t).filter((e=>"FUNCTION"===e.type)).every((e=>i[e.value.toUpperCase()].isExported)),r=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n"}}(e.value),l=(c=e.value)===a.InvalidReference?"#REF!":c;var c;if(s){return o=Df`
2189
2188
  <f>
2190
- ${Qb(t)}
2189
+ ${eS(t)}
2191
2190
  </f>
2192
- ${_f`<v>${l}</v>`}
2193
- `,n.push(["t",r]),{attrs:n,node:o}}if(""!==l)return n.push(["t",r]),o=_f`<v>${l}</v>`,{attrs:n,node:o}}function Kb(e,t,i=!1){let n=e;const o=[];return!i&&["TRUE","FALSE"].includes(n.trim())?(n="TRUE"===n?"1":"0",o.push(["t","b"])):!i&&Ci(n)||(n=Xm(e,t),o.push(["t","s"])),{attrs:o,node:_f`<v>${n}</v>`}}function Qb(e){let t;"="===e[0]&&(e=e.slice(1));try{t=Rg(e)}catch(t){return e}return t=Tg(t,"STRING",Jb),t=Tg(t,"FUNCALL",(e=>(e=function(e){const t=e.value.toUpperCase(),i=e.args,n=om[t];if(n){const o=qu.content[t].args.filter((e=>!e.optional)),s=o.length-e.args.length;if(s)for(let t=e.args.length;t<o.length;t++){const e=n[t-s];i.push({type:e.type,value:e.value})}}return{...e,args:i}}(e=function(e){const t=e.value.toUpperCase();return{...e,value:sm.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()})),e))),t=Tg(t,"REFERENCE",(e=>e.value===a.InvalidReference?{...e,value:"#REF!"}:e)),t?Ag(t):e}function Jb(e){const t=e.value.replace(new RegExp('"',"g"),""),i=ve(t);if(i){let n=[];return(t.match(ge)||t.match(pe))&&n.push("yyyy-mm-dd"),t.match(me)&&n.push("hh:mm:ss"),{...e,value:Qt(i.value,n.join(" "))}}return{...e,value:e.value.replace(/\\"/g,'""')}}function eS(e,t){const i=[];for(const n of t)switch(n.rule.type){case"CellIsRule":i.push(tS(n,n.rule,e));break;case"ColorScaleRule":i.push(iS(n,n.rule));break;case"IconSetRule":i.push(nS(n,n.rule));break;default:console.warn(`Conditional formatting ${n.rule.type} not implemented`)}return i}function tS(e,t,i){const n=oS(e),o=Wm(t.operator);n.push(...function(e){const t=Wm(e.operator);switch(e.operator){case"ContainsText":case"NotContains":case"BeginsWith":case"EndsWith":return[["type",t],["text",e.values[0]]];case"IsEmpty":case"IsNotEmpty":return[["type",t]];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":case"Between":case"NotBetween":return[["type","cellIs"]]}}(t),["operator",o]);const s=function(e,t){const i=e[0].split(":")[0],n=t.values;switch(t.operator){case"ContainsText":return[`NOT(ISERROR(SEARCH("${n[0]}",${i})))`];case"NotContains":return[`ISERROR(SEARCH("${n[0]}",${i}))`];case"BeginsWith":return[`LEFT(${i},LEN("${n[0]}"))="${n[0]}"`];case"EndsWith":return[`RIGHT(${i},LEN("${n[0]}"))="${n[0]}"`];case"IsEmpty":return[`LEN(TRIM(${i}))=0`];case"IsNotEmpty":return[`LEN(TRIM(${i}))>0`];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":return[n[0]];case"Between":case"NotBetween":return[n[0],n[1]]}}(e.ranges,t).map((e=>_f`<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}};return t.style.fillColor&&(r.fill={fgColor:{rgb:t.style.fillColor}}),n.push(["dxfId",Xm(r,i)]),_f`
2191
+ ${Df`<v>${l}</v>`}
2192
+ `,n.push(["t",r]),{attrs:n,node:o}}if(""!==l)return n.push(["t",r]),o=Df`<v>${l}</v>`,{attrs:n,node:o}}function Jb(e,t,i=!1){let n=e;const o=[];return!i&&["TRUE","FALSE"].includes(n.trim())?(n="TRUE"===n?"1":"0",o.push(["t","b"])):!i&&Ci(n)||(n=Qm(e,t),o.push(["t","s"])),{attrs:o,node:Df`<v>${n}</v>`}}function eS(e){let t;"="===e[0]&&(e=e.slice(1));try{t=Tg(e)}catch(t){return e}return t=Ng(t,"STRING",tS),t=Ng(t,"FUNCALL",(e=>(e=function(e){const t=e.value.toUpperCase(),i=e.args,n=rm[t];if(n){const o=ju.content[t].args.filter((e=>!e.optional)),s=o.length-e.args.length;if(s)for(let t=e.args.length;t<o.length;t++){const e=n[t-s];i.push({type:e.type,value:e.value})}}return{...e,args:i}}(e=function(e){const t=e.value.toUpperCase();return{...e,value:am.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()})),e))),t=Ng(t,"REFERENCE",(e=>e.value===a.InvalidReference?{...e,value:"#REF!"}:e)),t?Og(t):e}function tS(e){const t=e.value.replace(new RegExp('"',"g"),""),i=ve(t);if(i){let n=[];return(t.match(ge)||t.match(pe))&&n.push("yyyy-mm-dd"),t.match(me)&&n.push("hh:mm:ss"),{...e,value:Qt(i.value,n.join(" "))}}return{...e,value:e.value.replace(/\\"/g,'""')}}function iS(e,t){const i=[];for(const n of t)switch(n.rule.type){case"CellIsRule":i.push(nS(n,n.rule,e));break;case"ColorScaleRule":i.push(oS(n,n.rule));break;case"IconSetRule":i.push(sS(n,n.rule));break;default:console.warn(`Conditional formatting ${n.rule.type} not implemented`)}return i}function nS(e,t,i){const n=rS(e),o=qm(t.operator);n.push(...function(e){const t=qm(e.operator);switch(e.operator){case"ContainsText":case"NotContains":case"BeginsWith":case"EndsWith":return[["type",t],["text",e.values[0]]];case"IsEmpty":case"IsNotEmpty":return[["type",t]];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":case"Between":case"NotBetween":return[["type","cellIs"]]}}(t),["operator",o]);const s=function(e,t){const i=e[0].split(":")[0],n=t.values;switch(t.operator){case"ContainsText":return[`NOT(ISERROR(SEARCH("${n[0]}",${i})))`];case"NotContains":return[`ISERROR(SEARCH("${n[0]}",${i}))`];case"BeginsWith":return[`LEFT(${i},LEN("${n[0]}"))="${n[0]}"`];case"EndsWith":return[`RIGHT(${i},LEN("${n[0]}"))="${n[0]}"`];case"IsEmpty":return[`LEN(TRIM(${i}))=0`];case"IsNotEmpty":return[`LEN(TRIM(${i}))>0`];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":return[n[0]];case"Between":case"NotBetween":return[n[0],n[1]]}}(e.ranges,t).map((e=>Df`<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}};return t.style.fillColor&&(r.fill={fgColor:{rgb:t.style.fillColor}}),n.push(["dxfId",Qm(r,i)]),Df`
2194
2193
  <conditionalFormatting sqref="${e.ranges.join(" ")}">
2195
- <cfRule ${Tf(n)}>
2196
- ${Mf(s)}
2194
+ <cfRule ${Nf(n)}>
2195
+ ${Ff(s)}
2197
2196
  </cfRule>
2198
2197
  </conditionalFormatting>
2199
- `}function iS(e,t){const i=oS(e);i.push(["type","colorScale"]);const n=[];for(const o of e.ranges){const e=[],s=[];let r=!0;for(let i of["minimum","midpoint","maximum"]){const n=t[i];n&&("formula"!==n.type?(e.push(aS(n,i)),s.push([["rgb",ds(gt(n.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=>_f`<cfvo ${Tf(e)}/>`)),l=s.map((e=>_f`<color ${Tf(e)}/>`));n.push(_f`
2198
+ `}function oS(e,t){const i=rS(e);i.push(["type","colorScale"]);const n=[];for(const o of e.ranges){const e=[],s=[];let r=!0;for(let i of["minimum","midpoint","maximum"]){const n=t[i];n&&("formula"!==n.type?(e.push(cS(n,i)),s.push([["rgb",gs(gt(n.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=>Df`<cfvo ${Nf(e)}/>`)),l=s.map((e=>Df`<color ${Nf(e)}/>`));n.push(Df`
2200
2199
  <conditionalFormatting sqref="${o}">
2201
- <cfRule ${Tf(i)}>
2200
+ <cfRule ${Nf(i)}>
2202
2201
  <colorScale>
2203
- ${Mf(a)}
2204
- ${Mf(l)}
2202
+ ${Ff(a)}
2203
+ ${Ff(l)}
2205
2204
  </colorScale>
2206
2205
  </cfRule>
2207
2206
  </conditionalFormatting>
2208
- `)}return Mf(n)}function nS(e,t){const i=oS(e);i.push(["type","iconSet"]);const n=[];for(const s of e.ranges){const e=[[["type","percent"],["val",0]]];let r=!0;for(let i of["lowerInflectionPoint","upperInflectionPoint"]){if("formula"===t[i].type){r=!1;continue}const n=t[i];e.push([...aS(n,i),["gte","ge"===n.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 a=e.map((e=>_f`<cfvo ${Tf(e)} />`)),l=[["iconSet",(o=t.icons,Wp[rS(o)])]];sS(t.icons)&&l.push(["reverse","1"]),n.push(_f`
2207
+ `)}return Ff(n)}function sS(e,t){const i=rS(e);i.push(["type","iconSet"]);const n=[];for(const s of e.ranges){const e=[[["type","percent"],["val",0]]];let r=!0;for(let i of["lowerInflectionPoint","upperInflectionPoint"]){if("formula"===t[i].type){r=!1;continue}const n=t[i];e.push([...cS(n,i),["gte","ge"===n.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 a=e.map((e=>Df`<cfvo ${Nf(e)} />`)),l=[["iconSet",(o=t.icons,qp[lS(o)])]];aS(t.icons)&&l.push(["reverse","1"]),n.push(Df`
2209
2208
  <conditionalFormatting sqref="${s}">
2210
- <cfRule ${Tf(i)}>
2211
- <iconSet ${Tf(l)}>
2212
- ${Mf(a)}
2209
+ <cfRule ${Nf(i)}>
2210
+ <iconSet ${Nf(l)}>
2211
+ ${Ff(a)}
2213
2212
  </iconSet>
2214
2213
  </cfRule>
2215
2214
  </conditionalFormatting>
2216
- `)}var o;return Mf(n)}function oS(e){return[["priority",1],["stopIfTrue",e.stopIfTrue?1:0]]}function sS(e){const t=br[rS(e)];return e.upper===t.bad&&e.lower===t.good}function rS(e){return Object.keys(br).find((t=>Object.values(br[t]).includes(e.upper)))||"dots"}function aS(e,t){const i=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),n=[["type",i]];if("min"!==i&&"max"!==i){let t=e.value;if("formula"===i)try{t=Qb(e.value)}catch(i){t=e.value}n.push(["val",t])}return n}function lS(e,t,i){const n=[["xmlns:xdr",Gp.drawing],["xmlns:r",Xp],["xmlns:a",qp],["xmlns:c",Zp]],o=[];for(const[n,s]of Object.entries(i)){const{from:i,to:r}=cS(s,t),a=Qm(s.id),l=[["id",a],["name",`Chart ${a}`],["title","Chart"]];o.push(_f`
2215
+ `)}var o;return Ff(n)}function rS(e){return[["priority",1],["stopIfTrue",e.stopIfTrue?1:0]]}function aS(e){const t=Cr[lS(e)];return e.upper===t.bad&&e.lower===t.good}function lS(e){return Object.keys(Cr).find((t=>Object.values(Cr[t]).includes(e.upper)))||"dots"}function cS(e,t){const i=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),n=[["type",i]];if("min"!==i&&"max"!==i){let t=e.value;if("formula"===i)try{t=eS(e.value)}catch(i){t=e.value}n.push(["val",t])}return n}function hS(e,t,i){const n=[["xmlns:xdr",Zp.drawing],["xmlns:r",Qp],["xmlns:a",jp],["xmlns:c",Yp]],o=[];for(const[n,s]of Object.entries(i)){const{from:i,to:r}=dS(s,t),a=ef(s.id),l=[["id",a],["name",`Chart ${a}`],["title","Chart"]];o.push(Df`
2217
2216
  <xdr:twoCellAnchor>
2218
2217
  <xdr:from>
2219
2218
  <xdr:col>${i.col}</xdr:col>
@@ -2229,7 +2228,7 @@
2229
2228
  </xdr:to>
2230
2229
  <xdr:graphicFrame>
2231
2230
  <xdr:nvGraphicFramePr>
2232
- <xdr:cNvPr ${Tf(l)} />
2231
+ <xdr:cNvPr ${Nf(l)} />
2233
2232
  <xdr:cNvGraphicFramePr />
2234
2233
  </xdr:nvGraphicFramePr>
2235
2234
  <xdr:xfrm>
@@ -2237,78 +2236,78 @@
2237
2236
  <a:ext cx="0" cy="0"/>
2238
2237
  </xdr:xfrm>
2239
2238
  <a:graphic>
2240
- <a:graphicData uri="${Zp}">
2239
+ <a:graphicData uri="${Yp}">
2241
2240
  <c:chart r:id="${e[n]}" />
2242
2241
  </a:graphicData>
2243
2242
  </a:graphic>
2244
2243
  </xdr:graphicFrame>
2245
2244
  <xdr:clientData fLocksWithSheet="0"/>
2246
2245
  </xdr:twoCellAnchor>
2247
- `)}return Af(_f`
2248
- <xdr:wsDr ${Tf(n)}>
2249
- ${Mf(o)}
2246
+ `)}return Of(Df`
2247
+ <xdr:wsDr ${Nf(n)}>
2248
+ ${Ff(o)}
2250
2249
  </xdr:wsDr>
2251
- `)}function cS(e,t){const{x:i,y:n,height:o,width:s}=e,r=Object.values(t.cols),a=Object.values(t.rows),{index:l,offset:c}=hS(r,i),{index:h,offset:d}=hS(r,i+s),{index:u,offset:g}=hS(a,n),{index:p,offset:m}=hS(a,n+o);return{from:{col:l,colOff:c,row:u,rowOff:g},to:{col:h,colOff:d,row:p,rowOff:m}}}function hS(e,t){let i=0;for(const[n,o]of Object.entries(e)){if(i<=t&&t<i+o.size)return{index:parseInt(n),offset:Jm(t-i+H)};i+=o.size}return{index:e.length-1,offset:Jm(t-i+H)}}function dS(e){return Qe(e)?_f``:_f`
2250
+ `)}function dS(e,t){const{x:i,y:n,height:o,width:s}=e,r=Object.values(t.cols),a=Object.values(t.rows),{index:l,offset:c}=uS(r,i),{index:h,offset:d}=uS(r,i+s),{index:u,offset:g}=uS(a,n),{index:p,offset:m}=uS(a,n+o);return{from:{col:l,colOff:c,row:u,rowOff:g},to:{col:h,colOff:d,row:p,rowOff:m}}}function uS(e,t){let i=0;for(const[n,o]of Object.entries(e)){if(i<=t&&t<i+o.size)return{index:parseInt(n),offset:tf(t-i+H)};i+=o.size}return{index:e.length-1,offset:tf(t-i+H)}}function gS(e){return Qe(e)?Df``:Df`
2252
2251
  <font>
2253
- ${e.bold?_f`<b />`:""}
2254
- ${e.italic?_f`<i />`:""}
2255
- ${e.underline?_f`<u />`:""}
2256
- ${e.strike?_f`<strike />`:""}
2257
- ${e.size?_f`<sz val="${e.size}" />`:""}
2258
- ${e.color&&e.color.rgb?_f`<color rgb="${ds(e.color.rgb)}" />`:""}
2259
- ${e.name?_f`<name val="${e.name}" />`:""}
2252
+ ${e.bold?Df`<b />`:""}
2253
+ ${e.italic?Df`<i />`:""}
2254
+ ${e.underline?Df`<u />`:""}
2255
+ ${e.strike?Df`<strike />`:""}
2256
+ ${e.size?Df`<sz val="${e.size}" />`:""}
2257
+ ${e.color&&e.color.rgb?Df`<color rgb="${gs(e.color.rgb)}" />`:""}
2258
+ ${e.name?Df`<name val="${e.name}" />`:""}
2260
2259
  </font>
2261
- `}function uS(e){return e?Tf([["style",e.style],["color",ds(e.color.rgb)]]):_f``}const gS=_f`<tableStyleInfo name="TableStyleLight8" showFirstColumn="0" showLastColumn="0" showRowStripes="0" showColumnStripes="0"/>`;function pS(e,t,i){const n=_f`
2262
- <table ${Tf([["id",t],["name",`Table${t}`],["displayName",`Table${t}`],["ref",e.range],["xmlns",Gp.table],["xmlns:xr",Gp.revision],["xmlns:xr3",Gp.revision3],["xmlns:mc",Gp.markupCompatibility]])}>
2263
- ${function(e){const t=[["ref",e.range]];return _f`
2264
- <autoFilter ${Tf(t)}>
2265
- ${Mf(function(e){const t=[];for(const i of e.filters){const e=_f`
2266
- <filterColumn ${Tf([["colId",i.colId]])}>
2267
- ${mS(i)}
2260
+ `}function pS(e){return e?Nf([["style",e.style],["color",gs(e.color.rgb)]]):Df``}const mS=Df`<tableStyleInfo name="TableStyleLight8" showFirstColumn="0" showLastColumn="0" showRowStripes="0" showColumnStripes="0"/>`;function fS(e,t,i){const n=Df`
2261
+ <table ${Nf([["id",t],["name",`Table${t}`],["displayName",`Table${t}`],["ref",e.range],["xmlns",Zp.table],["xmlns:xr",Zp.revision],["xmlns:xr3",Zp.revision3],["xmlns:mc",Zp.markupCompatibility]])}>
2262
+ ${function(e){const t=[["ref",e.range]];return Df`
2263
+ <autoFilter ${Nf(t)}>
2264
+ ${Ff(function(e){const t=[];for(const i of e.filters){const e=Df`
2265
+ <filterColumn ${Nf([["colId",i.colId]])}>
2266
+ ${vS(i)}
2268
2267
  </filterColumn>
2269
2268
  `;t.push(e)}return t}(e))}
2270
2269
  </autoFilter>
2271
2270
  `}(e)}
2272
- ${function(e,t){var i;const n=Mi(e.range),o=[];for(const e of $e(0,qi(n).width)){const s=Vt(n.left+e,n.top),r=[["id",e+1],["name",(null===(i=t.cells[s])||void 0===i?void 0:i.content)||`col${e}`]];o.push(_f`<tableColumn ${Tf(r)}/>`)}return _f`
2273
- <tableColumns ${Tf([["count",o.length]])}>
2274
- ${Mf(o)}
2271
+ ${function(e,t){var i;const n=Fi(e.range),o=[];for(const e of $e(0,ji(n).width)){const s=Vt(n.left+e,n.top),r=[["id",e+1],["name",(null===(i=t.cells[s])||void 0===i?void 0:i.content)||`col${e}`]];o.push(Df`<tableColumn ${Nf(r)}/>`)}return Df`
2272
+ <tableColumns ${Nf([["count",o.length]])}>
2273
+ ${Ff(o)}
2275
2274
  </tableColumns>
2276
2275
  `}(e,i)}
2277
- ${gS}
2276
+ ${mS}
2278
2277
  </table>
2279
- `;return Af(n)}function mS(e){const t=e.displayedValues.map((e=>_f`<filter ${Tf([["val",e]])}/>`));return _f`
2280
- <filters ${Tf(e.displayBlanks?[["blank",1]]:[])}>
2281
- ${Mf(t)}
2278
+ `;return Of(n)}function vS(e){const t=e.displayedValues.map((e=>Df`<filter ${Nf([["val",e]])}/>`));return Df`
2279
+ <filters ${Nf(e.displayBlanks?[["blank",1]]:[])}>
2280
+ ${Ff(t)}
2282
2281
  </filters>
2283
- `}function fS(e){if(!Object.values(e).length)return _f``;const t=[];for(let[i,n]of Object.entries(e)){const e=[["min",parseInt(i)+1],["max",parseInt(i)+1],["width",qm(n.size||_)],["customWidth",1],["hidden",n.isHidden?1:0]];t.push(_f`
2284
- <col ${Tf(e)}/>
2285
- `)}return _f`
2282
+ `}function bS(e){if(!Object.values(e).length)return Df``;const t=[];for(let[i,n]of Object.entries(e)){const e=[["min",parseInt(i)+1],["max",parseInt(i)+1],["width",jm(n.size||_)],["customWidth",1],["hidden",n.isHidden?1:0]];t.push(Df`
2283
+ <col ${Nf(e)}/>
2284
+ `)}return Df`
2286
2285
  <cols>
2287
- ${Mf(t)}
2286
+ ${Ff(t)}
2288
2287
  </cols>
2289
- `}function vS(e,t,i){const n=[];for(let o=0;o<i.rowNumber;o++){const s=[["r",o+1]],r=i.rows[o]||{};s.push(["ht",Gm(r.size||F)],["customHeight",1],["hidden",r.isHidden?1:0]);const a=[];for(let n=0;n<i.colNumber;n++){const s=Vt(n,o),r=i.cells[s];if(r){const l=[["r",s]],c=jm(e,Zm(r,t));l.push(["s",c]);let h=[],d=_f``;if(r.isFormula){const e=Xb(r);if(!e)continue;({attrs:h,node:d}=e)}else if(r.content&&He(r.content)){const{label:t}=Ge(r.content);({attrs:h,node:d}=Kb(t,e.sharedStrings))}else if(r.content&&""!==r.content){const t=bS(n,o,i);({attrs:h,node:d}=Kb(r.content,e.sharedStrings,t))}l.push(...h),a.push(_f`<c ${Tf(l)}>
2288
+ `}function SS(e,t,i){const n=[];for(let o=0;o<i.rowNumber;o++){const s=[["r",o+1]],r=i.rows[o]||{};s.push(["ht",Zm(r.size||F)],["customHeight",1],["hidden",r.isHidden?1:0]);const a=[];for(let n=0;n<i.colNumber;n++){const s=Vt(n,o),r=i.cells[s];if(r){const l=[["r",s]],c=Xm(e,Ym(r,t));l.push(["s",c]);let h=[],d=Df``;if(r.isFormula){const e=Qb(r);if(!e)continue;({attrs:h,node:d}=e)}else if(r.content&&He(r.content)){const{label:t}=Ge(r.content);({attrs:h,node:d}=Jb(t,e.sharedStrings))}else if(r.content&&""!==r.content){const t=CS(n,o,i);({attrs:h,node:d}=Jb(r.content,e.sharedStrings,t))}l.push(...h),a.push(Df`<c ${Nf(l)}>
2290
2289
  ${d}
2291
- </c>`)}}(a.length||r.size!==F||r.isHidden)&&n.push(_f`
2292
- <row ${Tf(s)}>
2293
- ${Mf(a)}
2290
+ </c>`)}}(a.length||r.size!==F||r.isHidden)&&n.push(Df`
2291
+ <row ${Nf(s)}>
2292
+ ${Ff(a)}
2294
2293
  </row>
2295
- `)}return _f`
2294
+ `)}return Df`
2296
2295
  <sheetData>
2297
- ${Mf(n)}
2296
+ ${Ff(n)}
2298
2297
  </sheetData>
2299
- `}function bS(e,t,i){return i.filterTables.some((i=>{const n=Mi(i.range),o={...n,bottom:n.top};return Bi(e,t,o)}))}function SS(e,t,i){var n;const o=t.sheets[i].cells,s=[];for(const r in o){const a=null===(n=o[r])||void 0===n?void 0:n.content;if(a&&He(a)){const{label:n,url:o}=Ge(a);if(Ze(a)){const e=Ye(o),i=t.sheets.find((t=>t.id===e)),a=i?`${i.name}!A1`:X;s.push(_f`
2298
+ `}function CS(e,t,i){return i.filterTables.some((i=>{const n=Fi(i.range),o={...n,bottom:n.top};return Wi(e,t,o)}))}function ES(e,t,i){var n;const o=t.sheets[i].cells,s=[];for(const r in o){const a=null===(n=o[r])||void 0===n?void 0:n.content;if(a&&He(a)){const{label:n,url:o}=Ge(a);if(Ze(a)){const e=Ye(o),i=t.sheets.find((t=>t.id===e)),a=i?`${i.name}!A1`:X;s.push(Df`
2300
2299
  <hyperlink display="${n}" location="${a}" ref="${r}"/>
2301
- `)}else{const t=Ym(e.relsFiles,`xl/worksheets/_rels/sheet${i}.xml.rels`,{target:o,type:Yp.hyperlink,targetMode:"External"});s.push(_f`
2300
+ `)}else{const t=Km(e.relsFiles,`xl/worksheets/_rels/sheet${i}.xml.rels`,{target:o,type:Kp.hyperlink,targetMode:"External"});s.push(Df`
2302
2301
  <hyperlink r:id="${t}" ref="${r}"/>
2303
- `)}}}return s.length?_f`
2302
+ `)}}}return s.length?Df`
2304
2303
  <hyperlinks>
2305
- ${Mf(s)}
2304
+ ${Ff(s)}
2306
2305
  </hyperlinks>
2307
- `:_f``}function CS(e){if(e.length){const t=e.map((e=>_f`<mergeCell ref="${e}" />`));return _f`
2306
+ `:Df``}function wS(e){if(e.length){const t=e.map((e=>Df`<mergeCell ref="${e}" />`));return Df`
2308
2307
  <mergeCells count="${e.length}">
2309
- ${Mf(t)}
2308
+ ${Ff(t)}
2310
2309
  </mergeCells>
2311
- `}return _f``}function ES(e){const t=e.panes;let i=_f``;if(t&&(t.xSplit||t.ySplit)){const e=Vt(t.xSplit,t.ySplit),n=t.xSplit?_f`xSplit="${t.xSplit}"`:"",o=t.ySplit?_f`ySplit="${t.ySplit}"`:"",s=t.xSplit?_f`<selection pane="topRight"/>`:"",r=t.ySplit?_f`<selection pane="bottomLeft"/>`:"",a=t.xSplit&&t.ySplit?_f`<selection pane="bottomRight"/>`:"";i=_f`
2310
+ `}return Df``}function yS(e){const t=e.panes;let i=Df``;if(t&&(t.xSplit||t.ySplit)){const e=Vt(t.xSplit,t.ySplit),n=t.xSplit?Df`xSplit="${t.xSplit}"`:"",o=t.ySplit?Df`ySplit="${t.ySplit}"`:"",s=t.xSplit?Df`<selection pane="topRight"/>`:"",r=t.ySplit?Df`<selection pane="bottomLeft"/>`:"",a=t.xSplit&&t.ySplit?Df`<selection pane="bottomRight"/>`:"";i=Df`
2312
2311
  <pane
2313
2312
  ${n}
2314
2313
  ${o}
@@ -2318,123 +2317,123 @@
2318
2317
  ${s}
2319
2318
  ${r}
2320
2319
  ${a}
2321
- `}return _f`
2320
+ `}return Df`
2322
2321
  <sheetViews>
2323
2322
  <sheetView showGridLines="${e.areGridLinesVisible?1:0}" workbookViewId="0">
2324
2323
  ${i}
2325
2324
  </sheetView>
2326
2325
  </sheetViews>
2327
- `}function wS(e){const t=[],i=function(e){const t=[{},...Object.values(e.borders).map((e=>({left:Of(e.left),right:Of(e.right),bottom:Of(e.bottom),top:Of(e.top)})))];return{relsFiles:[],sharedStrings:[],styles:[{fontId:0,fillId:0,numFmtId:0,borderId:0,alignment:{vertical:"center"}}],fonts:[{size:G,family:2,color:{rgb:"000000"},name:"Calibri"}],fills:[{reservedAttribute:"none"},{reservedAttribute:"gray125"}],borders:t,numFmts:[],dxfs:[]}}(e);return t.push(function(e,t){const i=[["xmlns",Gp.workbook],["xmlns:r",Xp]],n=[];for(const[i,o]of Object.entries(e.sheets)){const e=[["state",o.isVisible?"visible":"hidden"],["name",o.name],["sheetId",parseInt(i)+1],["r:id",`rId${parseInt(i)+1}`]];n.push(_f`
2328
- <sheet ${Tf(e)} />
2329
- `),Ym(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Yp.sheet,target:`worksheets/sheet${i}.xml`})}return Rf(Af(_f`
2330
- <workbook ${Tf(i)}>
2326
+ `}function xS(e){const t=[],i=function(e){const t=[{},...Object.values(e.borders).map((e=>({left:Mf(e.left),right:Mf(e.right),bottom:Mf(e.bottom),top:Mf(e.top)})))];return{relsFiles:[],sharedStrings:[],styles:[{fontId:0,fillId:0,numFmtId:0,borderId:0,alignment:{vertical:"center"}}],fonts:[{size:G,family:2,color:{rgb:"000000"},name:"Calibri"}],fills:[{reservedAttribute:"none"},{reservedAttribute:"gray125"}],borders:t,numFmts:[],dxfs:[]}}(e);return t.push(function(e,t){const i=[["xmlns",Zp.workbook],["xmlns:r",Qp]],n=[];for(const[i,o]of Object.entries(e.sheets)){const e=[["state",o.isVisible?"visible":"hidden"],["name",o.name],["sheetId",parseInt(i)+1],["r:id",`rId${parseInt(i)+1}`]];n.push(Df`
2327
+ <sheet ${Nf(e)} />
2328
+ `),Km(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Kp.sheet,target:`worksheets/sheet${i}.xml`})}return Tf(Of(Df`
2329
+ <workbook ${Nf(i)}>
2331
2330
  <sheets>
2332
- ${Mf(n)}
2331
+ ${Ff(n)}
2333
2332
  </sheets>
2334
2333
  </workbook>
2335
- `),"xl/workbook.xml","workbook")}(e,i)),t.push(...function(e,t){const i=[];let n=1;for(const[o,s]of Object.entries(e.sheets)){const r=[["xmlns",Gp.worksheet],["xmlns:r",Xp]],a=[["defaultRowHeight",Gm(F)],["defaultColWidth",qm(_)]],l=yS(s,o,n,t,i);n+=s.filterTables.length;let c=_f``;const h=s.charts;if(h.length){const n=[];for(const s of h){const r=Qm(s.id),a=Ym(t.relsFiles,`xl/drawings/_rels/drawing${o}.xml.rels`,{target:`../charts/chart${r}.xml`,type:Yp.chart});n.push(a),i.push(Rf(zb(s,o,e),`xl/charts/chart${r}.xml`,"chart"))}const r=Ym(t.relsFiles,`xl/worksheets/_rels/sheet${o}.xml.rels`,{target:`../drawings/drawing${o}.xml`,type:Yp.drawing});i.push(Rf(lS(n,s,h),`xl/drawings/drawing${o}.xml`,"drawing")),c=_f`<drawing r:id="${r}" />`}const d=_f`
2336
- <worksheet ${Tf(r)}>
2337
- ${ES(s)}
2338
- <sheetFormatPr ${Tf(a)} />
2339
- ${fS(s.cols)}
2340
- ${vS(t,e,s)}
2341
- ${CS(s.merges)}
2342
- ${Mf(eS(t.dxfs,s.conditionalFormats))}
2343
- ${SS(t,e,o)}
2334
+ `),"xl/workbook.xml","workbook")}(e,i)),t.push(...function(e,t){const i=[];let n=1;for(const[o,s]of Object.entries(e.sheets)){const r=[["xmlns",Zp.worksheet],["xmlns:r",Qp]],a=[["defaultRowHeight",Zm(F)],["defaultColWidth",jm(_)]],l=RS(s,o,n,t,i);n+=s.filterTables.length;let c=Df``;const h=s.charts;if(h.length){const n=[];for(const s of h){const r=ef(s.id),a=Km(t.relsFiles,`xl/drawings/_rels/drawing${o}.xml.rels`,{target:`../charts/chart${r}.xml`,type:Kp.chart});n.push(a),i.push(Tf(Hb(s,o,e),`xl/charts/chart${r}.xml`,"chart"))}const r=Km(t.relsFiles,`xl/worksheets/_rels/sheet${o}.xml.rels`,{target:`../drawings/drawing${o}.xml`,type:Kp.drawing});i.push(Tf(hS(n,s,h),`xl/drawings/drawing${o}.xml`,"drawing")),c=Df`<drawing r:id="${r}" />`}const d=Df`
2335
+ <worksheet ${Nf(r)}>
2336
+ ${yS(s)}
2337
+ <sheetFormatPr ${Nf(a)} />
2338
+ ${bS(s.cols)}
2339
+ ${SS(t,e,s)}
2340
+ ${wS(s.merges)}
2341
+ ${Ff(iS(t.dxfs,s.conditionalFormats))}
2342
+ ${ES(t,e,o)}
2344
2343
  ${c}
2345
2344
  ${l}
2346
2345
  </worksheet>
2347
- `;i.push(Rf(Af(d),`xl/worksheets/sheet${o}.xml`,"sheet"))}return Ym(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Yp.sharedStrings,target:"sharedStrings.xml"}),Ym(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Yp.styles,target:"styles.xml"}),i}(e,i)),t.push(function(e){const t=_f`
2348
- <styleSheet ${Tf([["xmlns",Gp.styleSheet],["xmlns:r",Xp]])}>
2349
- ${function(e){const t=[];for(let[i,n]of Object.entries(e)){const e=[["numFmtId",parseInt(i)+nm],["formatCode",n.format]];t.push(_f`
2350
- <numFmt ${Tf(e)}/>
2351
- `)}return _f`
2346
+ `;i.push(Tf(Of(d),`xl/worksheets/sheet${o}.xml`,"sheet"))}return Km(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Kp.sharedStrings,target:"sharedStrings.xml"}),Km(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Kp.styles,target:"styles.xml"}),i}(e,i)),t.push(function(e){const t=Df`
2347
+ <styleSheet ${Nf([["xmlns",Zp.styleSheet],["xmlns:r",Qp]])}>
2348
+ ${function(e){const t=[];for(let[i,n]of Object.entries(e)){const e=[["numFmtId",parseInt(i)+sm],["formatCode",n.format]];t.push(Df`
2349
+ <numFmt ${Nf(e)}/>
2350
+ `)}return Df`
2352
2351
  <numFmts count="${e.length}">
2353
- ${Mf(t)}
2352
+ ${Ff(t)}
2354
2353
  </numFmts>
2355
2354
  `}(e.numFmts)}
2356
- ${i=e.fonts,_f`
2355
+ ${i=e.fonts,Df`
2357
2356
  <fonts count="${i.length}">
2358
- ${Mf(Object.values(i).map(dS))}
2357
+ ${Ff(Object.values(i).map(gS))}
2359
2358
  </fonts>
2360
2359
  `}
2361
- ${function(e){const t=[];for(let i of Object.values(e))void 0!==i.reservedAttribute?t.push(_f`
2360
+ ${function(e){const t=[];for(let i of Object.values(e))void 0!==i.reservedAttribute?t.push(Df`
2362
2361
  <fill>
2363
2362
  <patternFill patternType="${i.reservedAttribute}" />
2364
2363
  </fill>
2365
- `):t.push(_f`
2364
+ `):t.push(Df`
2366
2365
  <fill>
2367
2366
  <patternFill patternType="solid">
2368
- <fgColor rgb="${ds(i.fgColor.rgb)}" />
2367
+ <fgColor rgb="${gs(i.fgColor.rgb)}" />
2369
2368
  <bgColor indexed="64" />
2370
2369
  </patternFill>
2371
2370
  </fill>
2372
- `);return _f`
2371
+ `);return Df`
2373
2372
  <fills count="${e.length}">
2374
- ${Mf(t)}
2373
+ ${Ff(t)}
2375
2374
  </fills>
2376
2375
  `}(e.fills)}
2377
- ${function(e){const t=[];for(let i of Object.values(e))t.push(_f`
2376
+ ${function(e){const t=[];for(let i of Object.values(e))t.push(Df`
2378
2377
  <border>
2379
- <left ${uS(i.left)} />
2380
- <right ${uS(i.right)} />
2381
- <top ${uS(i.top)} />
2382
- <bottom ${uS(i.bottom)} />
2383
- <diagonal ${uS(i.diagonal)} />
2378
+ <left ${pS(i.left)} />
2379
+ <right ${pS(i.right)} />
2380
+ <top ${pS(i.top)} />
2381
+ <bottom ${pS(i.bottom)} />
2382
+ <diagonal ${pS(i.diagonal)} />
2384
2383
  </border>
2385
- `);return _f`
2384
+ `);return Df`
2386
2385
  <borders count="${e.length}">
2387
- ${Mf(t)}
2386
+ ${Ff(t)}
2388
2387
  </borders>
2389
2388
  `}(e.borders)}
2390
- ${function(e){const t=[];for(let i of e){const e=[["numFmtId",i.numFmtId],["fillId",i.fillId],["fontId",i.fontId],["borderId",i.borderId]],n=[];i.alignment&&i.alignment.vertical&&n.push(["vertical",i.alignment.vertical]),i.alignment&&i.alignment.horizontal&&n.push(["horizontal",i.alignment.horizontal]),t.push(_f`
2391
- <xf ${Tf(e)}>
2392
- ${n?_f`<alignment ${Tf(n)} />`:""}
2389
+ ${function(e){const t=[];for(let i of e){const e=[["numFmtId",i.numFmtId],["fillId",i.fillId],["fontId",i.fontId],["borderId",i.borderId]],n=[];i.alignment&&i.alignment.vertical&&n.push(["vertical",i.alignment.vertical]),i.alignment&&i.alignment.horizontal&&n.push(["horizontal",i.alignment.horizontal]),t.push(Df`
2390
+ <xf ${Nf(e)}>
2391
+ ${n?Df`<alignment ${Nf(n)} />`:""}
2393
2392
  </xf>
2394
- `)}return _f`
2393
+ `)}return Df`
2395
2394
  <cellXfs count="${e.length}">
2396
- ${Mf(t)}
2395
+ ${Ff(t)}
2397
2396
  </cellXfs>
2398
2397
  `}(e.styles)}
2399
- ${function(e){const t=[];for(const i of e){let e=_f``;i.font&&(e=dS(i.font));let n=_f``;i.fill&&(n=_f`
2398
+ ${function(e){const t=[];for(const i of e){let e=Df``;i.font&&(e=gS(i.font));let n=Df``;i.fill&&(n=Df`
2400
2399
  <fill>
2401
2400
  <patternFill>
2402
- <bgColor rgb="${ds(i.fill.fgColor.rgb)}" />
2401
+ <bgColor rgb="${gs(i.fill.fgColor.rgb)}" />
2403
2402
  </patternFill>
2404
2403
  </fill>
2405
- `),t.push(_f`
2404
+ `),t.push(Df`
2406
2405
  <dxf>
2407
2406
  ${e}
2408
2407
  ${n}
2409
2408
  </dxf>
2410
- `)}return _f`
2409
+ `)}return Df`
2411
2410
  <dxfs count="${e.length}">
2412
- ${Mf(t)}
2411
+ ${Ff(t)}
2413
2412
  </dxfs>
2414
2413
  `}(e.dxfs)}
2415
2414
  </styleSheet>
2416
- `;var i;return Rf(Af(t),"xl/styles.xml","styles")}(i)),t.push(function(e){const t=[["xmlns",Gp.sst],["count",e.length],["uniqueCount",e.length]],i=e.map((e=>_f`<si><t>${e}</t></si>`));return Rf(Af(_f`
2417
- <sst ${Tf(t)}>
2418
- ${Mf(i)}
2415
+ `;var i;return Tf(Of(t),"xl/styles.xml","styles")}(i)),t.push(function(e){const t=[["xmlns",Zp.sst],["count",e.length],["uniqueCount",e.length]],i=e.map((e=>Df`<si><t>${e}</t></si>`));return Tf(Of(Df`
2416
+ <sst ${Nf(t)}>
2417
+ ${Ff(i)}
2419
2418
  </sst>
2420
- `),"xl/sharedStrings.xml","sharedStrings")}(i.sharedStrings)),t.push(...function(e){const t=[];for(const i of e){const e=[];for(const t of i.rels){const i=[["Id",t.id],["Target",t.target],["Type",t.type]];t.targetMode&&i.push(["TargetMode",t.targetMode]),e.push(_f`
2421
- <Relationship ${Tf(i)} />
2422
- `)}const n=_f`
2423
- <Relationships xmlns="${Gp.Relationships}">
2424
- ${Mf(e)}
2419
+ `),"xl/sharedStrings.xml","sharedStrings")}(i.sharedStrings)),t.push(...function(e){const t=[];for(const i of e){const e=[];for(const t of i.rels){const i=[["Id",t.id],["Target",t.target],["Type",t.type]];t.targetMode&&i.push(["TargetMode",t.targetMode]),e.push(Df`
2420
+ <Relationship ${Nf(i)} />
2421
+ `)}const n=Df`
2422
+ <Relationships xmlns="${Zp.Relationships}">
2423
+ ${Ff(e)}
2425
2424
  </Relationships>
2426
- `;t.push(Rf(Af(n),i.path))}return t}(i.relsFiles)),t.push(function(e){const t=[];for(const i of e)i.contentType&&t.push(Nf("/"+i.path,jp[i.contentType]));return Rf(Af(_f`
2427
- <Types xmlns="${Gp.Types}">
2425
+ `;t.push(Tf(Of(n),i.path))}return t}(i.relsFiles)),t.push(function(e){const t=[];for(const i of e)i.contentType&&t.push(_f("/"+i.path,Xp[i.contentType]));return Tf(Of(Df`
2426
+ <Types xmlns="${Zp.Types}">
2428
2427
  <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />
2429
2428
  <Default Extension="xml" ContentType="application/xml" />
2430
- ${Mf(t)}
2429
+ ${Ff(t)}
2431
2430
  </Types>
2432
- `),"[Content_Types].xml")}(t)),t.push(function(){const e=[["Id","rId1"],["Type",Yp.document],["Target","xl/workbook.xml"]];return Rf(Af(_f`
2433
- <Relationships xmlns="${Gp.Relationships}">
2434
- <Relationship ${Tf(e)} />
2431
+ `),"[Content_Types].xml")}(t)),t.push(function(){const e=[["Id","rId1"],["Type",Kp.document],["Target","xl/workbook.xml"]];return Tf(Of(Df`
2432
+ <Relationships xmlns="${Zp.Relationships}">
2433
+ <Relationship ${Nf(e)} />
2435
2434
  </Relationships>
2436
- `),"_rels/.rels")}()),{name:"my_spreadsheet.xlsx",files:t}}function yS(e,t,i,n,o){let s=i;if(!e.filterTables.length)return new zp("");const r=`xl/worksheets/_rels/sheet${t}.xml.rels`,a=[];for(const t of e.filterTables){const i=Ym(n.relsFiles,r,{target:`../tables/table${s}.xml`,type:Yp.table});o.push(Rf(pS(t,s,e),`xl/tables/table${s}.xml`,"table")),a.push(_f`<tablePart r:id="${i}" />`),s++}return _f`
2435
+ `),"_rels/.rels")}()),{name:"my_spreadsheet.xlsx",files:t}}function RS(e,t,i,n,o){let s=i;if(!e.filterTables.length)return new Hp("");const r=`xl/worksheets/_rels/sheet${t}.xml.rels`,a=[];for(const t of e.filterTables){const i=Km(n.relsFiles,r,{target:`../tables/table${s}.xml`,type:Kp.table});o.push(Tf(fS(t,s,e),`xl/tables/table${s}.xml`,"table")),a.push(Df`<tablePart r:id="${i}" />`),s++}return Df`
2437
2436
  <tableParts count="${e.filterTables.length}">
2438
- ${Mf(a)}
2437
+ ${Ff(a)}
2439
2438
  </tableParts>
2440
- `}var xS;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(xS||(xS={}));const RS={},IS={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:N,HEADER_WIDTH:M,TOPBAR_HEIGHT:63,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:_,DEFAULT_CELL_HEIGHT:F,SCROLLBAR_WIDTH:D},TS={autofillModifiersRegistry:an,autofillRulesRegistry:Sn,cellMenuRegistry:qo,colMenuRegistry:Zo,linkMenuRegistry:Xn,functionRegistry:qu,uiPluginRegistry:ub,corePluginRegistry:db,rowMenuRegistry:jo,sidePanelRegistry:yr,figureRegistry:io,sheetMenuRegistry:Xo,chartSidePanelComponentRegistry:pr,chartComponentRegistry:sn,chartRegistry:on,topbarMenuRegistry:os,topbarComponentRegistry:xr,clickableCellRegistry:gb,otRegistry:ss,inverseCommandRegistry:no,cellRegistry:eo,cellPopoverRegistry:Jn},AS={LinkCell:kp},OS={args:Lr,toBoolean:Yr,toJsDate:Xr,toNumber:Hr,toString:Gr,toXC:Vt,toZone:Mi,toCartesian:Ut,numberToLetters:Lt,createFullMenuItem:Zn,UuidGenerator:Oi,formatValue:Qt,computeTextWidth:_e,isMarkdownLink:He,parseMarkdownLink:Ge,markdownLink:We,createEmptyWorkbookData:nv,createEmptySheet:iv,createEmptyExcelSheet:ov,getDefaultChartJsRuntime:_s,chartFontColor:ys,getMenuChildren:Mn,ChartColors:ws,EvaluationError:c,CellErrorLevel:l,getFillingMode:ks,rgbaToHex:Ct,colorToRGBA:Et,positionToZone:Qi,deepEquals:ot},NS={ChartPanel:mr,ChartFigure:Or,ChartJsComponent:rn,Grid:Ap,GridOverlay:up,ScorecardChart:Ir,LineConfigPanel:hr,LineBarPieDesignPanel:rr,BarConfigPanel:cs,LineBarPieConfigPanel:ls,GaugeChartConfigPanel:lr,GaugeChartDesignPanel:cr,ScorecardChartConfigPanel:ur,ScorecardChartDesignPanel:gr};e.AbstractChart=hs,e.CorePlugin=sv,e.DATETIME_FORMAT=Y,e.DispatchResult=pn,e.EvaluationError=c,e.Model=class extends jv{constructor(e={},i={},n=[],o=new Oi,s=!0){super(),this.corePlugins=[],this.uiPlugins=[],this.isReplayingCommand=!1,this.renderers=[],this.status=0,this.handlers=[],this.coreHandlers=[],this.dispatch=(e,t)=>{const i={type:e,...t};let n=this.status;if(this.getters.isReadonly()&&(o=i,!dn.has(o.type)))return new pn(68);var o;if(!this.session.canApplyOptimisticUpdate())return new pn(65);switch(n){case 0:const t=this.checkDispatchAllowed(i);if(!t.isSuccessful)return t;this.status=1;const{changes:n,commands:o}=this.state.recordChanges((()=>{gn(i)&&this.state.addCommand(i),this.dispatchToHandlers(this.handlers,i),this.finalize()}));this.session.save(o,n),this.status=0,this.trigger("update");break;case 1:if(gn(i)){const e=this.checkDispatchAllowed(i);if(!e.isSuccessful)return e;this.state.addCommand(i),this.dispatchToHandlers(this.handlers,i)}else this.dispatchToHandlers(this.handlers,i);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(gn(i))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,i)}return pn.Success},this.dispatchFromCorePlugin=(e,t)=>{const i={type:e,...t},n=this.status;this.status=2;const o=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(o,i),this.status=n,pn.Success},n=ev(e,n);const r=Qf(e,s);this.state=new Pb,this.uuidGenerator=o,this.config=this.setupConfig(i),this.session=this.setupSession(r.revisionId),this.config.moveClient=this.session.move.bind(this.session),this.history=new Db(this.dispatchFromCorePlugin,this.session),this.coreGetters={},this.range=new kb(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getSelectionRangeString=this.range.getSelectionRangeString.bind(this.range),this.getters={isReadonly:()=>"readonly"===this.config.mode||"dashboard"===this.config.mode,isDashboard:()=>"dashboard"===this.config.mode,canUndo:this.history.canUndo.bind(this.history),canRedo:this.history.canRedo.bind(this.history),getClient:this.session.getClient.bind(this.session),getConnectedClients:this.session.getConnectedClients.bind(this.session),isFullySynchronized:this.session.isFullySynchronized.bind(this.session)},this.uuidGenerator.setIsFastStrategy(!0),this.selection=new Lb(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range);for(let e of db.getAll())this.setupCorePlugin(e,r);Object.assign(this.getters,this.coreGetters);for(let e of ub.getAll())this.setupUiPlugin(e);this.uuidGenerator.setIsFastStrategy(!1),this.handlers.push(this.history),this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.isLoading=!0,this.setupSessionEvents(),this.session.loadInitialMessages(n),this.joinSession(),i.snapshotRequested&&this.session.snapshot(this.exportData()),t.markRaw(this),this.isLoading=!1,this.finalize()}joinSession(){this.session.join(this.config.client)}leaveSession(){this.session.leave()}setupUiPlugin(e){const t=new e(this.getters,this.state,this.dispatch,this.config,this.selection);for(let i of e.getters){if(!(i in t))throw new Error(`Invalid getter name: ${i} for plugin ${t.constructor}`);if(i in this.getters)throw new Error(`Getter "${i}" is already defined.`);this.getters[i]=t[i].bind(t)}this.uiPlugins.push(t),this.handlers.push(t);const i=e.layers.map((e=>[t,e]));this.renderers.push(...i),this.renderers.sort(((e,t)=>e[1]-t[1]))}setupCorePlugin(e,t){const i=new e(this.coreGetters,this.state,this.range,this.dispatchFromCorePlugin,this.config,this.uuidGenerator);for(let t of e.getters){if(!(t in i))throw new Error(`Invalid getter name: ${t} for plugin ${i.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=i[t].bind(i)}i.import(t),this.corePlugins.push(i),this.coreHandlers.push(i),this.handlers.push(i)}onRemoteRevisionReceived({commands:e}){for(let t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.uiPlugins,t),this.status=e}this.finalize()}setupSession(e){return new nb(_b(e,this.state.recordChanges.bind(this.state),(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-redone",this,this.finalize),this.session.on("revision-undone",this,this.finalize),this.session.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.session.on("collaborative-event-received",this,(()=>{this.trigger("update")}))}setupConfig(e){const t=e.client||{id:this.uuidGenerator.smallUuid(),name:s("Anonymous").toString()},i=e.transportService||new yb;return{...e,mode:e.mode||"normal",evalContext:e.evalContext||{},transportService:i,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e)}}checkDispatchAllowed(e){const t=this.handlers.map((t=>t.allowDispatch(e)));return t.some((e=>0!==e))?new pn(t.flat()):pn.Success}finalize(){if(!this.isLoading){this.status=3;for(const e of this.handlers)e.finalize();this.status=0}}dispatchToHandlers(e,t){t=Ae(t);for(const i of e)i.beforeHandle(t);for(const i of e)i.handle(t)}drawGrid(e){for(let[t,i]of this.renderers)e.ctx.save(),t.drawGrid(e,i),e.ctx.restore()}exportData(){let e=nv();for(let t of this.handlers)t instanceof sv&&t.export(e);return e.revisionId=this.session.getRevisionId()||K,e=Ae(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={...nv(),sheets:[ov(Kf,"Sheet1")]};for(let t of this.handlers)t instanceof zg&&t.exportForExcel(e);return e=Ae(e),wS(e)}},e.Registry=nn,e.Revision=tb,e.SPREADSHEET_DIMENSIONS=IS,e.Spreadsheet=wb,e.UIPlugin=Bg,e.__info__=RS,e.addFunction=function(e,t){qu.add(e,t)},e.astToFormula=Ag,e.cellTypes=AS,e.compile=$g,e.components=NS,e.convertAstNodes=Tg,e.coreTypes=un,e.findCellInNewZone=Xi,e.functionCache=kg,e.helpers=OS,e.invalidateEvaluationCommands=cn,e.load=Qf,e.parse=Rg,e.readonlyAllowedCommands=dn,e.registries=TS,e.setTranslationMethod=function(e){i=e},e.tokenize=Xu,Object.defineProperty(e,"__esModule",{value:!0}),RS.version="16.0.68",RS.date="2025-04-25T08:02:52.716Z",RS.hash="682d48e"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
2439
+ `}var IS;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(IS||(IS={}));const TS={},AS={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:O,HEADER_WIDTH:M,TOPBAR_HEIGHT:63,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:_,DEFAULT_CELL_HEIGHT:F,SCROLLBAR_WIDTH:D},NS={autofillModifiersRegistry:cn,autofillRulesRegistry:En,cellMenuRegistry:jo,colMenuRegistry:Yo,linkMenuRegistry:Qn,functionRegistry:ju,uiPluginRegistry:pb,corePluginRegistry:gb,rowMenuRegistry:Xo,sidePanelRegistry:Rr,figureRegistry:oo,sheetMenuRegistry:Qo,chartSidePanelComponentRegistry:fr,chartComponentRegistry:an,chartRegistry:rn,topbarMenuRegistry:rs,topbarComponentRegistry:Ir,clickableCellRegistry:mb,otRegistry:as,inverseCommandRegistry:so,cellRegistry:io,cellPopoverRegistry:to},OS={LinkCell:Lp},MS={args:Ur,toBoolean:Kr,toJsDate:Qr,toNumber:Gr,toString:Zr,toXC:Vt,toZone:Fi,toCartesian:Ut,numberToLetters:Lt,createFullMenuItem:Yn,UuidGenerator:Mi,formatValue:Qt,computeTextWidth:_e,isMarkdownLink:He,parseMarkdownLink:Ge,markdownLink:We,createEmptyWorkbookData:sv,createEmptySheet:ov,createEmptyExcelSheet:rv,getDefaultChartJsRuntime:Ds,chartFontColor:Rs,getMenuChildren:Fn,ChartColors:xs,EvaluationError:c,CellErrorLevel:l,getFillingMode:Ls,rgbaToHex:Ct,colorToRGBA:Et,positionToZone:en,deepEquals:ot},_S={ChartPanel:vr,ChartFigure:Mr,ChartJsComponent:ln,Grid:Op,GridOverlay:pp,ScorecardChart:Ar,LineConfigPanel:ur,LineBarPieDesignPanel:lr,BarConfigPanel:ds,LineBarPieConfigPanel:hs,GaugeChartConfigPanel:hr,GaugeChartDesignPanel:dr,ScorecardChartConfigPanel:pr,ScorecardChartDesignPanel:mr};e.AbstractChart=us,e.CorePlugin=av,e.DATETIME_FORMAT=Y,e.DispatchResult=fn,e.EvaluationError=c,e.Model=class extends Xv{constructor(e={},i={},n=[],o=new Mi,s=!0){super(),this.corePlugins=[],this.uiPlugins=[],this.isReplayingCommand=!1,this.renderers=[],this.status=0,this.handlers=[],this.coreHandlers=[],this.dispatch=(e,t)=>{const i={type:e,...t};let n=this.status;if(this.getters.isReadonly()&&(o=i,!gn.has(o.type)))return new fn(68);var o;if(!this.session.canApplyOptimisticUpdate())return new fn(65);switch(n){case 0:const t=this.checkDispatchAllowed(i);if(!t.isSuccessful)return t;this.status=1;const{changes:n,commands:o}=this.state.recordChanges((()=>{mn(i)&&this.state.addCommand(i),this.dispatchToHandlers(this.handlers,i),this.finalize()}));this.session.save(o,n),this.status=0,this.trigger("update");break;case 1:if(mn(i)){const e=this.checkDispatchAllowed(i);if(!e.isSuccessful)return e;this.state.addCommand(i),this.dispatchToHandlers(this.handlers,i)}else this.dispatchToHandlers(this.handlers,i);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(mn(i))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,i)}return fn.Success},this.dispatchFromCorePlugin=(e,t)=>{const i={type:e,...t},n=this.status;this.status=2;const o=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(o,i),this.status=n,fn.Success},n=iv(e,n);const r=ev(e,s);this.state=new Vb,this.uuidGenerator=o,this.config=this.setupConfig(i),this.session=this.setupSession(r.revisionId),this.config.moveClient=this.session.move.bind(this.session),this.history=new $b(this.dispatchFromCorePlugin,this.session),this.coreGetters={},this.range=new Lb(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getSelectionRangeString=this.range.getSelectionRangeString.bind(this.range),this.getters={isReadonly:()=>"readonly"===this.config.mode||"dashboard"===this.config.mode,isDashboard:()=>"dashboard"===this.config.mode,canUndo:this.history.canUndo.bind(this.history),canRedo:this.history.canRedo.bind(this.history),getClient:this.session.getClient.bind(this.session),getConnectedClients:this.session.getConnectedClients.bind(this.session),isFullySynchronized:this.session.isFullySynchronized.bind(this.session)},this.uuidGenerator.setIsFastStrategy(!0),this.selection=new Ub(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range);for(let e of gb.getAll())this.setupCorePlugin(e,r);Object.assign(this.getters,this.coreGetters);for(let e of pb.getAll())this.setupUiPlugin(e);this.uuidGenerator.setIsFastStrategy(!1),this.handlers.push(this.history),this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.isLoading=!0,this.setupSessionEvents(),this.session.loadInitialMessages(n),this.joinSession(),i.snapshotRequested&&this.session.snapshot(this.exportData()),t.markRaw(this),this.isLoading=!1,this.finalize()}joinSession(){this.session.join(this.config.client)}leaveSession(){this.session.leave()}setupUiPlugin(e){const t=new e(this.getters,this.state,this.dispatch,this.config,this.selection);for(let i of e.getters){if(!(i in t))throw new Error(`Invalid getter name: ${i} for plugin ${t.constructor}`);if(i in this.getters)throw new Error(`Getter "${i}" is already defined.`);this.getters[i]=t[i].bind(t)}this.uiPlugins.push(t),this.handlers.push(t);const i=e.layers.map((e=>[t,e]));this.renderers.push(...i),this.renderers.sort(((e,t)=>e[1]-t[1]))}setupCorePlugin(e,t){const i=new e(this.coreGetters,this.state,this.range,this.dispatchFromCorePlugin,this.config,this.uuidGenerator);for(let t of e.getters){if(!(t in i))throw new Error(`Invalid getter name: ${t} for plugin ${i.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=i[t].bind(i)}i.import(t),this.corePlugins.push(i),this.coreHandlers.push(i),this.handlers.push(i)}onRemoteRevisionReceived({commands:e}){for(let t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.uiPlugins,t),this.status=e}this.finalize()}setupSession(e){return new sb(Db(e,this.state.recordChanges.bind(this.state),(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-redone",this,this.finalize),this.session.on("revision-undone",this,this.finalize),this.session.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.session.on("collaborative-event-received",this,(()=>{this.trigger("update")}))}setupConfig(e){const t=e.client||{id:this.uuidGenerator.smallUuid(),name:s("Anonymous").toString()},i=e.transportService||new Rb;return{...e,mode:e.mode||"normal",evalContext:e.evalContext||{},transportService:i,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e)}}checkDispatchAllowed(e){const t=this.handlers.map((t=>t.allowDispatch(e)));return t.some((e=>0!==e))?new fn(t.flat()):fn.Success}finalize(){if(!this.isLoading){this.status=3;for(const e of this.handlers)e.finalize();this.status=0}}dispatchToHandlers(e,t){t=Ae(t);for(const i of e)i.beforeHandle(t);for(const i of e)i.handle(t)}drawGrid(e){for(let[t,i]of this.renderers)e.ctx.save(),t.drawGrid(e,i),e.ctx.restore()}exportData(){let e=sv();for(let t of this.handlers)t instanceof av&&t.export(e);return e.revisionId=this.session.getRevisionId()||K,e=Ae(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={...sv(),sheets:[rv(Jf,"Sheet1")]};for(let t of this.handlers)t instanceof Hg&&t.exportForExcel(e);return e=Ae(e),xS(e)}},e.Registry=sn,e.Revision=nb,e.SPREADSHEET_DIMENSIONS=AS,e.Spreadsheet=xb,e.UIPlugin=Wg,e.__info__=TS,e.addFunction=function(e,t){ju.add(e,t)},e.astToFormula=Og,e.cellTypes=OS,e.compile=Pg,e.components=_S,e.convertAstNodes=Ng,e.coreTypes=pn,e.findCellInNewZone=Qi,e.functionCache=Lg,e.helpers=MS,e.invalidateEvaluationCommands=dn,e.load=ev,e.parse=Tg,e.readonlyAllowedCommands=gn,e.registries=NS,e.setTranslationMethod=function(e){i=e},e.tokenize=Qu,Object.defineProperty(e,"__esModule",{value:!0}),TS.version="16.0.70",TS.date="2025-05-12T05:19:22.493Z",TS.hash="bbdc034"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);