@odoo/o-spreadsheet 16.1.14 → 16.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- !function(e,t){"use strict";let o=e=>e;function i(e,...t){if(1===t.length&&"object"==typeof t[0]){const o=t[0];e=e.replace(/\%\(?([^\)]+)\)s/g,((e,t)=>o[t]))}else t.length>0&&(e=e.replace(/\%s/g,(()=>t.shift())));return e}const n=function(e,...t){return i(o(e),...t)},r=function(e,...t){return new s(e,t)};class s extends String{constructor(e,t){super(e),this.values=t}valueOf(){const e=super.valueOf();return i(o(e),...this.values)}toString(){return this.valueOf()}}var a,l;!function(e){e.NotAvailable="#N/A",e.InvalidReference="#REF",e.BadExpression="#BAD_EXPR",e.CircularDependency="#CYCLE",e.UnknownFunction="#NAME?",e.GenericError="#ERROR"}(a||(a={})),function(e){e[e.silent=0]="silent",e[e.error=1]="error"}(l||(l={}));class c extends Error{constructor(e,t,o=l.error){super(t),this.errorType=e,this.logLevel=o}}class h extends c{constructor(e){super(a.BadExpression,e)}}class d extends c{constructor(){super(a.CircularDependency,r("Circular reference"))}}class u extends c{constructor(){super(a.InvalidReference,r("Invalid reference"))}}class g extends c{constructor(e){super(a.NotAvailable,e||r("Data not available"),e?l.error:l.silent)}}class p extends c{constructor(e){super(a.UnknownFunction,r('Unknown function: "%s"',e))}}const m=.5,f="#f5f5f5",v="#F8F9FA",b="#E8EAED",C="#595959",S="#666666",E="#3266ca",w="#FFFFFF",y=11982760,x="#01666b",I="#188038",R="#E6F4EA",T="#CEEAD6",A=["#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,N=96,_=23,F=15,D=18,k=14,$=4,P=4,L=3,U=P,V=17,z=250,B=1,H="400",W=10,G="'Roboto', arial",q=["thin","#000"],Z=["thin",I],j=/[ymdhs:]/,X=a.InvalidReference,Y="START_REVISION",K=20,Q="??",J="difference",ee="#00A04A",te="#DC6965",oe=.4,ie=["'","*","?","/","\\","[","]"],ne=/'|\*|\?|\/|\\|\[|\]/,re="|",se=r("Invalid expression");var ae;!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"}(ae||(ae={}));const le=[{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}],ce={};for(let e of le)ce[e.pt]=e.px;const he=new Date(1899,11,30),de=864e5,ue=2e3,ge=(new Date).getFullYear(),pe=new Date(0)-he,me=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,fe=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,ve=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function be(e){let t;const o=(e=e.trim()).match(ve);if(o){if(t=function(e){if(e=e.trim(),ve.test(e)){const t=/AM/i.test(e),o=/PM/i.test(e),i=(t||o?e.substring(0,e.length-2).trim():e).split(/:/),n=i.length>=2,r=3===i.length;let s=Number(i[0]),a=n?Number(i[1]):0,l=r?Number(i[2]):0,c=r?"hh:mm:ss":"hh:mm";if(t||o)c+=" a";else if(!n)return null;s>=12&&t?s-=12:s<12&&o&&(s+=12),a+=Math.floor(l/60),l%=60,s+=Math.floor(a/60),a%=60,s>=24&&(c="hhhh:mm:ss");return{value:s/24+a/1440+l/86400,format:c,jsDate:new Date(1899,11,30,s,a,l)}}return null}(o[0]),null===t)return null;e=e.replace(o[0],"").trim()}let i;const n=e.match(me),r=e.match(fe);if(n||r){let t;if(n?(t=n[0],i=Ce(t,"mdy")):(t=r[0],i=Ce(t,"ymd")),null===i)return null;e=e.replace(t,"").trim()}return""!==e||!i&&!t?null:i&&t?{value:i.value+t.value,format:i.format+" "+("hhhh:mm:ss"===t.format?"hh:mm:ss":t.format),jsDate:new Date(i.jsDate.getFullYear()+t.jsDate.getFullYear()-1899,i.jsDate.getMonth()+t.jsDate.getMonth()-11,i.jsDate.getDate()+t.jsDate.getDate()-30,i.jsDate.getHours()+t.jsDate.getHours(),i.jsDate.getMinutes()+t.jsDate.getMinutes(),i.jsDate.getSeconds()+t.jsDate.getSeconds())}:i||t}function Ce(e,t){const o="mdy"===t;if(o||"ymd"===t){const t=e.split(/\/|-|\s/),i=o?0:1,n=o?1:2,r=o?2:0,s=Number(t[i]),a=Number(t[n]),l=2===t[i].length&&s<10||2===t[n].length&&a<10,c=t[r]?function(e){const t=Number(e);switch(e.length){case 1:return ue+t;case 2:return ue+(ue+t>ge+10?-100:0)+t;case 3:case 4:return t}return 0}(t[r]):ge,h=new Date(c,s-1,a),d=e.match(/\/|-|\s/)[0];if(h.getMonth()!==s-1||h.getDate()!==a)return null;const u=h-he;let g=l?`mm${d}dd`:`m${d}d`;return t[r]&&(g=o?g+d+"yyyy":"yyyy"+d+g),{value:Math.round(u/de),format:g,jsDate:h}}return null}function Se(e){const t=Math.trunc(e);let o=new Date(t*de-pe),i=e-t;i=i<0?1+i:i;const n=Math.round(24*i),r=Math.round(24*(i-n/24)*60),s=Math.round(24*(i-n/24-r/24/60)*60*60);return o.setHours(n),o.setMinutes(r),o.setSeconds(s),o}function Ee(e){const t=e.getTime()-he.getTime();return Math.round(t/de)}function we(e){return new Date(e.getFullYear(),e.getMonth()+1,0).getDate()}function ye(e){return we(e)===e.getDate()}function xe(e,t,o){const i=e.getFullYear(),n=e.getMonth(),r=e.getDate(),s=new Date(i,n+t);return o&&r===we(e)||r>we(s)?s.setDate(we(s)):s.setDate(r),s}function Ie(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function Re(e,t,o){if(e===t)return 0;if(e>t){const o=t;t=e,e=o}const i=Se(e),n=Se(t);let r=i.getDate(),s=n.getDate();const a=i.getMonth(),l=n.getMonth(),c=i.getFullYear(),h=n.getFullYear();let d=0,u=0;switch(o){case 0:31===r&&(r=30),30===r&&31===s&&(s=30),1===a&&r===(Ie(c)?29:28)&&(r=30,1===l&&s===(Ie(h)?29:28)&&(s=30)),d=c+(30*a+r)/360,u=h+(30*l+s)/360;break;case 1:let o=365;const i=c===h;if(!i&&!(c+1===h)||!i&&a<l||!i&&a===l&&r<s){let e=0,t=0;for(let o=c;o<=h;o++)e++,t+=Ie(o)?366:365;o=t/e}else i?Ie(c)&&(o=366):(Ie(c)&&a<2&&(o=366),Ie(h)&&(l>1||1===l&&29===s)&&(o=366));d=e/o,u=t/o;break;case 2:d=e/360,u=t/360;break;case 3:d=e/365,u=t/365;break;case 4:31===r&&(r=30),31===s&&(s=30),d=c+(30*a+r)/360,u=h+(30*l+s)/360}return u-d}function Te(e){return JSON.stringify(e,Object.keys(e).sort())}function Ae(e){return'"'===e[0]&&(e=e.slice(1)),'"'===e[e.length-1]&&"\\"!==e[e.length-2]?e.slice(0,e.length-1):e}function Oe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Me(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 o in e)t[o]=Me(e[o]);return t;case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function Ne(e){return e.startsWith("'")&&(e=e.slice(1,-1).replace(/''/g,"'")),e}function _e(e){var t;return(null===(t=e.match(/\w/g))||void 0===t?void 0:t.length)!==e.length&&(e=`'${e}'`),e}function Fe(e,t,o){return e<t?t:e>o?o:e}function De(e,t=1){return t*(e+P)-P}function ke(e,t,o){e.save(),e.font=$e(o);const i=e.measureText(t).width;return e.restore(),i}function $e(e){return`${e.italic?"italic ":""}${e.bold?"bold":H} ${Pe(e)}px ${G}`}function Pe(e){const t=(null==e?void 0:e.fontSize)||W;if(!ce[t])throw new Error("Size of the font is not supported");return ce[t]}function Le(e,t,o=1){if(t<=e&&o>0)return[];if(0===o)throw new Error("range() step must not be zero");const i=Math.ceil(Math.abs((t-e)/o)),n=Array(i);for(let t=0;t<i;t++)n[t]=e+t*o;return n}function Ue(e){return e.reduce(((e,t,o,i)=>{if(1===Math.abs(t-i[o-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*Ve(e,t){t.next();for(const o of e){const e=t.next();yield{...o,next:e.done?void 0:e.value}}}function ze(e){return null!==be(e)}const Be=/^\[([^\[]+)\]\((.+)\)$/,He=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function We(e){return Be.test(e)}function Ge(e){return He.test(e)}function qe(e,t){return`[${e}](${t})`}function Ze(e){const t=e.match(Be)||[],o=t[1],i=t[2];if(!o||!i)throw new Error(`Could not parse markdown link ${e}.`);return{label:o,url:i}}const je="o-spreadsheet://";function Xe(e){return e.startsWith(je)}function Ye(e){return`${je}${e}`}function Ke(e){if(e.startsWith(je))return e.substr(je.length);throw new Error(`${e} is not a valid sheet link`)}function Qe(e){return void 0!==e}function Je(e){return void 0===e||Object.values(e).every((e=>"object"==typeof e?Je(e):!e))}function et(e,t){for(let[o,i]of Object.entries(t))if(Te(i)===Te(e))return parseInt(o,10);const o=Object.keys(t),i=0===o.length?0:Math.max(...o.map((e=>parseInt(e,10))));return t[i+1]=e,i+1}function tt(e){let t="";for(let o=0,i=e.length;o<i;o++)t+=e[o];return t}function ot(e){let t,o=!1;const i=()=>(o||(t=e instanceof Function?e():e,o=!0),t);return i.map=e=>ot((()=>e(i()))),i}function it(e,t){let o=e.slice(t).find((e=>e));return o||(o=e.slice(0,t).reverse().find((e=>e))),o||""}function nt(e,t){return"after"===e?t+1:t}function rt(e,t){if(e===t)return!0;if(e&&!t||t&&!e)return!1;const o=new Set;Object.keys(e).forEach((e=>o.add(e))),Object.keys(t).forEach((e=>o.add(e)));for(let i of o){if(typeof e[i]!=typeof e[i])return!1;if("object"==typeof e[i]){if(!rt(e[i],t[i]))return!1}else if(e[i]!==t[i])return!1}return!0}function st(e){const t={...e};return Object.keys(t).forEach((e=>!t[e]&&delete t[e])),t}function at(e){return e?e.toLowerCase():""}const lt=/rgba?\(|\s+|\)/gi,ct=/^#([A-F\d]{2}){3,4}$/g,ht=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function dt(e){return ut(e.toString(16).padStart(6,"0"))}function ut(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(lt,"").split(",");let o=255;if(3!==t.length&&4!==t.length)throw new Error("invalid color");if(4===t.length){const e=parseFloat(t.pop()||"1");o=Math.round(255*(e||1))}const i=t.map((e=>parseInt(e,10)));255!==o&&i.push(o);return"#"+tt(i.map((e=>e.toString(16).padStart(2,"0")))).toUpperCase()}(e):(t=e.replace("#","").toUpperCase(),3!==t.length&&4!==t.length||(t=t.split("").reduce(((e,t)=>e+t+t),"")),t=`#${t}`),!t.match(ct))throw new Error(`invalid color input: ${e}`);return t}function gt(e){try{return ut(e),!0}catch(e){return!1}}const pt=e=>e>=0&&e<=255;function mt(e,t,o,i=1){if(!pt(e)||!pt(t)||!pt(o)||i<0||i>1)throw new Error(`Invalid RGBA values ${[e,t,o,i]}`);return{a:i,b:o,g:t,r:e}}function ft(e){let{r:t,g:o,b:i}=bt(e);t/=255,o/=255,i/=255;const n=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return.2126*n(t)+.7152*n(o)+.0722*n(i)}function vt(e){let t=e.r.toString(16),o=e.g.toString(16),i=e.b.toString(16),n=Math.round(255*e.a).toString(16);return 1==t.length&&(t="0"+t),1==o.length&&(o="0"+o),1==i.length&&(i="0"+i),1==n.length&&(n="0"+n),"ff"===n&&(n=""),("#"+t+o+i+n).toUpperCase()}function bt(e){let t,o,i,n;if(7===(e=ut(e)).length)t=parseInt(e[1]+e[2],16),o=parseInt(e[3]+e[4],16),i=parseInt(e[5]+e[6],16),n=255;else{if(9!==e.length)throw new Error("Invalid color");t=parseInt(e[1]+e[2],16),o=parseInt(e[3]+e[4],16),i=parseInt(e[5]+e[6],16),n=parseInt(e[7]+e[8],16)}return n=+(n/255).toFixed(3),{a:n,r:t,g:o,b:i}}function Ct(e){(e={...e}).s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,o=t*(1-Math.abs(e.h/60%2-1)),i=e.l-t/2,n=0,r=0,s=0;return 0<=e.h&&e.h<60?(n=t,r=o,s=0):60<=e.h&&e.h<120?(n=o,r=t,s=0):120<=e.h&&e.h<180?(n=0,r=t,s=o):180<=e.h&&e.h<240?(n=0,r=o,s=t):240<=e.h&&e.h<300?(n=o,r=0,s=t):300<=e.h&&e.h<360&&(n=t,r=0,s=o),n=Math.round(255*(n+i)),r=Math.round(255*(r+i)),s=Math.round(255*(s+i)),{a:e.a,r:n,g:r,b:s}}function St(e){const t=e.r/255,o=e.g/255,i=e.b/255;let n=Math.min(t,o,i),r=Math.max(t,o,i),s=r-n,a=0,l=0,c=0;return a=0==s?0:r==t?(o-i)/s%6:r==o?(i-t)/s+2:(t-o)/s+4,a=Math.round(60*a),a<0&&(a+=360),c=(r+n)/2,l=0==s?0:s/(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 Et=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),wt=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),yt=new RegExp(/^([A-Z]{1,3})+$/,"i"),xt=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),It=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),Rt=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[Et.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 Tt(e){return xt.test(e)}function At(e){return It.test(e)}function Ot(e){return yt.test(e)}function Mt(e){return wt.test(e)}function Nt(e){const t=e.split("!"),o=t.pop();return{sheetName:Ne(t.join("!"))||void 0,xc:o}}function _t(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):_t(Math.floor(e/26)-1)+_t(e%26)}function Ft(e){let t=0;const o=e.length;for(let i=0;i<o;i++){t+=(e.charCodeAt(i)-65+(i<o-1?1:0))*26**(o-i-1)}return t}function Dt(e){const t=(e=e.toUpperCase().trim()).match(Et);if(null!==t){const[o,i,n]=t;if(o===e){return{col:Ft(i),row:parseInt(n,10)-1}}}throw new Error(`Invalid cell description: ${e}`)}function kt(e,t,o={colFixed:!1,rowFixed:!1}){return(o.colFixed?"$":"")+_t(e)+(o.rowFixed?"$":"")+String(t+1)}const $t=140,Pt=20,Lt=.035;function Ut(e){return Pt+($t-Pt)*Math.exp(-Lt*(e-1))}const Vt=/(^-?\d+(\.?\d*(e\d+)?)?|^-?\.\d+)(?!\w|!)/,zt="(\\s*(\\d+(,\\d{3,})*(\\.\\d*)?)|(\\.\\d+))(e(\\+|-)?\\d+)?(\\s*%)?",Bt="(\\s*-)?",Ht="(\\s*[\\$€])?",Wt="^(("+[Bt+Ht+zt,Bt+zt+Ht,Ht+Bt+zt].join(")|(")+"))$",Gt=new RegExp(Wt,"i");function qt(e){return!!e&&Gt.test(e.trim())}const Zt=/[,\$€]+/g;function jt(e){e=e.replace(Zt,"");let t=Number(e);return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}function Xt(e,t,o){const i=[...e].sort(((e,t)=>e-t));let n=(i.length+(o?-1:1))*t;if(o||n--,Number.isInteger(n))return i[n];const r=Math.ceil(n),s=Math.floor(n);return i[r]*(n-s)+i[s]*(r-n)}const Yt=20,Kt=11,Qt=/(\d+?)(?=(\d{3})+(?!\d)|$)/g,Jt=/0/g,eo={0:r("January"),1:r("February"),2:r("March"),3:r("April"),4:r("May"),5:r("June"),6:r("July"),7:r("August"),8:r("September"),9:r("October"),10:r("November"),11:r("December")},to={0:r("Sunday"),1:r("Monday"),2:r("Tuesday"),3:r("Wednesday"),4:r("Thursday"),5:r("Friday"),6:r("Saturday")},oo={};function io(e){let t=oo[e];return void 0===t&&(t=function(e){if(""===e)throw new Error("A format cannot be empty");let t=0,o=[];for(;t<e.length;){let i;if("["===e.charAt(t)){if("$"!==e.charAt(t+1))throw new Error(`Currency formats have to be prefixed by a $: ${e}`);if(i=e.substring(t+1).indexOf("]")+t+2,0===i)throw new Error(`Invalid currency brackets format: ${e}`);const n=e.substring(t+2,i-1);if(n.includes("["))throw new Error(`Invalid currency format: ${e}`);o.push({type:"STRING",format:n})}else{const n=e.substring(t).indexOf("[");i=n>-1?n+t:e.length;const r=e.substring(t,i);r.match(j)?o.push({type:"DATE",format:r}):o.push({type:"NUMBER",format:So(r)})}t=i}return o}(e),oo[e]=t),t}function no(e,t){switch(typeof e){case"string":return e;case"boolean":return e?"TRUE":"FALSE";case"number":t||(t=mo(e));return function(e,t){if("DATE"===t[0].type)return uo(e,t[0].format);let o=e<0?"-":"";for(let i of t)switch(i.type){case"NUMBER":o+=ro(Math.abs(e),i.format);break;case"STRING":o+=i.format}return o}(e,io(t));case"object":return"0"}}function ro(e,t){t.isPercent&&(e*=100),e/=t.magnitude;let o=0;void 0!==t.decimalPart&&(o=t.decimalPart.length);const{integerDigits:i,decimalDigits:n}=ao(e,o);let r=function(e,t,o){var i;const n="0"===e?"":e;let r=n;const s=t.length-n.length;if(s>0){const e=(t.substring(0,s).match(Jt)||[]).length;r="0".repeat(e)+r}o&&(r=(null===(i=r.match(Qt))||void 0===i?void 0:i.join(","))||r);return r}(i,t.integerPart,t.thousandsSeparator);return void 0!==t.decimalPart&&(r+="."+function(e,t){let o=e;if(t.length-e.length>0){const i=(t.substring(e.length,t.length+1).match(Jt)||[]).length;o+="0".repeat(i)}return o}(n||"",t.decimalPart)),t.isPercent&&(r+="%"),r}const so=[];function ao(e,t=Yt){const o=e.toString();if(o.includes("e"))return function(e,t=Yt){let o=so[t];o||(o=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),so[t]=o);const[i,n]=o.format(e).split(".");return{integerDigits:i,decimalDigits:n}}(e,t);if(Number.isInteger(e))return{integerDigits:o,decimalDigits:void 0};const i=o.indexOf(".");let n=o.substring(0,i),r=o.substring(i+1);if(0===t)return Number(r[0])>=5&&(n=(Number(n)+1).toString()),{integerDigits:n,decimalDigits:void 0};if(r.length>t){const{integerDigits:e,decimalDigits:o}=function(e,t){var o;let i="0",n=e,r=e.slice(0,t);const s=t;if(Number(e[s])<5)return{integerDigits:i,decimalDigits:r};const a=(null===(o=r.match(co))||void 0===o?void 0:o[0])||"",l=(Number(r)+1).toString(),c=r.slice(a.length),h=l.length>c.length;h&&!a?(i="1",n=void 0):n=h?a.slice(0,-1)+l:a+l;return{integerDigits:i,decimalDigits:n}}(r,t);r=o,"0"!==e&&(n=(Number(n)+Number(e)).toString())}return{integerDigits:n,decimalDigits:lo(r||"")}}function lo(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const co=/^0+/;function ho(e){try{return uo(1,e),!0}catch(e){return!1}}function uo(e,t){const o=Se(e),i=t.indexOf("h");let n="",r="";return i>0?(n=go(o,t.substring(0,i-1)),r=po(o,t.substring(i))):0===i?r=po(o,t):i<0&&(n=go(o,t)),n+(n&&r?" ":"")+r}function go(e,t){var o;const i=null===(o=t.match(/\/|-|\s/))||void 0===o?void 0:o[0];return(i?t.split(i):[t]).map((o=>{switch(o){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return to[e.getDay()].slice(0,3);case"dddd":return to[e.getDay()];case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return eo[e.getMonth()].slice(0,3);case"mmmm":return eo[e.getMonth()];case"mmmmm":return eo[e.getMonth()].slice(0,1);case"yy":const o=String(e.getFullYear()).replace("-","").padStart(2,"0");return o.slice(o.length-2);case"yyyy":return e.getFullYear();default:throw new Error(`invalid format: ${t}`)}})).join(i)}function po(e,t){let o=t.split(/:|\s/);const i=e.getHours(),n="a"===o[o.length-1];let r=i,s="";return n&&(r=0===r?12:r>12?r-12:r,s=i>=12?" PM":" AM",o.pop()),o.map((o=>{switch(o){case"hhhh":return Math.floor((e.getTime()-he)/36e5).toString();case"hh":return r.toString().padStart(2,"0");case"mm":return e.getMinutes().toString().padStart(2,"0");case"ss":return e.getSeconds().toString().padStart(2,"0");default:throw new Error(`invalid format: ${t}`)}})).join(":")+s}function mo(e){let{integerDigits:t,decimalDigits:o}=ao(e);if(!o)return"0";const i=t.replace("-","").length;if(i+2>Kt)return"0";const n=Kt-i-1;return({decimalDigits:o}=ao(e,Math.min(n,o.length))),o?"0."+"0".repeat(o.length):"0"}function fo(e){if(ze(e)){return be(e).format}if(!qt(e))return;const t=e.includes(".")?"0.00":"0",o=e.match(/[\$€]/);if(o){const i=e.match(/[\d]/),n="[$"+o.values().next().value+"]";return i.index<o.index?"#,##"+t+n:n+"#,##"+t}return e.includes("%")?t+"%":void 0}function vo(e,t,o){return wo(io(e||"#,##0").map((e=>"NUMBER"===e.type?[{...e,format:{...e.format,magnitude:t,decimalPart:void 0}},{type:"STRING",format:o}]:e)).flat())}function bo(e,t){var o;const i={...e},n=Math.sign(t),r=(null===(o=i.decimalPart)||void 0===o?void 0:o.length)||0,s=Math.min(Math.max(0,r+n),Yt);return i.decimalPart="0".repeat(s),""===i.decimalPart&&delete i.decimalPart,i}const Co=/,*?$/;function So(e){var t;if(function(e){return Boolean(e.replace(Eo,""))}(e=e.trim()))throw new Error(`Invalid number format: ${e}`);const o=e.includes("%"),i=(null===(t=e.match(Co))||void 0===t?void 0:t[0])||"",n=i?1e3**i.length:1;let r=e.slice(0,e.length-(i.length||0));const s=r.includes(",");if(r.match(/\..*,/))throw new Error("A format can't contain ',' symbol in the decimal part");r=r.replace("%","").replace(",","");const a=r.match(/[\%|,]/);if(a)throw new Error(`A format can only contain a single '${a[0]}' symbol`);const[l,c]=r.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:o,thousandsSeparator:s,decimalPart:c,magnitude:n}:{integerPart:l,isPercent:o,thousandsSeparator:s,magnitude:n}}const Eo=/[,#0.%]/g;function wo(e){let t="";for(let o of e){let e;switch(o.type){case"NUMBER":const t=o.format;e=t.integerPart,t.thousandsSeparator&&(e=e.slice(0,-3)+","+e.slice(-3)),void 0!==t.decimalPart&&(e+="."+t.decimalPart),t.isPercent&&(e+="%"),t.magnitude&&(e+=",".repeat(Math.log10(t.magnitude)/3));break;case"STRING":e=`[$${o.format}]`;break;case"DATE":e=o.format}t+=e}return t}class yo{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 yo?e:new yo(e,t.getSheetSize)}get unboundedZone(){return this._zone}get zone(){const{left:e,top:t,bottom:o,right:i}=this._zone;if(void 0!==i&&void 0!==o)return{left:e,top:t,right:i,bottom:o};if(void 0===o&&void 0!==i)return{right:i,top:t,left:e,bottom:this.getSheetSize(this.sheetId).height-1};if(void 0===i&&void 0!==o)return{bottom:o,left:e,top:t,right:this.getSheetSize(this.sheetId).width-1};throw new Error(r("Bad zone format"))}static getRangeParts(e,t){const o=e.split(":").map((e=>{const t=At(e);return{colFixed:!t&&e.startsWith("$"),rowFixed:t?e.startsWith("$"):e.includes("$",1)}})),i=void 0===t.bottom,n=void 0===t.right;return i&&(o[0].rowFixed=o[0].rowFixed||o[1].rowFixed,o[1].rowFixed=o[0].rowFixed||o[1].rowFixed,t.left===t.right&&(o[0].colFixed=o[0].colFixed||o[1].colFixed,o[1].colFixed=o[0].colFixed||o[1].colFixed)),n&&(o[0].colFixed=o[0].colFixed||o[1].colFixed,o[1].colFixed=o[0].colFixed||o[1].colFixed,t.top===t.bottom&&(o[0].rowFixed=o[0].rowFixed||o[1].rowFixed,o[1].rowFixed=o[0].rowFixed||o[1].rowFixed)),o}get isFullCol(){return void 0===this._zone.bottom}get isFullRow(){return void 0===this._zone.right}get rangeData(){return{_zone:this._zone,_sheetId:this.sheetId}}orderZone(){var e,t,o,i,n,r,s,a;const l={...this._zone};let c=this.parts;if(void 0!==l.right&&l.right<l.left){let n=l.right;l.right=l.left,l.left=n,c=[{colFixed:(null===(e=c[1])||void 0===e?void 0:e.colFixed)||!1,rowFixed:(null===(t=c[0])||void 0===t?void 0:t.rowFixed)||!1},{colFixed:(null===(o=c[0])||void 0===o?void 0:o.colFixed)||!1,rowFixed:(null===(i=c[1])||void 0===i?void 0:i.rowFixed)||!1}]}if(void 0!==l.bottom&&l.bottom<l.top){let e=l.bottom;l.bottom=l.top,l.top=e,c=[{colFixed:(null===(n=c[0])||void 0===n?void 0:n.colFixed)||!1,rowFixed:(null===(r=c[1])||void 0===r?void 0:r.rowFixed)||!1},{colFixed:(null===(s=c[1])||void 0===s?void 0:s.colFixed)||!1,rowFixed:(null===(a=c[0])||void 0===a?void 0:a.rowFixed)||!1}]}return this.clone({zone:l,parts:c})}clone(e){return new yo({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 xo(e,t,o){const i=o.sheetId===e?t:o.sheetId;return o.clone({sheetId:i})}function Io(e,t,o){return o?e.getRangeFromSheetXC(t,o):void 0}function Ro(e){const t=[];for(let o=0;o<e;o++){const e={cells:{}};t.push(e)}return t}class To{constructor(){this.isFastIdStrategy=!1,this.fastIdStart=0}setIsFastStrategy(e){this.isFastIdStrategy=e}uuidv4(){return this.isFastIdStrategy?(this.fastIdStart++,String(this.fastIdStart)):window.crypto&&window.crypto.getRandomValues?([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16))):"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}}function Ao(e){const t=function(e){const t=(e=e.split("!").pop()).replace(/\$/g,"").split(":").map((e=>e.trim()));let o,i,n,r,s=!1,a=!1,l=!1;const c=t[0],h=t[1]&&t[1];if(Tt(c))n=r=Ft(c),o=i=0,s=!0;else if(At(c))o=i=parseInt(c,10)-1,n=r=0,a=!0;else{const e=Dt(c);n=r=e.col,o=i=e.row,l=!0}if(2===t.length)if(Tt(h))r=Ft(h),s=!0;else if(At(h))i=parseInt(h,10)-1,a=!0;else{const e=Dt(h);r=e.col,i=e.row,o=s?i:o,n=a?r:n,l=!0}if(s&&a)throw new Error("Wrong zone xc. The zone cannot be at the same time a full column and a full row");const d={top:o,left:n,bottom:s?void 0:i,right:a?void 0:r};return l=l&&(a||s),l&&(d.hasHeader=l),d}(e);if(void 0!==t.right&&t.right<t.left){const e=t.left;t.left=t.right,t.right=e}if(void 0!==t.bottom&&t.bottom<t.top){const e=t.top;t.top=t.bottom,t.bottom=e}return t}function Oo(e){const t=Ao(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function Mo(e){const{bottom:t,top:o,left:i,right:n}=e;return!(void 0!==t&&isNaN(t)||isNaN(o)||isNaN(i)||void 0!==n&&isNaN(n))&&((void 0===e.bottom||e.bottom>=e.top&&e.bottom>=0)&&(void 0===e.right||e.right>=e.left&&e.right>=0)&&e.top>=0&&e.left>=0)}function No(e){const{top:t,bottom:o,left:i,right:n}=e,s="hasHeader"in e&&e.hasHeader,a=t===o&&i===n;if(void 0===o&&void 0!==n)return 0!==t||s?`${kt(i,t)}:${_t(n)}`:`${_t(i)}:${_t(n)}`;if(void 0===n&&void 0!==o)return 0!==i||s?`${kt(i,t)}:${o+1}`:`${t+1}:${o+1}`;if(void 0!==o&&void 0!==n)return a?kt(i,t):`${kt(i,t)}:${kt(n,o)}`;throw new Error(r("Bad zone format"))}function _o(e,t,o,i,n){const r="left"===t?"columns":"rows",s="before"===i?o-1:o,a=e["left"===t?"right":"bottom"];return e[t]<=s&&a&&a>s?Zo(e,r,"RESIZE",n):s<e[t]?Zo(e,r,"MOVE",n):{...e}}function Fo(e,t,o,i,n){const r="left"===t?"columns":"rows",s="before"===i?o-1:o,a="left"===t?"right":"bottom";return e[t]<=s&&e[a]>s?Zo(e,r,"RESIZE",n):s<e[t]?Zo(e,r,"MOVE",n):{...e}}function Do(e,t,o){const i="left"===t?"right":"bottom";let n=e[t],r=e[i];for(let s of o.sort(((e,t)=>t-e)))e[t]>s&&(n--,r--),e[t]<s&&e[i]>=s&&r--;return{...e,[t]:n,[i]:r}}function ko(e,t,o){const i="left"===t?"right":"bottom";let n=e[t],r=e[i];const s=e[i];for(let i of o.sort(((e,t)=>t-e)))e[t]>i&&(n--,void 0!==r&&r--),void 0!==s&&void 0!==r&&e[t]<=i&&s>=i&&r--;if(!(void 0!==r&&n>r))return{...e,[t]:n,[i]:r}}function $o(...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 Po(e,t){if(Uo(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 Lo(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function Uo(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function Vo(e,t,o){const{left:i,right:n,top:r,bottom:s}=o;return e>=i&&e<=n&&t>=r&&t<=s}function zo(e,t){return Lo($o(t,e),t)}function Bo(e,t){const o=e.map(Ao),i=t.map(Oo),n=Math.max(...o.concat(i).map((e=>e.bottom||0))),r=Math.max(...o.concat(i).map((e=>e.right||0))),s=o.map((e=>({...e,bottom:void 0===e.bottom?n+1:e.bottom,right:void 0===e.right?r+1:e.right}))),a=i.map((e=>({...e,bottom:void 0===e.bottom?n+1:e.bottom,right:void 0===e.right?r+1:e.right}))),l=function(e,t){const o=new Set(t.map((({col:e,row:t})=>`${e}-${t}`)));return e.filter((({col:e,row:t})=>!o.has(`${e}-${t}`)))}(s.map(qo).flat(),a.map(qo).flat()),c=function(e){if(0===e.length)return[];const[t,...o]=[...e].sort(((e,t)=>e.row-t.row)).sort(((e,t)=>e.col-t.col)),i=[];let n=Yo(t);for(const{col:e,row:t}of o)if(!Vo(e,t,n))if(e===n.left&&t===n.bottom+1){const e=n.bottom+1;n={...n,bottom:e}}else i.push(n),n=Yo({col:e,row:t});return[...i,n]}(l);return function(e){if(0===e.length)return[];if(e.some((e=>e.left!==e.right)))throw new Error("only columns can be merged");const t=[],o=Ho(e),i=(e,t)=>e.top===t.top&&e.bottom===t.bottom&&e.right+1===t.left;for(;o.length;){const e=o.reduce(((e,t)=>i(e,t)?$o(e,t):e),o.shift());t.push(e)}return Ho(t)}(c).map((e=>({...e,bottom:e.bottom===n+1?void 0:e.bottom,right:e.right===r+1?void 0:e.right}))).map(No)}function Ho(e){const t=[...e].sort(((e,t)=>t.right-e.right)).sort(((e,t)=>t.bottom-e.bottom)).sort(((e,t)=>e.top-t.top)).sort(((e,t)=>e.left-t.left)).reverse(),o=[];for(;0!==t.length;){const e=t.shift();t.some((t=>zo(e,t)))||o.push(e)}return o.reverse()}function Wo(e){return{height:e.bottom-e.top+1,width:e.right-e.left+1}}function Go(e){const{width:t,height:o}=Wo(e);return 1===t||1===o}function qo(e){const t=[],[o,i]=[e.right,e.left].sort(((e,t)=>e-t)),[n,r]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of Le(o,i+1))for(const o of Le(n,r+1))t.push({col:e,row:o});return t}function Zo(e,t,o,i){const n="both"===t?i[0]:"columns"===t?i:0,r="both"===t?i[1]:"rows"===t?i:0,s="hasHeader"in e&&e.hasHeader;let a;a=!function(e){return void 0===e.bottom}(e)||s?!(Ko(e)&&!s)||"columns"!==t:"rows"!==t;const l={...e};return a&&"MOVE"===o&&(l.left+=n,l.top+=r),void 0!==l.right&&(l.right+=n),void 0!==l.bottom&&(l.bottom+=r),l}function jo(e,t){let o,i;const{left:n,right:r,top:s,bottom:a}=e,{left:l,right:c,top:h,bottom:d}=t;return o=l!=n?l:c!=r?c:l,i=h!=s?h:d!=a?d:h,{col:o,row:i}}function Xo(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 Yo(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function Ko(e){return void 0===e.right}function Qo(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function Jo(...e){return e.length<2||1===Bo(e.map(No),[]).length}class ei 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;rt(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,o,i,n;const r=e.chartJsConfig;r.data&&r.data.datasets?(this.chart.data=r.data,(null===(t=r.options)||void 0===t?void 0:t.title)&&(this.chart.config.options.title=r.options.title),r.options&&"valueLabel"in r.options&&(null===(o=r.options)||void 0===o?void 0:o.valueLabel)&&(this.chart.config.options.valueLabel=r.options.valueLabel)):this.chart.data.datasets=void 0,this.chart.config.options.legend=null===(i=r.options)||void 0===i?void 0:i.legend,this.chart.config.options.scales=null===(n=r.options)||void 0===n?void 0:n.scales,this.chart.update({duration:0})}}ei.template="o-spreadsheet-ChartJsComponent",ei.props={figure:Object};const ti={};let oi=0;function ii(e,...t){const o="__sheet__"+oi++;return function(e,t){const o=document.createElement("style");o.textContent=function(e){const t=e.split(/(\{|\}|;)/).map((e=>e.trim())),o=[],i=[];let n=[];function r(e,t){const i=[];for(const n of o[e]){let s=t&&t+" "+n||n;s.includes("&")&&(s=n.replace(/&/g,t||"")),e<o.length-1&&(s=r(e+1,s)),i.push(s)}return i.join(", ")}function s(){n.length&&(i.push(r(0)+" {"),i.push(...n),i.push("}"),n=[])}for(;t.length;){let e=t.shift();"}"===e?(s(),o.pop()):("{"===t[0]&&(s(),o.push(e.split(/\s*,\s*/)),t.shift()),";"===t[0]&&n.push(" "+e+";"))}return i.join("\n")}(t),ti[e]=o}(o,String.raw(e,...t)),function(e){const t=ti[e];t.setAttribute("component",e),document.head.appendChild(t)}(o),o}function ni({strikethrough:e,underline:t}){return e||t?`${e?"line-through":""} ${t?"underline":""}`:"none"}function ri(e){const t=si(e);return e?(e.fillColor&&(t.background=e.fillColor),t):t}function si(e){const t={};if(!e)return t;if(e.bold&&(t["font-weight"]="bold"),e.italic&&(t["font-style"]="italic"),e.strikethrough||e.underline){let o=e.strikethrough?"line-through":"";o=e.underline?o+" underline":o,t["text-decoration"]=o}return e.textColor&&(t.color=e.textColor),t}function ai(e,t=!0){const o=t?"\n":"",i=Object.entries(e).map((([e,t])=>`${e}: ${t};`)).join(o);return i?"\n"+i+"\n":""}const li=1.2;ii`
1
+ !function(e,t){"use strict";let o=e=>e;function i(e,...t){if(1===t.length&&"object"==typeof t[0]){const o=t[0];e=e.replace(/\%\(?([^\)]+)\)s/g,((e,t)=>o[t]))}else t.length>0&&(e=e.replace(/\%s/g,(()=>t.shift())));return e}const n=function(e,...t){return i(o(e),...t)},r=function(e,...t){return new s(e,t)};class s extends String{constructor(e,t){super(e),this.values=t}valueOf(){const e=super.valueOf();return i(o(e),...this.values)}toString(){return this.valueOf()}}var a,l;!function(e){e.NotAvailable="#N/A",e.InvalidReference="#REF",e.BadExpression="#BAD_EXPR",e.CircularDependency="#CYCLE",e.UnknownFunction="#NAME?",e.GenericError="#ERROR"}(a||(a={})),function(e){e[e.silent=0]="silent",e[e.error=1]="error"}(l||(l={}));class c extends Error{constructor(e,t,o=l.error){super(t),this.errorType=e,this.logLevel=o}}class h extends c{constructor(e){super(a.BadExpression,e)}}class d extends c{constructor(){super(a.CircularDependency,r("Circular reference"))}}class u extends c{constructor(){super(a.InvalidReference,r("Invalid reference"))}}class g extends c{constructor(e){super(a.NotAvailable,e||r("Data not available"),e?l.error:l.silent)}}class p extends c{constructor(e){super(a.UnknownFunction,r('Unknown function: "%s"',e))}}const m=.5,f="#f5f5f5",v="#F8F9FA",b="#E8EAED",C="#595959",S="#666666",E="#3266ca",w="#FFFFFF",y=11982760,x="#01666b",I="#188038",R="#E6F4EA",T="#CEEAD6",A=["#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,N=96,_=23,F=15,D=18,k=14,$=4,P=4,L=3,U=P,V=17,z=250,B=1,H="400",W=10,G="'Roboto', arial",q=["thin","#000"],Z=["thin",I],j=/[ymdhs:]/,X=a.InvalidReference,Y="START_REVISION",K=20,Q="??",J="difference",ee="#00A04A",te="#DC6965",oe=.4,ie=["'","*","?","/","\\","[","]"],ne=/'|\*|\?|\/|\\|\[|\]/,re="|",se=r("Invalid expression");var ae;!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"}(ae||(ae={}));const le=[{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}],ce={};for(let e of le)ce[e.pt]=e.px;const he=new Date(1899,11,30),de=864e5,ue=2e3,ge=(new Date).getFullYear(),pe=new Date(0)-he,me=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,fe=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,ve=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function be(e){let t;const o=(e=e.trim()).match(ve);if(o){if(t=function(e){if(e=e.trim(),ve.test(e)){const t=/AM/i.test(e),o=/PM/i.test(e),i=(t||o?e.substring(0,e.length-2).trim():e).split(/:/),n=i.length>=2,r=3===i.length;let s=Number(i[0]),a=n?Number(i[1]):0,l=r?Number(i[2]):0,c=r?"hh:mm:ss":"hh:mm";if(t||o)c+=" a";else if(!n)return null;s>=12&&t?s-=12:s<12&&o&&(s+=12),a+=Math.floor(l/60),l%=60,s+=Math.floor(a/60),a%=60,s>=24&&(c="hhhh:mm:ss");return{value:s/24+a/1440+l/86400,format:c,jsDate:new Date(1899,11,30,s,a,l)}}return null}(o[0]),null===t)return null;e=e.replace(o[0],"").trim()}let i;const n=e.match(me),r=e.match(fe);if(n||r){let t;if(n?(t=n[0],i=Ce(t,"mdy")):(t=r[0],i=Ce(t,"ymd")),null===i)return null;e=e.replace(t,"").trim()}return""!==e||!i&&!t?null:i&&t?{value:i.value+t.value,format:i.format+" "+("hhhh:mm:ss"===t.format?"hh:mm:ss":t.format),jsDate:new Date(i.jsDate.getFullYear()+t.jsDate.getFullYear()-1899,i.jsDate.getMonth()+t.jsDate.getMonth()-11,i.jsDate.getDate()+t.jsDate.getDate()-30,i.jsDate.getHours()+t.jsDate.getHours(),i.jsDate.getMinutes()+t.jsDate.getMinutes(),i.jsDate.getSeconds()+t.jsDate.getSeconds())}:i||t}function Ce(e,t){const o="mdy"===t;if(o||"ymd"===t){const t=e.split(/\/|-|\s/),i=o?0:1,n=o?1:2,r=o?2:0,s=Number(t[i]),a=Number(t[n]),l=2===t[i].length&&s<10||2===t[n].length&&a<10,c=t[r]?function(e){const t=Number(e);switch(e.length){case 1:return ue+t;case 2:return ue+(ue+t>ge+10?-100:0)+t;case 3:case 4:return t}return 0}(t[r]):ge,h=new Date(c,s-1,a),d=e.match(/\/|-|\s/)[0];if(h.getMonth()!==s-1||h.getDate()!==a)return null;const u=h-he;let g=l?`mm${d}dd`:`m${d}d`;return t[r]&&(g=o?g+d+"yyyy":"yyyy"+d+g),{value:Math.round(u/de),format:g,jsDate:h}}return null}function Se(e){const t=Math.trunc(e);let o=new Date(t*de-pe),i=e-t;i=i<0?1+i:i;const n=Math.round(24*i),r=Math.round(24*(i-n/24)*60),s=Math.round(24*(i-n/24-r/24/60)*60*60);return o.setHours(n),o.setMinutes(r),o.setSeconds(s),o}function Ee(e){const t=e.getTime()-he.getTime();return Math.round(t/de)}function we(e){return new Date(e.getFullYear(),e.getMonth()+1,0).getDate()}function ye(e){return we(e)===e.getDate()}function xe(e,t,o){const i=e.getFullYear(),n=e.getMonth(),r=e.getDate(),s=new Date(i,n+t);return o&&r===we(e)||r>we(s)?s.setDate(we(s)):s.setDate(r),s}function Ie(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function Re(e,t,o){if(e===t)return 0;if(e>t){const o=t;t=e,e=o}const i=Se(e),n=Se(t);let r=i.getDate(),s=n.getDate();const a=i.getMonth(),l=n.getMonth(),c=i.getFullYear(),h=n.getFullYear();let d=0,u=0;switch(o){case 0:31===r&&(r=30),30===r&&31===s&&(s=30),1===a&&r===(Ie(c)?29:28)&&(r=30,1===l&&s===(Ie(h)?29:28)&&(s=30)),d=c+(30*a+r)/360,u=h+(30*l+s)/360;break;case 1:let o=365;const i=c===h;if(!i&&!(c+1===h)||!i&&a<l||!i&&a===l&&r<s){let e=0,t=0;for(let o=c;o<=h;o++)e++,t+=Ie(o)?366:365;o=t/e}else i?Ie(c)&&(o=366):(Ie(c)&&a<2&&(o=366),Ie(h)&&(l>1||1===l&&29===s)&&(o=366));d=e/o,u=t/o;break;case 2:d=e/360,u=t/360;break;case 3:d=e/365,u=t/365;break;case 4:31===r&&(r=30),31===s&&(s=30),d=c+(30*a+r)/360,u=h+(30*l+s)/360}return u-d}function Te(e){return JSON.stringify(e,Object.keys(e).sort())}function Ae(e){return'"'===e[0]&&(e=e.slice(1)),'"'===e[e.length-1]&&"\\"!==e[e.length-2]?e.slice(0,e.length-1):e}function Oe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Me(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 o in e)t[o]=Me(e[o]);return t;case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function Ne(e){return e.startsWith("'")&&(e=e.slice(1,-1).replace(/''/g,"'")),e}function _e(e){var t;return(null===(t=e.match(/\w/g))||void 0===t?void 0:t.length)!==e.length&&(e=`'${e}'`),e}function Fe(e,t,o){return e<t?t:e>o?o:e}function De(e,t=1){return t*(e+P)-P}function ke(e,t,o){const i=Pe(o);if($e[i]||($e[i]={}),void 0===$e[i][t]){e.save(),e.font=i;const o=e.measureText(t).width;e.restore(),$e[i][t]=o}return $e[i][t]}const $e={};function Pe(e){return`${e.italic?"italic ":""}${e.bold?"bold":H} ${Le(e)}px ${G}`}function Le(e){const t=(null==e?void 0:e.fontSize)||W;if(!ce[t])throw new Error("Size of the font is not supported");return ce[t]}function Ue(e,t,o=1){if(t<=e&&o>0)return[];if(0===o)throw new Error("range() step must not be zero");const i=Math.ceil(Math.abs((t-e)/o)),n=Array(i);for(let t=0;t<i;t++)n[t]=e+t*o;return n}function Ve(e){return e.reduce(((e,t,o,i)=>{if(1===Math.abs(t-i[o-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*ze(e,t){t.next();for(const o of e){const e=t.next();yield{...o,next:e.done?void 0:e.value}}}function Be(e){return null!==be(e)}const He=/^\[([^\[]+)\]\((.+)\)$/,We=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function Ge(e){return He.test(e)}function qe(e){return We.test(e)}function Ze(e,t){return`[${e}](${t})`}function je(e){const t=e.match(He)||[],o=t[1],i=t[2];if(!o||!i)throw new Error(`Could not parse markdown link ${e}.`);return{label:o,url:i}}const Xe="o-spreadsheet://";function Ye(e){return e.startsWith(Xe)}function Ke(e){return`${Xe}${e}`}function Qe(e){if(e.startsWith(Xe))return e.substr(Xe.length);throw new Error(`${e} is not a valid sheet link`)}function Je(e){return void 0!==e}function et(e){return void 0===e||Object.values(e).every((e=>"object"==typeof e?et(e):!e))}function tt(e,t){for(let[o,i]of Object.entries(t))if(Te(i)===Te(e))return parseInt(o,10);const o=Object.keys(t),i=0===o.length?0:Math.max(...o.map((e=>parseInt(e,10))));return t[i+1]=e,i+1}function ot(e){let t="";for(let o=0,i=e.length;o<i;o++)t+=e[o];return t}function it(e){let t,o=!1;const i=()=>(o||(t=e instanceof Function?e():e,o=!0),t);return i.map=e=>it((()=>e(i()))),i}function nt(e,t){let o=e.slice(t).find((e=>e));return o||(o=e.slice(0,t).reverse().find((e=>e))),o||""}function rt(e,t){return"after"===e?t+1:t}function st(e,t){if(e===t)return!0;if(e&&!t||t&&!e)return!1;const o=new Set;Object.keys(e).forEach((e=>o.add(e))),Object.keys(t).forEach((e=>o.add(e)));for(let i of o){if(typeof e[i]!=typeof e[i])return!1;if("object"==typeof e[i]){if(!st(e[i],t[i]))return!1}else if(e[i]!==t[i])return!1}return!0}function at(e){const t={...e};return Object.keys(t).forEach((e=>!t[e]&&delete t[e])),t}function lt(e){return e?e.toLowerCase():""}const ct=/rgba?\(|\s+|\)/gi,ht=/^#([A-F\d]{2}){3,4}$/g,dt=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function ut(e){return gt(e.toString(16).padStart(6,"0"))}function gt(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(ct,"").split(",");let o=255;if(3!==t.length&&4!==t.length)throw new Error("invalid color");if(4===t.length){const e=parseFloat(t.pop()||"1");o=Math.round(255*(e||1))}const i=t.map((e=>parseInt(e,10)));255!==o&&i.push(o);return"#"+ot(i.map((e=>e.toString(16).padStart(2,"0")))).toUpperCase()}(e):(t=e.replace("#","").toUpperCase(),3!==t.length&&4!==t.length||(t=t.split("").reduce(((e,t)=>e+t+t),"")),t=`#${t}`),!t.match(ht))throw new Error(`invalid color input: ${e}`);return t}function pt(e){try{return gt(e),!0}catch(e){return!1}}const mt=e=>e>=0&&e<=255;function ft(e,t,o,i=1){if(!mt(e)||!mt(t)||!mt(o)||i<0||i>1)throw new Error(`Invalid RGBA values ${[e,t,o,i]}`);return{a:i,b:o,g:t,r:e}}function vt(e){let{r:t,g:o,b:i}=Ct(e);t/=255,o/=255,i/=255;const n=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return.2126*n(t)+.7152*n(o)+.0722*n(i)}function bt(e){let t=e.r.toString(16),o=e.g.toString(16),i=e.b.toString(16),n=Math.round(255*e.a).toString(16);return 1==t.length&&(t="0"+t),1==o.length&&(o="0"+o),1==i.length&&(i="0"+i),1==n.length&&(n="0"+n),"ff"===n&&(n=""),("#"+t+o+i+n).toUpperCase()}function Ct(e){let t,o,i,n;if(7===(e=gt(e)).length)t=parseInt(e[1]+e[2],16),o=parseInt(e[3]+e[4],16),i=parseInt(e[5]+e[6],16),n=255;else{if(9!==e.length)throw new Error("Invalid color");t=parseInt(e[1]+e[2],16),o=parseInt(e[3]+e[4],16),i=parseInt(e[5]+e[6],16),n=parseInt(e[7]+e[8],16)}return n=+(n/255).toFixed(3),{a:n,r:t,g:o,b:i}}function St(e){(e={...e}).s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,o=t*(1-Math.abs(e.h/60%2-1)),i=e.l-t/2,n=0,r=0,s=0;return 0<=e.h&&e.h<60?(n=t,r=o,s=0):60<=e.h&&e.h<120?(n=o,r=t,s=0):120<=e.h&&e.h<180?(n=0,r=t,s=o):180<=e.h&&e.h<240?(n=0,r=o,s=t):240<=e.h&&e.h<300?(n=o,r=0,s=t):300<=e.h&&e.h<360&&(n=t,r=0,s=o),n=Math.round(255*(n+i)),r=Math.round(255*(r+i)),s=Math.round(255*(s+i)),{a:e.a,r:n,g:r,b:s}}function Et(e){const t=e.r/255,o=e.g/255,i=e.b/255;let n=Math.min(t,o,i),r=Math.max(t,o,i),s=r-n,a=0,l=0,c=0;return a=0==s?0:r==t?(o-i)/s%6:r==o?(i-t)/s+2:(t-o)/s+4,a=Math.round(60*a),a<0&&(a+=360),c=(r+n)/2,l=0==s?0:s/(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 wt=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),yt=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),xt=new RegExp(/^([A-Z]{1,3})+$/,"i"),It=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),Rt=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),Tt=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[wt.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 At(e){return It.test(e)}function Ot(e){return Rt.test(e)}function Mt(e){return xt.test(e)}function Nt(e){return yt.test(e)}function _t(e){const t=e.split("!"),o=t.pop();return{sheetName:Ne(t.join("!"))||void 0,xc:o}}function Ft(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Ft(Math.floor(e/26)-1)+Ft(e%26)}function Dt(e){let t=0;const o=e.length;for(let i=0;i<o;i++){t+=(e.charCodeAt(i)-65+(i<o-1?1:0))*26**(o-i-1)}return t}function kt(e){const t=(e=e.toUpperCase().trim()).match(wt);if(null!==t){const[o,i,n]=t;if(o===e){return{col:Dt(i),row:parseInt(n,10)-1}}}throw new Error(`Invalid cell description: ${e}`)}function $t(e,t,o={colFixed:!1,rowFixed:!1}){return(o.colFixed?"$":"")+Ft(e)+(o.rowFixed?"$":"")+String(t+1)}const Pt=140,Lt=20,Ut=.035;function Vt(e){return Lt+(Pt-Lt)*Math.exp(-Ut*(e-1))}const zt=/(^-?\d+(\.?\d*(e\d+)?)?|^-?\.\d+)(?!\w|!)/,Bt="(\\s*(\\d+(,\\d{3,})*(\\.\\d*)?)|(\\.\\d+))(e(\\+|-)?\\d+)?(\\s*%)?",Ht="(\\s*-)?",Wt="(\\s*[\\$€])?",Gt="^(("+[Ht+Wt+Bt,Ht+Bt+Wt,Wt+Ht+Bt].join(")|(")+"))$",qt=new RegExp(Gt,"i");function Zt(e){return!!e&&qt.test(e.trim())}const jt=/[,\$€]+/g;function Xt(e){e=e.replace(jt,"");let t=Number(e);return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}function Yt(e,t,o){const i=[...e].sort(((e,t)=>e-t));let n=(i.length+(o?-1:1))*t;if(o||n--,Number.isInteger(n))return i[n];const r=Math.ceil(n),s=Math.floor(n);return i[r]*(n-s)+i[s]*(r-n)}const Kt=20,Qt=11,Jt=/(\d+?)(?=(\d{3})+(?!\d)|$)/g,eo=/0/g,to={0:r("January"),1:r("February"),2:r("March"),3:r("April"),4:r("May"),5:r("June"),6:r("July"),7:r("August"),8:r("September"),9:r("October"),10:r("November"),11:r("December")},oo={0:r("Sunday"),1:r("Monday"),2:r("Tuesday"),3:r("Wednesday"),4:r("Thursday"),5:r("Friday"),6:r("Saturday")},io={};function no(e){let t=io[e];return void 0===t&&(t=function(e){if(""===e)throw new Error("A format cannot be empty");let t=0,o=[];for(;t<e.length;){let i;if("["===e.charAt(t)){if("$"!==e.charAt(t+1))throw new Error(`Currency formats have to be prefixed by a $: ${e}`);if(i=e.substring(t+1).indexOf("]")+t+2,0===i)throw new Error(`Invalid currency brackets format: ${e}`);const n=e.substring(t+2,i-1);if(n.includes("["))throw new Error(`Invalid currency format: ${e}`);o.push({type:"STRING",format:n})}else{const n=e.substring(t).indexOf("[");i=n>-1?n+t:e.length;const r=e.substring(t,i);r.match(j)?o.push({type:"DATE",format:r}):o.push({type:"NUMBER",format:Eo(r)})}t=i}return o}(e),io[e]=t),t}function ro(e,t){switch(typeof e){case"string":return e;case"boolean":return e?"TRUE":"FALSE";case"number":t||(t=fo(e));return function(e,t){if("DATE"===t[0].type)return go(e,t[0].format);let o=e<0?"-":"";for(let i of t)switch(i.type){case"NUMBER":o+=so(Math.abs(e),i.format);break;case"STRING":o+=i.format}return o}(e,no(t));case"object":return"0"}}function so(e,t){t.isPercent&&(e*=100),e/=t.magnitude;let o=0;void 0!==t.decimalPart&&(o=t.decimalPart.length);const{integerDigits:i,decimalDigits:n}=lo(e,o);let r=function(e,t,o){var i;const n="0"===e?"":e;let r=n;const s=t.length-n.length;if(s>0){const e=(t.substring(0,s).match(eo)||[]).length;r="0".repeat(e)+r}o&&(r=(null===(i=r.match(Jt))||void 0===i?void 0:i.join(","))||r);return r}(i,t.integerPart,t.thousandsSeparator);return void 0!==t.decimalPart&&(r+="."+function(e,t){let o=e;if(t.length-e.length>0){const i=(t.substring(e.length,t.length+1).match(eo)||[]).length;o+="0".repeat(i)}return o}(n||"",t.decimalPart)),t.isPercent&&(r+="%"),r}const ao=[];function lo(e,t=Kt){const o=e.toString();if(o.includes("e"))return function(e,t=Kt){let o=ao[t];o||(o=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),ao[t]=o);const[i,n]=o.format(e).split(".");return{integerDigits:i,decimalDigits:n}}(e,t);if(Number.isInteger(e))return{integerDigits:o,decimalDigits:void 0};const i=o.indexOf(".");let n=o.substring(0,i),r=o.substring(i+1);if(0===t)return Number(r[0])>=5&&(n=(Number(n)+1).toString()),{integerDigits:n,decimalDigits:void 0};if(r.length>t){const{integerDigits:e,decimalDigits:o}=function(e,t){var o;let i="0",n=e,r=e.slice(0,t);const s=t;if(Number(e[s])<5)return{integerDigits:i,decimalDigits:r};const a=(null===(o=r.match(ho))||void 0===o?void 0:o[0])||"",l=(Number(r)+1).toString(),c=r.slice(a.length),h=l.length>c.length;h&&!a?(i="1",n=void 0):n=h?a.slice(0,-1)+l:a+l;return{integerDigits:i,decimalDigits:n}}(r,t);r=o,"0"!==e&&(n=(Number(n)+Number(e)).toString())}return{integerDigits:n,decimalDigits:co(r||"")}}function co(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const ho=/^0+/;function uo(e){try{return go(1,e),!0}catch(e){return!1}}function go(e,t){const o=Se(e),i=t.indexOf("h");let n="",r="";return i>0?(n=po(o,t.substring(0,i-1)),r=mo(o,t.substring(i))):0===i?r=mo(o,t):i<0&&(n=po(o,t)),n+(n&&r?" ":"")+r}function po(e,t){var o;const i=null===(o=t.match(/\/|-|\s/))||void 0===o?void 0:o[0];return(i?t.split(i):[t]).map((o=>{switch(o){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return oo[e.getDay()].slice(0,3);case"dddd":return oo[e.getDay()];case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return to[e.getMonth()].slice(0,3);case"mmmm":return to[e.getMonth()];case"mmmmm":return to[e.getMonth()].slice(0,1);case"yy":const o=String(e.getFullYear()).replace("-","").padStart(2,"0");return o.slice(o.length-2);case"yyyy":return e.getFullYear();default:throw new Error(`invalid format: ${t}`)}})).join(i)}function mo(e,t){let o=t.split(/:|\s/);const i=e.getHours(),n="a"===o[o.length-1];let r=i,s="";return n&&(r=0===r?12:r>12?r-12:r,s=i>=12?" PM":" AM",o.pop()),o.map((o=>{switch(o){case"hhhh":return Math.floor((e.getTime()-he)/36e5).toString();case"hh":return r.toString().padStart(2,"0");case"mm":return e.getMinutes().toString().padStart(2,"0");case"ss":return e.getSeconds().toString().padStart(2,"0");default:throw new Error(`invalid format: ${t}`)}})).join(":")+s}function fo(e){let{integerDigits:t,decimalDigits:o}=lo(e);if(!o)return"0";const i=t.replace("-","").length;if(i+2>Qt)return"0";const n=Qt-i-1;return({decimalDigits:o}=lo(e,Math.min(n,o.length))),o?"0."+"0".repeat(o.length):"0"}function vo(e){if(Be(e)){return be(e).format}if(!Zt(e))return;const t=e.includes(".")?"0.00":"0",o=e.match(/[\$€]/);if(o){const i=e.match(/[\d]/),n="[$"+o.values().next().value+"]";return i.index<o.index?"#,##"+t+n:n+"#,##"+t}return e.includes("%")?t+"%":void 0}function bo(e,t,o){return yo(no(e||"#,##0").map((e=>"NUMBER"===e.type?[{...e,format:{...e.format,magnitude:t,decimalPart:void 0}},{type:"STRING",format:o}]:e)).flat())}function Co(e,t){var o;const i={...e},n=Math.sign(t),r=(null===(o=i.decimalPart)||void 0===o?void 0:o.length)||0,s=Math.min(Math.max(0,r+n),Kt);return i.decimalPart="0".repeat(s),""===i.decimalPart&&delete i.decimalPart,i}const So=/,*?$/;function Eo(e){var t;if(function(e){return Boolean(e.replace(wo,""))}(e=e.trim()))throw new Error(`Invalid number format: ${e}`);const o=e.includes("%"),i=(null===(t=e.match(So))||void 0===t?void 0:t[0])||"",n=i?1e3**i.length:1;let r=e.slice(0,e.length-(i.length||0));const s=r.includes(",");if(r.match(/\..*,/))throw new Error("A format can't contain ',' symbol in the decimal part");r=r.replace("%","").replace(",","");const a=r.match(/[\%|,]/);if(a)throw new Error(`A format can only contain a single '${a[0]}' symbol`);const[l,c]=r.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:o,thousandsSeparator:s,decimalPart:c,magnitude:n}:{integerPart:l,isPercent:o,thousandsSeparator:s,magnitude:n}}const wo=/[,#0.%]/g;function yo(e){let t="";for(let o of e){let e;switch(o.type){case"NUMBER":const t=o.format;e=t.integerPart,t.thousandsSeparator&&(e=e.slice(0,-3)+","+e.slice(-3)),void 0!==t.decimalPart&&(e+="."+t.decimalPart),t.isPercent&&(e+="%"),t.magnitude&&(e+=",".repeat(Math.log10(t.magnitude)/3));break;case"STRING":e=`[$${o.format}]`;break;case"DATE":e=o.format}t+=e}return t}class xo{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 xo?e:new xo(e,t.getSheetSize)}get unboundedZone(){return this._zone}get zone(){const{left:e,top:t,bottom:o,right:i}=this._zone;if(void 0!==i&&void 0!==o)return{left:e,top:t,right:i,bottom:o};if(void 0===o&&void 0!==i)return{right:i,top:t,left:e,bottom:this.getSheetSize(this.sheetId).height-1};if(void 0===i&&void 0!==o)return{bottom:o,left:e,top:t,right:this.getSheetSize(this.sheetId).width-1};throw new Error(r("Bad zone format"))}static getRangeParts(e,t){const o=e.split(":").map((e=>{const t=Ot(e);return{colFixed:!t&&e.startsWith("$"),rowFixed:t?e.startsWith("$"):e.includes("$",1)}})),i=void 0===t.bottom,n=void 0===t.right;return i&&(o[0].rowFixed=o[0].rowFixed||o[1].rowFixed,o[1].rowFixed=o[0].rowFixed||o[1].rowFixed,t.left===t.right&&(o[0].colFixed=o[0].colFixed||o[1].colFixed,o[1].colFixed=o[0].colFixed||o[1].colFixed)),n&&(o[0].colFixed=o[0].colFixed||o[1].colFixed,o[1].colFixed=o[0].colFixed||o[1].colFixed,t.top===t.bottom&&(o[0].rowFixed=o[0].rowFixed||o[1].rowFixed,o[1].rowFixed=o[0].rowFixed||o[1].rowFixed)),o}get isFullCol(){return void 0===this._zone.bottom}get isFullRow(){return void 0===this._zone.right}get rangeData(){return{_zone:this._zone,_sheetId:this.sheetId}}orderZone(){var e,t,o,i,n,r,s,a;const l={...this._zone};let c=this.parts;if(void 0!==l.right&&l.right<l.left){let n=l.right;l.right=l.left,l.left=n,c=[{colFixed:(null===(e=c[1])||void 0===e?void 0:e.colFixed)||!1,rowFixed:(null===(t=c[0])||void 0===t?void 0:t.rowFixed)||!1},{colFixed:(null===(o=c[0])||void 0===o?void 0:o.colFixed)||!1,rowFixed:(null===(i=c[1])||void 0===i?void 0:i.rowFixed)||!1}]}if(void 0!==l.bottom&&l.bottom<l.top){let e=l.bottom;l.bottom=l.top,l.top=e,c=[{colFixed:(null===(n=c[0])||void 0===n?void 0:n.colFixed)||!1,rowFixed:(null===(r=c[1])||void 0===r?void 0:r.rowFixed)||!1},{colFixed:(null===(s=c[1])||void 0===s?void 0:s.colFixed)||!1,rowFixed:(null===(a=c[0])||void 0===a?void 0:a.rowFixed)||!1}]}return this.clone({zone:l,parts:c})}clone(e){return new xo({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 Io(e,t,o){const i=o.sheetId===e?t:o.sheetId;return o.clone({sheetId:i})}function Ro(e,t,o){return o?e.getRangeFromSheetXC(t,o):void 0}function To(e){const t=[];for(let o=0;o<e;o++){const e={cells:{}};t.push(e)}return t}class Ao{constructor(){this.isFastIdStrategy=!1,this.fastIdStart=0}setIsFastStrategy(e){this.isFastIdStrategy=e}uuidv4(){return this.isFastIdStrategy?(this.fastIdStart++,String(this.fastIdStart)):window.crypto&&window.crypto.getRandomValues?([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,(e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16))):"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}}function Oo(e){const t=function(e){const t=(e=e.split("!").pop()).replace(/\$/g,"").split(":").map((e=>e.trim()));let o,i,n,r,s=!1,a=!1,l=!1;const c=t[0],h=t[1]&&t[1];if(At(c))n=r=Dt(c),o=i=0,s=!0;else if(Ot(c))o=i=parseInt(c,10)-1,n=r=0,a=!0;else{const e=kt(c);n=r=e.col,o=i=e.row,l=!0}if(2===t.length)if(At(h))r=Dt(h),s=!0;else if(Ot(h))i=parseInt(h,10)-1,a=!0;else{const e=kt(h);r=e.col,i=e.row,o=s?i:o,n=a?r:n,l=!0}if(s&&a)throw new Error("Wrong zone xc. The zone cannot be at the same time a full column and a full row");const d={top:o,left:n,bottom:s?void 0:i,right:a?void 0:r};return l=l&&(a||s),l&&(d.hasHeader=l),d}(e);if(void 0!==t.right&&t.right<t.left){const e=t.left;t.left=t.right,t.right=e}if(void 0!==t.bottom&&t.bottom<t.top){const e=t.top;t.top=t.bottom,t.bottom=e}return t}function Mo(e){const t=Oo(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function No(e){const{bottom:t,top:o,left:i,right:n}=e;return!(void 0!==t&&isNaN(t)||isNaN(o)||isNaN(i)||void 0!==n&&isNaN(n))&&((void 0===e.bottom||e.bottom>=e.top&&e.bottom>=0)&&(void 0===e.right||e.right>=e.left&&e.right>=0)&&e.top>=0&&e.left>=0)}function _o(e){const{top:t,bottom:o,left:i,right:n}=e,s="hasHeader"in e&&e.hasHeader,a=t===o&&i===n;if(void 0===o&&void 0!==n)return 0!==t||s?`${$t(i,t)}:${Ft(n)}`:`${Ft(i)}:${Ft(n)}`;if(void 0===n&&void 0!==o)return 0!==i||s?`${$t(i,t)}:${o+1}`:`${t+1}:${o+1}`;if(void 0!==o&&void 0!==n)return a?$t(i,t):`${$t(i,t)}:${$t(n,o)}`;throw new Error(r("Bad zone format"))}function Fo(e,t,o,i,n){const r="left"===t?"columns":"rows",s="before"===i?o-1:o,a=e["left"===t?"right":"bottom"];return e[t]<=s&&a&&a>s?jo(e,r,"RESIZE",n):s<e[t]?jo(e,r,"MOVE",n):{...e}}function Do(e,t,o,i,n){const r="left"===t?"columns":"rows",s="before"===i?o-1:o,a="left"===t?"right":"bottom";return e[t]<=s&&e[a]>s?jo(e,r,"RESIZE",n):s<e[t]?jo(e,r,"MOVE",n):{...e}}function ko(e,t,o){const i="left"===t?"right":"bottom";let n=e[t],r=e[i];for(let s of o.sort(((e,t)=>t-e)))e[t]>s&&(n--,r--),e[t]<s&&e[i]>=s&&r--;return{...e,[t]:n,[i]:r}}function $o(e,t,o){const i="left"===t?"right":"bottom";let n=e[t],r=e[i];const s=e[i];for(let i of o.sort(((e,t)=>t-e)))e[t]>i&&(n--,void 0!==r&&r--),void 0!==s&&void 0!==r&&e[t]<=i&&s>=i&&r--;if(!(void 0!==r&&n>r))return{...e,[t]:n,[i]:r}}function Po(...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 Lo(e,t){if(Vo(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 Uo(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function Vo(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function zo(e,t,o){const{left:i,right:n,top:r,bottom:s}=o;return e>=i&&e<=n&&t>=r&&t<=s}function Bo(e,t){return Uo(Po(t,e),t)}function Ho(e,t){const o=e.map(Oo),i=t.map(Mo),n=Math.max(...o.concat(i).map((e=>e.bottom||0))),r=Math.max(...o.concat(i).map((e=>e.right||0))),s=o.map((e=>({...e,bottom:void 0===e.bottom?n+1:e.bottom,right:void 0===e.right?r+1:e.right}))),a=i.map((e=>({...e,bottom:void 0===e.bottom?n+1:e.bottom,right:void 0===e.right?r+1:e.right}))),l=function(e,t){const o=new Set(t.map((({col:e,row:t})=>`${e}-${t}`)));return e.filter((({col:e,row:t})=>!o.has(`${e}-${t}`)))}(s.map(Zo).flat(),a.map(Zo).flat()),c=function(e){if(0===e.length)return[];const[t,...o]=[...e].sort(((e,t)=>e.row-t.row)).sort(((e,t)=>e.col-t.col)),i=[];let n=Ko(t);for(const{col:e,row:t}of o)if(!zo(e,t,n))if(e===n.left&&t===n.bottom+1){const e=n.bottom+1;n={...n,bottom:e}}else i.push(n),n=Ko({col:e,row:t});return[...i,n]}(l);return function(e){if(0===e.length)return[];if(e.some((e=>e.left!==e.right)))throw new Error("only columns can be merged");const t=[],o=Wo(e),i=(e,t)=>e.top===t.top&&e.bottom===t.bottom&&e.right+1===t.left;for(;o.length;){const e=o.reduce(((e,t)=>i(e,t)?Po(e,t):e),o.shift());t.push(e)}return Wo(t)}(c).map((e=>({...e,bottom:e.bottom===n+1?void 0:e.bottom,right:e.right===r+1?void 0:e.right}))).map(_o)}function Wo(e){const t=[...e].sort(((e,t)=>t.right-e.right)).sort(((e,t)=>t.bottom-e.bottom)).sort(((e,t)=>e.top-t.top)).sort(((e,t)=>e.left-t.left)).reverse(),o=[];for(;0!==t.length;){const e=t.shift();t.some((t=>Bo(e,t)))||o.push(e)}return o.reverse()}function Go(e){return{height:e.bottom-e.top+1,width:e.right-e.left+1}}function qo(e){const{width:t,height:o}=Go(e);return 1===t||1===o}function Zo(e){const t=[],[o,i]=[e.right,e.left].sort(((e,t)=>e-t)),[n,r]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of Ue(o,i+1))for(const o of Ue(n,r+1))t.push({col:e,row:o});return t}function jo(e,t,o,i){const n="both"===t?i[0]:"columns"===t?i:0,r="both"===t?i[1]:"rows"===t?i:0,s="hasHeader"in e&&e.hasHeader;let a;a=!function(e){return void 0===e.bottom}(e)||s?!(Qo(e)&&!s)||"columns"!==t:"rows"!==t;const l={...e};return a&&"MOVE"===o&&(l.left+=n,l.top+=r),void 0!==l.right&&(l.right+=n),void 0!==l.bottom&&(l.bottom+=r),l}function Xo(e,t){let o,i;const{left:n,right:r,top:s,bottom:a}=e,{left:l,right:c,top:h,bottom:d}=t;return o=l!=n?l:c!=r?c:l,i=h!=s?h:d!=a?d:h,{col:o,row:i}}function Yo(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 Ko(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function Qo(e){return void 0===e.right}function Jo(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function ei(...e){return e.length<2||1===Ho(e.map(_o),[]).length}class ti 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;st(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,o,i,n;const r=e.chartJsConfig;r.data&&r.data.datasets?(this.chart.data=r.data,(null===(t=r.options)||void 0===t?void 0:t.title)&&(this.chart.config.options.title=r.options.title),r.options&&"valueLabel"in r.options&&(null===(o=r.options)||void 0===o?void 0:o.valueLabel)&&(this.chart.config.options.valueLabel=r.options.valueLabel)):this.chart.data.datasets=void 0,this.chart.config.options.legend=null===(i=r.options)||void 0===i?void 0:i.legend,this.chart.config.options.scales=null===(n=r.options)||void 0===n?void 0:n.scales,this.chart.update({duration:0})}}ti.template="o-spreadsheet-ChartJsComponent",ti.props={figure:Object};const oi={};let ii=0;function ni(e,...t){const o="__sheet__"+ii++;return function(e,t){const o=document.createElement("style");o.textContent=function(e){const t=e.split(/(\{|\}|;)/).map((e=>e.trim())),o=[],i=[];let n=[];function r(e,t){const i=[];for(const n of o[e]){let s=t&&t+" "+n||n;s.includes("&")&&(s=n.replace(/&/g,t||"")),e<o.length-1&&(s=r(e+1,s)),i.push(s)}return i.join(", ")}function s(){n.length&&(i.push(r(0)+" {"),i.push(...n),i.push("}"),n=[])}for(;t.length;){let e=t.shift();"}"===e?(s(),o.pop()):("{"===t[0]&&(s(),o.push(e.split(/\s*,\s*/)),t.shift()),";"===t[0]&&n.push(" "+e+";"))}return i.join("\n")}(t),oi[e]=o}(o,String.raw(e,...t)),function(e){const t=oi[e];t.setAttribute("component",e),document.head.appendChild(t)}(o),o}function ri({strikethrough:e,underline:t}){return e||t?`${e?"line-through":""} ${t?"underline":""}`:"none"}function si(e){const t=ai(e);return e?(e.fillColor&&(t.background=e.fillColor),t):t}function ai(e){const t={};if(!e)return t;if(e.bold&&(t["font-weight"]="bold"),e.italic&&(t["font-style"]="italic"),e.strikethrough||e.underline){let o=e.strikethrough?"line-through":"";o=e.underline?o+" underline":o,t["text-decoration"]=o}return e.textColor&&(t.color=e.textColor),t}function li(e,t=!0){const o=t?"\n":"",i=Object.entries(e).map((([e,t])=>`${e}: ${t};`)).join(o);return i?"\n"+i+"\n":""}const ci=1.2;ni`
2
2
  div.o-scorecard {
3
3
  font-family: ${G};
4
4
  user-select: none;
@@ -17,15 +17,15 @@
17
17
 
18
18
  .o-title-text {
19
19
  text-align: left;
20
- height: ${li+"em"};
21
- line-height: ${li+"em"};
20
+ height: ${ci+"em"};
21
+ line-height: ${ci+"em"};
22
22
  overflow: hidden;
23
23
  white-space: nowrap;
24
24
  }
25
25
 
26
26
  .o-key-text {
27
- line-height: ${li+"em"};
28
- height: ${li+"em"};
27
+ line-height: ${ci+"em"};
28
+ height: ${ci+"em"};
29
29
  overflow: hidden;
30
30
  white-space: nowrap;
31
31
  }
@@ -40,8 +40,8 @@
40
40
  }
41
41
 
42
42
  .o-baseline-text {
43
- line-height: ${li+"em"};
44
- height: ${li+"em"};
43
+ line-height: ${ci+"em"};
44
+ height: ${ci+"em"};
45
45
  overflow: hidden;
46
46
  white-space: nowrap;
47
47
 
@@ -50,7 +50,7 @@
50
50
  }
51
51
  }
52
52
  }
53
- `;class ci 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 ft(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(){const e=.96*this.props.figure.width,t=this.getWidestElement(),o=t.getElementMaxFontSize(this.getDrawableHeight(),this);let i=function(e,t,o,i=.25){let n=1;if(o(n)>e)return n;if(o(t)<e)return t;let r=(n+t)/2,s=o(r),a=0;for(;Math.abs(s-e)>i&&a<20;)s>=e?t=(n+t)/2:n=(n+t)/2,r=(n+t)/2,s=o(r),a++;return r}(e,o,(e=>t.getElementWidth(e,this.ctx,this)))/o;const n=(new di).getElementMaxFontSize(this.getDrawableHeight(),this)*i,r=(new hi).getElementMaxFontSize(this.getDrawableHeight(),this)*i;return{titleStyle:this.getTextStyle({fontSize:18,color:this.secondaryFontColor}),keyStyle:this.getTextStyle({fontSize:n,cellStyle:this.runtime.keyValueStyle,color:this.primaryFontColor}),baselineStyle:this.getTextStyle({fontSize:r}),baselineValueStyle:this.getTextStyle({fontSize:r,cellStyle:this.runtime.baselineStyle,color:this.runtime.baselineColor||this.secondaryFontColor}),baselineDescrStyle:this.getTextStyle({fontSize:.9*r,color:this.secondaryFontColor})}}getTextStyle(e){const t=si(e.cellStyle);return t["font-size"]=`${e.fontSize}px`,t.display="inline-block",!t.color&&e.color&&(t.color=e.color),ai(t)}getDrawableHeight(){const e=2*this.chartPadding;let t=this.props.figure.height-e;return t-=this.title?18*li:0,t}getWidestElement(){const e=new hi,t=new di;return e.getElementWidth(.35,this.ctx,this)>t.getElementWidth(.65,this.ctx,this)?e:t}}ci.template="o-spreadsheet-ScorecardChart";class hi{getElementWidth(e,t,o){if(!o.runtime)return 0;const i=o.baseline,n="neutral"!==o.baselineArrowDirection?"A "+i:i;t.font=`${e}px ${G}`;let r=t.measureText(n).width;return t.font=`${.9*e}px ${G}`,r+=t.measureText(o.baselineDescr).width,r}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.35*e:0)/li}}class di{getElementWidth(e,t,o){if(!o.runtime)return 0;const i=o.keyValue||"";return t.font=`${e}px ${G}`,t.measureText(i).width}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.65*e:e)/li}}function ui(e){return 8===(e=ut(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}ci.props={figure:Object};class gi{constructor(e,t,o){this.title=e.title,this.sheetId=t,this.getters=o}static validateChartDefinition(e,t){throw new Error("This method should be implemented by sub class")}static transformDefinition(e,t){throw new Error("This method should be implemented by sub class")}static getDefinitionFromContextCreation(e){throw new Error("This method should be implemented by sub class")}}function pi(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?ko(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?_o(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):{...e}}var mi,fi;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(mi||(mi={})),function(e){e.PlainText="text/plain",e.Html="text/html"}(fi||(fi={}));const vi=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),bi=new Set([...vi,"DUPLICATE_SHEET","EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT"]),Ci=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","REFRESH_SEARCH","UPDATE_SEARCH","CLEAR_SEARCH","EVALUATE_CELLS","SET_CURRENT_CONTENT","SET_FORMULA_VISIBILITY","OPEN_CELL_POPOVER","CLOSE_CELL_POPOVER","UPDATE_FILTER"]),Si=new Set(["UPDATE_CELL","UPDATE_CELL_POSITION","CLEAR_CELL","DELETE_CONTENT","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","RESIZE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","UNHIDE_COLUMNS_ROWS","SET_GRID_LINES_VISIBILITY","UNFREEZE_COLUMNS","UNFREEZE_ROWS","FREEZE_COLUMNS","FREEZE_ROWS","UNFREEZE_COLUMNS_ROWS","ADD_MERGE","REMOVE_MERGE","CREATE_SHEET","DELETE_SHEET","DUPLICATE_SHEET","MOVE_SHEET","RENAME_SHEET","HIDE_SHEET","SHOW_SHEET","MOVE_RANGES","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT","CREATE_FIGURE","DELETE_FIGURE","UPDATE_FIGURE","SET_FORMATTING","CLEAR_FORMATTING","SET_BORDER","CREATE_CHART","UPDATE_CHART","CREATE_FILTER_TABLE","REMOVE_FILTER_TABLE","CREATE_IMAGE"]);function Ei(e){return Si.has(e.type)}class wi{constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new wi}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var yi,xi,Ii;function Ri(e,t,o,i){let n=!1;const r=[];for(let i in o){let s=o[i];if(s.labelCell){const e=Oi(s.labelCell,t);s.labelCell!==e&&(n=!0,s={...s,labelCell:e})}const a=Oi(s.dataRange,t);void 0===a||e.getRangeString(a,a.sheetId)===X?(n=!0,s=void 0):a!==s.dataRange&&(n=!0,s={...s,dataRange:a}),r[i]=s}let s=i;const a=Oi(s,t);a!==s&&(n=!0,s=a);return{isStale:n,dataSets:r.filter(Qe),labelRange:s}}function Ti(e,t,o){return o.map((o=>({dataRange:xo(e,t,o.dataRange),labelCell:o.labelCell?xo(e,t,o.labelCell):void 0})))}function Ai(e,t,o){return o?xo(e,t,o):void 0}function Oi(e,t){if(!e)return;const o=t(e);switch(o.changeType){case"NONE":return e;case"REMOVE":return;default:return o.range}}function Mi(e,t,o,i){const n=[];for(const r of t){const t=e.getRangeFromSheetXC(o,r),{unboundedZone:s,sheetId:a,invalidSheetName:l}=t;if(!l)if(s.left!==s.right&&s.top!==s.bottom){if(void 0===s.right)continue;for(let t=s.left;t<=s.right;t++){const o={...s,left:t,right:t};n.push(Ni(e,a,o,i?{top:o.top,bottom:o.top,left:o.left,right:o.left}:void 0))}}else s.left===s.right&&s.top===s.bottom?i||n.push(Ni(e,a,s,void 0)):n.push(Ni(e,a,s,i?{top:s.top,bottom:s.top,left:s.left,right:s.left}:void 0))}return n}function Ni(e,t,o,i){if(o.left!==o.right&&o.top!==o.bottom)throw new Error(`Zone should be a single column or row: ${No(o)}`);if(i){const n=No(o),r=No(i);return{labelCell:e.getRangeFromSheetXC(t,r),dataRange:e.getRangeFromSheetXC(t,n)}}return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,No(o))}}function _i(e,t){var o;const i=null===(o=t.labelCell)||void 0===o?void 0:o.zone;let n=t.dataRange.zone;if(i){const{height:e,width:t}=Wo(n);1===e?n={...n,left:n.left+1}:1===t&&(n={...n,top:n.top+1})}const r=t.dataRange.clone({zone:n});return{label:t.labelCell?e.getRangeString(t.labelCell,"forceSheetReference"):void 0,range:e.getRangeString(r,"forceSheetReference")}}function Fi(e,t){let o;if(e.labelRange){const i=pi(Ao(e.labelRange),t);o=i?No(i):void 0}const i=e.dataSets.map(Ao).map((e=>pi(e,t))).filter(Qe).map(No);return{...e,labelRange:o,dataSets:i}}e.CommandResult=void 0,(yi=e.CommandResult||(e.CommandResult={}))[yi.Success=0]="Success",yi[yi.CancelledForUnknownReason=1]="CancelledForUnknownReason",yi[yi.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",yi[yi.MergeIsDestructive=3]="MergeIsDestructive",yi[yi.CellIsMerged=4]="CellIsMerged",yi[yi.InvalidTarget=5]="InvalidTarget",yi[yi.EmptyUndoStack=6]="EmptyUndoStack",yi[yi.EmptyRedoStack=7]="EmptyRedoStack",yi[yi.NotEnoughElements=8]="NotEnoughElements",yi[yi.NotEnoughSheets=9]="NotEnoughSheets",yi[yi.MissingSheetName=10]="MissingSheetName",yi[yi.DuplicatedSheetName=11]="DuplicatedSheetName",yi[yi.DuplicatedSheetId=12]="DuplicatedSheetId",yi[yi.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",yi[yi.WrongSheetMove=14]="WrongSheetMove",yi[yi.WrongSheetPosition=15]="WrongSheetPosition",yi[yi.InvalidAnchorZone=16]="InvalidAnchorZone",yi[yi.SelectionOutOfBound=17]="SelectionOutOfBound",yi[yi.TargetOutOfSheet=18]="TargetOutOfSheet",yi[yi.WrongCutSelection=19]="WrongCutSelection",yi[yi.WrongPasteSelection=20]="WrongPasteSelection",yi[yi.WrongPasteOption=21]="WrongPasteOption",yi[yi.WrongFigurePasteOption=22]="WrongFigurePasteOption",yi[yi.EmptyClipboard=23]="EmptyClipboard",yi[yi.EmptyRange=24]="EmptyRange",yi[yi.InvalidRange=25]="InvalidRange",yi[yi.InvalidZones=26]="InvalidZones",yi[yi.InvalidSheetId=27]="InvalidSheetId",yi[yi.InvalidFigureId=28]="InvalidFigureId",yi[yi.InputAlreadyFocused=29]="InputAlreadyFocused",yi[yi.MaximumRangesReached=30]="MaximumRangesReached",yi[yi.InvalidChartDefinition=31]="InvalidChartDefinition",yi[yi.InvalidDataSet=32]="InvalidDataSet",yi[yi.InvalidLabelRange=33]="InvalidLabelRange",yi[yi.InvalidScorecardKeyValue=34]="InvalidScorecardKeyValue",yi[yi.InvalidScorecardBaseline=35]="InvalidScorecardBaseline",yi[yi.InvalidGaugeDataRange=36]="InvalidGaugeDataRange",yi[yi.EmptyGaugeRangeMin=37]="EmptyGaugeRangeMin",yi[yi.GaugeRangeMinNaN=38]="GaugeRangeMinNaN",yi[yi.EmptyGaugeRangeMax=39]="EmptyGaugeRangeMax",yi[yi.GaugeRangeMaxNaN=40]="GaugeRangeMaxNaN",yi[yi.GaugeRangeMinBiggerThanRangeMax=41]="GaugeRangeMinBiggerThanRangeMax",yi[yi.GaugeLowerInflectionPointNaN=42]="GaugeLowerInflectionPointNaN",yi[yi.GaugeUpperInflectionPointNaN=43]="GaugeUpperInflectionPointNaN",yi[yi.GaugeLowerBiggerThanUpper=44]="GaugeLowerBiggerThanUpper",yi[yi.InvalidAutofillSelection=45]="InvalidAutofillSelection",yi[yi.WrongComposerSelection=46]="WrongComposerSelection",yi[yi.MinBiggerThanMax=47]="MinBiggerThanMax",yi[yi.LowerBiggerThanUpper=48]="LowerBiggerThanUpper",yi[yi.MidBiggerThanMax=49]="MidBiggerThanMax",yi[yi.MinBiggerThanMid=50]="MinBiggerThanMid",yi[yi.FirstArgMissing=51]="FirstArgMissing",yi[yi.SecondArgMissing=52]="SecondArgMissing",yi[yi.MinNaN=53]="MinNaN",yi[yi.MidNaN=54]="MidNaN",yi[yi.MaxNaN=55]="MaxNaN",yi[yi.ValueUpperInflectionNaN=56]="ValueUpperInflectionNaN",yi[yi.ValueLowerInflectionNaN=57]="ValueLowerInflectionNaN",yi[yi.MinInvalidFormula=58]="MinInvalidFormula",yi[yi.MidInvalidFormula=59]="MidInvalidFormula",yi[yi.MaxInvalidFormula=60]="MaxInvalidFormula",yi[yi.ValueUpperInvalidFormula=61]="ValueUpperInvalidFormula",yi[yi.ValueLowerInvalidFormula=62]="ValueLowerInvalidFormula",yi[yi.InvalidSortZone=63]="InvalidSortZone",yi[yi.WaitingSessionConfirmation=64]="WaitingSessionConfirmation",yi[yi.MergeOverlap=65]="MergeOverlap",yi[yi.TooManyHiddenElements=66]="TooManyHiddenElements",yi[yi.Readonly=67]="Readonly",yi[yi.InvalidViewportSize=68]="InvalidViewportSize",yi[yi.InvalidScrollingDirection=69]="InvalidScrollingDirection",yi[yi.FigureDoesNotExist=70]="FigureDoesNotExist",yi[yi.InvalidConditionalFormatId=71]="InvalidConditionalFormatId",yi[yi.InvalidCellPopover=72]="InvalidCellPopover",yi[yi.EmptyTarget=73]="EmptyTarget",yi[yi.InvalidFreezeQuantity=74]="InvalidFreezeQuantity",yi[yi.FrozenPaneOverlap=75]="FrozenPaneOverlap",yi[yi.ValuesNotChanged=76]="ValuesNotChanged",yi[yi.InvalidFilterZone=77]="InvalidFilterZone",yi[yi.FilterOverlap=78]="FilterOverlap",yi[yi.FilterNotFound=79]="FilterNotFound",yi[yi.MergeInFilter=80]="MergeInFilter",yi[yi.NonContinuousTargets=81]="NonContinuousTargets",yi[yi.DuplicatedFigureId=82]="DuplicatedFigureId",yi[yi.InvalidSelectionStep=83]="InvalidSelectionStep",yi[yi.DuplicatedChartId=84]="DuplicatedChartId",yi[yi.ChartDoesNotExist=85]="ChartDoesNotExist",yi[yi.InvalidHeaderIndex=86]="InvalidHeaderIndex",yi[yi.InvalidQuantity=87]="InvalidQuantity",function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(xi||(xi={})),function(e){e[e.Background=0]="Background",e[e.Highlights=1]="Highlights",e[e.Clipboard=2]="Clipboard",e[e.Search=3]="Search",e[e.Chart=4]="Chart",e[e.Autofill=5]="Autofill",e[e.Selection=6]="Selection",e[e.Headers=7]="Headers"}(Ii||(Ii={}));const Di=["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 ki{constructor(){this.graphColorIndex=0}next(){return Di[this.graphColorIndex++%Di.length]}}function $i(e){return e&&ft(e)<.3?"#FFFFFF":"#000000"}function Pi(e){if(e.dataSets){const t=void 0!==e.dataSets.find((e=>!Rt.test(e)));if(t)return 32;if(e.dataSets.map(Ao).some((e=>e.top!==e.bottom&&Ko(e))))return 32}return 0}function Li(e){if(e.labelRange){if(!Rt.test(e.labelRange||""))return 33}return 0}function Ui(e,t,o){if(e){if("text"===o||(null==t?void 0:t.type)!==mi.number||e.type!==mi.number)return e.formattedValue;{let i=t.value-e.value;if("percentage"===o&&0!==i&&(i=i/e.value*100),"percentage"!==o&&e.format)return no(i,e.format);const n=Math.abs(parseFloat(i.toFixed(2))).toLocaleString();return"percentage"===o?n+"%":n}}return""}function Vi(e,t,o,i,n){if("text"===t||(null==e?void 0:e.type)!==mi.number||(null==o?void 0:o.type)!==mi.number)return;const r=o.value-e.value;return r>0?i:r<0?n:void 0}function zi(e,t,o){if("text"===o||(null==e?void 0:e.type)!==mi.number||(null==t?void 0:t.type)!==mi.number)return"neutral";const i=t.value-e.value;return i>0?"up":i<0?"down":"neutral"}const Bi={Errors:{25:r("The range is invalid"),51:r("The argument is missing. Please provide a value"),52:r("The second argument is missing. Please provide a value"),53:r("The minpoint must be a number"),54:r("The midpoint must be a number"),55:r("The maxpoint must be a number"),56:r("The first value must be a number"),57:r("The second value must be a number"),47:r("Minimum must be smaller then Maximum"),50:r("Minimum must be smaller then Midpoint"),49:r("Midpoint must be smaller then Maximum"),48:r("Lower inflection point must be smaller than upper inflection point"),58:r("Invalid Minpoint formula"),60:r("Invalid Maxpoint formula"),59:r("Invalid Midpoint formula"),61:r("Invalid upper inflection point formula"),62:r("Invalid lower inflection point formula"),24:r("A range needs to be defined"),Unexpected:r("The rule is invalid for an unknown reason")},ColorScale:r("Color scale"),IconSet:r("Icon set")},Hi={IsEmpty:r("Is empty"),IsNotEmpty:r("Is not empty"),ContainsText:r("Contains"),NotContains:r("Does not contain"),BeginsWith:r("Starts with"),EndsWith:r("Ends with"),Equal:r("Is equal to"),NotEqual:r("Is not equal to"),GreaterThan:r("Is greater than"),GreaterThanOrEqual:r("Is greater than or equal to"),LessThan:r("Is less than"),LessThanOrEqual:r("Is less than or equal to"),Between:r("Is between"),NotBetween:r("Is not between")},Wi={Series:r("Series"),Errors:{Unexpected:r("The chart definition is invalid for an unknown reason"),32:r("The dataset is invalid"),33:r("Labels are invalid"),34:r("The key value is invalid"),35:r("The baseline value is invalid"),36:r("The data range is invalid"),37:r("A minimum range limit value is needed"),38:r("The minimum range limit value must be a number"),39:r("A maximum range limit value is needed"),40:r("The maximum range limit value must be a number"),41:r("Minimum range limit must be smaller than maximum range limit"),42:r("The lower inflection point value must be a number"),43:r("The upper inflection point value must be a number")}},Gi={Automatic:r("Automatic"),Number:r("Number"),Percent:r("Percent"),Currency:r("Currency"),CurrencyRounded:r("Currency rounded"),Date:r("Date"),Time:r("Time"),DateTime:r("Date time"),Duration:r("Duration"),CustomCurrency:r("Custom currency")},qi={Custom:r("Custom")},Zi=r("Merged cells are preventing this operation. Unmerge those cells and try again.");function ji(e,t){if(t.dataRange){const o=t.labelCell?[No(t.labelCell.zone)]:[],i=Bo([No(t.dataRange.zone)],o)[0];if(void 0===i)return[];const n=e.getRangeFromSheetXC(t.dataRange.sheetId,i);return e.getRangeValues(n).map((e=>""===e?void 0:e))}return[]}function Xi(e,t){const o=Le(0,Math.max(e.length,...t.map((e=>{var t;return(null===(t=e.data)||void 0===t?void 0:t.length)||0})))).filter((o=>{const i=e[o],n=t.map((e=>{var t;return null===(t=e.data)||void 0===t?void 0:t[o]}));return i||n.some((e=>0===e||Boolean(e)))}));return{labels:o.map((t=>e[t]||"")),dataSetsValues:t.map((e=>({...e,data:o.map((t=>e.data[t]))})))}}function Yi(e,t){const o=new Set(e),i={};o.forEach((e=>{i[e]=new Array(t.length).fill(0)}));for(const o of Le(0,e.length)){const r=e[o];for(const e of Le(0,t.length))i[r][e]+="number"==typeof(n=t[e].data[o])?n:0}var n;return{labels:Object.keys(i),dataSetsValues:t.map(((e,t)=>({...e,data:Object.values(i).map((e=>e[t]))})))}}function Ki(e){return e?e.length>K?e.substring(0,K)+"…":e:""}function Qi(e,t,o){return{type:e.type,options:{responsive:!0,maintainAspectRatio:!1,layout:{padding:{left:20,right:20,top:e.title?10:25,bottom:10}},elements:{line:{fill:!1},point:{hitRadius:15}},animation:{duration:0},hover:{animationDuration:10},responsiveAnimationDuration:0,title:{display:!!e.title,fontSize:22,fontStyle:"normal",text:n(e.title),fontColor:o},legend:{onClick:void 0}},data:{labels:t.map(Ki),datasets:[]}}}function Ji(e,t,o){let i={values:[],formattedValues:[]};if(o)o.invalidXc||o.invalidSheetName||(i={formattedValues:e.getRangeFormattedValues(o),values:e.getRangeValues(o).map((e=>String(e)))});else if(1===t.length)for(let o=0;o<ji(e,t[0]).length;o++)i.formattedValues.push(""),i.values.push("");else if(t[0]){i={formattedValues:Le(0,ji(e,t[0]).length).map((e=>e.toString())),values:i.formattedValues}}return i}function en(e,t){const o=[];for(const[i,n]of Object.entries(t)){let t;if(n.labelCell){const o=n.labelCell,r=o?e.getEvaluatedCell({sheetId:o.sheetId,col:o.zone.left,row:o.zone.top}):void 0;t=r&&o?Ki(r.formattedValue):t=`${Wi.Series} ${parseInt(i)+1}`}else t=t=`${Wi.Series} ${parseInt(i)+1}`;let r=n.dataRange?ji(e,n):[];o.push({data:r,label:t})}return o}function tn(e){return 0===e?"origin":e-1}class on extends gi{constructor(e,t,o){super(e,t,o),this.type="bar",this.dataSets=Mi(o,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Io(o,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated}static transformDefinition(e,t){return Fi(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,Pi,Li)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:!1,stacked:!1,aggregated:!1,legendPosition:"top",title:e.title||"",type:"bar",verticalAxisPosition:"left",labelRange:e.auxiliaryRange||void 0}}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}copyForSheetId(e){const t=Ti(this.sheetId,e,this.dataSets),o=Ai(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new on(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new on(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,o){return{type:"bar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,o||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,o||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated}}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>_i(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:ui(this.background||w),fontColor:ui($i(this.background)),dataSets:e}}updateRanges(e){const{dataSets:t,labelRange:o,isStale:i}=Ri(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const n=this.getDefinitionWithSpecificDataSets(t,o);return new on(n,this.sheetId,this.getters)}}function nn(e){return e.dataRange&&!Rt.test(e.dataRange)?36:0}function rn(e,t){return t((t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):0),(t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):0))}function sn(e){return e.sectionRule&&Number(e.sectionRule.rangeMin)>=Number(e.sectionRule.rangeMax)?41:0}function an(e,t){if(""===e)switch(t){case"rangeMin":return 37;case"rangeMax":return 39}return 0}function ln(e,t){if(isNaN(e))switch(t){case"rangeMin":return 38;case"rangeMax":return 40;case"lowerInflectionPointValue":return 42;case"upperInflectionPointValue":return 43}return 0}class cn extends gi{constructor(e,t,o){super(e,t,o),this.type="gauge",this.dataRange=Io(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,nn,e.chainValidations(rn(an,e.batchValidations),rn(ln,e.batchValidations),sn),e.chainValidations((o=ln,(0,e.batchValidations)((e=>e.sectionRule?o(e.sectionRule.lowerInflectionPoint.value,"lowerInflectionPointValue"):0),(e=>e.sectionRule?o(e.sectionRule.upperInflectionPoint.value,"upperInflectionPointValue"):0)))));var o}static transformDefinition(e,t){let o;return e.dataRange&&(o=pi(Ao(e.dataRange),t)),{...e,dataRange:o?No(o):void 0}}static getDefinitionFromContextCreation(e){return{background:e.background,title:e.title||"",type:"gauge",dataRange:e.range?e.range[0]:void 0,sectionRule:{colors:{lowerColor:"#cc0000",middleColor:"#f1c232",upperColor:"#6aa84f"},rangeMin:"0",rangeMax:"100",lowerInflectionPoint:{type:"percentage",value:"15"},upperInflectionPoint:{type:"percentage",value:"40"}}}}copyForSheetId(e){const t=Ai(this.sheetId,e,this.dataRange),o=this.getDefinitionWithSpecificRanges(t,e);return new cn(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.dataRange,e);return new cn(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=Oi(this.dataRange,e);if(this.dataRange===t)return this;const o=this.getDefinitionWithSpecificRanges(t);return new cn(o,this.sheetId,this.getters)}}const hn={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},dn={inSeconds:function(e){return Math.floor(e/hn.second)},inMinutes:function(e){return Math.floor(e/hn.minute)},inHours:function(e){return Math.floor(e/hn.hour)},inDays:function(e){return Math.floor(e/hn.day)},inMonths:function(e){return Math.floor(e/hn.month)},inYears:function(e){return Math.floor(e/hn.year)}},un=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function gn(e,t){const o=function(e){const t=(e=(e=e.replace(/y/g,"Y")).replace(/d/g,"D")).indexOf("h");e=t>=0?e.slice(0,t).replace(/m/g,"M")+e.slice(t):e.replace(/m/g,"M");e.includes("a")||(e=e.replace(/h/g,"H"));return e}(t),i=function(e,t){const o=e.map((e=>{var t;return null===(t=be(e))||void 0===t?void 0:t.jsDate}));if(o.some((e=>void 0===e))||e.length<2)return;const i=o.map((e=>e.getTime())),n=Math.max(...i)-Math.min(...i),r=function(e){if(e.includes("s"))return"second";if(e.includes("m"))return"minute";if(e.includes("h")||e.includes("H"))return"hour";if(e.includes("D"))return"day";if(e.includes("M"))return"month";return"year"}(t);if(hn.second>=hn[r]&&dn.inSeconds(n)<180)return"second";if(hn.minute>=hn[r]&&dn.inMinutes(n)<180)return"minute";if(hn.hour>=hn[r]&&dn.inHours(n)<96)return"hour";if(hn.day>=hn[r]&&dn.inDays(n)<90)return"day";if(hn.month>=hn[r]&&dn.inMonths(n)<36)return"month";return"year"}(e,o),n={};return i&&(n[i]=o),{parser:o,displayFormats:n,unit:i}}class pn extends gi{constructor(e,t,o){super(e,t,o),this.type="line",this.dataSets=Mi(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Io(this.getters,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.stacked=e.stacked,this.aggregated=e.aggregated}static validateChartDefinition(e,t){return e.checkValidations(t,Pi,Li)}static transformDefinition(e,t){return Fi(e,t)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:!1,labelsAsText:!1,legendPosition:"top",title:e.title||"",type:"line",verticalAxisPosition:"left",labelRange:e.auxiliaryRange||void 0,stacked:!1,aggregated:!1}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,o){return{type:"line",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,o||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,o||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,stacked:this.stacked,aggregated:this.aggregated}}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(e){const{dataSets:t,labelRange:o,isStale:i}=Ri(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const n=this.getDefinitionWithSpecificDataSets(t,o);return new pn(n,this.sheetId,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>_i(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:ui(this.background||w),fontColor:ui($i(this.background)),dataSets:e}}copyForSheetId(e){const t=Ti(this.sheetId,e,this.dataSets),o=Ai(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new pn(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new pn(t,e,this.getters)}}function mn(e,t){return vn(e,t)||bn(e,t)}function fn(e,t){return function(e,t){return!e.labelsAsText&&vn(e.labelRange,t)}(e,t)?"time":function(e,t){return!e.labelsAsText&&bn(e.labelRange,t)}(e,t)?"linear":"category"}function vn(e,t){if(!e||!bn(e,t))return!1;const o=t.getEvaluatedCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}).format;return Boolean(o&&un.test(o))}function bn(e,t){if(!e)return!1;const o=t.getRangeValues(e);return!o.some((e=>isNaN(Number(e))&&e))&&!o.every((e=>!e))}class Cn extends gi{constructor(e,t,o){super(e,t,o),this.type="pie",this.dataSets=Mi(o,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Io(o,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated}static transformDefinition(e,t){return Fi(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,Pi,Li)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:!1,legendPosition:"top",title:e.title||"",type:"pie",labelRange:e.auxiliaryRange||void 0,aggregated:!1}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinitionWithSpecificDataSets(e,t,o){return{type:"pie",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,o||this.sheetId))),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,o||this.sheetId):void 0,title:this.title,aggregated:this.aggregated}}copyForSheetId(e){const t=Ti(this.sheetId,e,this.dataSets),o=Ai(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new Cn(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Cn(t,e,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>_i(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:ui(this.background||w),fontColor:ui($i(this.background)),verticalAxisPosition:"left",dataSets:e}}updateRanges(e){const{dataSets:t,labelRange:o,isStale:i}=Ri(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const n=this.getDefinitionWithSpecificDataSets(t,o);return new Cn(n,this.sheetId,this.getters)}}function Sn(e,t){const o=[],i=Math.max(...t.map((e=>e.data.length)));for(let t=0;t<=i;t++)o.push(e.next());return o}function En(e){return e.keyValue&&!Rt.test(e.keyValue)?34:0}function wn(e){return e.baseline&&!Rt.test(e.baseline)?35:0}class yn extends gi{constructor(e,t,o){super(e,t,o),this.type="scorecard",this.keyValue=Io(o,t,e.keyValue),this.baseline=Io(o,t,e.baseline),this.baselineMode=e.baselineMode,this.baselineDescr=e.baselineDescr,this.background=e.background,this.baselineColorUp=e.baselineColorUp,this.baselineColorDown=e.baselineColorDown}static validateChartDefinition(e,t){return e.checkValidations(t,En,wn)}static getDefinitionFromContextCreation(e){return{background:e.background,type:"scorecard",keyValue:e.range?e.range[0]:void 0,title:e.title||"",baselineMode:J,baselineColorUp:ee,baselineColorDown:te,baseline:e.auxiliaryRange||""}}static transformDefinition(e,t){let o,i;return e.baseline&&(o=pi(Ao(e.baseline),t)),e.keyValue&&(i=pi(Ao(e.keyValue),t)),{...e,baseline:o?No(o):void 0,keyValue:i?No(i):void 0}}copyForSheetId(e){const t=Ai(this.sheetId,e,this.baseline),o=Ai(this.sheetId,e,this.keyValue),i=this.getDefinitionWithSpecificRanges(t,o,e);return new yn(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,e);return new yn(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue)}getContextCreation(){return{background:this.background,title:this.title,range:this.keyValue?[this.getters.getRangeString(this.keyValue,this.sheetId)]:void 0,auxiliaryRange:this.baseline?this.getters.getRangeString(this.baseline,this.sheetId):void 0}}getDefinitionWithSpecificRanges(e,t,o){return{baselineColorDown:this.baselineColorDown,baselineColorUp:this.baselineColorUp,baselineMode:this.baselineMode,title:this.title,type:"scorecard",background:this.background,baseline:e?this.getters.getRangeString(e,o||this.sheetId):void 0,baselineDescr:this.baselineDescr,keyValue:t?this.getters.getRangeString(t,o||this.sheetId):void 0}}getDefinitionForExcel(){}updateRanges(e){const t=Oi(this.baseline,e),o=Oi(this.keyValue,e);if(this.baseline===t&&this.keyValue===o)return this;const i=this.getDefinitionWithSpecificRanges(t,o);return new yn(i,this.sheetId,this.getters)}}class xn{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 In=new xn;In.add("bar",{match:e=>"bar"===e,createChart:(e,t,o)=>new on(e,t,o),getChartRuntime:function(e,t){let o=Ji(t,e.dataSets,e.labelRange).formattedValues,i=en(t,e.dataSets);({labels:o,dataSetsValues:i}=Xi(o,i)),e.aggregated&&({labels:o,dataSetsValues:i}=Yi(o,i));const n=function(e,t){var o;const i=$i(e.background),n=Qi(e,t,i),r={labels:{fontColor:i}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,n.options.legend={...null===(o=n.options)||void 0===o?void 0:o.legend,...r},n.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},n.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:i}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:i,beginAtZero:!0}}]},e.stacked&&(n.options.scales.xAxes[0].stacked=!0,n.options.scales.yAxes[0].stacked=!0),n}(e,o),r=new ki;for(let{label:e,data:t}of i){const o=r.next(),i={label:e,data:t,borderColor:o,backgroundColor:o};n.data.datasets.push(i)}return{chartJsConfig:n,background:e.background||w}},validateChartDefinition:(e,t)=>on.validateChartDefinition(e,t),transformDefinition:(e,t)=>on.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>on.getDefinitionFromContextCreation(e),name:r("Bar")}),In.add("line",{match:e=>"line"===e,createChart:(e,t,o)=>new pn(e,t,o),getChartRuntime:function(e,t){const o=fn(e,t),i=Ji(t,e.dataSets,e.labelRange);let n="linear"===o?i.values:i.formattedValues,r=en(t,e.dataSets);({labels:n,dataSetsValues:r}=Xi(n,r)),"time"===o&&({labels:n,dataSetsValues:r}=function(e,t){if(0===e.length||e.every((e=>!e)))return{labels:e,dataSetsValues:t};const o=[...e],i=Me(t);for(let e=0;e<o.length;e++)if(!o[e]){o[e]=it(o,e);for(let t of i)t.data[e]=void 0}return{labels:o,dataSetsValues:i}}(n,r)),e.aggregated&&({labels:n,dataSetsValues:r}=Yi(n,r));const s=function(e,t){var o;const i=$i(e.background),n=Qi(e,t,i),r={labels:{fontColor:i,generateLabels(e){const{data:t}=e,o=window.Chart.defaults.global.legend.labels.generateLabels(e);for(const[e,i]of o.entries())i.fillStyle=t.datasets[e].borderColor;return o}}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,n.options.legend={...null===(o=n.options)||void 0===o?void 0:o.legend,...r},n.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},n.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:i}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:i,beginAtZero:!0}}]},e.stacked&&(n.options.scales.yAxes[0].stacked=!0),n}(e,n),a=function(e,t){if(t)return e.getEvaluatedCell({sheetId:t.sheetId,col:t.zone.left,row:t.zone.top}).format}(t,e.labelRange);"time"===o?(s.options.scales.xAxes[0].type="time",s.options.scales.xAxes[0].time=gn(n,a),s.options.scales.xAxes[0].ticks.maxTicksLimit=15):"linear"===o&&(s.options.scales.xAxes[0].type="linear",s.options.scales.xAxes[0].ticks.callback=e=>no(e,a));const l=new ki;for(let[t,{label:i,data:a}]of r.entries()){["linear","time"].includes(o)&&(a=a.map(((e,t)=>({x:n[t]||void 0,y:e}))));const r=l.next();let c=bt(r);e.stacked&&(c.a=oe);const h={label:i,data:a,lineTension:0,borderColor:r,backgroundColor:vt(c),pointBackgroundColor:r,fill:!!e.stacked&&tn(t)};s.data.datasets.push(h)}return{chartJsConfig:s,background:e.background||w}},validateChartDefinition:(e,t)=>pn.validateChartDefinition(e,t),transformDefinition:(e,t)=>pn.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>pn.getDefinitionFromContextCreation(e),name:r("Line")}),In.add("pie",{match:e=>"pie"===e,createChart:(e,t,o)=>new Cn(e,t,o),getChartRuntime:function(e,t){let o=Ji(t,e.dataSets,e.labelRange).formattedValues,i=en(t,e.dataSets);({labels:o,dataSetsValues:i}=Xi(o,i)),e.aggregated&&({labels:o,dataSetsValues:i}=Yi(o,i));const n=function(e,t){var o;const i=$i(e.background),n=Qi(e,t,i),r={labels:{fontColor:i}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,n.options.legend={...null===(o=n.options)||void 0===o?void 0:o.legend,...r},n.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},n.options.tooltips={callbacks:{title:function(e,t){return t.datasets[e[0].datasetIndex].label}}},n}(e,o),r=new ki;for(let{label:e,data:t}of i){const o={label:e,data:t,borderColor:"#FFFFFF",backgroundColor:Sn(r,i)};n.data.datasets.push(o)}return{chartJsConfig:n,background:e.background||w}},validateChartDefinition:(e,t)=>Cn.validateChartDefinition(e,t),transformDefinition:(e,t)=>Cn.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Cn.getDefinitionFromContextCreation(e),name:r("Pie")}),In.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,o)=>new yn(e,t,o),getChartRuntime:function(e,t){let o,i,r="",s="";if(e.keyValue){const i={sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top};o=t.getEvaluatedCell(i),r=String(o.value),s=o.formattedValue}const a=e.baseline;if(a){const o={sheetId:e.baseline.sheetId,col:e.baseline.zone.left,row:e.baseline.zone.top};i=t.getEvaluatedCell(o)}const l=t.getBackgroundOfSingleCellChart(e.background,e.keyValue);return{title:n(e.title),keyValue:s||r,baselineDisplay:Ui(i,o,e.baselineMode),baselineArrow:zi(i,o,e.baselineMode),baselineColor:Vi(i,e.baselineMode,o,e.baselineColorUp,e.baselineColorDown),baselineDescr:e.baselineDescr?n(e.baselineDescr):"",fontColor:$i(l),background:l,baselineStyle:"percentage"!==e.baselineMode&&a?t.getCellStyle({sheetId:a.sheetId,col:a.zone.left,row:a.zone.top}):void 0,keyValueStyle:e.keyValue?t.getCellStyle({sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top}):void 0}},validateChartDefinition:(e,t)=>yn.validateChartDefinition(e,t),transformDefinition:(e,t)=>yn.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>yn.getDefinitionFromContextCreation(e),name:r("Scorecard")}),In.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,o)=>new cn(e,t,o),getChartRuntime:function(e,t){const o=function(e){const t=Qi(e,[],$i(e.background));return t.options.hover=void 0,t.options.events=[],t.options.layout={padding:{left:30,right:30,top:e.title?10:25,bottom:25}},t.options.needle={radiusPercentage:2,widthPercentage:3.2,lengthPercentage:80,color:"#000000"},t.options.valueLabel={display:!1,formatter:null,color:"#FFFFFF",backgroundColor:"#000000",fontSize:30,borderRadius:5,padding:{top:5,right:5,bottom:5,left:5},bottomMarginPercentage:5},t}(e),i=e.sectionRule.colors,n=e.sectionRule.lowerInflectionPoint,r=e.sectionRule.upperInflectionPoint,s=Number(n.value),a=Number(r.value),l=Number(e.sectionRule.rangeMin),c=Number(e.sectionRule.rangeMax),h=c-l,d=[];if(""!==n.value){const e="number"===n.type?s:l+h*s/100;d.push({value:Fe(e,l,c),color:i.lowerColor})}if(""!==r.value){const e="number"===r.type?a:l+h*a/100;d.push({value:Fe(e,l,c),color:i.middleColor})}const u=[],g=[];d.sort(((e,t)=>e.value-t.value)).map((e=>{u.push(e.value),g.push(e.color)})),u.push(c),g.push(i.upperColor);const p=e.dataRange,m=h/30;let f=l-m,v=null,b=!1;if(void 0!==p){const e=t.getEvaluatedCell({sheetId:p.sheetId,col:p.zone.left,row:p.zone.top});e.type===mi.number&&(f=Fe(e.value,l-m,c+m),v=()=>t.getRangeFormattedValues(p)[0],b=!0)}return o.options.valueLabel.display=b,o.options.valueLabel.formatter=v,o.data.datasets.push({data:u,minValue:Number(e.sectionRule.rangeMin),value:f,backgroundColor:g}),{chartJsConfig:o,background:t.getBackgroundOfSingleCellChart(e.background,p)}},validateChartDefinition:(e,t)=>cn.validateChartDefinition(e,t),transformDefinition:(e,t)=>cn.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>cn.getDefinitionFromContextCreation(e),name:r("Gauge")});const Rn=new xn;Rn.add("line",ei),Rn.add("bar",ei),Rn.add("pie",ei),Rn.add("gauge",ei),Rn.add("scorecard",ci);const Tn=e=>({isVisible:()=>!0,isEnabled:()=>!0,isReadonlyAllowed:!1,description:"",action:!1,children:[],separator:!1,icon:!1,id:e});function An(e,t){return Object.assign({},Tn(e),t)}function On(e){return"function"!=typeof e}class Mn extends xn{add(e,t){return this.content[e]=An(e,t),this}addChild(e,t,o){const i=t.splice(0,1)[0];let n=this.content[i];if(!n)throw new Error(`Path ${i+":"+t.join(":")} not found`);for(let e of t)if(n=n.children.filter(On).find((t=>t.id===e)),!n)throw new Error(`Path ${i+":"+t.join(":")} not found`);return"function"!=typeof o?n.children.push(An(e,o)):n.children.push(o),this}getAll(){return super.getAll().sort(((e,t)=>e.sequence-t.sequence))}}function Nn(){const e=t.useState({x:0,y:0,width:0,height:0});let o=document.querySelector(".o-spreadsheet");function i(){if(o||(o=document.querySelector(".o-spreadsheet")),o){const{top:t,left:i,width:n,height:r}=o.getBoundingClientRect();e.x=i,e.y=t,e.width=n,e.height=r}}return i(),t.onMounted(i),t.onPatched(i),e}function _n(e){const o=t.useState({x:0,y:0,width:0,height:0});function i(){const t=e.el;if(null===t)return;const{top:i,left:n,width:r,height:s}=t.getBoundingClientRect();o.x=n,o.y=i,o.width=r,o.height=s}return t.onMounted(i),t.onPatched(i),o}function Fn(e,t){const o=[];for(const i of e.children)"function"==typeof i?o.push(...i(t)):o.push(i);return o.sort(((e,t)=>e.sequence-t.sequence))}function Dn(e,t){return"function"==typeof e.name?e.name(t):e.name}function kn(){const e=document.querySelector(".o-grid-overlay");if(e){const{top:t,left:o}=null==e?void 0:e.getBoundingClientRect();return{top:t,left:o}}throw new Error("Can't find spreadsheet position")}function $n(e,t){return(o=Po(Pn(e),Pn(t)))?{x:o.left,y:o.top,width:o.right-o.left,height:o.bottom-o.top}:void 0;var o}function Pn(e){return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}ii`
53
+ `;class hi 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 vt(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(){const e=.96*this.props.figure.width,t=this.getWidestElement(),o=t.getElementMaxFontSize(this.getDrawableHeight(),this);let i=function(e,t,o,i=.25){let n=1;if(o(n)>e)return n;if(o(t)<e)return t;let r=(n+t)/2,s=o(r),a=0;for(;Math.abs(s-e)>i&&a<20;)s>=e?t=(n+t)/2:n=(n+t)/2,r=(n+t)/2,s=o(r),a++;return r}(e,o,(e=>t.getElementWidth(e,this.ctx,this)))/o;const n=(new ui).getElementMaxFontSize(this.getDrawableHeight(),this)*i,r=(new di).getElementMaxFontSize(this.getDrawableHeight(),this)*i;return{titleStyle:this.getTextStyle({fontSize:18,color:this.secondaryFontColor}),keyStyle:this.getTextStyle({fontSize:n,cellStyle:this.runtime.keyValueStyle,color:this.primaryFontColor}),baselineStyle:this.getTextStyle({fontSize:r}),baselineValueStyle:this.getTextStyle({fontSize:r,cellStyle:this.runtime.baselineStyle,color:this.runtime.baselineColor||this.secondaryFontColor}),baselineDescrStyle:this.getTextStyle({fontSize:.9*r,color:this.secondaryFontColor})}}getTextStyle(e){const t=ai(e.cellStyle);return t["font-size"]=`${e.fontSize}px`,t.display="inline-block",!t.color&&e.color&&(t.color=e.color),li(t)}getDrawableHeight(){const e=2*this.chartPadding;let t=this.props.figure.height-e;return t-=this.title?18*ci:0,t}getWidestElement(){const e=new di,t=new ui;return e.getElementWidth(.35,this.ctx,this)>t.getElementWidth(.65,this.ctx,this)?e:t}}hi.template="o-spreadsheet-ScorecardChart";class di{getElementWidth(e,t,o){if(!o.runtime)return 0;const i=o.baseline,n="neutral"!==o.baselineArrowDirection?"A "+i:i;t.font=`${e}px ${G}`;let r=t.measureText(n).width;return t.font=`${.9*e}px ${G}`,r+=t.measureText(o.baselineDescr).width,r}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.35*e:0)/ci}}class ui{getElementWidth(e,t,o){if(!o.runtime)return 0;const i=o.keyValue||"";return t.font=`${e}px ${G}`,t.measureText(i).width}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.65*e:e)/ci}}function gi(e){return 8===(e=gt(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}hi.props={figure:Object};class pi{constructor(e,t,o){this.title=e.title,this.sheetId=t,this.getters=o}static validateChartDefinition(e,t){throw new Error("This method should be implemented by sub class")}static transformDefinition(e,t){throw new Error("This method should be implemented by sub class")}static getDefinitionFromContextCreation(e){throw new Error("This method should be implemented by sub class")}}function mi(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?$o(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?Fo(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):{...e}}var fi,vi;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(fi||(fi={})),function(e){e.PlainText="text/plain",e.Html="text/html"}(vi||(vi={}));const bi=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),Ci=new Set([...bi,"DUPLICATE_SHEET","EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT"]),Si=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","REFRESH_SEARCH","UPDATE_SEARCH","CLEAR_SEARCH","EVALUATE_CELLS","SET_CURRENT_CONTENT","SET_FORMULA_VISIBILITY","OPEN_CELL_POPOVER","CLOSE_CELL_POPOVER","UPDATE_FILTER"]),Ei=new Set(["UPDATE_CELL","UPDATE_CELL_POSITION","CLEAR_CELL","DELETE_CONTENT","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","RESIZE_COLUMNS_ROWS","HIDE_COLUMNS_ROWS","UNHIDE_COLUMNS_ROWS","SET_GRID_LINES_VISIBILITY","UNFREEZE_COLUMNS","UNFREEZE_ROWS","FREEZE_COLUMNS","FREEZE_ROWS","UNFREEZE_COLUMNS_ROWS","ADD_MERGE","REMOVE_MERGE","CREATE_SHEET","DELETE_SHEET","DUPLICATE_SHEET","MOVE_SHEET","RENAME_SHEET","HIDE_SHEET","SHOW_SHEET","MOVE_RANGES","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT","CREATE_FIGURE","DELETE_FIGURE","UPDATE_FIGURE","SET_FORMATTING","CLEAR_FORMATTING","SET_BORDER","CREATE_CHART","UPDATE_CHART","CREATE_FILTER_TABLE","REMOVE_FILTER_TABLE","CREATE_IMAGE"]);function wi(e){return Ei.has(e.type)}class yi{constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new yi}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var xi,Ii,Ri;function Ti(e,t,o,i){let n=!1;const r=[];for(let i in o){let s=o[i];if(s.labelCell){const e=Mi(s.labelCell,t);s.labelCell!==e&&(n=!0,s={...s,labelCell:e})}const a=Mi(s.dataRange,t);void 0===a||e.getRangeString(a,a.sheetId)===X?(n=!0,s=void 0):a!==s.dataRange&&(n=!0,s={...s,dataRange:a}),r[i]=s}let s=i;const a=Mi(s,t);a!==s&&(n=!0,s=a);return{isStale:n,dataSets:r.filter(Je),labelRange:s}}function Ai(e,t,o){return o.map((o=>({dataRange:Io(e,t,o.dataRange),labelCell:o.labelCell?Io(e,t,o.labelCell):void 0})))}function Oi(e,t,o){return o?Io(e,t,o):void 0}function Mi(e,t){if(!e)return;const o=t(e);switch(o.changeType){case"NONE":return e;case"REMOVE":return;default:return o.range}}function Ni(e,t,o,i){const n=[];for(const r of t){const t=e.getRangeFromSheetXC(o,r),{unboundedZone:s,sheetId:a,invalidSheetName:l}=t;if(!l)if(s.left!==s.right&&s.top!==s.bottom){if(void 0===s.right)continue;for(let t=s.left;t<=s.right;t++){const o={...s,left:t,right:t};n.push(_i(e,a,o,i?{top:o.top,bottom:o.top,left:o.left,right:o.left}:void 0))}}else s.left===s.right&&s.top===s.bottom?i||n.push(_i(e,a,s,void 0)):n.push(_i(e,a,s,i?{top:s.top,bottom:s.top,left:s.left,right:s.left}:void 0))}return n}function _i(e,t,o,i){if(o.left!==o.right&&o.top!==o.bottom)throw new Error(`Zone should be a single column or row: ${_o(o)}`);if(i){const n=_o(o),r=_o(i);return{labelCell:e.getRangeFromSheetXC(t,r),dataRange:e.getRangeFromSheetXC(t,n)}}return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,_o(o))}}function Fi(e,t){var o;const i=null===(o=t.labelCell)||void 0===o?void 0:o.zone;let n=t.dataRange.zone;if(i){const{height:e,width:t}=Go(n);1===e?n={...n,left:n.left+1}:1===t&&(n={...n,top:n.top+1})}const r=t.dataRange.clone({zone:n});return{label:t.labelCell?e.getRangeString(t.labelCell,"forceSheetReference"):void 0,range:e.getRangeString(r,"forceSheetReference")}}function Di(e,t){let o;if(e.labelRange){const i=mi(Oo(e.labelRange),t);o=i?_o(i):void 0}const i=e.dataSets.map(Oo).map((e=>mi(e,t))).filter(Je).map(_o);return{...e,labelRange:o,dataSets:i}}e.CommandResult=void 0,(xi=e.CommandResult||(e.CommandResult={}))[xi.Success=0]="Success",xi[xi.CancelledForUnknownReason=1]="CancelledForUnknownReason",xi[xi.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",xi[xi.MergeIsDestructive=3]="MergeIsDestructive",xi[xi.CellIsMerged=4]="CellIsMerged",xi[xi.InvalidTarget=5]="InvalidTarget",xi[xi.EmptyUndoStack=6]="EmptyUndoStack",xi[xi.EmptyRedoStack=7]="EmptyRedoStack",xi[xi.NotEnoughElements=8]="NotEnoughElements",xi[xi.NotEnoughSheets=9]="NotEnoughSheets",xi[xi.MissingSheetName=10]="MissingSheetName",xi[xi.DuplicatedSheetName=11]="DuplicatedSheetName",xi[xi.DuplicatedSheetId=12]="DuplicatedSheetId",xi[xi.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",xi[xi.WrongSheetMove=14]="WrongSheetMove",xi[xi.WrongSheetPosition=15]="WrongSheetPosition",xi[xi.InvalidAnchorZone=16]="InvalidAnchorZone",xi[xi.SelectionOutOfBound=17]="SelectionOutOfBound",xi[xi.TargetOutOfSheet=18]="TargetOutOfSheet",xi[xi.WrongCutSelection=19]="WrongCutSelection",xi[xi.WrongPasteSelection=20]="WrongPasteSelection",xi[xi.WrongPasteOption=21]="WrongPasteOption",xi[xi.WrongFigurePasteOption=22]="WrongFigurePasteOption",xi[xi.EmptyClipboard=23]="EmptyClipboard",xi[xi.EmptyRange=24]="EmptyRange",xi[xi.InvalidRange=25]="InvalidRange",xi[xi.InvalidZones=26]="InvalidZones",xi[xi.InvalidSheetId=27]="InvalidSheetId",xi[xi.InvalidFigureId=28]="InvalidFigureId",xi[xi.InputAlreadyFocused=29]="InputAlreadyFocused",xi[xi.MaximumRangesReached=30]="MaximumRangesReached",xi[xi.InvalidChartDefinition=31]="InvalidChartDefinition",xi[xi.InvalidDataSet=32]="InvalidDataSet",xi[xi.InvalidLabelRange=33]="InvalidLabelRange",xi[xi.InvalidScorecardKeyValue=34]="InvalidScorecardKeyValue",xi[xi.InvalidScorecardBaseline=35]="InvalidScorecardBaseline",xi[xi.InvalidGaugeDataRange=36]="InvalidGaugeDataRange",xi[xi.EmptyGaugeRangeMin=37]="EmptyGaugeRangeMin",xi[xi.GaugeRangeMinNaN=38]="GaugeRangeMinNaN",xi[xi.EmptyGaugeRangeMax=39]="EmptyGaugeRangeMax",xi[xi.GaugeRangeMaxNaN=40]="GaugeRangeMaxNaN",xi[xi.GaugeRangeMinBiggerThanRangeMax=41]="GaugeRangeMinBiggerThanRangeMax",xi[xi.GaugeLowerInflectionPointNaN=42]="GaugeLowerInflectionPointNaN",xi[xi.GaugeUpperInflectionPointNaN=43]="GaugeUpperInflectionPointNaN",xi[xi.GaugeLowerBiggerThanUpper=44]="GaugeLowerBiggerThanUpper",xi[xi.InvalidAutofillSelection=45]="InvalidAutofillSelection",xi[xi.WrongComposerSelection=46]="WrongComposerSelection",xi[xi.MinBiggerThanMax=47]="MinBiggerThanMax",xi[xi.LowerBiggerThanUpper=48]="LowerBiggerThanUpper",xi[xi.MidBiggerThanMax=49]="MidBiggerThanMax",xi[xi.MinBiggerThanMid=50]="MinBiggerThanMid",xi[xi.FirstArgMissing=51]="FirstArgMissing",xi[xi.SecondArgMissing=52]="SecondArgMissing",xi[xi.MinNaN=53]="MinNaN",xi[xi.MidNaN=54]="MidNaN",xi[xi.MaxNaN=55]="MaxNaN",xi[xi.ValueUpperInflectionNaN=56]="ValueUpperInflectionNaN",xi[xi.ValueLowerInflectionNaN=57]="ValueLowerInflectionNaN",xi[xi.MinInvalidFormula=58]="MinInvalidFormula",xi[xi.MidInvalidFormula=59]="MidInvalidFormula",xi[xi.MaxInvalidFormula=60]="MaxInvalidFormula",xi[xi.ValueUpperInvalidFormula=61]="ValueUpperInvalidFormula",xi[xi.ValueLowerInvalidFormula=62]="ValueLowerInvalidFormula",xi[xi.InvalidSortZone=63]="InvalidSortZone",xi[xi.WaitingSessionConfirmation=64]="WaitingSessionConfirmation",xi[xi.MergeOverlap=65]="MergeOverlap",xi[xi.TooManyHiddenElements=66]="TooManyHiddenElements",xi[xi.Readonly=67]="Readonly",xi[xi.InvalidViewportSize=68]="InvalidViewportSize",xi[xi.InvalidScrollingDirection=69]="InvalidScrollingDirection",xi[xi.FigureDoesNotExist=70]="FigureDoesNotExist",xi[xi.InvalidConditionalFormatId=71]="InvalidConditionalFormatId",xi[xi.InvalidCellPopover=72]="InvalidCellPopover",xi[xi.EmptyTarget=73]="EmptyTarget",xi[xi.InvalidFreezeQuantity=74]="InvalidFreezeQuantity",xi[xi.FrozenPaneOverlap=75]="FrozenPaneOverlap",xi[xi.ValuesNotChanged=76]="ValuesNotChanged",xi[xi.InvalidFilterZone=77]="InvalidFilterZone",xi[xi.FilterOverlap=78]="FilterOverlap",xi[xi.FilterNotFound=79]="FilterNotFound",xi[xi.MergeInFilter=80]="MergeInFilter",xi[xi.NonContinuousTargets=81]="NonContinuousTargets",xi[xi.DuplicatedFigureId=82]="DuplicatedFigureId",xi[xi.InvalidSelectionStep=83]="InvalidSelectionStep",xi[xi.DuplicatedChartId=84]="DuplicatedChartId",xi[xi.ChartDoesNotExist=85]="ChartDoesNotExist",xi[xi.InvalidHeaderIndex=86]="InvalidHeaderIndex",xi[xi.InvalidQuantity=87]="InvalidQuantity",function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(Ii||(Ii={})),function(e){e[e.Background=0]="Background",e[e.Highlights=1]="Highlights",e[e.Clipboard=2]="Clipboard",e[e.Search=3]="Search",e[e.Chart=4]="Chart",e[e.Autofill=5]="Autofill",e[e.Selection=6]="Selection",e[e.Headers=7]="Headers"}(Ri||(Ri={}));const ki=["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 $i{constructor(){this.graphColorIndex=0}next(){return ki[this.graphColorIndex++%ki.length]}}function Pi(e){return e&&vt(e)<.3?"#FFFFFF":"#000000"}function Li(e){if(e.dataSets){const t=void 0!==e.dataSets.find((e=>!Tt.test(e)));if(t)return 32;if(e.dataSets.map(Oo).some((e=>e.top!==e.bottom&&Qo(e))))return 32}return 0}function Ui(e){if(e.labelRange){if(!Tt.test(e.labelRange||""))return 33}return 0}function Vi(e,t,o){if(e){if("text"===o||(null==t?void 0:t.type)!==fi.number||e.type!==fi.number)return e.formattedValue;{let i=t.value-e.value;if("percentage"===o&&0!==i&&(i=i/e.value*100),"percentage"!==o&&e.format)return ro(i,e.format);const n=Math.abs(parseFloat(i.toFixed(2))).toLocaleString();return"percentage"===o?n+"%":n}}return""}function zi(e,t,o,i,n){if("text"===t||(null==e?void 0:e.type)!==fi.number||(null==o?void 0:o.type)!==fi.number)return;const r=o.value-e.value;return r>0?i:r<0?n:void 0}function Bi(e,t,o){if("text"===o||(null==e?void 0:e.type)!==fi.number||(null==t?void 0:t.type)!==fi.number)return"neutral";const i=t.value-e.value;return i>0?"up":i<0?"down":"neutral"}const Hi={Errors:{25:r("The range is invalid"),51:r("The argument is missing. Please provide a value"),52:r("The second argument is missing. Please provide a value"),53:r("The minpoint must be a number"),54:r("The midpoint must be a number"),55:r("The maxpoint must be a number"),56:r("The first value must be a number"),57:r("The second value must be a number"),47:r("Minimum must be smaller then Maximum"),50:r("Minimum must be smaller then Midpoint"),49:r("Midpoint must be smaller then Maximum"),48:r("Lower inflection point must be smaller than upper inflection point"),58:r("Invalid Minpoint formula"),60:r("Invalid Maxpoint formula"),59:r("Invalid Midpoint formula"),61:r("Invalid upper inflection point formula"),62:r("Invalid lower inflection point formula"),24:r("A range needs to be defined"),Unexpected:r("The rule is invalid for an unknown reason")},ColorScale:r("Color scale"),IconSet:r("Icon set")},Wi={IsEmpty:r("Is empty"),IsNotEmpty:r("Is not empty"),ContainsText:r("Contains"),NotContains:r("Does not contain"),BeginsWith:r("Starts with"),EndsWith:r("Ends with"),Equal:r("Is equal to"),NotEqual:r("Is not equal to"),GreaterThan:r("Is greater than"),GreaterThanOrEqual:r("Is greater than or equal to"),LessThan:r("Is less than"),LessThanOrEqual:r("Is less than or equal to"),Between:r("Is between"),NotBetween:r("Is not between")},Gi={Series:r("Series"),Errors:{Unexpected:r("The chart definition is invalid for an unknown reason"),32:r("The dataset is invalid"),33:r("Labels are invalid"),34:r("The key value is invalid"),35:r("The baseline value is invalid"),36:r("The data range is invalid"),37:r("A minimum range limit value is needed"),38:r("The minimum range limit value must be a number"),39:r("A maximum range limit value is needed"),40:r("The maximum range limit value must be a number"),41:r("Minimum range limit must be smaller than maximum range limit"),42:r("The lower inflection point value must be a number"),43:r("The upper inflection point value must be a number")}},qi={Automatic:r("Automatic"),Number:r("Number"),Percent:r("Percent"),Currency:r("Currency"),CurrencyRounded:r("Currency rounded"),Date:r("Date"),Time:r("Time"),DateTime:r("Date time"),Duration:r("Duration"),CustomCurrency:r("Custom currency")},Zi={Custom:r("Custom")},ji=r("Merged cells are preventing this operation. Unmerge those cells and try again.");function Xi(e,t){if(t.dataRange){const o=t.labelCell?[_o(t.labelCell.zone)]:[],i=Ho([_o(t.dataRange.zone)],o)[0];if(void 0===i)return[];const n=e.getRangeFromSheetXC(t.dataRange.sheetId,i);return e.getRangeValues(n).map((e=>""===e?void 0:e))}return[]}function Yi(e,t){const o=Ue(0,Math.max(e.length,...t.map((e=>{var t;return(null===(t=e.data)||void 0===t?void 0:t.length)||0})))).filter((o=>{const i=e[o],n=t.map((e=>{var t;return null===(t=e.data)||void 0===t?void 0:t[o]}));return i||n.some((e=>0===e||Boolean(e)))}));return{labels:o.map((t=>e[t]||"")),dataSetsValues:t.map((e=>({...e,data:o.map((t=>e.data[t]))})))}}function Ki(e,t){const o=new Set(e),i={};o.forEach((e=>{i[e]=new Array(t.length).fill(0)}));for(const o of Ue(0,e.length)){const r=e[o];for(const e of Ue(0,t.length))i[r][e]+="number"==typeof(n=t[e].data[o])?n:0}var n;return{labels:Object.keys(i),dataSetsValues:t.map(((e,t)=>({...e,data:Object.values(i).map((e=>e[t]))})))}}function Qi(e){return e?e.length>K?e.substring(0,K)+"…":e:""}function Ji(e,t,o){return{type:e.type,options:{responsive:!0,maintainAspectRatio:!1,layout:{padding:{left:20,right:20,top:e.title?10:25,bottom:10}},elements:{line:{fill:!1},point:{hitRadius:15}},animation:{duration:0},hover:{animationDuration:10},responsiveAnimationDuration:0,title:{display:!!e.title,fontSize:22,fontStyle:"normal",text:n(e.title),fontColor:o},legend:{onClick:void 0}},data:{labels:t.map(Qi),datasets:[]}}}function en(e,t,o){let i={values:[],formattedValues:[]};if(o)o.invalidXc||o.invalidSheetName||(i={formattedValues:e.getRangeFormattedValues(o),values:e.getRangeValues(o).map((e=>String(e)))});else if(1===t.length)for(let o=0;o<Xi(e,t[0]).length;o++)i.formattedValues.push(""),i.values.push("");else if(t[0]){i={formattedValues:Ue(0,Xi(e,t[0]).length).map((e=>e.toString())),values:i.formattedValues}}return i}function tn(e,t){const o=[];for(const[i,n]of Object.entries(t)){let t;if(n.labelCell){const o=n.labelCell,r=o?e.getEvaluatedCell({sheetId:o.sheetId,col:o.zone.left,row:o.zone.top}):void 0;t=r&&o?Qi(r.formattedValue):t=`${Gi.Series} ${parseInt(i)+1}`}else t=t=`${Gi.Series} ${parseInt(i)+1}`;let r=n.dataRange?Xi(e,n):[];o.push({data:r,label:t})}return o}function on(e){return 0===e?"origin":e-1}class nn extends pi{constructor(e,t,o){super(e,t,o),this.type="bar",this.dataSets=Ni(o,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ro(o,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated}static transformDefinition(e,t){return Di(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,Li,Ui)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:!1,stacked:!1,aggregated:!1,legendPosition:"top",title:e.title||"",type:"bar",verticalAxisPosition:"left",labelRange:e.auxiliaryRange||void 0}}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}copyForSheetId(e){const t=Ai(this.sheetId,e,this.dataSets),o=Oi(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new nn(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new nn(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,o){return{type:"bar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,o||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,o||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated}}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>Fi(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:gi(this.background||w),fontColor:gi(Pi(this.background)),dataSets:e}}updateRanges(e){const{dataSets:t,labelRange:o,isStale:i}=Ti(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const n=this.getDefinitionWithSpecificDataSets(t,o);return new nn(n,this.sheetId,this.getters)}}function rn(e){return e.dataRange&&!Tt.test(e.dataRange)?36:0}function sn(e,t){return t((t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):0),(t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):0))}function an(e){return e.sectionRule&&Number(e.sectionRule.rangeMin)>=Number(e.sectionRule.rangeMax)?41:0}function ln(e,t){if(""===e)switch(t){case"rangeMin":return 37;case"rangeMax":return 39}return 0}function cn(e,t){if(isNaN(e))switch(t){case"rangeMin":return 38;case"rangeMax":return 40;case"lowerInflectionPointValue":return 42;case"upperInflectionPointValue":return 43}return 0}class hn extends pi{constructor(e,t,o){super(e,t,o),this.type="gauge",this.dataRange=Ro(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,rn,e.chainValidations(sn(ln,e.batchValidations),sn(cn,e.batchValidations),an),e.chainValidations((o=cn,(0,e.batchValidations)((e=>e.sectionRule?o(e.sectionRule.lowerInflectionPoint.value,"lowerInflectionPointValue"):0),(e=>e.sectionRule?o(e.sectionRule.upperInflectionPoint.value,"upperInflectionPointValue"):0)))));var o}static transformDefinition(e,t){let o;return e.dataRange&&(o=mi(Oo(e.dataRange),t)),{...e,dataRange:o?_o(o):void 0}}static getDefinitionFromContextCreation(e){return{background:e.background,title:e.title||"",type:"gauge",dataRange:e.range?e.range[0]:void 0,sectionRule:{colors:{lowerColor:"#cc0000",middleColor:"#f1c232",upperColor:"#6aa84f"},rangeMin:"0",rangeMax:"100",lowerInflectionPoint:{type:"percentage",value:"15"},upperInflectionPoint:{type:"percentage",value:"40"}}}}copyForSheetId(e){const t=Oi(this.sheetId,e,this.dataRange),o=this.getDefinitionWithSpecificRanges(t,e);return new hn(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.dataRange,e);return new hn(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=Mi(this.dataRange,e);if(this.dataRange===t)return this;const o=this.getDefinitionWithSpecificRanges(t);return new hn(o,this.sheetId,this.getters)}}const dn={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},un={inSeconds:function(e){return Math.floor(e/dn.second)},inMinutes:function(e){return Math.floor(e/dn.minute)},inHours:function(e){return Math.floor(e/dn.hour)},inDays:function(e){return Math.floor(e/dn.day)},inMonths:function(e){return Math.floor(e/dn.month)},inYears:function(e){return Math.floor(e/dn.year)}},gn=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function pn(e,t){const o=function(e){const t=(e=(e=e.replace(/y/g,"Y")).replace(/d/g,"D")).indexOf("h");e=t>=0?e.slice(0,t).replace(/m/g,"M")+e.slice(t):e.replace(/m/g,"M");e.includes("a")||(e=e.replace(/h/g,"H"));return e}(t),i=function(e,t){const o=e.map((e=>{var t;return null===(t=be(e))||void 0===t?void 0:t.jsDate}));if(o.some((e=>void 0===e))||e.length<2)return;const i=o.map((e=>e.getTime())),n=Math.max(...i)-Math.min(...i),r=function(e){if(e.includes("s"))return"second";if(e.includes("m"))return"minute";if(e.includes("h")||e.includes("H"))return"hour";if(e.includes("D"))return"day";if(e.includes("M"))return"month";return"year"}(t);if(dn.second>=dn[r]&&un.inSeconds(n)<180)return"second";if(dn.minute>=dn[r]&&un.inMinutes(n)<180)return"minute";if(dn.hour>=dn[r]&&un.inHours(n)<96)return"hour";if(dn.day>=dn[r]&&un.inDays(n)<90)return"day";if(dn.month>=dn[r]&&un.inMonths(n)<36)return"month";return"year"}(e,o),n={};return i&&(n[i]=o),{parser:o,displayFormats:n,unit:i}}class mn extends pi{constructor(e,t,o){super(e,t,o),this.type="line",this.dataSets=Ni(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ro(this.getters,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.stacked=e.stacked,this.aggregated=e.aggregated}static validateChartDefinition(e,t){return e.checkValidations(t,Li,Ui)}static transformDefinition(e,t){return Di(e,t)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:!1,labelsAsText:!1,legendPosition:"top",title:e.title||"",type:"line",verticalAxisPosition:"left",labelRange:e.auxiliaryRange||void 0,stacked:!1,aggregated:!1}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,o){return{type:"line",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,o||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,o||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,stacked:this.stacked,aggregated:this.aggregated}}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(e){const{dataSets:t,labelRange:o,isStale:i}=Ti(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const n=this.getDefinitionWithSpecificDataSets(t,o);return new mn(n,this.sheetId,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>Fi(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:gi(this.background||w),fontColor:gi(Pi(this.background)),dataSets:e}}copyForSheetId(e){const t=Ai(this.sheetId,e,this.dataSets),o=Oi(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new mn(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new mn(t,e,this.getters)}}function fn(e,t){return bn(e,t)||Cn(e,t)}function vn(e,t){return function(e,t){return!e.labelsAsText&&bn(e.labelRange,t)}(e,t)?"time":function(e,t){return!e.labelsAsText&&Cn(e.labelRange,t)}(e,t)?"linear":"category"}function bn(e,t){if(!e||!Cn(e,t))return!1;const o=t.getEvaluatedCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}).format;return Boolean(o&&gn.test(o))}function Cn(e,t){if(!e)return!1;const o=t.getRangeValues(e);return!o.some((e=>isNaN(Number(e))&&e))&&!o.every((e=>!e))}class Sn extends pi{constructor(e,t,o){super(e,t,o),this.type="pie",this.dataSets=Ni(o,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ro(o,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated}static transformDefinition(e,t){return Di(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,Li,Ui)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:!1,legendPosition:"top",title:e.title||"",type:"pie",labelRange:e.auxiliaryRange||void 0,aggregated:!1}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinitionWithSpecificDataSets(e,t,o){return{type:"pie",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,o||this.sheetId))),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,o||this.sheetId):void 0,title:this.title,aggregated:this.aggregated}}copyForSheetId(e){const t=Ai(this.sheetId,e,this.dataSets),o=Oi(this.sheetId,e,this.labelRange),i=this.getDefinitionWithSpecificDataSets(t,o,e);return new Sn(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Sn(t,e,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>Fi(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:gi(this.background||w),fontColor:gi(Pi(this.background)),verticalAxisPosition:"left",dataSets:e}}updateRanges(e){const{dataSets:t,labelRange:o,isStale:i}=Ti(this.getters,e,this.dataSets,this.labelRange);if(!i)return this;const n=this.getDefinitionWithSpecificDataSets(t,o);return new Sn(n,this.sheetId,this.getters)}}function En(e,t){const o=[],i=Math.max(...t.map((e=>e.data.length)));for(let t=0;t<=i;t++)o.push(e.next());return o}function wn(e){return e.keyValue&&!Tt.test(e.keyValue)?34:0}function yn(e){return e.baseline&&!Tt.test(e.baseline)?35:0}class xn extends pi{constructor(e,t,o){super(e,t,o),this.type="scorecard",this.keyValue=Ro(o,t,e.keyValue),this.baseline=Ro(o,t,e.baseline),this.baselineMode=e.baselineMode,this.baselineDescr=e.baselineDescr,this.background=e.background,this.baselineColorUp=e.baselineColorUp,this.baselineColorDown=e.baselineColorDown}static validateChartDefinition(e,t){return e.checkValidations(t,wn,yn)}static getDefinitionFromContextCreation(e){return{background:e.background,type:"scorecard",keyValue:e.range?e.range[0]:void 0,title:e.title||"",baselineMode:J,baselineColorUp:ee,baselineColorDown:te,baseline:e.auxiliaryRange||""}}static transformDefinition(e,t){let o,i;return e.baseline&&(o=mi(Oo(e.baseline),t)),e.keyValue&&(i=mi(Oo(e.keyValue),t)),{...e,baseline:o?_o(o):void 0,keyValue:i?_o(i):void 0}}copyForSheetId(e){const t=Oi(this.sheetId,e,this.baseline),o=Oi(this.sheetId,e,this.keyValue),i=this.getDefinitionWithSpecificRanges(t,o,e);return new xn(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,e);return new xn(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue)}getContextCreation(){return{background:this.background,title:this.title,range:this.keyValue?[this.getters.getRangeString(this.keyValue,this.sheetId)]:void 0,auxiliaryRange:this.baseline?this.getters.getRangeString(this.baseline,this.sheetId):void 0}}getDefinitionWithSpecificRanges(e,t,o){return{baselineColorDown:this.baselineColorDown,baselineColorUp:this.baselineColorUp,baselineMode:this.baselineMode,title:this.title,type:"scorecard",background:this.background,baseline:e?this.getters.getRangeString(e,o||this.sheetId):void 0,baselineDescr:this.baselineDescr,keyValue:t?this.getters.getRangeString(t,o||this.sheetId):void 0}}getDefinitionForExcel(){}updateRanges(e){const t=Mi(this.baseline,e),o=Mi(this.keyValue,e);if(this.baseline===t&&this.keyValue===o)return this;const i=this.getDefinitionWithSpecificRanges(t,o);return new xn(i,this.sheetId,this.getters)}}class In{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 In;Rn.add("bar",{match:e=>"bar"===e,createChart:(e,t,o)=>new nn(e,t,o),getChartRuntime:function(e,t){let o=en(t,e.dataSets,e.labelRange).formattedValues,i=tn(t,e.dataSets);({labels:o,dataSetsValues:i}=Yi(o,i)),e.aggregated&&({labels:o,dataSetsValues:i}=Ki(o,i));const n=function(e,t){var o;const i=Pi(e.background),n=Ji(e,t,i),r={labels:{fontColor:i}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,n.options.legend={...null===(o=n.options)||void 0===o?void 0:o.legend,...r},n.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},n.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:i}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:i,beginAtZero:!0}}]},e.stacked&&(n.options.scales.xAxes[0].stacked=!0,n.options.scales.yAxes[0].stacked=!0),n}(e,o),r=new $i;for(let{label:e,data:t}of i){const o=r.next(),i={label:e,data:t,borderColor:o,backgroundColor:o};n.data.datasets.push(i)}return{chartJsConfig:n,background:e.background||w}},validateChartDefinition:(e,t)=>nn.validateChartDefinition(e,t),transformDefinition:(e,t)=>nn.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>nn.getDefinitionFromContextCreation(e),name:r("Bar")}),Rn.add("line",{match:e=>"line"===e,createChart:(e,t,o)=>new mn(e,t,o),getChartRuntime:function(e,t){const o=vn(e,t),i=en(t,e.dataSets,e.labelRange);let n="linear"===o?i.values:i.formattedValues,r=tn(t,e.dataSets);({labels:n,dataSetsValues:r}=Yi(n,r)),"time"===o&&({labels:n,dataSetsValues:r}=function(e,t){if(0===e.length||e.every((e=>!e)))return{labels:e,dataSetsValues:t};const o=[...e],i=Me(t);for(let e=0;e<o.length;e++)if(!o[e]){o[e]=nt(o,e);for(let t of i)t.data[e]=void 0}return{labels:o,dataSetsValues:i}}(n,r)),e.aggregated&&({labels:n,dataSetsValues:r}=Ki(n,r));const s=function(e,t){var o;const i=Pi(e.background),n=Ji(e,t,i),r={labels:{fontColor:i,generateLabels(e){const{data:t}=e,o=window.Chart.defaults.global.legend.labels.generateLabels(e);for(const[e,i]of o.entries())i.fillStyle=t.datasets[e].borderColor;return o}}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,n.options.legend={...null===(o=n.options)||void 0===o?void 0:o.legend,...r},n.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},n.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:i}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:i,beginAtZero:!0}}]},e.stacked&&(n.options.scales.yAxes[0].stacked=!0),n}(e,n),a=function(e,t){if(t)return e.getEvaluatedCell({sheetId:t.sheetId,col:t.zone.left,row:t.zone.top}).format}(t,e.labelRange);"time"===o?(s.options.scales.xAxes[0].type="time",s.options.scales.xAxes[0].time=pn(n,a),s.options.scales.xAxes[0].ticks.maxTicksLimit=15):"linear"===o&&(s.options.scales.xAxes[0].type="linear",s.options.scales.xAxes[0].ticks.callback=e=>ro(e,a));const l=new $i;for(let[t,{label:i,data:a}]of r.entries()){["linear","time"].includes(o)&&(a=a.map(((e,t)=>({x:n[t]||void 0,y:e}))));const r=l.next();let c=Ct(r);e.stacked&&(c.a=oe);const h={label:i,data:a,lineTension:0,borderColor:r,backgroundColor:bt(c),pointBackgroundColor:r,fill:!!e.stacked&&on(t)};s.data.datasets.push(h)}return{chartJsConfig:s,background:e.background||w}},validateChartDefinition:(e,t)=>mn.validateChartDefinition(e,t),transformDefinition:(e,t)=>mn.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>mn.getDefinitionFromContextCreation(e),name:r("Line")}),Rn.add("pie",{match:e=>"pie"===e,createChart:(e,t,o)=>new Sn(e,t,o),getChartRuntime:function(e,t){let o=en(t,e.dataSets,e.labelRange).formattedValues,i=tn(t,e.dataSets);({labels:o,dataSetsValues:i}=Yi(o,i)),e.aggregated&&({labels:o,dataSetsValues:i}=Ki(o,i));const n=function(e,t){var o;const i=Pi(e.background),n=Ji(e,t,i),r={labels:{fontColor:i}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,n.options.legend={...null===(o=n.options)||void 0===o?void 0:o.legend,...r},n.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},n.options.tooltips={callbacks:{title:function(e,t){return t.datasets[e[0].datasetIndex].label}}},n}(e,o),r=new $i;for(let{label:e,data:t}of i){const o={label:e,data:t,borderColor:"#FFFFFF",backgroundColor:En(r,i)};n.data.datasets.push(o)}return{chartJsConfig:n,background:e.background||w}},validateChartDefinition:(e,t)=>Sn.validateChartDefinition(e,t),transformDefinition:(e,t)=>Sn.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Sn.getDefinitionFromContextCreation(e),name:r("Pie")}),Rn.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,o)=>new xn(e,t,o),getChartRuntime:function(e,t){let o,i,r="",s="";if(e.keyValue){const i={sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top};o=t.getEvaluatedCell(i),r=String(o.value),s=o.formattedValue}const a=e.baseline;if(a){const o={sheetId:e.baseline.sheetId,col:e.baseline.zone.left,row:e.baseline.zone.top};i=t.getEvaluatedCell(o)}const l=t.getBackgroundOfSingleCellChart(e.background,e.keyValue);return{title:n(e.title),keyValue:s||r,baselineDisplay:Vi(i,o,e.baselineMode),baselineArrow:Bi(i,o,e.baselineMode),baselineColor:zi(i,e.baselineMode,o,e.baselineColorUp,e.baselineColorDown),baselineDescr:e.baselineDescr?n(e.baselineDescr):"",fontColor:Pi(l),background:l,baselineStyle:"percentage"!==e.baselineMode&&a?t.getCellStyle({sheetId:a.sheetId,col:a.zone.left,row:a.zone.top}):void 0,keyValueStyle:e.keyValue?t.getCellStyle({sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top}):void 0}},validateChartDefinition:(e,t)=>xn.validateChartDefinition(e,t),transformDefinition:(e,t)=>xn.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>xn.getDefinitionFromContextCreation(e),name:r("Scorecard")}),Rn.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,o)=>new hn(e,t,o),getChartRuntime:function(e,t){const o=function(e){const t=Ji(e,[],Pi(e.background));return t.options.hover=void 0,t.options.events=[],t.options.layout={padding:{left:30,right:30,top:e.title?10:25,bottom:25}},t.options.needle={radiusPercentage:2,widthPercentage:3.2,lengthPercentage:80,color:"#000000"},t.options.valueLabel={display:!1,formatter:null,color:"#FFFFFF",backgroundColor:"#000000",fontSize:30,borderRadius:5,padding:{top:5,right:5,bottom:5,left:5},bottomMarginPercentage:5},t}(e),i=e.sectionRule.colors,n=e.sectionRule.lowerInflectionPoint,r=e.sectionRule.upperInflectionPoint,s=Number(n.value),a=Number(r.value),l=Number(e.sectionRule.rangeMin),c=Number(e.sectionRule.rangeMax),h=c-l,d=[];if(""!==n.value){const e="number"===n.type?s:l+h*s/100;d.push({value:Fe(e,l,c),color:i.lowerColor})}if(""!==r.value){const e="number"===r.type?a:l+h*a/100;d.push({value:Fe(e,l,c),color:i.middleColor})}const u=[],g=[];d.sort(((e,t)=>e.value-t.value)).map((e=>{u.push(e.value),g.push(e.color)})),u.push(c),g.push(i.upperColor);const p=e.dataRange,m=h/30;let f=l-m,v=null,b=!1;if(void 0!==p){const e=t.getEvaluatedCell({sheetId:p.sheetId,col:p.zone.left,row:p.zone.top});e.type===fi.number&&(f=Fe(e.value,l-m,c+m),v=()=>t.getRangeFormattedValues(p)[0],b=!0)}return o.options.valueLabel.display=b,o.options.valueLabel.formatter=v,o.data.datasets.push({data:u,minValue:Number(e.sectionRule.rangeMin),value:f,backgroundColor:g}),{chartJsConfig:o,background:t.getBackgroundOfSingleCellChart(e.background,p)}},validateChartDefinition:(e,t)=>hn.validateChartDefinition(e,t),transformDefinition:(e,t)=>hn.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>hn.getDefinitionFromContextCreation(e),name:r("Gauge")});const Tn=new In;Tn.add("line",ti),Tn.add("bar",ti),Tn.add("pie",ti),Tn.add("gauge",ti),Tn.add("scorecard",hi);const An=e=>({isVisible:()=>!0,isEnabled:()=>!0,isReadonlyAllowed:!1,description:"",action:!1,children:[],separator:!1,icon:!1,id:e});function On(e,t){return Object.assign({},An(e),t)}function Mn(e){return"function"!=typeof e}class Nn extends In{add(e,t){return this.content[e]=On(e,t),this}addChild(e,t,o){const i=t.splice(0,1)[0];let n=this.content[i];if(!n)throw new Error(`Path ${i+":"+t.join(":")} not found`);for(let e of t)if(n=n.children.filter(Mn).find((t=>t.id===e)),!n)throw new Error(`Path ${i+":"+t.join(":")} not found`);return"function"!=typeof o?n.children.push(On(e,o)):n.children.push(o),this}getAll(){return super.getAll().sort(((e,t)=>e.sequence-t.sequence))}}function _n(){const e=t.useState({x:0,y:0,width:0,height:0});let o=document.querySelector(".o-spreadsheet");function i(){if(o||(o=document.querySelector(".o-spreadsheet")),o){const{top:t,left:i,width:n,height:r}=o.getBoundingClientRect();e.x=i,e.y=t,e.width=n,e.height=r}}return i(),t.onMounted(i),t.onPatched(i),e}function Fn(e){const o=t.useState({x:0,y:0,width:0,height:0});function i(){const t=e.el;if(null===t)return;const{top:i,left:n,width:r,height:s}=t.getBoundingClientRect();o.x=n,o.y=i,o.width=r,o.height=s}return t.onMounted(i),t.onPatched(i),o}function Dn(e,t){const o=[];for(const i of e.children)"function"==typeof i?o.push(...i(t)):o.push(i);return o.sort(((e,t)=>e.sequence-t.sequence))}function kn(e,t){return"function"==typeof e.name?e.name(t):e.name}function $n(){const e=document.querySelector(".o-grid-overlay");if(e){const{top:t,left:o}=null==e?void 0:e.getBoundingClientRect();return{top:t,left:o}}throw new Error("Can't find spreadsheet position")}function Pn(e,t){return(o=Lo(Ln(e),Ln(t)))?{x:o.left,y:o.top,width:o.right-o.left,height:o.bottom-o.top}:void 0;var o}function Ln(e){return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}ni`
54
54
  .o-popover {
55
55
  position: absolute;
56
56
  z-index: ${ae.Popover};
@@ -59,7 +59,7 @@
59
59
  width: fit-content;
60
60
  height: fit-content;
61
61
  }
62
- `;class Ln extends t.Component{constructor(){super(...arguments),this.popoverRef=t.useRef("popover"),this.currentPosition=void 0,this.currentDisplayValue=void 0,this.spreadsheetRect=Nn()}setup(){this.containerRect=function(){const e=t.useState({x:0,y:0,width:0,height:0}),o=t.useComponent(),i=Nn();function n(){const t=o.env,n="getPopoverContainerRect"in t?t.getPopoverContainerRect():i;e.x=n.x,e.y=n.y,e.width=n.width,e.height=n.height}return n(),t.onMounted(n),t.onPatched(n),e}(),t.useEffect((()=>{var e,t,o,i;if(!this.containerRect)throw new Error("Popover container is not defined");const n=this.popoverRef.el,r=$n(this.props.anchorRect,this.containerRect),s=r?"block":"none";if("none"!==this.currentDisplayValue&&"none"===s&&(null===(t=(e=this.props).onPopoverHidden)||void 0===t||t.call(e)),n.style.display=s,this.currentDisplayValue=s,!r)return;const a={width:this.props.maxWidth,height:this.props.maxHeight},l={width:n.getBoundingClientRect().width,height:n.getBoundingClientRect().height},c=this.spreadsheetRect,h="BottomLeft"===this.props.positioning?new Vn(r,this.containerRect,a,c):new zn(r,this.containerRect,a,c),d=h.getCss(l,this.props.verticalOffset);for(const e of Object.keys(d))n.style[e]=d[e];const u=h.getCurrentPosition(l);this.currentPosition&&u!==this.currentPosition&&(null===(i=(o=this.props).onPopoverMoved)||void 0===i||i.call(o)),this.currentPosition=u}))}get popoverStyle(){return ai({"z-index":`${this.props.zIndex}`})}}Ln.template="o-spreadsheet-Popover",Ln.defaultProps={positioning:"BottomLeft",verticalOffset:0,onMouseWheel:()=>{},onPopoverMoved:()=>{},onPopoverHidden:()=>{},zIndex:ae.Popover},Ln.props={anchorRect:Object,containerRect:{type:Object,optional:!0},positioning:{type:String,optional:!0},maxWidth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},verticalOffset:{type:Number,optional:!0},onMouseWheel:{type:Function,optional:!0},onPopoverHidden:{type:Function,optional:!0},onPopoverMoved:{type:Function,optional:!0},zIndex:{type:Number,optional:!0},slots:Object};class Un{constructor(e,t,o,i){this.anchorRect=e,this.containerRect=t,this.propsMaxSize=o,this.spreadsheetOffset=i}shouldRenderAtBottom(e){return e<=this.availableHeightDown||this.availableHeightDown>=this.availableHeightUp}shouldRenderAtRight(e){return e<=this.availableWidthRight||this.availableWidthRight>=this.availableWidthLeft}getMaxHeight(e){const t=this.shouldRenderAtBottom(e)?this.availableHeightDown:this.availableHeightUp;return this.propsMaxSize.height?Math.min(t,this.propsMaxSize.height):t}getMaxWidth(e){const t=this.shouldRenderAtRight(e)?this.availableWidthRight:this.availableWidthLeft;return this.propsMaxSize.width?Math.min(t,this.propsMaxSize.width):t}getCss(e,t){const o=this.getMaxHeight(e.height),i=this.getMaxWidth(e.width),n=Math.min(o,e.height),r=Math.min(i,e.width),s=this.shouldRenderAtBottom(e.height),a=this.shouldRenderAtRight(e.width);t=s?t:-t;return{"max-height":o+"px","max-width":i+"px",top:this.getTopCoordinate(n,s)-this.spreadsheetOffset.y-t+"px",left:this.getLeftCoordinate(r,a)-this.spreadsheetOffset.x+"px"}}getCurrentPosition(e){const t=this.shouldRenderAtBottom(e.height),o=this.shouldRenderAtRight(e.width);return t&&o?"BottomRight":t&&!o?"BottomLeft":!t&&o?"TopRight":"TopLeft"}}class Vn extends Un{get availableHeightUp(){return this.anchorRect.y-this.containerRect.y}get availableHeightDown(){return this.containerRect.height-this.availableHeightUp-this.anchorRect.height}get availableWidthRight(){return this.containerRect.x+this.containerRect.width-this.anchorRect.x}get availableWidthLeft(){return this.anchorRect.x+this.anchorRect.width-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y+this.anchorRect.height:this.anchorRect.y-e}getLeftCoordinate(e,t){return t?this.anchorRect.x:this.anchorRect.x+this.anchorRect.width-e}}class zn extends Un{get availableHeightUp(){return this.anchorRect.y+this.anchorRect.height-this.containerRect.y}get availableHeightDown(){return this.containerRect.y+this.containerRect.height-this.anchorRect.y}get availableWidthRight(){return this.containerRect.width-this.anchorRect.width-this.availableWidthLeft}get availableWidthLeft(){return this.anchorRect.x-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y:this.anchorRect.y+this.anchorRect.height-e}getLeftCoordinate(e,t){return t?this.anchorRect.x+this.anchorRect.width:this.anchorRect.x-e}}ii`
62
+ `;class Un extends t.Component{constructor(){super(...arguments),this.popoverRef=t.useRef("popover"),this.currentPosition=void 0,this.currentDisplayValue=void 0,this.spreadsheetRect=_n()}setup(){this.containerRect=function(){const e=t.useState({x:0,y:0,width:0,height:0}),o=t.useComponent(),i=_n();function n(){const t=o.env,n="getPopoverContainerRect"in t?t.getPopoverContainerRect():i;e.x=n.x,e.y=n.y,e.width=n.width,e.height=n.height}return n(),t.onMounted(n),t.onPatched(n),e}(),t.useEffect((()=>{var e,t,o,i;if(!this.containerRect)throw new Error("Popover container is not defined");const n=this.popoverRef.el,r=Pn(this.props.anchorRect,this.containerRect),s=r?"block":"none";if("none"!==this.currentDisplayValue&&"none"===s&&(null===(t=(e=this.props).onPopoverHidden)||void 0===t||t.call(e)),n.style.display=s,this.currentDisplayValue=s,!r)return;const a={width:this.props.maxWidth,height:this.props.maxHeight},l={width:n.getBoundingClientRect().width,height:n.getBoundingClientRect().height},c=this.spreadsheetRect,h="BottomLeft"===this.props.positioning?new zn(r,this.containerRect,a,c):new Bn(r,this.containerRect,a,c),d=h.getCss(l,this.props.verticalOffset);for(const e of Object.keys(d))n.style[e]=d[e];const u=h.getCurrentPosition(l);this.currentPosition&&u!==this.currentPosition&&(null===(i=(o=this.props).onPopoverMoved)||void 0===i||i.call(o)),this.currentPosition=u}))}get popoverStyle(){return li({"z-index":`${this.props.zIndex}`})}}Un.template="o-spreadsheet-Popover",Un.defaultProps={positioning:"BottomLeft",verticalOffset:0,onMouseWheel:()=>{},onPopoverMoved:()=>{},onPopoverHidden:()=>{},zIndex:ae.Popover},Un.props={anchorRect:Object,containerRect:{type:Object,optional:!0},positioning:{type:String,optional:!0},maxWidth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},verticalOffset:{type:Number,optional:!0},onMouseWheel:{type:Function,optional:!0},onPopoverHidden:{type:Function,optional:!0},onPopoverMoved:{type:Function,optional:!0},zIndex:{type:Number,optional:!0},slots:Object};class Vn{constructor(e,t,o,i){this.anchorRect=e,this.containerRect=t,this.propsMaxSize=o,this.spreadsheetOffset=i}shouldRenderAtBottom(e){return e<=this.availableHeightDown||this.availableHeightDown>=this.availableHeightUp}shouldRenderAtRight(e){return e<=this.availableWidthRight||this.availableWidthRight>=this.availableWidthLeft}getMaxHeight(e){const t=this.shouldRenderAtBottom(e)?this.availableHeightDown:this.availableHeightUp;return this.propsMaxSize.height?Math.min(t,this.propsMaxSize.height):t}getMaxWidth(e){const t=this.shouldRenderAtRight(e)?this.availableWidthRight:this.availableWidthLeft;return this.propsMaxSize.width?Math.min(t,this.propsMaxSize.width):t}getCss(e,t){const o=this.getMaxHeight(e.height),i=this.getMaxWidth(e.width),n=Math.min(o,e.height),r=Math.min(i,e.width),s=this.shouldRenderAtBottom(e.height),a=this.shouldRenderAtRight(e.width);t=s?t:-t;return{"max-height":o+"px","max-width":i+"px",top:this.getTopCoordinate(n,s)-this.spreadsheetOffset.y-t+"px",left:this.getLeftCoordinate(r,a)-this.spreadsheetOffset.x+"px"}}getCurrentPosition(e){const t=this.shouldRenderAtBottom(e.height),o=this.shouldRenderAtRight(e.width);return t&&o?"BottomRight":t&&!o?"BottomLeft":!t&&o?"TopRight":"TopLeft"}}class zn extends Vn{get availableHeightUp(){return this.anchorRect.y-this.containerRect.y}get availableHeightDown(){return this.containerRect.height-this.availableHeightUp-this.anchorRect.height}get availableWidthRight(){return this.containerRect.x+this.containerRect.width-this.anchorRect.x}get availableWidthLeft(){return this.anchorRect.x+this.anchorRect.width-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y+this.anchorRect.height:this.anchorRect.y-e}getLeftCoordinate(e,t){return t?this.anchorRect.x:this.anchorRect.x+this.anchorRect.width-e}}class Bn extends Vn{get availableHeightUp(){return this.anchorRect.y+this.anchorRect.height-this.containerRect.y}get availableHeightDown(){return this.containerRect.y+this.containerRect.height-this.anchorRect.y}get availableWidthRight(){return this.containerRect.width-this.anchorRect.width-this.availableWidthLeft}get availableWidthLeft(){return this.anchorRect.x-this.containerRect.x}getTopCoordinate(e,t){return t?this.anchorRect.y:this.anchorRect.y+this.anchorRect.height-e}getLeftCoordinate(e,t){return t?this.anchorRect.x+this.anchorRect.width:this.anchorRect.x-e}}ni`
63
63
  .o-menu {
64
64
  background-color: white;
65
65
  padding: ${8}px 0px;
@@ -109,13 +109,13 @@
109
109
  }
110
110
  }
111
111
  }
112
- `;class Bn extends t.Component{constructor(){super(...arguments),this.subMenu=t.useState({isOpen:!1,position:null,scrollOffset:0,menuItems:[]}),this.menuRef=t.useRef("menu"),this.position=_n(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(){const e=this.visibleMenuItems;let t=this.getMenuItemsHeight(e);return e[e.length-1].separator&&(t-=11),16+t}get popoverProps(){const e=1===this.props.depth;return{anchorRect:{x:this.props.position.x-z*(this.props.depth-1),y:this.props.position.y,width:e?0:z,height:e?0:28},positioning:"TopRight",verticalOffset:e?0:8,onPopoverHidden:()=>this.closeSubMenu(),onPopoverMoved:()=>this.closeSubMenu(),maxHeight:this.menuHeight}}getColor(e){return e.textColor?`color: ${e.textColor}`:void 0}async activateMenu(e){var t,o;const i=await e.action(this.env);this.close(),null===(o=(t=this.props).onMenuClicked)||void 0===o||o.call(t,{detail:i})}close(){this.closeSubMenu(),this.props.onClose()}subMenuVerticalPosition(e){const t=this.visibleMenuItems.slice(0,e);return this.position.y+this.getMenuItemsHeight(t)+8}onExternalClick(e){this.menuRef.el&&Array.from(document.querySelectorAll(".o-spreadsheet .o-menu")).some((t=>function(e,t){return!!t.target&&e.contains(t.target)}(t,e)))||(e.closedMenuId=this.props.menuId,this.close())}getMenuItemsHeight(e){const t=e.filter((e=>e.separator)).length;return 28*e.length+11*t}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 o=this.subMenuVerticalPosition(t);this.subMenu.position={x:this.position.x+this.props.depth*z,y:o-(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 o;return(null===(o=e.parentMenu)||void 0===o?void 0:o.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())}}Bn.template="o-spreadsheet-Menu",Bn.components={Menu:Bn,Popover:Ln},Bn.defaultProps={depth:1},Bn.props={position:Object,menuItems:Array,depth:{type:Number,optional:!0},onClose:Function,onMenuClicked:{type:Function,optional:!0},menuId:{type:String,optional:!0}},ii`
112
+ `;class Hn extends t.Component{constructor(){super(...arguments),this.subMenu=t.useState({isOpen:!1,position:null,scrollOffset:0,menuItems:[]}),this.menuRef=t.useRef("menu"),this.position=Fn(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(){const e=this.visibleMenuItems;let t=this.getMenuItemsHeight(e);return e[e.length-1].separator&&(t-=11),16+t}get popoverProps(){const e=1===this.props.depth;return{anchorRect:{x:this.props.position.x-z*(this.props.depth-1),y:this.props.position.y,width:e?0:z,height:e?0:28},positioning:"TopRight",verticalOffset:e?0:8,onPopoverHidden:()=>this.closeSubMenu(),onPopoverMoved:()=>this.closeSubMenu(),maxHeight:this.menuHeight}}getColor(e){return e.textColor?`color: ${e.textColor}`:void 0}async activateMenu(e){var t,o;const i=await e.action(this.env);this.close(),null===(o=(t=this.props).onMenuClicked)||void 0===o||o.call(t,{detail:i})}close(){this.closeSubMenu(),this.props.onClose()}subMenuVerticalPosition(e){const t=this.visibleMenuItems.slice(0,e);return this.position.y+this.getMenuItemsHeight(t)+8}onExternalClick(e){this.menuRef.el&&Array.from(document.querySelectorAll(".o-spreadsheet .o-menu")).some((t=>function(e,t){return!!t.target&&e.contains(t.target)}(t,e)))||(e.closedMenuId=this.props.menuId,this.close())}getMenuItemsHeight(e){const t=e.filter((e=>e.separator)).length;return 28*e.length+11*t}getName(e){return kn(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 o=this.subMenuVerticalPosition(t);this.subMenu.position={x:this.position.x+this.props.depth*z,y:o-(this.subMenu.scrollOffset||0)},this.subMenu.menuItems=Dn(e,this.env).filter((e=>!e.isVisible||e.isVisible(this.env))),this.subMenu.isOpen=!0,this.subMenu.parentMenu=e}isParentMenu(e,t){var o;return(null===(o=e.parentMenu)||void 0===o?void 0:o.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:Un},Hn.defaultProps={depth:1},Hn.props={position:Object,menuItems:Array,depth:{type:Number,optional:!0},onClose:Function,onMenuClicked:{type:Function,optional:!0},menuId:{type:String,optional:!0}},ni`
113
113
  .o-chart-container {
114
114
  width: 100%;
115
115
  height: 100%;
116
116
  position: relative;
117
117
  }
118
- `;class Hn 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.menuButtonRect=_n(this.menuButtonRef),this.position=_n(this.chartContainerRef)}getMenuItemRegistry(){const e=new Mn;return e.add("edit",{name:r("Edit"),sequence:1,action:()=>{this.env.model.dispatch("SELECT_FIGURE",{id:this.props.figure.id}),this.env.openSidePanel("ChartPanel")}}),e.add("copy",{name:r("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.write(this.env.model.getters.getClipboardContent())}}),e.add("cut",{name:r("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.write(this.env.model.getters.getClipboardContent())}}),e.add("delete",{name:r("Delete"),sequence:10,action:()=>{this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:this.props.figure.id}),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{x:e,y:t,width:o}=this.menuButtonRect,i={x:e>=z?e-z:e+o,y:t};this.openContextMenu(i)}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=Rn.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}function Wn(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause(19)&&e.raiseError(r("This operation is not allowed with multiple selections."))}Hn.template="o-spreadsheet-ChartFigure",Hn.components={Menu:Bn},Hn.props={figure:Object,onFigureDeleted:Function};const Gn={wrongPasteSelection:r("This operation is not allowed with multiple selections."),willRemoveExistingMerge:r("This operation is not possible due to a merge. Please remove the merges first than try again."),wrongFigurePasteOption:r("Cannot do a special paste of a figure."),frozenPaneOverlap:r("Cannot paste merged cells over a frozen pane.")};function qn(e,t){t.isSuccessful||(t.reasons.includes(20)?e.raiseError(Gn.wrongPasteSelection):t.reasons.includes(2)?e.raiseError(Gn.willRemoveExistingMerge):t.reasons.includes(22)?e.raiseError(Gn.wrongFigurePasteOption):t.reasons.includes(75)&&e.raiseError(Gn.frozenPaneOverlap))}function Zn(e,t,o){const i=e.model.dispatch("PASTE",{target:t,pasteOption:o});qn(e,i)}function jn(e,t,o){const i=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,text:o});qn(e,i)}function Xn(e,t){const o=In.getAll().find((t=>t.match(e.type)));if(!o)throw new Error("Unknown chart type.");return o.transformDefinition(e,t)}function Yn(e,t){var o;let i=e;e.left!==e.right&&(i={...e,left:e.left+1});const r=[No(i)],s=t.getActiveSheetId(),a=t.getCell({sheetId:s,col:e.left,row:e.top});if(1===Qo(e)&&(null==a?void 0:a.content))return{type:"scorecard",title:"",background:(null===(o=a.style)||void 0===o?void 0:o.fillColor)||void 0,keyValue:No(e),baselineMode:J,baselineColorUp:ee,baselineColorDown:te};let l="";const c=t.getEvaluatedCellsInZone(s,{...i,bottom:i.top}),h=!!c.find((e=>e.type!==mi.empty&&e.type!==mi.number));if(h){const e=c.filter((e=>e.type!==mi.error&&e.type!==mi.empty)).map((e=>e.formattedValue)),t=e.splice(-1)[0];l=e.join(", "),t&&(l+=(l?" "+n("and")+" ":"")+t)}let d;e.left!==e.right&&(d=No({...e,right:e.left,top:h?e.top+1:e.top}));const u=i.right===i.left?"none":"top";return mn(d?t.getRangeFromSheetXC(s,d):void 0,t)?{title:l,dataSets:r,labelsAsText:!1,stacked:!1,aggregated:!1,labelRange:d,type:"line",dataSetsHaveTitle:h,verticalAxisPosition:"left",legendPosition:u}:{title:l,dataSets:r,labelRange:d,type:"bar",stacked:!1,aggregated:!1,dataSetsHaveTitle:h,verticalAxisPosition:"left",legendPosition:u}}function Kn(e,t){const o=Me(t),i=e.getSheetViewDimension(),n=i.width,r=i.height;if(o.width>n){const e=n/o.width;o.width=n,o.height=o.height*e}if(o.height>r){const e=r/o.height;o.height=r,o.width=o.width*e}return o}const Qn=[mi.number,mi.error,mi.text,mi.boolean];function Jn(e,t,o,i,n){let s=wi.Success,a=i.right>i.left;if(e.model.getters.doesIntersectMerge(t,i)){let o;a=!1;for(let n=i.top;n<=i.bottom;n++){o=[];for(let r=i.left;r<=i.right;r++){let i=e.model.getters.getMerge({sheetId:t,col:r,row:n});i&&!o.includes(i.id.toString())&&o.push(i.id.toString())}if(o.length>=2){a=!0;break}}}const{col:l,row:c}=o;if(a)s=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:n});else{const o=e.model.getters.getContiguousZone(t,i);Lo(o,i)?s=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:n}):e.askConfirmation(r("We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?"),(()=>{i=o,s=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:n})}),(()=>{s=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:n})}))}if(s.isCancelledBecause(63)){const{col:t,row:n}=o;e.model.selection.selectZone({cell:{col:t,row:n},zone:i}),e.raiseError(r("Cannot sort. To sort, select only cells or only merges that have the same size."))}}const er={filterOverlap:r("You cannot create overlapping filters."),nonContinuousTargets:r("A filter can only be created on a continuous selection."),mergeInFilter:r("You can't create a filter over a range that contains a merge.")};function tr(e,t,o){const i=e.model.dispatch("CREATE_FILTER_TABLE",{target:o,sheetId:t});i.isCancelledBecause(78)?e.raiseError(er.filterOverlap):i.isCancelledBecause(80)?e.raiseError(er.mergeInFilter):i.isCancelledBecause(81)&&e.raiseError(er.nonContinuousTargets)}function or(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 ir(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 nr(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function rr(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const sr=async e=>{e.model.dispatch("COPY"),await e.clipboard.write(e.model.getters.getClipboardContent())},ar=async e=>{Wn(e),await e.clipboard.write(e.model.getters.getClipboardContent())},lr=async e=>hr(e),cr=async e=>hr(e,"onlyValue");async function hr(e,t){const o=e.model.getters.getClipboardTextContent(),i=await e.clipboard.readText();switch(i.status){case"ok":const n=e.model.getters.getSelectedZones();i&&i.content!==o?jn(e,n,i.content):Zn(e,n,t);break;case"notImplemented":e.raiseError(r("Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead."));break;case"permissionDenied":e.raiseError(r("Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings."))}}const dr=e=>Zn(e,e.model.getters.getSelectedZones(),"onlyFormat"),ur=e=>!e.model.getters.isCutOperation(),gr=e=>{if(e.model.getters.getSelectedZones().length>1)return r("Delete rows");let t,o;const i=e.model.getters.getActiveRows();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.top,o=i.bottom}return t===o?r("Delete row %s",(t+1).toString()):r("Delete rows %s - %s",(t+1).toString(),(o+1).toString())},pr=e=>{let t=[...e.model.getters.getActiveRows()];if(!t.length){const o=e.model.getters.getSelectedZones()[0];for(let e=o.top;e<=o.bottom;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},mr=e=>{if(e.model.getters.getSelectedZones().length>1)return r("Delete columns");let t,o;const i=e.model.getters.getActiveCols();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.left,o=i.right}return t===o?r("Delete column %s",_t(t)):r("Delete columns %s - %s",_t(t),_t(o))},fr=e=>{let t=[...e.model.getters.getActiveCols()];if(!t.length){const o=e.model.getters.getSelectedZones()[0];for(let e=o.left;e<=o.right;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},vr=e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});qn(e,o)},br=e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});qn(e,o)},Cr=e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});qn(e,o)},Sr=e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});qn(e,o)},Er=e=>{const t=e.model.getters.getActiveRows();let o,i;if(t.size)o=Math.min(...t),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.top,i=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",base:o,quantity:i,dimension:"ROW"})},wr=e=>{const t=e.model.getters.getActiveRows();let o,i;if(t.size)o=Math.max(...t),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.bottom,i=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",base:o,quantity:i,dimension:"ROW"})},yr=e=>{const t=e.model.getters.getActiveCols();let o,i;if(t.size)o=Math.min(...t),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.left,i=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",dimension:"COL",base:o,quantity:i})},xr=e=>{const t=e.model.getters.getActiveCols();let o,i;if(t.size)o=Math.max(...t),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.right,i=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",dimension:"COL",base:o,quantity:i})};const Ir=e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},Rr=e=>{let{col:t,row:o}=e.model.getters.getActivePosition();e.model.dispatch("OPEN_CELL_POPOVER",{col:t,row:o,popoverType:"LinkEditor"})},Tr=e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,o)},Ar=e=>{const{anchor:t,zones:o}=e.model.getters.getSelection(),i=e.model.getters.getActiveSheetId();Jn(e,i,t.cell,o[0],"ascending")},Or=e=>{const{anchor:t,zones:o}=e.model.getters.getSelection(),i=e.model.getters.getActiveSheetId();Jn(e,i,t.cell,o[0],"descending")},Mr=e=>1===e.model.getters.getSelectedZones().length,Nr=new Mn;Nr.add("cut",{name:r("Cut"),description:"Ctrl+X",sequence:10,action:ar}).add("copy",{name:r("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:sr}).add("paste",{name:r("Paste"),description:"Ctrl+V",sequence:30,action:lr}).add("paste_special",{name:r("Paste special"),sequence:40,separator:!0,isVisible:ur}).addChild("paste_value_only",["paste_special"],{name:r("Paste values only"),sequence:10,action:cr}).addChild("paste_format_only",["paste_special"],{name:r("Paste format only"),sequence:20,action:dr}).add("add_row_before",{name:e=>{const t=ir(e);return 1===t?r("Insert row"):r("Insert %s rows",t.toString())},sequence:70,action:Er,isVisible:Mr}).add("add_column_before",{name:e=>{const t=or(e);return 1===t?r("Insert column"):r("Insert %s columns",t.toString())},sequence:90,action:yr,isVisible:Mr}).add("insert_cell",{name:r("Insert cells"),sequence:100,isVisible:Mr,separator:!0}).addChild("insert_cell_down",["insert_cell"],{name:r("Shift down"),sequence:10,action:vr}).addChild("insert_cell_right",["insert_cell"],{name:r("Shift right"),sequence:20,action:br}).add("delete_row",{name:gr,sequence:110,action:pr,isVisible:Mr}).add("delete_column",{name:mr,sequence:120,action:fr,isVisible:Mr}).add("delete_cell",{name:r("Delete cells"),sequence:130,isVisible:Mr}).addChild("delete_cell_up",["delete_cell"],{name:r("Shift up"),sequence:10,action:Cr}).addChild("delete_cell_down",["delete_cell"],{name:r("Shift left"),sequence:20,action:Sr}).add("insert_link",{name:r("Insert link"),separator:!0,sequence:150,action:Rr});const _r=new Mn;_r.add("cut",{name:r("Cut"),description:"Ctrl+X",sequence:10,action:ar}).add("copy",{name:r("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:sr}).add("paste",{name:r("Paste"),description:"Ctrl+V",sequence:30,action:lr}).add("paste_special",{name:r("Paste special"),sequence:40,separator:!0,isVisible:ur}).addChild("paste_value_only",["paste_special"],{name:r("Paste value only"),sequence:10,action:cr}).addChild("paste_format_only",["paste_special"],{name:r("Paste format only"),sequence:20,action:dr}).add("sort_columns",{name:e=>e.model.getters.getActiveCols().size>1?r("Sort columns"):r("Sort column"),sequence:50,isVisible:Mr,separator:!0}).addChild("sort_ascending",["sort_columns"],{name:r("Ascending (A ⟶ Z)"),sequence:10,action:Ar}).addChild("sort_descending",["sort_columns"],{name:r("Descending (Z ⟶ A)"),sequence:20,action:Or}).add("add_column_before",{name:e=>{const t=or(e);return 1===t?r("Insert column left"):r("Insert %s columns left",t.toString())},sequence:70,action:yr}).add("add_column_after",{name:e=>{const t=or(e);return 1===t?r("Insert column right"):r("Insert %s columns right",t.toString())},sequence:80,action:xr}).add("delete_column",{name:mr,sequence:90,action:fr,isVisible:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getElementsFromSelection("COL");return e.model.getters.canRemoveHeaders(t,"COL",o)}}).add("clear_column",{name:e=>{if(e.model.getters.getSelectedZones().length>1)return r("Clear columns");let t,o;const i=e.model.getters.getActiveCols();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.left,o=i.right}return t===o?r("Clear column %s",_t(t)):r("Clear columns %s - %s",_t(t),_t(o))},sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId(),o=[...e.model.getters.getActiveCols()].map((o=>e.model.getters.getColsZone(t,o,o)));e.model.dispatch("DELETE_CONTENT",{target:o,sheetId:e.model.getters.getActiveSheetId()})}}).add("hide_columns",{name:e=>{const t=e.model.getters.getElementsFromSelection("COL");let o=t[0],i=t[t.length-1];return 1===t.length?r("Hide column %s",_t(o).toString()):i-o+1===t.length?r("Hide columns %s - %s",_t(o).toString(),_t(i).toString()):r("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(),o=e.model.getters.getElementsFromSelection("COL");return e.model.getters.canRemoveHeaders(t,"COL",o)},separator:!0}).add("unhide_columns",{name:r("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:r("Conditional formatting"),sequence:110,action:Ir});const Fr=new Mn;function Dr(e,t,o=(()=>{})){const i=e=>{e.preventDefault(),o(e)},n=t=>{t.preventDefault(),e(t)},r=e=>{e.preventDefault(),t(e),window.removeEventListener("mousedown",i),window.removeEventListener("mouseup",r),window.removeEventListener("dragstart",s),window.removeEventListener("mousemove",n),window.removeEventListener("wheel",n)};function s(e){e.preventDefault()}window.addEventListener("mousedown",i),window.addEventListener("mouseup",r),window.addEventListener("dragstart",s),window.addEventListener("mousemove",n),window.addEventListener("wheel",n,{passive:!1})}function kr(e,t,o,i=!1){let n,r,s,a,l,c=null;const h=e.model.getters,d=h.getActiveSheetId(),u=kn();let g,p;const m=o=>{if(n=o,c)return;const{x:s,y:f}=h.getMainViewportCoordinates();let{top:v,left:b,bottom:C,right:S}=h.getActiveMainViewport(),{scrollX:E,scrollY:w}=h.getActiveSheetDOMScrollInfo();const{xSplit:y,ySplit:x}=h.getPaneDivisions(d);let I=!1,R=$t;const T=n.clientX-u.left;if(g=h.getColIndex(T),"vertical"!==i){const t=r.clientX-u.left,o=h.getEdgeScrollCol(T,t,a);if(o.canEdgeScroll){let t;switch(I=!0,R=Math.min(R,o.delay),o.direction){case"reset":g=y,t=y;break;case 1:g=S,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-s}}const A=n.clientY-u.top;if(p=h.getRowIndex(A),"horizontal"!==i){const t=r.clientY-u.top,o=h.getEdgeScrollRow(A,t,l);if(o.canEdgeScroll){let t;switch(I=!0,R=Math.min(R,o.delay),o.direction){case"reset":p=x,t=x;break;case 1:p=C,t=v+o.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}}I||(-1===p&&(p=A<0?0:h.getNumberRows(d)-1),-1===g&&T<0&&(g=T<0?0:h.getNumberCols(d)-1)),t(g,p,n),I&&(e.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:E,offsetY:w}),c=setTimeout((()=>{c=null,m(n)}),Math.round(R))),r=n};Dr(m,(()=>{clearTimeout(c),o()}),(e=>{r=e,s=e,a=s.clientX-u.left,l=s.clientY-u.top}))}Fr.add("cut",{name:r("Cut"),sequence:10,description:"Ctrl+X",action:ar}).add("copy",{name:r("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:sr}).add("paste",{name:r("Paste"),description:"Ctrl+V",sequence:30,action:lr}).add("paste_special",{name:r("Paste special"),sequence:40,separator:!0,isVisible:ur}).addChild("paste_value_only",["paste_special"],{name:r("Paste value only"),sequence:10,action:cr}).addChild("paste_format_only",["paste_special"],{name:r("Paste format only"),sequence:20,action:dr}).add("add_row_before",{name:e=>{const t=ir(e);return 1===t?r("Insert row above"):r("Insert %s rows above",t.toString())},sequence:50,action:Er}).add("add_row_after",{name:e=>{const t=ir(e);return 1===t?r("Insert row below"):r("Insert %s rows below",t.toString())},sequence:60,action:wr}).add("delete_row",{name:gr,sequence:70,action:pr,isVisible:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getElementsFromSelection("ROW");return e.model.getters.canRemoveHeaders(t,"ROW",o)}}).add("clear_row",{name:e=>{if(e.model.getters.getSelectedZones().length>1)return r("Clear rows");let t,o;const i=e.model.getters.getActiveRows();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.top,o=i.bottom}return t===o?r("Clear row %s",(t+1).toString()):r("Clear rows %s - %s",(t+1).toString(),(o+1).toString())},sequence:80,action:e=>{const t=e.model.getters.getActiveSheetId(),o=[...e.model.getters.getActiveRows()].map((o=>e.model.getters.getRowsZone(t,o,o)));e.model.dispatch("DELETE_CONTENT",{target:o,sheetId:e.model.getters.getActiveSheetId()})}}).add("hide_rows",{name:e=>{const t=e.model.getters.getElementsFromSelection("ROW");let o=t[0],i=t[t.length-1];return 1===t.length?r("Hide row %s",(o+1).toString()):i-o+1===t.length?r("Hide rows %s - %s",(o+1).toString(),(i+1).toString()):r("Hide rows")},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(),o=e.model.getters.getElementsFromSelection("ROW");return e.model.getters.canRemoveHeaders(t,"ROW",o)},separator:!0}).add("unhide_rows",{name:r("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:r("Conditional formatting"),sequence:90,action:Ir}),ii`
118
+ `;class Wn 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.menuButtonRect=Fn(this.menuButtonRef),this.position=Fn(this.chartContainerRef)}getMenuItemRegistry(){const e=new Nn;return e.add("edit",{name:r("Edit"),sequence:1,action:()=>{this.env.model.dispatch("SELECT_FIGURE",{id:this.props.figure.id}),this.env.openSidePanel("ChartPanel")}}),e.add("copy",{name:r("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.write(this.env.model.getters.getClipboardContent())}}),e.add("cut",{name:r("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.write(this.env.model.getters.getClipboardContent())}}),e.add("delete",{name:r("Delete"),sequence:10,action:()=>{this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:this.props.figure.id}),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{x:e,y:t,width:o}=this.menuButtonRect,i={x:e>=z?e-z:e+o,y:t};this.openContextMenu(i)}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=Tn.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}function Gn(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause(19)&&e.raiseError(r("This operation is not allowed with multiple selections."))}Wn.template="o-spreadsheet-ChartFigure",Wn.components={Menu:Hn},Wn.props={figure:Object,onFigureDeleted:Function};const qn={wrongPasteSelection:r("This operation is not allowed with multiple selections."),willRemoveExistingMerge:r("This operation is not possible due to a merge. Please remove the merges first than try again."),wrongFigurePasteOption:r("Cannot do a special paste of a figure."),frozenPaneOverlap:r("Cannot paste merged cells over a frozen pane.")};function Zn(e,t){t.isSuccessful||(t.reasons.includes(20)?e.raiseError(qn.wrongPasteSelection):t.reasons.includes(2)?e.raiseError(qn.willRemoveExistingMerge):t.reasons.includes(22)?e.raiseError(qn.wrongFigurePasteOption):t.reasons.includes(75)&&e.raiseError(qn.frozenPaneOverlap))}function jn(e,t,o){const i=e.model.dispatch("PASTE",{target:t,pasteOption:o});Zn(e,i)}function Xn(e,t,o){const i=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,text:o});Zn(e,i)}function Yn(e,t){const o=Rn.getAll().find((t=>t.match(e.type)));if(!o)throw new Error("Unknown chart type.");return o.transformDefinition(e,t)}function Kn(e,t){var o;let i=e;e.left!==e.right&&(i={...e,left:e.left+1});const r=[_o(i)],s=t.getActiveSheetId(),a=t.getCell({sheetId:s,col:e.left,row:e.top});if(1===Jo(e)&&(null==a?void 0:a.content))return{type:"scorecard",title:"",background:(null===(o=a.style)||void 0===o?void 0:o.fillColor)||void 0,keyValue:_o(e),baselineMode:J,baselineColorUp:ee,baselineColorDown:te};let l="";const c=t.getEvaluatedCellsInZone(s,{...i,bottom:i.top}),h=!!c.find((e=>e.type!==fi.empty&&e.type!==fi.number));if(h){const e=c.filter((e=>e.type!==fi.error&&e.type!==fi.empty)).map((e=>e.formattedValue)),t=e.splice(-1)[0];l=e.join(", "),t&&(l+=(l?" "+n("and")+" ":"")+t)}let d;e.left!==e.right&&(d=_o({...e,right:e.left,top:h?e.top+1:e.top}));const u=i.right===i.left?"none":"top";return fn(d?t.getRangeFromSheetXC(s,d):void 0,t)?{title:l,dataSets:r,labelsAsText:!1,stacked:!1,aggregated:!1,labelRange:d,type:"line",dataSetsHaveTitle:h,verticalAxisPosition:"left",legendPosition:u}:{title:l,dataSets:r,labelRange:d,type:"bar",stacked:!1,aggregated:!1,dataSetsHaveTitle:h,verticalAxisPosition:"left",legendPosition:u}}function Qn(e,t){const o=Me(t),i=e.getSheetViewDimension(),n=i.width,r=i.height;if(o.width>n){const e=n/o.width;o.width=n,o.height=o.height*e}if(o.height>r){const e=r/o.height;o.height=r,o.width=o.width*e}return o}const Jn=[fi.number,fi.error,fi.text,fi.boolean];function er(e,t,o,i,n){let s=yi.Success,a=i.right>i.left;if(e.model.getters.doesIntersectMerge(t,i)){let o;a=!1;for(let n=i.top;n<=i.bottom;n++){o=[];for(let r=i.left;r<=i.right;r++){let i=e.model.getters.getMerge({sheetId:t,col:r,row:n});i&&!o.includes(i.id.toString())&&o.push(i.id.toString())}if(o.length>=2){a=!0;break}}}const{col:l,row:c}=o;if(a)s=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:n});else{const o=e.model.getters.getContiguousZone(t,i);Uo(o,i)?s=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:n}):e.askConfirmation(r("We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?"),(()=>{i=o,s=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:n})}),(()=>{s=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:i,sortDirection:n})}))}if(s.isCancelledBecause(63)){const{col:t,row:n}=o;e.model.selection.selectZone({cell:{col:t,row:n},zone:i}),e.raiseError(r("Cannot sort. To sort, select only cells or only merges that have the same size."))}}const tr={filterOverlap:r("You cannot create overlapping filters."),nonContinuousTargets:r("A filter can only be created on a continuous selection."),mergeInFilter:r("You can't create a filter over a range that contains a merge.")};function or(e,t,o){const i=e.model.dispatch("CREATE_FILTER_TABLE",{target:o,sheetId:t});i.isCancelledBecause(78)?e.raiseError(tr.filterOverlap):i.isCancelledBecause(80)?e.raiseError(tr.mergeInFilter):i.isCancelledBecause(81)&&e.raiseError(tr.nonContinuousTargets)}function ir(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 nr(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 rr(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function sr(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const ar=async e=>{e.model.dispatch("COPY"),await e.clipboard.write(e.model.getters.getClipboardContent())},lr=async e=>{Gn(e),await e.clipboard.write(e.model.getters.getClipboardContent())},cr=async e=>dr(e),hr=async e=>dr(e,"onlyValue");async function dr(e,t){const o=e.model.getters.getClipboardTextContent(),i=await e.clipboard.readText();switch(i.status){case"ok":const n=e.model.getters.getSelectedZones();i&&i.content!==o?Xn(e,n,i.content):jn(e,n,t);break;case"notImplemented":e.raiseError(r("Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead."));break;case"permissionDenied":e.raiseError(r("Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings."))}}const ur=e=>jn(e,e.model.getters.getSelectedZones(),"onlyFormat"),gr=e=>!e.model.getters.isCutOperation(),pr=e=>{if(e.model.getters.getSelectedZones().length>1)return r("Delete rows");let t,o;const i=e.model.getters.getActiveRows();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.top,o=i.bottom}return t===o?r("Delete row %s",(t+1).toString()):r("Delete rows %s - %s",(t+1).toString(),(o+1).toString())},mr=e=>{let t=[...e.model.getters.getActiveRows()];if(!t.length){const o=e.model.getters.getSelectedZones()[0];for(let e=o.top;e<=o.bottom;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},fr=e=>{if(e.model.getters.getSelectedZones().length>1)return r("Delete columns");let t,o;const i=e.model.getters.getActiveCols();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.left,o=i.right}return t===o?r("Delete column %s",Ft(t)):r("Delete columns %s - %s",Ft(t),Ft(o))},vr=e=>{let t=[...e.model.getters.getActiveCols()];if(!t.length){const o=e.model.getters.getSelectedZones()[0];for(let e=o.left;e<=o.right;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},br=e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});Zn(e,o)},Cr=e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});Zn(e,o)},Sr=e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});Zn(e,o)},Er=e=>{const t=e.model.getters.getSelectedZone(),o=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});Zn(e,o)},wr=e=>{const t=e.model.getters.getActiveRows();let o,i;if(t.size)o=Math.min(...t),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.top,i=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",base:o,quantity:i,dimension:"ROW"})},yr=e=>{const t=e.model.getters.getActiveRows();let o,i;if(t.size)o=Math.max(...t),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.bottom,i=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",base:o,quantity:i,dimension:"ROW"})},xr=e=>{const t=e.model.getters.getActiveCols();let o,i;if(t.size)o=Math.min(...t),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.left,i=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",dimension:"COL",base:o,quantity:i})},Ir=e=>{const t=e.model.getters.getActiveCols();let o,i;if(t.size)o=Math.max(...t),i=t.size;else{const t=e.model.getters.getSelectedZones()[0];o=t.right,i=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",dimension:"COL",base:o,quantity:i})};const Rr=e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},Tr=e=>{let{col:t,row:o}=e.model.getters.getActivePosition();e.model.dispatch("OPEN_CELL_POPOVER",{col:t,row:o,popoverType:"LinkEditor"})},Ar=e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,o)},Or=e=>{const{anchor:t,zones:o}=e.model.getters.getSelection(),i=e.model.getters.getActiveSheetId();er(e,i,t.cell,o[0],"ascending")},Mr=e=>{const{anchor:t,zones:o}=e.model.getters.getSelection(),i=e.model.getters.getActiveSheetId();er(e,i,t.cell,o[0],"descending")},Nr=e=>1===e.model.getters.getSelectedZones().length,_r=new Nn;_r.add("cut",{name:r("Cut"),description:"Ctrl+X",sequence:10,action:lr}).add("copy",{name:r("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:ar}).add("paste",{name:r("Paste"),description:"Ctrl+V",sequence:30,action:cr}).add("paste_special",{name:r("Paste special"),sequence:40,separator:!0,isVisible:gr}).addChild("paste_value_only",["paste_special"],{name:r("Paste values only"),sequence:10,action:hr}).addChild("paste_format_only",["paste_special"],{name:r("Paste format only"),sequence:20,action:ur}).add("add_row_before",{name:e=>{const t=nr(e);return 1===t?r("Insert row"):r("Insert %s rows",t.toString())},sequence:70,action:wr,isVisible:Nr}).add("add_column_before",{name:e=>{const t=ir(e);return 1===t?r("Insert column"):r("Insert %s columns",t.toString())},sequence:90,action:xr,isVisible:Nr}).add("insert_cell",{name:r("Insert cells"),sequence:100,isVisible:Nr,separator:!0}).addChild("insert_cell_down",["insert_cell"],{name:r("Shift down"),sequence:10,action:br}).addChild("insert_cell_right",["insert_cell"],{name:r("Shift right"),sequence:20,action:Cr}).add("delete_row",{name:pr,sequence:110,action:mr,isVisible:Nr}).add("delete_column",{name:fr,sequence:120,action:vr,isVisible:Nr}).add("delete_cell",{name:r("Delete cells"),sequence:130,isVisible:Nr}).addChild("delete_cell_up",["delete_cell"],{name:r("Shift up"),sequence:10,action:Sr}).addChild("delete_cell_down",["delete_cell"],{name:r("Shift left"),sequence:20,action:Er}).add("insert_link",{name:r("Insert link"),separator:!0,sequence:150,action:Tr});const Fr=new Nn;Fr.add("cut",{name:r("Cut"),description:"Ctrl+X",sequence:10,action:lr}).add("copy",{name:r("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:ar}).add("paste",{name:r("Paste"),description:"Ctrl+V",sequence:30,action:cr}).add("paste_special",{name:r("Paste special"),sequence:40,separator:!0,isVisible:gr}).addChild("paste_value_only",["paste_special"],{name:r("Paste value only"),sequence:10,action:hr}).addChild("paste_format_only",["paste_special"],{name:r("Paste format only"),sequence:20,action:ur}).add("sort_columns",{name:e=>e.model.getters.getActiveCols().size>1?r("Sort columns"):r("Sort column"),sequence:50,isVisible:Nr,separator:!0}).addChild("sort_ascending",["sort_columns"],{name:r("Ascending (A ⟶ Z)"),sequence:10,action:Or}).addChild("sort_descending",["sort_columns"],{name:r("Descending (Z ⟶ A)"),sequence:20,action:Mr}).add("add_column_before",{name:e=>{const t=ir(e);return 1===t?r("Insert column left"):r("Insert %s columns left",t.toString())},sequence:70,action:xr}).add("add_column_after",{name:e=>{const t=ir(e);return 1===t?r("Insert column right"):r("Insert %s columns right",t.toString())},sequence:80,action:Ir}).add("delete_column",{name:fr,sequence:90,action:vr,isVisible:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getElementsFromSelection("COL");return e.model.getters.canRemoveHeaders(t,"COL",o)}}).add("clear_column",{name:e=>{if(e.model.getters.getSelectedZones().length>1)return r("Clear columns");let t,o;const i=e.model.getters.getActiveCols();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.left,o=i.right}return t===o?r("Clear column %s",Ft(t)):r("Clear columns %s - %s",Ft(t),Ft(o))},sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId(),o=[...e.model.getters.getActiveCols()].map((o=>e.model.getters.getColsZone(t,o,o)));e.model.dispatch("DELETE_CONTENT",{target:o,sheetId:e.model.getters.getActiveSheetId()})}}).add("hide_columns",{name:e=>{const t=e.model.getters.getElementsFromSelection("COL");let o=t[0],i=t[t.length-1];return 1===t.length?r("Hide column %s",Ft(o).toString()):i-o+1===t.length?r("Hide columns %s - %s",Ft(o).toString(),Ft(i).toString()):r("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(),o=e.model.getters.getElementsFromSelection("COL");return e.model.getters.canRemoveHeaders(t,"COL",o)},separator:!0}).add("unhide_columns",{name:r("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:r("Conditional formatting"),sequence:110,action:Rr});const Dr=new Nn;function kr(e,t,o=(()=>{})){const i=e=>{e.preventDefault(),o(e)},n=t=>{t.preventDefault(),e(t)},r=e=>{e.preventDefault(),t(e),window.removeEventListener("mousedown",i),window.removeEventListener("mouseup",r),window.removeEventListener("dragstart",s),window.removeEventListener("mousemove",n),window.removeEventListener("wheel",n)};function s(e){e.preventDefault()}window.addEventListener("mousedown",i),window.addEventListener("mouseup",r),window.addEventListener("dragstart",s),window.addEventListener("mousemove",n),window.addEventListener("wheel",n,{passive:!1})}function $r(e,t,o,i=!1){let n,r,s,a,l,c=null;const h=e.model.getters,d=h.getActiveSheetId(),u=$n();let g,p;const m=o=>{if(n=o,c)return;const{x:s,y:f}=h.getMainViewportCoordinates();let{top:v,left:b,bottom:C,right:S}=h.getActiveMainViewport(),{scrollX:E,scrollY:w}=h.getActiveSheetDOMScrollInfo();const{xSplit:y,ySplit:x}=h.getPaneDivisions(d);let I=!1,R=Pt;const T=n.clientX-u.left;if(g=h.getColIndex(T),"vertical"!==i){const t=r.clientX-u.left,o=h.getEdgeScrollCol(T,t,a);if(o.canEdgeScroll){let t;switch(I=!0,R=Math.min(R,o.delay),o.direction){case"reset":g=y,t=y;break;case 1:g=S,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-s}}const A=n.clientY-u.top;if(p=h.getRowIndex(A),"horizontal"!==i){const t=r.clientY-u.top,o=h.getEdgeScrollRow(A,t,l);if(o.canEdgeScroll){let t;switch(I=!0,R=Math.min(R,o.delay),o.direction){case"reset":p=x,t=x;break;case 1:p=C,t=v+o.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}}I||(-1===p&&(p=A<0?0:h.getNumberRows(d)-1),-1===g&&T<0&&(g=T<0?0:h.getNumberCols(d)-1)),t(g,p,n),I&&(e.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:E,offsetY:w}),c=setTimeout((()=>{c=null,m(n)}),Math.round(R))),r=n};kr(m,(()=>{clearTimeout(c),o()}),(e=>{r=e,s=e,a=s.clientX-u.left,l=s.clientY-u.top}))}Dr.add("cut",{name:r("Cut"),sequence:10,description:"Ctrl+X",action:lr}).add("copy",{name:r("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:ar}).add("paste",{name:r("Paste"),description:"Ctrl+V",sequence:30,action:cr}).add("paste_special",{name:r("Paste special"),sequence:40,separator:!0,isVisible:gr}).addChild("paste_value_only",["paste_special"],{name:r("Paste value only"),sequence:10,action:hr}).addChild("paste_format_only",["paste_special"],{name:r("Paste format only"),sequence:20,action:ur}).add("add_row_before",{name:e=>{const t=nr(e);return 1===t?r("Insert row above"):r("Insert %s rows above",t.toString())},sequence:50,action:wr}).add("add_row_after",{name:e=>{const t=nr(e);return 1===t?r("Insert row below"):r("Insert %s rows below",t.toString())},sequence:60,action:yr}).add("delete_row",{name:pr,sequence:70,action:mr,isVisible:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getElementsFromSelection("ROW");return e.model.getters.canRemoveHeaders(t,"ROW",o)}}).add("clear_row",{name:e=>{if(e.model.getters.getSelectedZones().length>1)return r("Clear rows");let t,o;const i=e.model.getters.getActiveRows();if(0!==i.size)t=Math.min(...i),o=Math.max(...i);else{const i=e.model.getters.getSelectedZones()[0];t=i.top,o=i.bottom}return t===o?r("Clear row %s",(t+1).toString()):r("Clear rows %s - %s",(t+1).toString(),(o+1).toString())},sequence:80,action:e=>{const t=e.model.getters.getActiveSheetId(),o=[...e.model.getters.getActiveRows()].map((o=>e.model.getters.getRowsZone(t,o,o)));e.model.dispatch("DELETE_CONTENT",{target:o,sheetId:e.model.getters.getActiveSheetId()})}}).add("hide_rows",{name:e=>{const t=e.model.getters.getElementsFromSelection("ROW");let o=t[0],i=t[t.length-1];return 1===t.length?r("Hide row %s",(o+1).toString()):i-o+1===t.length?r("Hide rows %s - %s",(o+1).toString(),(i+1).toString()):r("Hide rows")},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(),o=e.model.getters.getElementsFromSelection("ROW");return e.model.getters.canRemoveHeaders(t,"ROW",o)},separator:!0}).add("unhide_rows",{name:r("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:r("Conditional formatting"),sequence:90,action:Rr}),ni`
119
119
  .o-autofill {
120
120
  height: 6px;
121
121
  width: 6px;
@@ -143,9 +143,9 @@
143
143
  white-space: nowrap;
144
144
  }
145
145
  }
146
- `;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=Pr),e}onMouseDown(e){this.state.handler=!0,this.state.position={left:0,top:0};const{scrollY:t,scrollX:o}=this.env.model.getters.getActiveSheetScrollInfo(),i=e.clientX+o,n=e.clientY+t;let r,s;Dr((e=>{const t=kn(),{scrollY:o,scrollX:a}=this.env.model.getters.getActiveSheetScrollInfo();this.state.position={left:e.clientX-i+a,top:e.clientY-n+o};const l=this.env.model.getters.getColIndex(e.clientX-t.left),c=this.env.model.getters.getRowIndex(e.clientY-t.top);if(r!==l||s!==c){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getNumberCols(e),o=this.env.model.getters.getNumberRows(e);r=-1===l?r:Fe(l,0,t),s=-1===c?s:Fe(c,0,o),void 0!==r&&void 0!==s&&this.env.model.dispatch("AUTOFILL_SELECT",{col:r,row:s})}}),(()=>{this.state.handler=!1,this.env.model.dispatch("AUTOFILL")}))}onDblClick(){this.env.model.dispatch("AUTOFILL_AUTO")}}$r.template="o-spreadsheet-Autofill",$r.props={position:Object};class Pr extends t.Component{}Pr.template=t.xml`
146
+ `;class Pr 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=Lr),e}onMouseDown(e){this.state.handler=!0,this.state.position={left:0,top:0};const{scrollY:t,scrollX:o}=this.env.model.getters.getActiveSheetScrollInfo(),i=e.clientX+o,n=e.clientY+t;let r,s;kr((e=>{const t=$n(),{scrollY:o,scrollX:a}=this.env.model.getters.getActiveSheetScrollInfo();this.state.position={left:e.clientX-i+a,top:e.clientY-n+o};const l=this.env.model.getters.getColIndex(e.clientX-t.left),c=this.env.model.getters.getRowIndex(e.clientY-t.top);if(r!==l||s!==c){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getNumberCols(e),o=this.env.model.getters.getNumberRows(e);r=-1===l?r:Fe(l,0,t),s=-1===c?s:Fe(c,0,o),void 0!==r&&void 0!==s&&this.env.model.dispatch("AUTOFILL_SELECT",{col:r,row:s})}}),(()=>{this.state.handler=!1,this.env.model.dispatch("AUTOFILL")}))}onDblClick(){this.env.model.dispatch("AUTOFILL_AUTO")}}Pr.template="o-spreadsheet-Autofill",Pr.props={position:Object};class Lr extends t.Component{}Lr.template=t.xml`
147
147
  <div t-esc="props.content"/>
148
- `,Pr.props={content:String},ii`
148
+ `,Lr.props={content:String},ni`
149
149
  .o-client-tag {
150
150
  position: absolute;
151
151
  border-top-left-radius: 4px;
@@ -155,7 +155,7 @@
155
155
  opacity: 0;
156
156
  pointer-events: none;
157
157
  }
158
- `;class Lr extends t.Component{get tagStyle(){const{col:e,row:t,color:o}=this.props,{height:i}=this.env.model.getters.getSheetViewDimensionWithHeaders(),{x:n,y:r}=this.env.model.getters.getVisibleRect({left:e,top:t,right:e,bottom:t});return`bottom: ${i-r+15}px;left: ${n-1}px;border: 1px solid ${o};background-color: ${o};${this.props.active?"opacity:1 !important":""}`}}Lr.template="o-spreadsheet-ClientTag",Lr.props={active:Boolean,name:String,color:String,col:Number,row:Number};const Ur=/(.*?)\((.*?)\)(.*)/,Vr=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function zr(e){let t=e.split("\n");const o=[];for(let e of t)e=e.trim(),e&&o.push(Br(e));return o}function Br(e){let t,o=e.match(Ur),i=o[1].trim(),n=[],r=!1,s=!1,a=!1;for(let e of o[2].split(",")){const o=e.trim().toUpperCase();let i=Vr.find((e=>o===e));i?n.push(i):"RANGE<ANY>"===o?n.push("RANGE"):"OPTIONAL"===o?r=!0:"REPEATING"===o?s=!0:"LAZY"===o?a=!0:o.startsWith("DEFAULT=")&&(t=e.trim().slice(8))}const l={name:i,description:o[3].trim(),type:n};return r&&(l.optional=!0),s&&(l.repeating=!0),a&&(l.lazy=!0),void 0!==t&&(l.default=!0,l.defaultValue=t),l}function Hr(e){let t=0,o=0,i=0;for(let n of e.args)t++,n.optional||n.repeating||n.default||o++,n.repeating&&i++;const n=e;return n.minArgRequired=o,n.maxArgPossible=i?1/0:t,n.nbrArgRepeating=i,n.getArgToFocus=function(e,t){if(!t)return e=>e;if(1===t)return t=>Math.min(t,e);const o=e-t;return e=>{if(e<=o)return e;return o+((e-o)%t||t)}}(t,i),n}const Wr=["number","string","boolean","undefined"];function Gr(e,t){if(!e())throw new Error(t)}const qr=e=>r("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function Zr(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(qt(e)||""===e)return jt(e);const t=be(e);if(t)return t.value;throw new Error(qr(e));default:return 0}}function jr(e){if(""===e)throw new Error(qr(e));return Zr(e)}function Xr(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}function Yr(e){return"string"==typeof e?e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):e}const Kr=e=>r("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function Qr(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(Kr(e))}return!1;case"number":return!!e;default:return!1}}function Jr(e){return Se(Zr(e))}function es(e,t,o){for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let n=0;n<o;n++)for(let o=0;o<e;o++)t(i[o][n])}else o(i)}function ts(e,t){es(e,t,t)}function os(e,t){es(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(jr(e))}))}function is(e,t,o,i){let n=i;for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let r=0;r<o;r++)for(let o=0;o<e;o++)n=t(n,i[o][r])}else n=o(n,i);return n}function ns(e,t,o){return is(e,t,t,o)}function rs(e,t,o){return is(e,((e,o)=>"number"==typeof o?t(e,o):e),((e,o)=>t(e,jr(o))),o)}function ss(e,t,o){return is(e,((e,o)=>null!=o?t(e,"number"==typeof o?o:"boolean"==typeof o?Zr(o):0):e),((e,o)=>t(e,Zr(o))),o)}function as(e,t){return function(e,t,o){for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let n=0;n<o;n++)for(let o=0;o<e;o++)if(!t(i[o][n]))return}else if(!o(i))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error(Kr(e));return Qr(e)}(e))))}function ls(e,t){let o,i,n=e.substring(0,2);"<="===n||">="===n||"<>"===n?(o=n,i=e.substring(2)):(n=e.substring(0,1),"<"===n||">"===n||"="===n?(o=n,i=e.substring(1)):(o="=",i=e)),qt(i)?i=Zr(i):"TRUE"!==i&&"FALSE"!==i||(i=Qr(i));const r={operator:o,operand:i};return"string"==typeof i&&(t&&(i+="*"),r.regexp=function(e){let t="",o="";for(let i of e)"?"===i&&"~"!==o?t+=".":"*"===i&&"~"!==o?t+=".*":("*"!==i&&"?"!==i||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(i)&&(t+="\\"),t+=i),o=i;return new RegExp("^"+t+"$","i")}(i)),r}function cs(e,t){const{operator:o,operand:i}=t;if(void 0===e||void 0===i)return!1;if("number"==typeof i&&"="===o)return Xr(e)===Xr(i);if("<>"===o||"="===o){let n;return n=typeof e==typeof i&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===i),"="===o?n:!n}if(typeof e==typeof i)switch(o){case"<":return e<i;case">":return e>i;case"<=":return e<=i;case">=":return e>=i}return!1}function hs(e,t,o=!1){const i=e.length;if(i%2==1)throw new Error(r("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const n=e[0].length,s=e[0][0].length;let a=[];for(let t=0;t<i-1;t+=2){const i=e[t];if(!Array.isArray(i)||i.length!==n||i[0].length!==s)throw new Error(r("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=Xr(e[t+1]);a.push(ls(l,o))}for(let o=0;o<n;o++)for(let n=0;n<s;n++){let r=!0;for(let t=0;t<i-1;t+=2){if(r=cs(e[t][o][n],a[t/2]),!r)break}r&&t(o,n)}}function ds(e,t){return Yr(e[0][t])}function us(e,t){return Yr(e[t][0])}function gs(e,t,o,i,n,r){if(null==t)return-1;const s=typeof t;let a,l,c,h,d,u,g=0,p=n-1;for(;p-g>=0;){for(c=Math.floor((g+p)/2),h=c,d=r(e,h),u=typeof d;g<h&&s!==u;)h--,d=r(e,h),u=typeof d;u===s&&void 0!==d?("strict"===o&&d===t?(a=d,l=h):"nextSmaller"===o&&d<=t?(void 0===a||a<d||a===d&&"asc"===i&&l<h||a===d&&"desc"===i&&l>h)&&(a=d,l=h):"nextGreater"===o&&d>=t&&(void 0===a||a>d||a===d&&"asc"===i&&l<h||a===d&&"desc"===i&&l>h)&&(a=d,l=h),"asc"===i&&d>t||"desc"===i&&d<=t?p=h-1:g=c+1):g=c+1}return void 0!==l?l:-1}function ps(e,t,o,i,n,r=!1){if(null==t)return-1;const s=r?(e,t)=>n(e,i-t-1):n;let a,l=-1;for(let n=0;n<i;n++){const c=s(e,n);if(c===t)return r?i-n-1:n;"nextSmaller"===o?(!a&&ms(t,c)>=0||ms(t,c)>=0&&ms(c,a)>0)&&(a=c,l=n):"nextGreater"===o&&(!a&&ms(t,c)<=0||ms(t,c)<=0&&ms(c,a)<0)&&(a=c,l=n)}return r?i-l-1:l}function ms(e,t){let o=Wr.indexOf(typeof e)-Wr.indexOf(typeof t);return 0===o&&("string"==typeof e&&"string"==typeof t?o=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?o=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(o=Number(e)-Number(t))),o}const fs={description:r("Apply a large number format"),args:zr(`\n value (number) ${r("The number.")}\n unit (string, optional) ${r("The formatting unit. Use 'k', 'm', or 'b' to force the unit")}\n `),returns:["NUMBER"],computeFormat:(e,t)=>{const o=Math.abs(Zr(e.value)),i=e.format;if(void 0!==t){switch(null==t?void 0:t.value){case"k":return vo(i,1e3,"k");case"m":return vo(i,1e6,"m");case"b":return vo(i,1e9,"b");default:throw new Error(r("The formatting unit should be 'k', 'm' or 'b'."))}}return o<1e5?vo(i,0,""):o<1e8?vo(i,1e3,"k"):o<1e11?vo(i,1e6,"m"):vo(i,1e9,"b")},compute:function(e){return Zr(e)}};var vs=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:fs});const bs={description:r("Absolute value of a number."),args:zr(`\n value (number) ${r("The number of which to return the absolute value.")}\n `),returns:["NUMBER"],compute:function(e){return Math.abs(Zr(e))},isExported:!0},Cs={description:r("Inverse cosine of a value, in radians."),args:zr(`\n value (number) ${r("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=Zr(e);return Gr((()=>Math.abs(t)<=1),r("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},Ss={description:r("Inverse hyperbolic cosine of a number."),args:zr(`\n value (number) ${r("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=Zr(e);return Gr((()=>t>=1),r("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},Es={description:r("Inverse cotangent of a value."),args:zr(`\n value (number) ${r("The value for which to calculate the inverse cotangent.")}\n `),returns:["NUMBER"],compute:function(e){const t=Zr(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},ws={description:r("Inverse hyperbolic cotangent of a value."),args:zr(`\n value (number) ${r("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=Zr(e);return Gr((()=>Math.abs(t)>1),r("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},ys={description:r("Inverse sine of a value, in radians."),args:zr(`\n value (number) ${r("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=Zr(e);return Gr((()=>Math.abs(t)<=1),r("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},xs={description:r("Inverse hyperbolic sine of a number."),args:zr(`\n value (number) ${r("The value for which to calculate the inverse hyperbolic sine.")}\n `),returns:["NUMBER"],compute:function(e){return Math.asinh(Zr(e))},isExported:!0},Is={description:r("Inverse tangent of a value, in radians."),args:zr(`\n value (number) ${r("The value for which to calculate the inverse tangent.")}\n `),returns:["NUMBER"],compute:function(e){return Math.atan(Zr(e))},isExported:!0},Rs={description:r("Angle from the X axis to a point (x,y), in radians."),args:zr(`\n x (number) ${r("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")}\n y (number) ${r("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 o=Zr(e),i=Zr(t);return Gr((()=>0!==o||0!==i),r("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(i,o)},isExported:!0},Ts={description:r("Inverse hyperbolic tangent of a number."),args:zr(`\n value (number) ${r("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=Zr(e);return Gr((()=>Math.abs(t)<1),r("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},As={description:r("Rounds number up to nearest multiple of factor."),args:zr(`\n value (number) ${r("The value to round up to the nearest integer multiple of factor.")}\n factor (number, default=1) ${r("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 o=Zr(e),i=Zr(t);return Gr((()=>i>=0||o<=0),r("The factor (%s) must be positive when the value (%s) is positive.",i.toString(),o.toString())),i?Math.ceil(o/i)*i:0},isExported:!0},Os={description:r("Rounds number up to nearest multiple of factor."),args:zr(`\n number (number) ${r("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${r("The number to whose multiples number will be rounded. The sign of significance will be ignored.")}\n mode (number, default=0) ${r("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1,o=0){let i=Zr(t);if(0===i)return 0;const n=Zr(e);if(i=Math.abs(i),n>=0)return Math.ceil(n/i)*i;return 0===Zr(o)?-Math.floor(Math.abs(n)/i)*i:-Math.ceil(Math.abs(n)/i)*i},isExported:!0},Ms={description:r("Rounds number up to nearest multiple of factor."),args:zr(`\n number (number) ${r("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${r("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 Os.compute(e,t,0)},isExported:!0},Ns={description:r("Cosine of an angle provided in radians."),args:zr(`\n angle (number) ${r("The angle to find the cosine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cos(Zr(e))},isExported:!0},_s={description:r("Hyperbolic cosine of any real number."),args:zr(`\n value (number) ${r("Any real value to calculate the hyperbolic cosine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cosh(Zr(e))},isExported:!0},Fs={description:r("Cotangent of an angle provided in radians."),args:zr(`\n angle (number) ${r("The angle to find the cotangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=Zr(e);return Gr((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},Ds={description:r("Hyperbolic cotangent of any real number."),args:zr(`\n value (number) ${r("Any real value to calculate the hyperbolic cotangent of.")}\n `),returns:["NUMBER"],compute:function(e){const t=Zr(e);return Gr((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},ks={description:r("Number of empty values."),args:zr(`\n value1 (any, range) ${r("The first value or range in which to count the number of blanks.")}\n value2 (any, range, repeating) ${r("Additional values or ranges in which to count the number of blanks.")}\n `),returns:["NUMBER"],compute:function(...e){return ns(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},$s={description:r("A conditional count across a range."),args:zr(`\n range (range) ${r("The range that is tested against criterion.")}\n criterion (string) ${r("The pattern or test to apply to range.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;return hs(e,((e,o)=>{t+=1})),t},isExported:!0},Ps={description:r("Count values depending on multiple criteria."),args:zr(`\n criteria_range1 (range) ${r("The range to check against criterion1.")}\n criterion1 (string) ${r("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${r("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${r("Additional criteria to check.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;return hs(e,((e,o)=>{t+=1})),t},isExported:!0};function Ls(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const Us={description:r("Counts number of unique values in a range."),args:zr(`\n value1 (any, range) ${r("The first value or range to consider for uniqueness.")}\n value2 (any, range, repeating) ${r("Additional values or ranges to consider for uniqueness.")}\n `),returns:["NUMBER"],compute:function(...e){return ns(e,((e,t)=>Ls(t)?e.add(t):e),new Set).size}},Vs={description:r("Counts number of unique values in a range, filtered by a set of criteria."),args:zr(`\n range (range) ${r("The range of cells from which the number of unique values will be counted.")}\n criteria_range1 (range) ${r("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${r("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${r("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${r("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let o=new Set;return hs(t,((t,i)=>{const n=e[t][i];Ls(n)&&o.add(n)})),o.size}},zs={description:r("Cosecant of an angle provided in radians."),args:zr(`\n angle (number) ${r("The angle to find the cosecant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=Zr(e);return Gr((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},Bs={description:r("Hyperbolic cosecant of any real number."),args:zr(`\n value (number) ${r("Any real value to calculate the hyperbolic cosecant of.")}\n `),returns:["NUMBER"],compute:function(e){const t=Zr(e);return Gr((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},Hs={description:r("Converts from another base to decimal."),args:zr(`\n value (string) ${r("The number to convert.")},\n base (number) ${r("The base to convert the value from.")},\n `),returns:["NUMBER"],compute:function(e,t){let o=Zr(t);o=Math.floor(o),Gr((()=>2<=o&&o<=36),r("The base (%s) must be between 2 and 36 inclusive.",o.toString()));const i=Xr(e);if(""===i)return 0;Gr((()=>!!i.match(/^-?[a-z0-9]+$/i)),r("The value (%s) must be a valid base %s representation.",i,o.toString()));const n=parseInt(i,o);return Gr((()=>!isNaN(n)),r("The value (%s) must be a valid base %s representation.",i,o.toString())),n},isExported:!0},Ws={description:r("Converts an angle value in radians to degrees."),args:zr(`\n angle (number) ${r("The angle to convert from radians to degrees.")}\n `),returns:["NUMBER"],compute:function(e){return 180*Zr(e)/Math.PI},isExported:!0},Gs={description:r("Euler's number, e (~2.718) raised to a power."),args:zr(`\n value (number) ${r("The exponent to raise e.")}\n `),returns:["NUMBER"],compute:function(e){return Math.exp(Zr(e))},isExported:!0},qs={description:r("Rounds number down to nearest multiple of factor."),args:zr(`\n value (number) ${r("The value to round down to the nearest integer multiple of factor.")}\n factor (number, default=1) ${r("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 o=Zr(e),i=Zr(t);return Gr((()=>i>=0||o<=0),r("The factor (%s) must be positive when the value (%s) is positive.",i.toString(),o.toString())),i?Math.floor(o/i)*i:0},isExported:!0},Zs={description:r("Rounds number down to nearest multiple of factor."),args:zr(`\n number (number) ${r("The value to round down to the nearest integer multiple of significance.")}\n significance (number, default=1) ${r("The number to whose multiples number will be rounded. The sign of significance will be ignored.")}\n mode (number, default=0) ${r("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1,o=0){let i=Zr(t);if(0===i)return 0;const n=Zr(e);if(i=Math.abs(i),n>=0)return Math.floor(n/i)*i;return 0===Zr(o)?-Math.ceil(Math.abs(n)/i)*i:-Math.floor(Math.abs(n)/i)*i},isExported:!0},js={description:r("Rounds number down to nearest multiple of factor."),args:zr(`\n number (number) ${r("The value to round down to the nearest integer multiple of significance.")}\n significance (number, default=1) ${r("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 Zs.compute(e,t,0)},isExported:!0},Xs={description:r("Whether the provided value is even."),args:zr(`\n value (number) ${r("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=jr(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},Ys={description:r("Rounds number up to nearest multiple of factor."),args:zr(`\n number (number) ${r("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${r("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 Os.compute(e,t,0)},isExported:!0},Ks={description:r("Whether the provided value is even."),args:zr(`\n value (number) ${r("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=jr(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},Qs={description:r("The logarithm of a number, base e (euler's number)."),args:zr(`\n value (number) ${r("The value for which to calculate the logarithm, base e.")}\n `),returns:["NUMBER"],compute:function(e){const t=Zr(e);return Gr((()=>t>0),r("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},Js={description:r("Modulo (remainder) operator."),args:zr(`\n dividend (number) ${r("The number to be divided to find the remainder.")}\n divisor (number) ${r("The number to divide by.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){const o=Zr(t);Gr((()=>0!==o),r("The divisor must be different from 0."));const i=Zr(e)%o;return i>0&&o<0||i<0&&o>0?i+o:i},isExported:!0},ea={description:r("Rounds a number up to the nearest odd integer."),args:zr(`\n value (number) ${r("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=Zr(e);let o=Math.ceil(Math.abs(t));return o=1&o?o:o+1,t<0?-o:o},isExported:!0},ta={description:r("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},oa={description:r("A number raised to a power."),args:zr(`\n base (number) ${r("The number to raise to the exponent power.")}\n exponent (number) ${r("The exponent to raise base to.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){const o=Zr(e),i=Zr(t);return Gr((()=>o>=0||Number.isInteger(i)),r("The exponent (%s) must be an integer when the base is negative.",i.toString())),Math.pow(o,i)},isExported:!0},ia={description:r("Result of multiplying a series of numbers together."),args:zr(`\n factor1 (number, range<number>) ${r("The first number or range to calculate for the product.")}\n factor2 (number, range<number>, repeating) ${r("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,o=1;for(let i of e)if(Array.isArray(i))for(let e of i)for(let i of e)"number"==typeof i&&(o*=i,t+=1);else null!=i&&(o*=jr(i),t+=1);return 0===t?0:o},isExported:!0},na={description:r("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},ra={description:r("Random integer between two values, inclusive."),args:zr(`\n low (number) ${r("The low end of the random range.")}\n high (number) ${r("The high end of the random range.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){let o=Zr(e);Number.isInteger(o)||(o=Math.ceil(o));let i=Zr(t);return Number.isInteger(i)||(i=Math.floor(i)),Gr((()=>o<=i),r("The high (%s) must be greater than or equal to the low (%s).",i.toString(),o.toString())),o+Math.ceil((i-o+1)*Math.random())-1},isExported:!0},sa={description:r("Rounds a number according to standard rules."),args:zr(`\n value (number) ${r("The value to round to places number of places.")}\n places (number, default=0) ${r("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 o=Zr(e);let i=Zr(t);const n=Math.abs(o);let r;return 0===i?r=Math.round(n):(Number.isInteger(i)||(i=Math.trunc(i)),r=Math.round(n*Math.pow(10,i))/Math.pow(10,i)),o>=0?r:-r},isExported:!0},aa={description:r("Rounds down a number."),args:zr(`\n value (number) ${r("The value to round to places number of places, always rounding down.")}\n places (number, default=0) ${r("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 o=Zr(e);let i=Zr(t);const n=Math.abs(o);let r;return 0===i?r=Math.floor(n):(Number.isInteger(i)||(i=Math.trunc(i)),r=Math.floor(n*Math.pow(10,i))/Math.pow(10,i)),o>=0?r:-r},isExported:!0},la={description:r("Rounds up a number."),args:zr(`\n value (number) ${r("The value to round to places number of places, always rounding up.")}\n places (number, default=0) ${r("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 o=Zr(e);let i=Zr(t);const n=Math.abs(o);let r;return 0===i?r=Math.ceil(n):(Number.isInteger(i)||(i=Math.trunc(i)),r=Math.ceil(n*Math.pow(10,i))/Math.pow(10,i)),o>=0?r:-r},isExported:!0},ca={description:r("Secant of an angle provided in radians."),args:zr(`\n angle (number) ${r("The angle to find the secant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cos(Zr(e))},isExported:!0},ha={description:r("Hyperbolic secant of any real number."),args:zr(`\n value (number) ${r("Any real value to calculate the hyperbolic secant of.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cosh(Zr(e))},isExported:!0},da={description:r("Sine of an angle provided in radians."),args:zr(`\n angle (number) ${r("The angle to find the sine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sin(Zr(e))},isExported:!0},ua={description:r("Hyperbolic sine of any real number."),args:zr(`\n value (number) ${r("Any real value to calculate the hyperbolic sine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sinh(Zr(e))},isExported:!0},ga={description:r("Positive square root of a positive number."),args:zr(`\n value (number) ${r("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=Zr(e);return Gr((()=>t>=0),r("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},pa={description:r("Sum of a series of numbers and/or cells."),args:zr(`\n value1 (number, range<number>) ${r("The first number or range to add together.")}\n value2 (number, range<number>, repeating) ${r("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 rs(e,((e,t)=>e+t),0)},isExported:!0},ma={description:r("A conditional sum across a range."),args:zr(`\n criteria_range (range) ${r("The range which is tested against criterion.")}\n criterion (string) ${r("The pattern or test to apply to range.")}\n sum_range (range, default=criteria_range) ${r("The range to be summed, if different from range.")}\n `),returns:["NUMBER"],compute:function(e,t,o){void 0===o&&(o=e);let i=0;return hs([e,t],((e,t)=>{const n=o[e][t];"number"==typeof n&&(i+=n)})),i},isExported:!0},fa={description:r("Sums a range depending on multiple criteria."),args:zr(`\n sum_range (range) ${r("The range to sum.")}\n criteria_range1 (range) ${r("The range to check against criterion1.")}\n criterion1 (string) ${r("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${r("Additional ranges to check.")}\n criterion2 (string, repeating) ${r("Additional criteria to check.")}\n `),returns:["NUMBER"],compute:function(e,...t){let o=0;return hs(t,((t,i)=>{const n=e[t][i];"number"==typeof n&&(o+=n)})),o},isExported:!0},va={description:r("Tangent of an angle provided in radians."),args:zr(`\n angle (number) ${r("The angle to find the tangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tan(Zr(e))},isExported:!0},ba={description:r("Hyperbolic tangent of any real number."),args:zr(`\n value (number) ${r("Any real value to calculate the hyperbolic tangent of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tanh(Zr(e))},isExported:!0},Ca={description:r("Truncates a number."),args:zr(`\n value (number) ${r("The value to be truncated.")}\n places (number, default=0) ${r("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 o=Zr(e);let i=Zr(t);return 0===i?Math.trunc(o):(Number.isInteger(i)||(i=Math.trunc(i)),Math.trunc(o*Math.pow(10,i))/Math.pow(10,i))},isExported:!0};var Sa=Object.freeze({__proto__:null,ABS:bs,ACOS:Cs,ACOSH:Ss,ACOT:Es,ACOTH:ws,ASIN:ys,ASINH:xs,ATAN:Is,ATAN2:Rs,ATANH:Ts,CEILING:As,CEILING_MATH:Os,CEILING_PRECISE:Ms,COS:Ns,COSH:_s,COT:Fs,COTH:Ds,COUNTBLANK:ks,COUNTIF:$s,COUNTIFS:Ps,COUNTUNIQUE:Us,COUNTUNIQUEIFS:Vs,CSC:zs,CSCH:Bs,DECIMAL:Hs,DEGREES:Ws,EXP:Gs,FLOOR:qs,FLOOR_MATH:Zs,FLOOR_PRECISE:js,ISEVEN:Xs,ISO_CEILING:Ys,ISODD:Ks,LN:Qs,MOD:Js,ODD:ea,PI:ta,POWER:oa,PRODUCT:ia,RAND:na,RANDBETWEEN:ra,ROUND:sa,ROUNDDOWN:aa,ROUNDUP:la,SEC:ca,SECH:ha,SIN:da,SINH:ua,SQRT:ga,SUM:pa,SUMIF:ma,SUMIFS:fa,TAN:va,TANH:ba,TRUNC:Ca});function Ea(e,t,o){let i=[],n=[],s=0,a=0;ts([e],(e=>{i.push(e),s+=1})),ts([t],(e=>{n.push(e),a+=1})),Gr((()=>s===a),r("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",s.toString(),a.toString()));let l=0,c=0,h=0;for(let e=0;e<s;e++){const t=i[e],o=n[e];"number"==typeof t&&"number"==typeof o&&(l+=1,c+=t,h+=o)}Gr((()=>0!==l&&(!o||1!==l)),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const d=c/l,u=h/l;let g=0;for(let e=0;e<s;e++){const t=i[e],o=n[e];"number"==typeof t&&"number"==typeof o&&(g+=(t-d)*(o-u))}return g/(l-(o?1:0))}function wa(e,t,o){let i=0,n=0;const s=o?ss:rs;n=s(e,((e,t)=>(i+=1,e+t)),0),Gr((()=>0!==i&&(!t||1!==i)),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const a=n/i;return s(e,((e,t)=>e+Math.pow(t-a,2)),0)/(i-(t?1:0))}function ya(e,t,o){const i=Zr(t);Gr((()=>o?0<=i&&i<=1:0<i&&i<1),r("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let n,s=[],a=0;return ts(e,(e=>{"number"==typeof e&&(n=gs(s,e,"nextSmaller","asc",s.length,((e,t)=>e[t])),s.splice(n+1,0,e),a++)})),Gr((()=>0!==a),r("[[FUNCTION_NAME]] has no valid input data.")),o||Gr((()=>1/(a+1)<=i&&i<=a/(a+1)),r("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),Xt(s,i,o)}const xa={description:r("Average magnitude of deviations from mean."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;const o=rs(e,((e,o)=>(t+=1,e+o)),0);Gr((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const i=o/t;return rs(e,((e,t)=>e+Math.abs(i-t)),0)/t},isExported:!0},Ia={description:r("Numerical average value in a dataset, ignoring text."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range to consider when calculating the average value.")}\n value2 (number, range<number>, repeating) ${r("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 o=rs(e,((e,o)=>(t+=1,e+o)),0);return Gr((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/t},isExported:!0},Ra=r("[[FUNCTION_NAME]] has mismatched range sizes."),Ta=r("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),Aa={description:r("Weighted average."),args:zr(`\n values (number, range<number>) ${r("Values to average.")}\n weights (number, range<number>) ${r("Weights for each corresponding value.")}\n additional_values (number, range<number>, repeating) ${r("Additional values to average.")}\n additional_weights (number, range<number>, repeating) ${r("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,o,i=0,n=0;Gr((()=>e.length%2==0),r("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let s=0;s<e.length-1;s+=2)if(t=e[s],o=e[s+1],Array.isArray(t)){Gr((()=>Array.isArray(o)),Ra);let e=t.length,s=t[0].length;Gr((()=>e===o.length&&s===o[0].length),Ra);for(let a=0;a<e;a++)for(let e=0;e<s;e++){let s=t[a][e],l=o[a][e],c="number"==typeof s,h="number"==typeof l;Gr((()=>c===h),r("[[FUNCTION_NAME]] expects number values.")),h&&(Gr((()=>l>=0),Ta),i+=s*l,n+=l)}}else o=Zr(o),t=Zr(t),Gr((()=>o>=0),Ta),i+=t*o,n+=o;return Gr((()=>0!==n),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/n}},Oa={description:r("Numerical average value in a dataset."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range to consider when calculating the average value.")}\n value2 (number, range<number>, repeating) ${r("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 o=ss(e,((e,o)=>(t+=1,e+o)),0);return Gr((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/t},isExported:!0},Ma={description:r("Average of values depending on criteria."),args:zr(`\n criteria_range (range) ${r("The range to check against criterion.")}\n criterion (string) ${r("The pattern or test to apply to criteria_range.")}\n average_range (range, default=criteria_range) ${r("The range to average. If not included, criteria_range is used for the average instead.")}\n `),returns:["NUMBER"],compute:function(e,t,o){null==o&&(o=e);let i=0,n=0;return hs([e,t],((t,r)=>{const s=(o||e)[t][r];"number"==typeof s&&(i+=1,n+=s)})),Gr((()=>0!==i),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),n/i},isExported:!0},Na={description:r("Average of values depending on multiple criteria."),args:zr(`\n average_range (range) ${r("The range to average.")}\n criteria_range1 (range) ${r("The range to check against criterion1.")}\n criterion1 (string) ${r("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${r("Additional criteria_range and criterion to check.")}\n criterion2 (string, repeating) ${r("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let o=0,i=0;return hs(t,((t,n)=>{const r=e[t][n];"number"==typeof r&&(o+=1,i+=r)})),Gr((()=>0!==o),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/o},isExported:!0},_a={description:r("The number of numeric values in dataset."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range to consider when counting.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to consider when counting.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;for(let o of e)if(Array.isArray(o))for(let e of o)for(let o of e)"number"==typeof o&&(t+=1);else("string"!=typeof o||qt(o)||be(o))&&(t+=1);return t},isExported:!0},Fa={description:r("The number of values in a dataset."),args:zr(`\n value1 (any, range) ${r("The first value or range to consider when counting.")}\n value2 (any, range, repeating) ${r("Additional values or ranges to consider when counting.")}\n `),returns:["NUMBER"],compute:function(...e){return ns(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},Da={description:r("The covariance of a dataset."),args:zr(`\n data_y (any, range) ${r("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${r("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return Ea(e,t,!1)},isExported:!0},ka={description:r("The covariance of a dataset."),args:zr(`\n data_y (any, range) ${r("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${r("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return Ea(e,t,!1)},isExported:!0},$a={description:r("The sample covariance of a dataset."),args:zr(`\n data_y (any, range) ${r("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${r("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return Ea(e,t,!0)},isExported:!0},Pa={description:r("Nth largest element from a data set."),args:zr(`\n data (any, range) ${r("Array or range containing the dataset to consider.")}\n n (number) ${r("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 o=Math.trunc(Zr(t));let i,n=[],s=0;ts([e],(e=>{"number"==typeof e&&(i=gs(n,e,"nextSmaller","asc",n.length,((e,t)=>e[t])),n.splice(i+1,0,e),s++,s>o&&(n.shift(),s--))}));const a=n.shift();return Gr((()=>void 0!==a),r("[[FUNCTION_NAME]] has no valid input data.")),Gr((()=>s>=o),r("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",o.toString())),a},isExported:!0},La={description:r("Maximum value in a numeric dataset."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range to consider when calculating the maximum value.")}\n value2 (number, range<number>, repeating) ${r("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=rs(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},Ua={description:r("Maximum numeric value in a dataset."),args:zr(`\n value1 (any, range) ${r("The first value or range to consider when calculating the maximum value.")}\n value2 (any, range, repeating) ${r("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=ss(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},Va={description:r("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:zr(`\n range (range) ${r("The range of cells from which the maximum will be determined.")}\n criteria_range1 (range) ${r("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${r("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${r("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${r("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let o=-1/0;return hs(t,((t,i)=>{const n=e[t][i];"number"==typeof n&&(o=o<n?n:o)})),o===-1/0?0:o},isExported:!0},za={description:r("Median value in a numeric dataset."),args:zr(`\n value1 (any, range) ${r("The first value or range to consider when calculating the median value.")}\n value2 (any, range, repeating) ${r("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 os(e,(e=>{t.push(e)})),ya(t,.5,!0)},isExported:!0},Ba={description:r("Minimum value in a numeric dataset."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range to consider when calculating the minimum value.")}\n value2 (number, range<number>, repeating) ${r("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=rs(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},Ha={description:r("Minimum numeric value in a dataset."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range to consider when calculating the minimum value.")}\n value2 (number, range<number>, repeating) ${r("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=ss(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},Wa={description:r("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:zr(`\n range (range) ${r("The range of cells from which the minimum will be determined.")}\n criteria_range1 (range) ${r("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${r("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${r("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${r("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let o=1/0;return hs(t,((t,i)=>{const n=e[t][i];"number"==typeof n&&(o=o>n?n:o)})),o===1/0?0:o},isExported:!0},Ga={description:r("Value at a given percentile of a dataset."),args:zr(`\n data (any, range) ${r("The array or range containing the dataset to consider.")}\n percentile (number) ${r("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 Za.compute(e,t)},isExported:!0},qa={description:r("Value at a given percentile of a dataset exclusive of 0 and 1."),args:zr(`\n data (any, range) ${r("The array or range containing the dataset to consider.")}\n percentile (number) ${r("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 ya([e],t,!1)},isExported:!0},Za={description:r("Value at a given percentile of a dataset."),args:zr(`\n data (any, range) ${r("The array or range containing the dataset to consider.")}\n percentile (number) ${r("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 ya([e],t,!0)},isExported:!0},ja={description:r("Value nearest to a specific quartile of a dataset."),args:zr(`\n data (any, range) ${r("The array or range containing the dataset to consider.")}\n quartile_number (number) ${r("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 Ya.compute(e,t)},isExported:!0},Xa={description:r("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:zr(`\n data (any, range) ${r("The array or range containing the dataset to consider.")}\n quartile_number (number) ${r("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 ya([e],.25*Math.trunc(Zr(t)),!1)},isExported:!0},Ya={description:r("Value nearest to a specific quartile of a dataset."),args:zr(`\n data (any, range) ${r("The array or range containing the dataset to consider.")}\n quartile_number (number) ${r("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 ya([e],.25*Math.trunc(Zr(t)),!0)},isExported:!0},Ka={description:r("Nth smallest element in a data set."),args:zr(`\n data (any, range) ${r("The array or range containing the dataset to consider.")}\n n (number) ${r("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 o=Math.trunc(Zr(t));let i,n=[],s=0;ts([e],(e=>{"number"==typeof e&&(i=gs(n,e,"nextSmaller","asc",n.length,((e,t)=>e[t])),n.splice(i+1,0,e),s++,s>o&&(n.pop(),s--))}));const a=n.pop();return Gr((()=>void 0!==a),r("[[FUNCTION_NAME]] has no valid input data.")),Gr((()=>s>=o),r("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",o.toString())),a},isExported:!0},Qa={description:r("Standard deviation."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(nl.compute(...e))},isExported:!0},Ja={description:r("Standard deviation of entire population."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(rl.compute(...e))},isExported:!0},el={description:r("Standard deviation."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(sl.compute(...e))},isExported:!0},tl={description:r("Standard deviation of sample (text as 0)."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(al.compute(...e))},isExported:!0},ol={description:r("Standard deviation of entire population."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(ll.compute(...e))},isExported:!0},il={description:r("Standard deviation of entire population (text as 0)."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(cl.compute(...e))},isExported:!0},nl={description:r("Variance."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return wa(e,!0,!1)},isExported:!0},rl={description:r("Variance of entire population."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return wa(e,!1,!1)},isExported:!0},sl={description:r("Variance."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return wa(e,!0,!1)},isExported:!0},al={description:r("Variance of sample (text as 0)."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return wa(e,!0,!0)},isExported:!0},ll={description:r("Variance of entire population."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return wa(e,!1,!1)},isExported:!0},cl={description:r("Variance of entire population (text as 0)."),args:zr(`\n value1 (number, range<number>) ${r("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return wa(e,!1,!0)},isExported:!0};var hl=Object.freeze({__proto__:null,AVEDEV:xa,AVERAGE:Ia,AVERAGE_WEIGHTED:Aa,AVERAGEA:Oa,AVERAGEIF:Ma,AVERAGEIFS:Na,COUNT:_a,COUNTA:Fa,COVAR:Da,COVARIANCE_P:ka,COVARIANCE_S:$a,LARGE:Pa,MAX:La,MAXA:Ua,MAXIFS:Va,MEDIAN:za,MIN:Ba,MINA:Ha,MINIFS:Wa,PERCENTILE:Ga,PERCENTILE_EXC:qa,PERCENTILE_INC:Za,QUARTILE:ja,QUARTILE_EXC:Xa,QUARTILE_INC:Ya,SMALL:Ka,STDEV:Qa,STDEV_P:Ja,STDEV_S:el,STDEVA:tl,STDEVP:ol,STDEVPA:il,VAR:nl,VAR_P:rl,VAR_S:sl,VARA:al,VARP:ll,VARPA:cl});function dl(e,t,o){var i;const n=new Map,s=e.length;for(let t=s-1;t>=0;t--)n.set(Xr(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(r("The field must be a number or a string"));let a;if("number"==typeof t){if(a=Math.trunc(t)-1,a<0||s-1<a)throw new Error(r("The field (%s) must be one of %s or must be a number between 1 and %s inclusive.",t.toString(),s.toString()))}else{const e=Xr(t).toUpperCase();if(a=null!==(i=n.get(e))&&void 0!==i?i:-1,-1===a)throw new Error(r("The field (%s) must be one of %s.",Xr(t),[...n.keys()].toString()))}const l=o[0].length;if(l<2)throw new Error(r("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const h=e[0].length;for(let t=1;t<l;t++){let i=[],r=!0;for(let s=0;s<o.length;s++){const a=Xr(o[s][0]).toUpperCase(),l=n.get(a),c=o[s][t];if(void 0!==c){if(void 0===l){r=!1;break}i.push([e[l].slice(1,h)]),i.push(c)}}if(r){if(!(i.length>0)){c=new Set(Array(h-1).keys());break}hs(i,((e,t)=>{c.add(t)}),!0)}}const d=e[a];return[...c].map((e=>d[e+1]))}const ul=zr(`\n database (range) ${r("The array or range containing the data to consider, structured in such a way that the first row contains the labels for each column's values.")}\n field (any) ${r("Indicates which column in database contains the values to be extracted and operated on.")}\n criteria (range) ${r("An array or range containing zero or more criteria to filter the database values by before operating.")}\n`),gl={description:r("Average of a set of values from a table-like range."),args:ul,returns:["NUMBER"],compute:function(e,t,o){const i=dl(e,t,o);return Ia.compute([i])},isExported:!0},pl={description:r("Counts values from a table-like range."),args:ul,returns:["NUMBER"],compute:function(e,t,o){const i=dl(e,t,o);return _a.compute([i])},isExported:!0},ml={description:r("Counts values and text from a table-like range."),args:ul,returns:["NUMBER"],compute:function(e,t,o){const i=dl(e,t,o);return Fa.compute([i])},isExported:!0},fl={description:r("Single value from a table-like range."),args:ul,returns:["NUMBER"],compute:function(e,t,o){const i=dl(e,t,o);return Gr((()=>1===i.length),r("More than one match found in DGET evaluation.")),i[0]},isExported:!0},vl={description:r("Maximum of values from a table-like range."),args:ul,returns:["NUMBER"],compute:function(e,t,o){const i=dl(e,t,o);return La.compute([i])},isExported:!0},bl={description:r("Minimum of values from a table-like range."),args:ul,returns:["NUMBER"],compute:function(e,t,o){const i=dl(e,t,o);return Ba.compute([i])},isExported:!0},Cl={description:r("Product of values from a table-like range."),args:ul,returns:["NUMBER"],compute:function(e,t,o){const i=dl(e,t,o);return ia.compute([i])},isExported:!0},Sl={description:r("Standard deviation of population sample from table."),args:ul,returns:["NUMBER"],compute:function(e,t,o){const i=dl(e,t,o);return Qa.compute([i])},isExported:!0},El={description:r("Standard deviation of entire population from table."),args:ul,returns:["NUMBER"],compute:function(e,t,o){const i=dl(e,t,o);return ol.compute([i])},isExported:!0},wl={description:r("Sum of values from a table-like range."),args:ul,returns:["NUMBER"],compute:function(e,t,o){const i=dl(e,t,o);return pa.compute([i])},isExported:!0},yl={description:r("Variance of population sample from table-like range."),args:ul,returns:["NUMBER"],compute:function(e,t,o){const i=dl(e,t,o);return nl.compute([i])},isExported:!0},xl={description:r("Variance of a population from a table-like range."),args:ul,returns:["NUMBER"],compute:function(e,t,o){const i=dl(e,t,o);return ll.compute([i])},isExported:!0};var Il=Object.freeze({__proto__:null,DAVERAGE:gl,DCOUNT:pl,DCOUNTA:ml,DGET:fl,DMAX:vl,DMIN:bl,DPRODUCT:Cl,DSTDEV:Sl,DSTDEVP:El,DSUM:wl,DVAR:yl,DVARP:xl});const Rl={description:r("Converts year/month/day into a date."),args:zr(`\n year (number) ${r("The year component of the date.")}\n month (number) ${r("The month component of the date.")}\n day (number) ${r("The day component of the date.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o){let i=Math.trunc(Zr(e));const n=Math.trunc(Zr(t)),s=Math.trunc(Zr(o));Gr((()=>0<=i&&i<=9999),r("The year (%s) must be between 0 and 9999 inclusive.",i.toString())),i<1900&&(i+=1900);const a=Ee(new Date(i,n-1,s));return Gr((()=>a>=0),r("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),a},isExported:!0},Tl={description:r("Converts a date string to a date value."),args:zr(`\n date_string (string) ${r("The string representing the date.")}\n `),returns:["NUMBER"],compute:function(e){const t=Xr(e),o=be(t);return Gr((()=>null!==o),r("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(o.value)},isExported:!0},Al={description:r("Day of the month that a specific date falls on."),args:zr(`\n date (string) ${r("The date from which to extract the day.")}\n `),returns:["NUMBER"],compute:function(e){return Jr(e).getDate()},isExported:!0},Ol={description:r("Number of days between two dates."),args:zr(`\n end_date (date) ${r("The end of the date range.")}\n start_date (date) ${r("The start of the date range.")}\n `),returns:["NUMBER"],compute:function(e,t){const o=Jr(e),i=Jr(t),n=o.getTime()-i.getTime();return Math.round(n/de)},isExported:!0},Ml={description:r("Number of days between two dates on a 360-day year (months of 30 days)."),args:zr(`\n start_date (date) ${r("The start date to consider in the calculation.")}\n end_date (date) ${r("The end date to consider in the calculation.")}\n method (number, default=0) ${r("An indicator of what day count method to use. (0) US NASD method (1) European method")}\n `),returns:["NUMBER"],compute:function(e,t,o=0){const i=Zr(e),n=Zr(t),r=Qr(o)?4:0,s=Yl.compute(e,t,r);return Math.sign(n-i)*Math.round(360*s)},isExported:!0},Nl={description:r("Date a number of months before/after another date."),args:zr(`\n start_date (date) ${r("The date from which to calculate the result.")}\n months (number) ${r("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 Ee(xe(Jr(e),Math.trunc(Zr(t)),!1))},isExported:!0},_l={description:r("Last day of a month before or after a date."),args:zr(`\n start_date (date) ${r("The date from which to calculate the result.")}\n months (number) ${r("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 o=Jr(e),i=Math.trunc(Zr(t)),n=o.getFullYear(),r=o.getMonth();return Ee(new Date(n,r+i+1,0))},isExported:!0},Fl={description:r("Hour component of a specific time."),args:zr(`\n time (date) ${r("The time from which to calculate the hour component.")}\n `),returns:["NUMBER"],compute:function(e){return Jr(e).getHours()},isExported:!0},Dl={description:r("ISO week number of the year."),args:zr(`\n date (date) ${r("The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n `),returns:["NUMBER"],compute:function(e){const t=Jr(e),o=t.getFullYear();let i=1;for(;4!==new Date(o,0,i).getDay();)i+=1;const n=new Date(o,0,i-3);let r=31;for(;4!==new Date(o,11,r).getDay();)r-=1;const s=new Date(o,11,r+3);let a,l;switch(a=n.getTime()<=t.getTime()?t.getTime()<=s.getTime()?0:1:-1,a){case 0:l=n;break;case 1:l=new Date(o,11,r+3+1);break;case-1:let e=1;for(;4!==new Date(o-1,0,e).getDay();)e+=1;l=new Date(o-1,0,e-3)}const c=(t.getTime()-l.getTime())/de;return Math.floor(c/7)+1},isExported:!0},kl={description:r("Minute component of a specific time."),args:zr(`\n time (date) ${r("The time from which to calculate the minute component.")}\n `),returns:["NUMBER"],compute:function(e){return Jr(e).getMinutes()},isExported:!0},$l={description:r("Month of the year a specific date falls in"),args:zr(`\n date (date) ${r("The date from which to extract the month.")}\n `),returns:["NUMBER"],compute:function(e){return Jr(e).getMonth()+1},isExported:!0},Pl={description:r("Net working days between two provided days."),args:zr(`\n start_date (date) ${r("The start date of the period from which to calculate the number of net working days.")}\n end_date (date) ${r("The end date of the period from which to calculate the number of net working days.")}\n holidays (date, range<date>, optional) ${r("A range or array constant containing the date serial numbers to consider holidays.")}\n `),returns:["NUMBER"],compute:function(e,t,o){return Ul.compute(e,t,1,o)},isExported:!0};function Ll(e){if("string"==typeof e){Gr((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),r('When weekend is a string (%s) it must be composed of "0" or "1".',e));let t=[];for(let o=0;o<7;o++)"1"===e[o]&&t.push((o+1)%7);return t}if("number"==typeof e)return Gr((()=>1<=e&&e<=7||11<=e&&e<=17),r("The weekend (%s) must be a string or a number in the range 1-7 or 11-17.",e.toString())),e<=7?[e-2==-1?6:e-2,e-1]:[e-11];throw Error(r("The weekend must be a number or a string."))}const Ul={description:r("Net working days between two dates (specifying weekends)."),args:zr(`\n start_date (date) ${r("The start date of the period from which to calculate the number of net working days.")}\n end_date (date) ${r("The end date of the period from which to calculate the number of net working days.")}\n weekend (any, default=1) ${r("A number or string representing which days of the week are considered weekends.")}\n holidays (date, range<date>, optional) ${r("A range or array constant containing the dates to consider as holidays.")}\n `),returns:["NUMBER"],compute:function(e,t,o=1,i){const n=Jr(e),r=Jr(t),s=Ll(o);let a=new Set;void 0!==i&&ts([i],(e=>{const t=Jr(e);a.add(t.getTime())}));const l=n.getTime()>r.getTime(),c=new Date((l?n:r).getTime());let h=new Date((l?r:n).getTime());const d=c.getTime();let u=h.getTime(),g=0;for(;u<=d;)s.includes(h.getDay())||a.has(u)||(g+=1),h.setDate(h.getDate()+1),u=h.getTime();return l?-g:g},isExported:!0},Vl={description:r("Current date and time as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy hh:mm:ss",compute:function(){let e=new Date;e.setMilliseconds(0);const t=e.getTime()-he.getTime(),o=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/de)+o},isExported:!0},zl={description:r("Minute component of a specific time."),args:zr(`\n time (date) ${r("The time from which to calculate the second component.")}\n `),returns:["NUMBER"],compute:function(e){return Jr(e).getSeconds()},isExported:!0},Bl={description:r("Converts hour/minute/second into a time."),args:zr(`\n hour (number) ${r("The hour component of the time.")}\n minute (number) ${r("The minute component of the time.")}\n second (number) ${r("The second component of the time.")}\n `),returns:["DATE"],computeFormat:()=>"hh:mm:ss a",compute:function(e,t,o){let i=Math.trunc(Zr(e)),n=Math.trunc(Zr(t)),s=Math.trunc(Zr(o));return n+=Math.floor(s/60),s=s%60+(s<0?60:0),i+=Math.floor(n/60),n=n%60+(n<0?60:0),i%=24,Gr((()=>i>=0),r("The function [[FUNCTION_NAME]] result cannot be negative")),i/24+n/1440+s/86400},isExported:!0},Hl={description:r("Converts a time string into its serial number representation."),args:zr(`\n time_string (string) ${r("The string that holds the time representation.")}\n `),returns:["NUMBER"],compute:function(e){const t=Xr(e),o=be(t);Gr((()=>null!==o),r("The time_string (%s) cannot be parsed to date/time.",t));const i=o.value-Math.trunc(o.value);return i<0?1+i:i},isExported:!0},Wl={description:r("Current date as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(){const e=new Date;return Ee(new Date(e.getFullYear(),e.getMonth(),e.getDate()))},isExported:!0},Gl={description:r("Day of the week of the date provided (as number)."),args:zr(`\n date (date) ${r("The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n type (number, default=1) ${r("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 o=Jr(e),i=Math.round(Zr(t)),n=o.getDay();return Gr((()=>[1,2,3].includes(i)),r("The type (%s) must be 1, 2 or 3.",i.toString())),1===i?n+1:2===i?0===n?7:n:0===n?6:n-1},isExported:!0},ql={description:r("Week number of the year."),args:zr(`\n date (date) ${r("The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n type (number, default=1) ${r("A number representing the day that a week starts on. Sunday = 1.")}\n `),returns:["NUMBER"],compute:function(e,t=1){const o=Jr(e),i=Math.round(Zr(t));if(Gr((()=>1===i||2===i||11<=i&&i<=17||21===i),r("The type (%s) is out of range.",i.toString())),21===i)return Dl.compute(e);let n;n=1===i||2===i?i-1:i-10==7?0:i-10;const s=o.getFullYear();let a=1,l=new Date(s,0,a);for(;l.getDay()!==n;)a+=1,l=new Date(s,0,a);const c=(o.getTime()-l.getTime())/de;return c<0?1:Math.floor(c/7)+(1===a?1:2)},isExported:!0},Zl={description:r("Date after a number of workdays."),args:zr(`\n start_date (date) ${r("The date from which to begin counting.")}\n num_days (number) ${r("The number of working days to advance from start_date. If negative, counts backwards.")}\n holidays (date, range<date>, optional) ${r("A range or array constant containing the dates to consider holidays.")}\n `),returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o){return jl.compute(e,t,1,o)},isExported:!0},jl={description:r("Date after a number of workdays (specifying weekends)."),args:zr(`\n start_date (date) ${r("The date from which to begin counting.")}\n num_days (number) ${r("The number of working days to advance from start_date. If negative, counts backwards.")}\n weekend (any, default=1) ${r("A number or string representing which days of the week are considered weekends.")}\n holidays (date, range<date>, optional) ${r("A range or array constant containing the dates to consider holidays.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o=1,i){let n=Jr(e),s=Math.trunc(Zr(t));"string"==typeof o&&Gr((()=>"1111111"!==o),r("The weekend (%s) must be different from '1111111'.",o));const a=Ll(o);let l=new Set;void 0!==i&&ts([i],(e=>{const t=Jr(e);l.add(t.getTime())}));let c=new Date(n.getTime()),h=c.getTime();const d=Math.sign(s);let u=Math.abs(s);for(;u>0;)c.setDate(c.getDate()+d),h=c.getTime(),a.includes(c.getDay())||l.has(h)||(u-=1);const g=h-he.getTime();return Math.round(g/de)},isExported:!0},Xl={description:r("Year specified by a given date."),args:zr(`\n date (date) ${r("The date from which to extract the year.")}\n `),returns:["NUMBER"],compute:function(e){return Jr(e).getFullYear()},isExported:!0},Yl={description:r("Exact number of years between two dates."),args:zr(`\n start_date (date) ${r("The start date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n end_date (date) ${r("The end date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n day_count_convention (number, default=0) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o=0){let i=Math.trunc(Zr(e)),n=Math.trunc(Zr(t));const s=Math.trunc(Zr(o));return Gr((()=>i>=0),r("The start_date (%s) must be positive or null.",i.toString())),Gr((()=>n>=0),r("The end_date (%s) must be positive or null.",n.toString())),Gr((()=>0<=s&&s<=4),r("The day_count_convention (%s) must be between 0 and 4 inclusive.",s.toString())),Re(i,n,s)}},Kl={description:r("First day of the month preceding a date."),args:zr(`\n date (date) ${r("The date from which to calculate the result.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Jr(e),o=t.getFullYear(),i=t.getMonth();return Ee(new Date(o,i,1))}},Ql={description:r("Last day of the month following a date."),args:zr(`\n date (date) ${r("The date from which to calculate the result.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){return _l.compute(e,0)}},Jl={description:r("Quarter of the year a specific date falls in"),args:zr(`\n date (date) ${r("The date from which to extract the quarter.")}\n `),returns:["NUMBER"],compute:function(e){return Math.ceil((Jr(e).getMonth()+1)/3)}},ec={description:r("First day of the quarter of the year a specific date falls in."),args:zr(`\n date (date) ${r("The date from which to calculate the start of quarter.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Jl.compute(e),o=Xl.compute(e);return Ee(new Date(o,3*(t-1),1))}},tc={description:r("Last day of the quarter of the year a specific date falls in."),args:zr(`\n date (date) ${r("The date from which to calculate the end of quarter.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Jl.compute(e),o=Xl.compute(e);return Ee(new Date(o,3*t,0))}},oc={description:r("First day of the year a specific date falls in."),args:zr(`\n date (date) ${r("The date from which to calculate the start of the year.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Xl.compute(e);return Ee(new Date(t,0,1))}},ic={description:r("Last day of the year a specific date falls in."),args:zr(`\n date (date) ${r("The date from which to calculate the end of the year.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Xl.compute(e);return Ee(new Date(t+1,0,0))}};var nc=Object.freeze({__proto__:null,DATE:Rl,DATEVALUE:Tl,DAY:Al,DAYS:Ol,DAYS360:Ml,EDATE:Nl,EOMONTH:_l,HOUR:Fl,ISOWEEKNUM:Dl,MINUTE:kl,MONTH:$l,NETWORKDAYS:Pl,NETWORKDAYS_INTL:Ul,NOW:Vl,SECOND:zl,TIME:Bl,TIMEVALUE:Hl,TODAY:Wl,WEEKDAY:Gl,WEEKNUM:ql,WORKDAY:Zl,WORKDAY_INTL:jl,YEAR:Xl,YEARFRAC:Yl,MONTH_START:Kl,MONTH_END:Ql,QUARTER:Jl,QUARTER_START:ec,QUARTER_END:tc,YEAR_START:oc,YEAR_END:ic});const rc={description:r("Compare two numeric values, returning 1 if they're equal."),args:zr(`\n number1 (number) ${r("The first number to compare.")}\n number2 (number, default=0) ${r("The second number to compare.")}\n `),returns:["NUMBER"],compute:function(e,t=0){return Zr(e)===Zr(t)?1:0},isExported:!0};var sc=Object.freeze({__proto__:null,DELTA:rc});function ac(e,t){Gr((()=>e<t),r("The maturity (%s) must be strictly greater than the settlement (%s).",t.toString(),e.toString()))}function lc(e,t){Gr((()=>t<e),r("The settlement date (%s) must be strictly greater than the issue date (%s).",e.toString(),t.toString()))}function cc(e){Gr((()=>[1,2,4].includes(e)),r("The frequency (%s) must be one of %s",e.toString(),[1,2,4].toString()))}function hc(e){Gr((()=>0<=e&&e<=4),r("The day_count_convention (%s) must be between 0 and 4 inclusive.",e.toString()))}function dc(e){Gr((()=>e>0),r("The redemption (%s) must be strictly positive.",e.toString()))}function uc(e){Gr((()=>e>0),r("The price (%s) must be strictly positive.",e.toString()))}function gc(e){Gr((()=>e>0),r("The number_of_periods (%s) must be greater than 0.",e.toString()))}function pc(e){Gr((()=>e>0),r("The rate (%s) must be strictly positive.",e.toString()))}function mc(e){Gr((()=>e>0),r("The life (%s) must be strictly positive.",e.toString()))}function fc(e){Gr((()=>e>=0),r("The cost (%s) must be positive or null.",e.toString()))}function vc(e){Gr((()=>e>0),r("The period (%s) must be strictly positive.",e.toString()))}function bc(e){Gr((()=>e>=0),r("The salvage (%s) must be positive or null.",e.toString()))}function Cc(e){Gr((()=>e>0),r("The present value (%s) must be strictly positive.",e.toString()))}function Sc(e,t){Gr((()=>e<=t),r("The period (%s) must be less than or equal life (%s).",e.toString(),t.toString()))}function Ec(e){Gr((()=>e>0),r("The investment (%s) must be strictly positive.",e.toString()))}function wc(e){Gr((()=>e>0),r("The discount (%s) must be strictly positive.",e.toString()))}function yc(e){Gr((()=>e<1),r("The discount (%s) must be smaller than 1.",e.toString()))}function xc(e){Gr((()=>e>0),r("The depreciation factor (%s) must be strictly positive.",e.toString()))}function Ic(e,t){const o=Jr(e),i=Jr(t),n=new Date(o);n.setFullYear(o.getFullYear()+1),Gr((()=>i.getTime()<=n.getTime()),r("The settlement date (%s) must at most one year after the maturity date (%s).",e.toString(),t.toString()))}function Rc(e,t,o){gc(o),Gr((()=>e>0),r("The first_period (%s) must be strictly positive.",e.toString())),Gr((()=>t>0),r("The last_period (%s) must be strictly positive.",t.toString())),Gr((()=>e<=t),r("The first_period (%s) must be smaller or equal to the last_period (%s).",e.toString(),t.toString())),Gr((()=>t<=o),r("The last_period (%s) must be smaller or equal to the number_of_periods (%s).",e.toString(),o.toString()))}function Tc(e){Gr((()=>e>-1),r("The rate_guess (%s) must be strictly greater than -1.",e.toString()))}function Ac(e,t){Gr((()=>e.length===t.length&&e[0].length===t[0].length),r("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."))}function Oc(e){Gr((()=>e.every((t=>t>=e[0]))),r("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e[0].toString()))}const Mc=zr(`\nsettlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\nmaturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\nfrequency (number) ${r("The number of interest or coupon payments per year (1, 2, or 4).")}\nday_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n`);function Nc(e,t,o,i,n=1e-10,s){let a,l,c,h,d=o,u=!1,g=0;do{c=e(d),isNaN(c)?(Gr((()=>g<i&&void 0!==s),r("Function [[FUNCTION_NAME]] didn't find any result.")),g++,d=s(h),h=d):(a=d-c/t(d),l=Math.abs(a-d),d=a,u=l<n||Math.abs(c)<n,Gr((()=>g<i),r("Function [[FUNCTION_NAME]] didn't find any result.")),g++)}while(!u);return d}const _c={description:r("Accrued interest of security paying at maturity."),args:zr(`\n issue (date) ${r("The date the security was initially issued.")}\n maturity (date) ${r("The maturity date of the security.")}\n rate (number) ${r("The annualized rate of interest.")}\n redemption (number) ${r("The redemption amount per 100 face value, or par.")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n=0){n=n||0;const r=Math.trunc(Zr(e)),s=Math.trunc(Zr(t)),a=Zr(i),l=Zr(o),c=Math.trunc(Zr(n));lc(s,r),hc(c),dc(a),pc(l);return a*l*Yl.compute(r,s,n)},isExported:!0},Fc={description:r("Depreciation for an accounting period."),args:zr(`\n cost (number) ${r("The initial cost of the asset.")}\n purchase_date (date) ${r("The date the asset was purchased.")}\n first_period_end (date) ${r("The date the first period ended.")}\n salvage (number) ${r("The value of the asset at the end of depreciation.")}\n period (number) ${r("The single period within life for which to calculate depreciation.")}\n rate (number) ${r("The deprecation rate.")}\n day_count_convention (number, optional) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,s,a=0){a=a||0;const l=Zr(e),c=Math.trunc(Zr(t)),h=Math.trunc(Zr(o)),d=Zr(i),u=Zr(n),g=Zr(s),p=Math.trunc(Zr(a));!function(e){Gr((()=>e>0),r("The cost (%s) must be strictly positive.",e.toString()))}(l),bc(d),function(e,t){Gr((()=>e<=t),r("The salvage (%s) must be smaller or equal than the cost (%s).",e.toString(),t.toString()))}(d,l),function(e){Gr((()=>e>=0),r("The period (%s) must be positive or null.",e.toString()))}(u),pc(g),hc(p),Gr((()=>c<=h),r("The purchase_date (%s) must be before the first_period_end (%s).",c.toString(),h.toString()));const m=u<1&&u>0?1:Math.trunc(u),f=l*g,v=Yl.compute(c,h,p),b=c===h?f:f*v,C=l-b-f*m;return C>=d?0===m?b:f:d-C<f?f-(d-C):0},isExported:!0},Dc={description:r("Days in coupon period containing settlement date."),args:Mc,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const n=Math.trunc(Zr(e)),r=Math.trunc(Zr(t)),s=Math.trunc(Zr(o)),a=Math.trunc(Zr(i));if(ac(n,r),cc(s),hc(a),1===a){const n=Uc.compute(e,t,o,i);return Pc.compute(e,t,o,i)-n}return(3===a?365:360)/s},isExported:!0},kc={description:r("Days from settlement until next coupon."),args:Mc,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const n=Math.trunc(Zr(e)),r=Math.trunc(Zr(t)),s=Math.trunc(Zr(o)),a=Math.trunc(Zr(i));ac(n,r),cc(s),hc(a);const l=Uc.compute(n,r,o,i);if([1,2,3].includes(a))return n-l;if(4===a){const e=Re(l,n,a);return Math.round(360*e)}const c=Jr(n),h=Jr(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&&ye(h)&&ye(c)&&(f=30),31!==f||30!==m&&31!==m||(f=30),2===g&&ye(h)&&(m=30),31===m&&(m=30),360*(u-d)+30*(p-g)+(f-m)},isExported:!0},$c={description:r("Days from settlement until next coupon."),args:Mc,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const n=Math.trunc(Zr(e)),r=Math.trunc(Zr(t)),s=Math.trunc(Zr(o)),a=Math.trunc(Zr(i));ac(n,r),cc(s),hc(a);const l=Pc.compute(n,r,o,i);if([1,2,3].includes(a))return l-n;if(4===a){const e=Re(n,l,a);return Math.round(360*e)}const c=kc.compute(e,t,o,a);return Dc.compute(e,t,o,a)-c},isExported:!0},Pc={description:r("Next coupon date after the settlement date."),args:Mc,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o,i=0){i=i||0;const n=Math.trunc(Zr(e)),r=Math.trunc(Zr(t)),s=Math.trunc(Zr(o)),a=Math.trunc(Zr(i));ac(n,r),cc(s),hc(a);const l=12/s,c=Lc.compute(e,t,o,i);return Ee(xe(Jr(r),-(c-1)*l,!0))},isExported:!0},Lc={description:r("Number of coupons between settlement and maturity."),args:Mc,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const n=Math.trunc(Zr(e)),r=Math.trunc(Zr(t)),s=Math.trunc(Zr(o)),a=Math.trunc(Zr(i));ac(n,r),cc(s),hc(a);let l=1,c=r;const h=12/s;for(;c>n;)c=Ee(xe(Jr(c),-h,!1)),l++;return l-1},isExported:!0},Uc={description:r("Last coupon date prior to or on the settlement date."),args:Mc,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o,i=0){i=i||0;const n=Math.trunc(Zr(e)),r=Math.trunc(Zr(t)),s=Math.trunc(Zr(o)),a=Math.trunc(Zr(i));ac(n,r),cc(s),hc(a);const l=12/s,c=Lc.compute(e,t,o,i);return Ee(xe(Jr(r),-c*l,!0))},isExported:!0},Vc={description:r("Cumulative interest paid over a set of periods."),args:zr(`\n rate (number) ${r("The interest rate.")}\n number_of_periods (number) ${r("The number of payments to be made.")}\n present_value (number) ${r("The current value of the annuity.")}\n first_period (number) ${r("The number of the payment period to begin the cumulative calculation.")}\n last_period (number) ${r("The number of the payment period to end the cumulative calculation.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,r=0){const s=Zr(i),a=Zr(n),l=Zr(e),c=Zr(o),h=Zr(t);Rc(s,a,h),pc(l),Cc(c);let d=0;for(let t=s;t<=a;t++){d+=Qc.compute(e,t,h,o,0,r)}return d},isExported:!0},zc={description:r("Cumulative principal paid over a set of periods."),args:zr(`\n rate (number) ${r("The interest rate.")}\n number_of_periods (number) ${r("The number of payments to be made.")}\n present_value (number) ${r("The current value of the annuity.")}\n first_period (number) ${r("The number of the payment period to begin the cumulative calculation.")}\n last_period (number) ${r("The number of the payment period to end the cumulative calculation.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,r=0){const s=Zr(i),a=Zr(n),l=Zr(e),c=Zr(o),h=Zr(t);Rc(s,a,h),pc(l),Cc(c);let d=0;for(let t=s;t<=a;t++){d+=lh.compute(e,t,h,o,0,r)}return d},isExported:!0},Bc={description:r("Depreciation via declining balance method."),args:zr(`\n cost (number) ${r("The initial cost of the asset.")}\n salvage (number) ${r("The value of the asset at the end of depreciation.")}\n life (number) ${r("The number of periods over which the asset is depreciated.")}\n period (number) ${r("The single period within life for which to calculate depreciation.")}\n month (number, optional) ${r("The number of months in the first year of depreciation.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,...n){const s=Zr(e),a=Zr(t),l=Zr(o),c=Math.trunc(Zr(i)),h=n.length?Math.trunc(Zr(n[0])):12,d=l+(12===h?0:1);fc(s),bc(a),vc(c),mc(l),Gr((()=>1<=h&&h<=12),r("The month (%s) must be between 1 and 12 inclusive.",h.toString())),Gr((()=>c<=d),r("The period (%s) must be less than or equal to %s.",c.toString(),d.toString()));const u=h/12;let g=1-Math.pow(a/s,1/l);g=Math.round(1e3*g)/1e3;let p=s,m=s*(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},Hc={description:r("Depreciation via double-declining balance method."),args:zr(`\n cost (number) ${r("The initial cost of the asset.")}\n salvage (number) ${r("The value of the asset at the end of depreciation.")}\n life (number) ${r("The number of periods over which the asset is depreciated.")}\n period (number) ${r("The single period within life for which to calculate depreciation.")}\n factor (number, default=2) ${r("The factor by which depreciation decreases.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,n=2){n=n||0;const r=Zr(e),s=Zr(t),a=Zr(o),l=Zr(i),c=Zr(n);if(fc(r),bc(s),vc(l),mc(a),Sc(l,a),xc(c),0===r||s>=r)return 0;const h=c/a;if(h>1)return 1===i?r-s:0;if(l<=1)return r*h;const d=r*Math.pow(1-h,l-1),u=r*Math.pow(1-h,l),g=u<s?d-s:d-u;return Math.max(g,0)},isExported:!0},Wc={description:r("Discount rate of a security based on price."),args:zr(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n price (number) ${r("The price at which the security is bought per 100 face value.")}\n redemption (number) ${r("The redemption amount per 100 face value, or par.")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n=0){n=n||0;const r=Math.trunc(Zr(e)),s=Math.trunc(Zr(t)),a=Zr(o),l=Zr(i),c=Math.trunc(Zr(n));ac(r,s),hc(c),uc(a),dc(l);return(l-a)/l/Yl.compute(r,s,c)},isExported:!0},Gc={description:r("Convert a decimal fraction to decimal value."),args:zr(`\n fractional_price (number) ${r("The price quotation given using fractional decimal conventions.")}\n unit (number) ${r("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.")}\n `),returns:["NUMBER"],compute:function(e,t){const o=Zr(e),i=Math.trunc(Zr(t));Gr((()=>i>0),r("The unit (%s) must be strictly positive.",i.toString()));const n=Math.trunc(o);return n+(o-n)*(10**Math.ceil(Math.log10(i))/i)},isExported:!0},qc={description:r("Convert a decimal value to decimal fraction."),args:zr(`\n decimal_price (number) ${r("The price quotation given as a decimal value.")}\n unit (number) ${r("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 o=Zr(e),i=Math.trunc(Zr(t));Gr((()=>i>0),r("The unit (%s) must be strictly positive.",i.toString()));const n=Math.trunc(o);return n+(o-n)*(i/10**Math.ceil(Math.log10(i)))},isExported:!0},Zc={description:r("Number of periods for an investment to reach a value."),args:zr(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${r("The annualized rate of interest.")}\n yield (number) ${r("The expected annual yield of the security.")}\n frequency (number) ${r("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,s=0){s=s||0;const a=Math.trunc(Zr(e)),l=Math.trunc(Zr(t)),c=Zr(o),h=Zr(i),d=Math.trunc(Zr(n)),u=Math.trunc(Zr(s));ac(a,l),cc(d),hc(u),Gr((()=>c>=0),r("The rate (%s) must be positive or null.",c.toString())),Gr((()=>h>=0),r("The yield (%s) must be positive or null.",h.toString()));const g=Yl.compute(a,l,u),p=g-Math.trunc(g)||1/d,m=Math.ceil(g*d),f=c/d,v=h/d;let b=0,C=0;for(let e=1;e<=m;e++){const t=(f+(e===m?1:0))/(1+v)**e;C+=(p+(e-1)/d)*t,b+=t}return 0===b?0:C/b},isExported:!0},jc={description:r("Annual effective interest rate."),args:zr(`\n nominal_rate (number) ${r("The nominal interest rate per year.")}\n periods_per_year (number) ${r("The number of compounding periods per year.")}\n `),returns:["NUMBER"],compute:function(e,t){const o=Zr(e),i=Math.trunc(Zr(t));return Gr((()=>o>0),r("The nominal rate (%s) must be strictly greater than 0.",o.toString())),Gr((()=>i>0),r("The number of periods by year (%s) must strictly greater than 0.",i.toString())),Math.pow(1+o/i,i)-1},isExported:!0},Xc={description:r("Future value of an annuity investment."),args:zr(`\n rate (number) ${r("The interest rate.")}\n number_of_periods (number) ${r("The number of payments to be made.")}\n payment_amount (number) ${r("The amount per period to be paid.")}\n present_value (number, default=0) ${r("The current value of the annuity.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,n=0){i=i||0,n=n||0;const r=Zr(e),s=Zr(t),a=Zr(o),l=Zr(i),c=Qr(n)?1:0;return r?-l*(1+r)**s-a*(1+r*c)*((1+r)**s-1)/r:-(l+a*s)},isExported:!0},Yc={description:r("Future value of principal from series of rates."),args:zr(`\n principal (number) ${r("The amount of initial capital or value to compound against.")}\n rate_schedule (number, range<number>) ${r("A series of interest rates to compound against the principal.")}\n `),returns:["NUMBER"],compute:function(e,t){return ns([t],((e,t)=>e*(1+Zr(t))),Zr(e))},isExported:!0},Kc={description:r("Calculates effective interest rate."),args:zr(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n investment (number) ${r("The amount invested in the security.")}\n redemption (number) ${r("The amount to be received at maturity.")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n=0){const r=Math.trunc(Zr(e)),s=Math.trunc(Zr(t)),a=Zr(i),l=Zr(o);ac(r,s),Ec(l),dc(a);return(a-l)/l/Yl.compute(r,s,n)},isExported:!0},Qc={description:r("Payment on the principal of an investment."),args:zr(`\n rate (number) ${r("The annualized rate of interest.")}\n period (number) ${r("The amortization period, in terms of number of periods.")}\n number_of_periods (number) ${r("The number of payments to be made.")}\n present_value (number) ${r("The current value of the annuity.")}\n future_value (number, default=0) ${r("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,n=0,r=0){return ah.compute(e,o,i,n,r)-lh.compute(e,t,o,i,n,r)},isExported:!0},Jc={description:r("Internal rate of return given periodic cashflows."),args:zr(`\n cashflow_amounts (number, range<number>) ${r("An array or range containing the income or payments associated with the investment.")}\n rate_guess (number, default=0.1) ${r("An estimate for what the internal rate of return will be.")}\n `),returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t=.1){const o=Zr(t);Tc(o);let i=!1,n=!1,s=[];os([e],(e=>{e>0&&(i=!0),e<0&&(n=!0),s.push(e)})),Gr((()=>i&&n),r("The cashflow_amounts must include negative and positive values."));const a=s.shift();return Nc((function(e){return function(e,t,o){const i=o.length;let n=0;return o.reduce(((t,o)=>(n++,t+o*e**(i-n))),t*e**i)}(e,a,s)}),(function(e){return function(e,t,o){const i=o.length;let n=0;return o.reduce(((t,o)=>(n++,t+o*(i-n)*e**(i-n-1))),t*i*e**(i-1))}(e,a,s)}),o+1,20,1e-5)-1},isExported:!0},eh={description:r("Returns the interest paid at a particular period of an investment."),args:zr(`\n rate (number) ${r("The interest rate.")}\n period (number) ${r("The period for which you want to view the interest payment.")}\n number_of_periods (number) ${r("The number of payments to be made.")}\n present_value (number) ${r("The current value of the annuity.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i){const n=Zr(e),s=Zr(t),a=Zr(o),l=Zr(i);Gr((()=>0!==a),r("The number of periods must be different than 0.",a.toString()));return-1*(l-l*(s/a))*n},isExported:!0},th={description:r("Modified Macaulay duration."),args:zr(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${r("The annualized rate of interest.")}\n yield (number) ${r("The expected annual yield of the security.")}\n frequency (number) ${r("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,r=0){return Zc.compute(e,t,o,i,n,r)/(1+Zr(i)/Math.trunc(Zr(n)))},isExported:!0},oh={description:r("Modified internal rate of return."),args:zr(`\n cashflow_amounts (range<number>) ${r("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")}\n financing_rate (number) ${r("The interest rate paid on funds invested.")}\n reinvestment_return_rate (number) ${r("The return (as a percentage) earned on reinvestment of income received from the investment.")}\n `),returns:["NUMBER"],compute:function(e,t,o){const i=Zr(t),n=Zr(o),s=(a=e,a.length?a[0].map(((e,t)=>a.map((e=>e[t])))):a).flat().filter(Qe).map(Zr);var a;const l=s.length;let c=0,h=0;for(const e of Le(0,l)){const t=s[e];t>=0?c+=t*(n+1)**(l-e-1):h+=t/(i+1)**e}Gr((()=>0!==h&&0!==c),r("There must be both positive and negative values in cashflow_amounts."));return(-c/h)**(1/(l-1))-1},isExported:!0},ih={description:r("Annual nominal interest rate."),args:zr(`\n effective_rate (number) ${r("The effective interest rate per year.")}\n periods_per_year (number) ${r("The number of compounding periods per year.")}\n `),returns:["NUMBER"],compute:function(e,t){const o=Zr(e),i=Math.trunc(Zr(t));return Gr((()=>o>0),r("The effective rate (%s) must must strictly greater than 0.",o.toString())),Gr((()=>i>0),r("The number of periods by year (%s) must strictly greater than 0.",i.toString())),(Math.pow(o+1,1/i)-1)*i},isExported:!0},nh={description:r("Number of payment periods for an investment."),args:zr(`\n rate (number) ${r("The interest rate.")}\n payment_amount (number) ${r("The amount of each payment made.")}\n present_value (number) ${r("The current value of the annuity.")}\n future_value (number, default=0) ${r("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i=0,n=0){i=i||0,n=n||0;const r=Zr(e),s=Zr(t),a=Zr(o),l=Zr(i),c=Qr(n)?1:0;if(0===r)return-(l+a)/s;const h=s*(1+r*c)/r;return Math.log((h-l)/(a+h))/Math.log(1+r)},isExported:!0};const rh={description:r("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:zr(`\n discount (number) ${r("The discount rate of the investment over one period.")}\n cashflow1 (number, range<number>) ${r("The first future cash flow.")}\n cashflow2 (number, range<number>, repeating) ${r("Additional future cash flows.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,...t){const o=Zr(e);return Gr((()=>-1!==o),r("The discount (%s) must be different from -1.",o.toString())),function(e,t,o){let i=0;return rs(o,((t,o)=>(i++,t+o/(1+e)**i)),t)}(o,0,t)},isExported:!0},sh={description:r("Computes the number of periods needed for an investment to reach a value."),args:zr(`\n rate (number) ${r("The rate at which the investment grows each period.")}\n present_value (number) ${r("The investment's current value.")}\n future_value (number) ${r("The investment's desired future value.")}\n `),returns:["NUMBER"],compute:function(e,t,o){const i=Zr(e),n=Zr(t),s=Zr(o);return pc(i),Gr((()=>n>0),r("The present_value (%s) must be strictly positive.",n.toString())),Gr((()=>s>0),r("The future_value (%s) must be strictly positive.",s.toString())),(Math.log(s)-Math.log(n))/Math.log(1+i)},isExported:!0},ah={description:r("Periodic payment for an annuity investment."),args:zr(`\n rate (number) ${r("The annualized rate of interest.")}\n number_of_periods (number) ${r("The number of payments to be made.")}\n present_value (number) ${r("The current value of the annuity.")}\n future_value (number, default=0) ${r("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,n=0){i=i||0,n=n||0;const r=Zr(t),s=Zr(e),a=Qr(n)?1:0;let l=Zr(i),c=Zr(o);if(gc(r),0===s)return-(l+c)/r;let h=-(c*(1+s)**r+l);return h=h*s/((1+s*a)*((1+s)**r-1)),h},isExported:!0},lh={description:r("Payment on the principal of an investment."),args:zr(`\n rate (number) ${r("The annualized rate of interest.")}\n period (number) ${r("The amortization period, in terms of number of periods.")}\n number_of_periods (number) ${r("The number of payments to be made.")}\n present_value (number) ${r("The current value of the annuity.")}\n future_value (number, default=0) ${r("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,n=0,s=0){n=n||0,s=s||0;const a=Zr(o),l=Zr(e),c=Zr(t),h=Qr(s)?1:0,d=Zr(n),u=Zr(i);gc(a),Gr((()=>c>0&&c<=a),r("The period must be between 1 and number_of_periods",a.toString()));const g=ah.compute(l,a,u,d,s);if(1===h&&1===c)return g;return g+-Xc.compute(l,0===h?c-1:c-2,g,u+g*h,0)*l},isExported:!0},ch={description:r("Present value of an annuity investment."),args:zr(`\n rate (number) ${r("The interest rate.")}\n number_of_periods (number) ${r("The number of payments to be made.")}\n payment_amount (number) ${r("The amount per period to be paid.")}\n future_value (number, default=0) ${r("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,n=0){i=i||0,n=n||0;const r=Zr(e),s=Zr(t),a=Zr(o),l=Zr(i),c=Qr(n)?1:0;return r?-(a*(1+r*c)*((1+r)**s-1)/r+l)/(1+r)**s:-(l+a*s)},isExported:!0},hh={description:r("Price of a security paying periodic interest."),args:zr(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${r("The annualized rate of interest.")}\n yield (number) ${r("The expected annual yield of the security.")}\n redemption (number) ${r("The redemption amount per 100 face value, or par.")}\n frequency (number) ${r("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,s,a=0){a=a||0;const l=Math.trunc(Zr(e)),c=Math.trunc(Zr(t)),h=Zr(o),d=Zr(i),u=Zr(n),g=Math.trunc(Zr(s)),p=Math.trunc(Zr(a));ac(l,c),cc(g),hc(p),Gr((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),Gr((()=>d>=0),r("The yield (%s) must be positive or null.",d.toString())),dc(u);const m=Yl.compute(l,c,p)*g,f=Math.ceil(m),v=m-Math.floor(m)||1,b=1+d/g,C=100*h/g;if(1===f)return(C+u)/(v*d/g+1)-C*(1-v);let S=0;for(let e=1;e<=f;e++)S+=C/b**(e-1+v);return u/b**(f-1+v)+S-C*(1-v)},isExported:!0},dh={description:r("Price of a discount security."),args:zr(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n discount (number) ${r("The discount rate of the security at time of purchase.")}\n redemption (number) ${r("The redemption amount per 100 face value, or par.")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n=0){n=n||0;const r=Math.trunc(Zr(e)),s=Math.trunc(Zr(t)),a=Zr(o),l=Zr(i),c=Math.trunc(Zr(n));ac(r,s),hc(c),wc(a),dc(l);return l-a*l*Yl.compute(r,s,c)},isExported:!0},uh={description:r("Calculates the price of a security paying interest at maturity, based on expected yield."),args:zr(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n issue (date) ${r("The date the security was initially issued.")}\n rate (number) ${r("The annualized rate of interest.")}\n yield (number) ${r("The expected annual yield of the security.")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,s=0){s=s||0;const a=Math.trunc(Zr(e)),l=Math.trunc(Zr(t)),c=Math.trunc(Zr(o)),h=Zr(i),d=Zr(n),u=Math.trunc(Zr(s));lc(a,c),ac(a,l),hc(u),Gr((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),Gr((()=>d>=0),r("The yield (%s) must be positive or null.",d.toString()));const g=Yl.compute(a,l,u),p=Yl.compute(a,c,u);return(100+Yl.compute(c,l,u)*h*100)/(1+g*d)-p*h*100},isExported:!0},gh=.1,ph={description:r("Interest rate of an annuity investment."),args:zr(`\n number_of_periods (number) ${r("The number of payments to be made.")}\n payment_per_period (number) ${r("The amount per period to be paid.")}\n present_value (number) ${r("The current value of the annuity.")}\n future_value (number, default=0) ${r("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n rate_guess (number, default=0.1) ${r("An estimate for what the interest rate will be.")}\n `),returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t,o,i=0,n=0,s=.1){i=i||0,n=n||0,s=s||gh;const a=Zr(e),l=Zr(t),c=Qr(n)?1:0,h=Zr(s);let d=Zr(i),u=Zr(o);gc(a),Gr((()=>[l,u,d].some((e=>e>0))&&[l,u,d].some((e=>e<0))),r("There must be both positive and negative values in [payment_amount, present_value, future_value].",a.toString())),Tc(h),d-=l*c,u+=l*c;return Nc((e=>{const t=Math.pow(1+e,a);return d+u*t+l*((t-1)/e)}),(e=>{const t=Math.pow(1+e,a-1),o=Math.pow(1+e,a);return u*a*t+l*(a*t/e-(o-1)/e/e)}),h,40,1e-5)},isExported:!0},mh={description:r("Amount received at maturity for a security."),args:zr(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n investment (number) ${r("The amount invested (irrespective of face value of each security).")}\n discount (number) ${r("The discount rate of the security invested in.")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n=0){n=n||0;const r=Math.trunc(Zr(e)),s=Math.trunc(Zr(t)),a=Zr(o),l=Zr(i),c=Math.trunc(Zr(n));ac(r,s),hc(c),Ec(a),wc(l);return a/(1-l*Yl.compute(r,s,c))},isExported:!0},fh={description:r("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:zr(`\n number_of_periods (number) ${r("The number of periods.")}\n present_value (number) ${r("The present value of the investment.")}\n future_value (number) ${r("The future value of the investment.")}\n `),returns:["NUMBER"],compute:function(e,t,o){const i=Zr(e),n=Zr(t),r=Zr(o);return gc(i),(r/n)**(1/i)-1},isExported:!0},vh={description:r("Depreciation of an asset using the straight-line method."),args:zr(`\n cost (number) ${r("The initial cost of the asset.")}\n salvage (number) ${r("The value of the asset at the end of depreciation.")}\n life (number) ${r("The number of periods over which the asset is depreciated.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o){return(Zr(e)-Zr(t))/Zr(o)},isExported:!0},bh={description:r("Depreciation via sum of years digit method."),args:zr(`\n cost (number) ${r("The initial cost of the asset.")}\n salvage (number) ${r("The value of the asset at the end of depreciation.")}\n life (number) ${r("The number of periods over which the asset is depreciated.")}\n period (number) ${r("The single period within life for which to calculate depreciation.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i){const n=Zr(e),r=Zr(t),s=Zr(o),a=Zr(i);vc(a),mc(s),Sc(a,s);return(s-a+1)/(s*(s+1)/2)*(n-r)},isExported:!0},Ch={description:r("Price of a US Treasury bill."),args:zr(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n discount (number) ${r("The discount rate of the bill at time of purchase.")}\n `),returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Zr(e)),n=Math.trunc(Zr(t)),r=Zr(o);ac(i,n),Ic(i,n),wc(r),yc(r);return 100*(1-r*Yl.compute(i,n,2))},isExported:!0},Sh={description:r("Equivalent rate of return for a US Treasury bill."),args:zr(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n discount (number) ${r("The discount rate of the bill at time of purchase.")}\n `),returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Zr(e)),n=Math.trunc(Zr(t)),r=Zr(o);ac(i,n),Ic(i,n),wc(r),yc(r);const s=Ol.compute(n,i);if(s<=182)return 365*r/(360-r*s);const a=Ch.compute(i,n,r)/100,l=s/(366===s?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},Eh={description:r("The yield of a US Treasury bill based on price."),args:zr(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n price (number) ${r("The price at which the security is bought per 100 face value.")}\n `),returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(Zr(e)),n=Math.trunc(Zr(t)),r=Zr(o);ac(i,n),Ic(i,n),uc(r);return(100-r)/r*(1/Yl.compute(i,n,2))},isExported:!0},wh={description:r("Variable declining balance. WARNING : does not handle decimal periods."),args:zr(`\n cost (number) ${r("The initial cost of the asset.")}\n salvage (number) ${r("The value of the asset at the end of depreciation.")}\n life (number) ${r("The number of periods over which the asset is depreciated.")}\n start (number) ${r("Starting period to calculate depreciation.")}\n end (number) ${r("Ending period to calculate depreciation.")}\n factor (number, default=2) ${r("The number of months in the first year of depreciation.")}\n no_switch (number, default=false) ${r("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,s=2,a=false){s=s||0;const l=Zr(e),c=Zr(t),h=Zr(o),d=Math.trunc(Zr(i)),u=Math.trunc(Zr(n)),g=Zr(s),p=Qr(a);if(fc(l),bc(c),function(e,t,o){mc(o),Gr((()=>e>=0),r("The start_period (%s) must be greater or equal than 0.",e.toString())),Gr((()=>t>=0),r("The end_period (%s) must be greater or equal than 0.",t.toString())),Gr((()=>e<=t),r("The start_period (%s) must be smaller or equal to the end_period (%s).",e.toString(),t.toString())),Gr((()=>t<=o),r("The end_period (%s) must be smaller or equal to the life (%s).",e.toString(),o.toString()))}(d,u,h),xc(g),0===l)return 0;if(c>=l)return d<1?l-c:0;const m=g/h;if(m>=1)return d<1?l-c:0;let f=l,v=0,b=0,C=!1;for(let e=0;e<u;e++){if(!C||p){const t=f*m,o=(f-c)/(h-e);!p&&o>t?(C=!0,v=o):v=t}const t=Math.max(f-v,c);e>=d&&(b+=f-t),f=t}return b},isExported:!0},yh={description:r("Internal rate of return given non-periodic cash flows."),args:zr(`\n cashflow_amounts (range<number>) ${r("An range containing the income or payments associated with the investment.")}\n cashflow_dates (range<number>) ${r("An range with dates corresponding to the cash flows in cashflow_amounts.")}\n rate_guess (number, default=0.1) ${r("An estimate for what the internal rate of return will be.")}\n `),returns:["NUMBER"],compute:function(e,t,o=.1){const i=Zr(o=o||0),n=e.flat().map(Zr),s=t.flat().map(Zr);var a;Ac(e,t),a=n,Gr((()=>a.some((e=>e>0))&&a.some((e=>e<0))),r("There must be both positive and negative values in cashflow_amounts.")),Oc(s),Tc(i);const l=new Map;for(const e of Le(0,s.length)){const t=s[e];l.has(t)?l.set(t,l.get(t)+n[e]):l.set(t,n[e])}const c=Array.from(l.keys()),h=c.map((e=>l.get(e)));return Nc((e=>{let t=h[0];for(const o of Le(1,h.length)){const i=(c[0]-c[o])/365;t+=h[o]*(1+e)**i}return t}),(e=>{let t=0;for(const o of Le(1,h.length)){const i=(c[0]-c[o])/365;t+=i*h[o]*(1+e)**(i-1)}return t}),i,40,1e-5,(e=>e?e/10-.9:-.9))},isExported:!0},xh={description:r("Net present value given to non-periodic cash flows.."),args:zr(`\n discount (number) ${r("The discount rate of the investment over one period.")}\n cashflow_amounts (number, range<number>) ${r("An range containing the income or payments associated with the investment.")}\n cashflow_dates (number, range<number>) ${r("An range with dates corresponding to the cash flows in cashflow_amounts.")}\n `),returns:["NUMBER"],compute:function(e,t,o){const i=Zr(e),n=Array.isArray(t)?t.flat().map(jr):[jr(t)],s=Array.isArray(o)?o.flat().map(jr):[jr(o)];if(Array.isArray(o)&&Array.isArray(t)?Ac(t,o):Gr((()=>n.length===s.length),r("There must be the same number of values in cashflow_amounts and cashflow_dates.")),Oc(s),pc(i),1===n.length)return n[0];const a=new Map;for(const e of Le(0,s.length)){const t=s[e];a.has(t)?a.set(t,a.get(t)+n[e]):a.set(t,n[e])}const l=Array.from(a.keys()),c=l.map((e=>a.get(e)));let h=c[0];for(const e of Le(1,c.length)){const t=(l[0]-l[e])/365;h+=c[e]*(1+i)**t}return h},isExported:!0},Ih={description:r("Annual yield of a security paying periodic interest."),args:zr(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${r("The annualized rate of interest.")}\n price (number) ${r("The price at which the security is bought per 100 face value.")}\n redemption (number) ${r("The redemption amount per 100 face value, or par.")}\n frequency (number) ${r("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,s,a=0){a=a||0;const l=Math.trunc(Zr(e)),c=Math.trunc(Zr(t)),h=Zr(o),d=Zr(i),u=Zr(n),g=Math.trunc(Zr(s)),p=Math.trunc(Zr(a));ac(l,c),cc(g),hc(p),Gr((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),uc(d),dc(u);const m=Yl.compute(l,c,p)*g,f=Math.ceil(m),v=m-Math.floor(m)||1,b=100*h/g;if(1===f){const e=d+b*(1-v);return(u+b-e)*g*(1/v)/e}const C=Nc((function(e){return function(e,t,o,i,n,r){let s=r-(e+n*(1-t))*i**(o-1+t);for(let e=1;e<=o;e++)s+=n*i**(e-1);return s}(d,v,f,e,b,u)}),(function(e){return function(e,t,o,i,n){let r=-(e+n*(1-t))*(o-1+t)*i**(o-2+t);for(let e=1;e<=o;e++)r+=n*(e-1)*i**(e-2);return r}(d,v,f,e,b)}),1+(h+1)/g,100,1e-5);return(C-1)*g},isExported:!0},Rh={description:r("Annual yield of a discount security."),args:zr(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n price (number) ${r("The price at which the security is bought per 100 face value.")}\n redemption (number) ${r("The redemption amount per 100 face value, or par.")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n=0){n=n||0;const r=Math.trunc(Zr(e)),s=Math.trunc(Zr(t)),a=Zr(o),l=Zr(i),c=Math.trunc(Zr(n));ac(r,s),hc(c),uc(a),dc(l);return(l/a-1)/Yl.compute(e,t,n)},isExported:!0},Th={description:r("Annual yield of a security paying interest at maturity."),args:zr(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n issue (date) ${r("The date the security was initially issued.")}\n rate (number) ${r("The annualized rate of interest.")}\n price (number) ${r("The price at which the security is bought.")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,s=0){s=s||0;const a=Math.trunc(Zr(e)),l=Math.trunc(Zr(t)),c=Math.trunc(Zr(o)),h=Zr(i),d=Zr(n),u=Math.trunc(Zr(s));ac(a,l),hc(u),Gr((()=>a>=c),r("The settlement (%s) must be greater than or equal to the issue (%s).",a.toString(),c.toString())),Gr((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),uc(d);const g=Yl.compute(c,l,u),p=Yl.compute(c,a,u),m=Yl.compute(a,l,u);return(100*(1+h*g)/(d+100*h*p)-1)/m},isExported:!0};var Ah=Object.freeze({__proto__:null,ACCRINTM:_c,AMORLINC:Fc,COUPDAYS:Dc,COUPDAYBS:kc,COUPDAYSNC:$c,COUPNCD:Pc,COUPNUM:Lc,COUPPCD:Uc,CUMIPMT:Vc,CUMPRINC:zc,DB:Bc,DDB:Hc,DISC:Wc,DOLLARDE:Gc,DOLLARFR:qc,DURATION:Zc,EFFECT:jc,FV:Xc,FVSCHEDULE:Yc,INTRATE:Kc,IPMT:Qc,IRR:Jc,ISPMT:eh,MDURATION:th,MIRR:oh,NOMINAL:ih,NPER:nh,NPV:rh,PDURATION:sh,PMT:ah,PPMT:lh,PV:ch,PRICE:hh,PRICEDISC:dh,PRICEMAT:uh,RATE:ph,RECEIVED:mh,RRI:fh,SLN:vh,SYD:bh,TBILLPRICE:Ch,TBILLEQ:Sh,TBILLYIELD:Eh,VDB:wh,XIRR:yh,XNPV:xh,YIELD:Ih,YIELDDISC:Rh,YIELDMAT:Th});const Oh={description:r("Whether a value is an error other than #N/A."),args:zr(`value (any, lazy) ${r("The value to be verified as an error type.")}`),returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return(null==e?void 0:e.errorType)!=a.NotAvailable}},isExported:!0},Mh={description:r("Whether a value is an error."),args:zr(`value (any, lazy) ${r("The value to be verified as an error type.")}`),returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},Nh={description:r("Whether a value is `true` or `false`."),args:zr(`value (any, lazy) ${r("The value to be verified as a logical TRUE or FALSE.")}`),returns:["BOOLEAN"],compute:function(e){try{return"boolean"==typeof e()}catch(e){return!1}},isExported:!0},_h={description:r("Whether a value is the error #N/A."),args:zr(`value (any, lazy) ${r("The value to be verified as an error type.")}`),returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return(null==e?void 0:e.errorType)==a.NotAvailable}},isExported:!0},Fh={description:r("Whether a value is non-textual."),args:zr(`value (any, lazy) ${r("The value to be checked.")}`),returns:["BOOLEAN"],compute:function(e){try{return"string"!=typeof e()}catch(e){return!0}},isExported:!0},Dh={description:r("Whether a value is a number."),args:zr(`value (any, lazy) ${r("The value to be verified as a number.")}`),returns:["BOOLEAN"],compute:function(e){try{return"number"==typeof e()}catch(e){return!1}},isExported:!0},kh={description:r("Whether a value is text."),args:zr(`value (any, lazy) ${r("The value to be verified as text.")}`),returns:["BOOLEAN"],compute:function(e){try{return"string"==typeof e()}catch(e){return!1}},isExported:!0},$h={description:r("Whether the referenced cell is empty"),args:zr(`value (any, lazy) ${r("Reference to the cell that will be checked for emptiness.")}`),returns:["BOOLEAN"],compute:function(e){try{return null===e()}catch(e){return!1}},isExported:!0},Ph={description:r("Returns the error value #N/A."),args:zr(""),returns:["BOOLEAN"],compute:function(e){throw new g},isExported:!0};var Lh=Object.freeze({__proto__:null,ISERR:Oh,ISERROR:Mh,ISLOGICAL:Nh,ISNA:_h,ISNONTEXT:Fh,ISNUMBER:Dh,ISTEXT:kh,ISBLANK:$h,NA:Ph});const Uh={description:r("Logical `and` operator."),args:zr(`\n logical_expression1 (boolean, range<boolean>) ${r("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${r("More expressions that represent logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!0;return as(e,(e=>(t=!0,o=o&&e,o))),Gr((()=>t),r("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0},Vh={description:r("Returns value depending on logical expression."),args:zr(`\n logical_expression (boolean) ${r("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) ${r("The value the function returns if logical_expression is TRUE.")}\n value_if_false (any, lazy, default=FALSE) ${r("The value the function returns if logical_expression is FALSE.")}\n `),returns:["ANY"],compute:function(e,t,o=(()=>!1)){const i=Qr(e)?t():o();return null==i?"":i},isExported:!0},zh={description:r("Value if it is not an error, otherwise 2nd argument."),args:zr(`\n value (any, lazy) ${r("The value to return if value itself is not an error.")}\n value_if_error (any, lazy, default=${r("An empty value")}) ${r("The value the function returns if value is an error.")}\n `),returns:["ANY"],computeFormat:(e,t=(()=>({value:""})))=>{var o;try{return e().format}catch(e){return null===(o=t())||void 0===o?void 0:o.format}},compute:function(e,t=(()=>"")){let o;try{o=e()}catch(e){o=t()}return null==o?"":o},isExported:!0},Bh={description:r("Value if it is not an #N/A error, otherwise 2nd argument."),args:zr(`\n value (any, lazy) ${r("The value to return if value itself is not #N/A an error.")}\n value_if_error (any, lazy, default=${r("An empty value")}) ${r("The value the function returns if value is an #N/A error.")}\n `),returns:["ANY"],compute:function(e,t=(()=>"")){let o;try{o=e()}catch(i){o=i.errorType===a.NotAvailable?t():e()}return null==o?"":o},isExported:!0},Hh={description:r("Returns a value depending on multiple logical expressions."),args:zr(`\n condition1 (boolean, lazy) ${r("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")}\n value1 (any, lazy) ${r("The returned value if condition1 is TRUE.")}\n condition2 (boolean, lazy, repeating) ${r("Additional conditions to be evaluated if the previous ones are FALSE.")}\n value2 (any, lazy, repeating) ${r("Additional values to be returned if their corresponding conditions are TRUE.")}\n `),returns:["ANY"],compute:function(...e){Gr((()=>e.length%2==0),r("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(Qr(e[t]())){const o=e[t+1]();return null!==o?o:""}throw new Error(r("No match."))},isExported:!0},Wh={description:r("Returns opposite of provided logical value."),args:zr(`logical_expression (boolean) ${r("An expression or reference to a cell holding an expression that represents some logical value.")}\n `),returns:["BOOLEAN"],compute:function(e){return!Qr(e)},isExported:!0},Gh={description:r("Logical `or` operator."),args:zr(`\n logical_expression1 (boolean, range<boolean>) ${r("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${r("More expressions that evaluate to logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!1;return as(e,(e=>(t=!0,o=o||e,!o))),Gr((()=>t),r("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0},qh={description:r("Logical `xor` operator."),args:zr(`\n logical_expression1 (boolean, range<boolean>) ${r("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${r("More expressions that evaluate to logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!1;return as(e,(e=>(t=!0,o=o?!e:e,!0))),Gr((()=>t),r("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0};var Zh=Object.freeze({__proto__:null,AND:Uh,IF:Vh,IFERROR:zh,IFNA:Bh,IFS:Hh,NOT:Wh,OR:Gh,XOR:qh});function jh(e,t){if(void 0===e)throw new g(r("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",Xr(t)))}const Xh={description:r("Column number of a specified cell."),args:zr(`cell_reference (meta, default=${r("The cell in which the formula is entered")}) ${r("The cell whose column number will be returned. Column A corresponds to 1.")}\n `),returns:["NUMBER"],compute:function(e){var t;const o=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this));Gr((()=>!!o),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Oo(o).left+1},isExported:!0},Yh={description:r("Number of columns in a specified array or range."),args:zr(`range (meta) ${r("The range whose column count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=Oo(e);return t.right-t.left+1},isExported:!0},Kh={description:r("Horizontal lookup"),args:zr(`\n search_key (any) ${r("The value to search for. For example, 42, 'Cats', or I24.")}\n range (range) ${r("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")}\n index (number) ${r("The row index of the value to be returned, where the first row in range is numbered 1.")}\n is_sorted (boolean, default=true) ${r("Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned.")}\n `),returns:["ANY"],compute:function(e,t,o,i=true){const n=Math.trunc(Zr(o)),s=Yr(e);Gr((()=>1<=n&&n<=t[0].length),r("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=Qr(i)?gs(t,s,"nextSmaller","asc",t.length,us):ps(t,s,"strict",t.length,us);const l=t[a];return jh(l,e),l[n-1]},isExported:!0},Qh={description:r("Look up a value."),args:zr(`\n search_key (any) ${r("The value to search for. For example, 42, 'Cats', or I24.")}\n search_array (range) ${r("One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.")}\n result_range (range, optional) ${r("The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method.")}\n `),returns:["ANY"],compute:function(e,t,o){let i=t.length,n=t[0].length;const s=Yr(e),a=n>=i,l=gs(t,s,"nextSmaller","asc",a?n:i,a?ds:us);return-1===l&&jh(void 0,e),jh(a?t[0][l]:t[l][n-1],e),void 0===o?a?t[i-1][l]:t[l][n-1]:(i=o.length,n=o[0].length,Gr((()=>1===i||1===n),r("The result_range must be a single row or a single column.")),i>1?(Gr((()=>l<=i-1),r("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(l+1).toString())),o[l][0]):(Gr((()=>l<=n-1),r("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(l+1).toString())),o[0][l]))},isExported:!0},Jh={description:r("Position of item in range that matches value."),args:zr(`\n search_key (any) ${r("The value to search for. For example, 42, 'Cats', or I24.")}\n range (any, range) ${r("The one-dimensional array to be searched.")}\n search_type (number, default=1) ${r("The search method. 1 (default) finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order.")}\n `),returns:["NUMBER"],compute:function(e,t,o=1){let i=Zr(o);const n=Yr(e),s=t.length,a=t[0].length;Gr((()=>1===s||1===a),r("The range must be a single row or a single column."));let l=-1;const c=1===s?ds:us,h=1===s?t[0].length:t.length;switch(i=Math.sign(i),i){case 1:l=gs(t,n,"nextSmaller","asc",h,c);break;case 0:l=ps(t,n,"strict",h,c);break;case-1:l=gs(t,n,"nextGreater","desc",h,c)}return jh(1===s?t[0][l]:t[l],e),l+1},isExported:!0},ed={description:r("Row number of a specified cell."),args:zr(`cell_reference (meta, default=${r("The cell in which the formula is entered by default")}) ${r("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)),Gr((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Oo(e).top+1},isExported:!0},td={description:r("Number of rows in a specified array or range."),args:zr(`range (meta) ${r("The range whose row count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=Oo(e);return t.bottom-t.top+1},isExported:!0},od={description:r("Vertical lookup."),args:zr(`\n search_key (any) ${r("The value to search for. For example, 42, 'Cats', or I24.")}\n range (any, range) ${r("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")}\n index (number) ${r("The column index of the value to be returned, where the first column in range is numbered 1.")}\n is_sorted (boolean, default=true) ${r("Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned.")}\n `),returns:["ANY"],compute:function(e,t,o,i=true){const n=Math.trunc(Zr(o)),s=Yr(e);Gr((()=>1<=n&&n<=t.length),r("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=Qr(i)?gs(t,s,"nextSmaller","asc",t[0].length,ds):ps(t,s,"strict",t[0].length,ds);const l=t[n-1][a];return jh(l,e),l},isExported:!0},id={description:r("Search a range for a match and return the corresponding item from a second range."),args:zr(`\n search_key (any) ${r("The value to search for.")}\n lookup_range (any, range) ${r("The range to consider for the search. Should be a single column or a single row.")}\n return_range (any, range) ${r("The range containing the return value. Should have the same dimensions as lookup_range.")}\n if_not_found (any, lazy, optional) ${r("If a valid match is not found, return this value.")}\n match_mode (any, default=0) ${r("(0) Exact match. (-1) Return next smaller item if no match. (1) Return next greater item if no match.")}\n search_mode (any, default=1) ${r("(1) Search starting at first item. (-1) Search starting at last item. (2) Perform a binary search that relies on lookup_array being sorted in ascending order. If not sorted, invalid results will be returned. (-2) Perform a binary search that relies on lookup_array being sorted in descending order. If not sorted, invalid results will be returned. ")}\n\n `),returns:["ANY"],compute:function(e,t,o,i,n=0,s=1){const a=Math.trunc(Zr(n)),l=Math.trunc(Zr(s)),c=Yr(e);Gr((()=>1===t.length||1===t[0].length),r("lookup_range should be either a single row or single column.")),Gr((()=>1===o.length||1===o[0].length),r("return_range should be either a single row or single column.")),Gr((()=>o.length===t.length&&o[0].length===t[0].length),r("return_range should have the same dimensions as lookup_range.")),Gr((()=>[-1,1,-2,2].includes(l)),r("searchMode should be a value in [-1, 1, -2, 2].")),Gr((()=>[-1,0,1].includes(a)),r("matchMode should be a value in [-1, 0, 1]."));const h=1===t.length?ds:us,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=gs(t,c,u,2===l?"asc":"desc",d,h)}else p=ps(t,c,u,d,h,g);if(-1!==p)return 1===t.length?o[0][p]:o[p][0];const m=null==i?void 0:i();return jh(m,e),m},isExported:!0};var nd=Object.freeze({__proto__:null,COLUMN:Xh,COLUMNS:Yh,HLOOKUP:Kh,LOOKUP:Qh,MATCH:Jh,ROW:ed,ROWS:td,VLOOKUP:od,XLOOKUP:id});const rd={description:r("Sum of two numbers."),args:zr(`\n value1 (number) ${r("The first addend.")}\n value2 (number) ${r("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 Zr(e)+Zr(t)}},sd={description:r("Concatenation of two values."),args:zr(`\n value1 (string) ${r("The value to which value2 will be appended.")}\n value2 (string) ${r("The value to append to value1.")}\n `),returns:["STRING"],compute:function(e,t){return Xr(e)+Xr(t)},isExported:!0},ad={description:r("One number divided by another."),args:zr(`\n dividend (number) ${r("The number to be divided.")}\n divisor (number) ${r("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 o=Zr(t);return Gr((()=>0!==o),r("The divisor must be different from zero.")),Zr(e)/o}};function ld(e){return null==e}const cd={number:0,string:"",boolean:!1},hd={description:r("Equal."),args:zr(`\n value1 (any) ${r("The first value.")}\n value2 (any) ${r("The value to test against value1 for equality.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return e=ld(e)?cd[typeof t]:e,t=ld(t)?cd[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function dd(e,t,o){e=ld(e)?cd[typeof t]:e,t=ld(t)?cd[typeof e]:t,"number"!=typeof e&&(e=Xr(e).toUpperCase()),"number"!=typeof t&&(t=Xr(t).toUpperCase());const i=typeof e,n=typeof t;return"string"===i&&"number"===n||("string"!==n||"number"!==i)&&o(e,t)}const ud={description:r("Strictly greater than."),args:zr(`\n value1 (any) ${r("The value to test as being greater than value2.")}\n value2 (any) ${r("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return dd(e,t,((e,t)=>e>t))}},gd={description:r("Greater than or equal to."),args:zr(`\n value1 (any) ${r("The value to test as being greater than or equal to value2.")}\n value2 (any) ${r("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return dd(e,t,((e,t)=>e>=t))}},pd={description:r("Less than."),args:zr(`\n value1 (any) ${r("The value to test as being less than value2.")}\n value2 (any) ${r("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!gd.compute(e,t)}},md={description:r("Less than or equal to."),args:zr(`\n value1 (any) ${r("The value to test as being less than or equal to value2.")}\n value2 (any) ${r("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!ud.compute(e,t)}},fd={description:r("Difference of two numbers."),args:zr(`\n value1 (number) ${r("The minuend, or number to be subtracted from.")}\n value2 (number) ${r("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 Zr(e)-Zr(t)}},vd={description:r("Product of two numbers"),args:zr(`\n factor1 (number) ${r("The first multiplicand.")}\n factor2 (number) ${r("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 Zr(e)*Zr(t)}},bd={description:r("Not equal."),args:zr(`\n value1 (any) ${r("The first value.")}\n value2 (any) ${r("The value to test against value1 for inequality.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!hd.compute(e,t)}},Cd={description:r("A number raised to a power."),args:zr(`\n base (number) ${r("The number to raise to the exponent power.")}\n exponent (number) ${r("The exponent to raise base to.")}\n `),returns:["NUMBER"],compute:function(e,t){return oa.compute(e,t)}},Sd={description:r("A number with the sign reversed."),args:zr(`\n value (number) ${r("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-Zr(e)}},Ed={description:r("Value interpreted as a percentage."),args:zr(`\n percentage (number) ${r("The value to interpret as a percentage.")}\n `),returns:["NUMBER"],compute:function(e){return Zr(e)/100}},wd={description:r("A specified number, unchanged."),args:zr(`\n value (any) ${r("The number to return.")}\n `),returns:["ANY"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){return null===e?"":e}};var yd=Object.freeze({__proto__:null,ADD:rd,CONCAT:sd,DIVIDE:ad,EQ:hd,GT:ud,GTE:gd,LT:pd,LTE:md,MINUS:fd,MULTIPLY:vd,NE:bd,POW:Cd,UMINUS:Sd,UNARY_PERCENT:Ed,UPLUS:wd});const xd=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,Id={description:r("Gets character associated with number."),args:zr(`\n table_number (number) ${r("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(Zr(e));return Gr((()=>t>=1),r("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},Rd={description:r("Remove non-printable characters from a piece of text."),args:zr(`\n text (string) ${r("The text whose non-printable characters are to be removed.")}\n `),returns:["STRING"],compute:function(e){const t=Xr(e);let o="";for(const e of t)e&&e.charCodeAt(0)>31&&(o+=e);return o},isExported:!0},Td={description:r("Appends strings to one another."),args:zr(`\n string1 (string, range<string>) ${r("The initial string.")}\n string2 (string, range<string>, repeating) ${r("More strings to append in sequence.")}\n `),returns:["STRING"],compute:function(...e){return ns(e,((e,t)=>e+Xr(t)),"")},isExported:!0},Ad={description:r("Tests whether two strings are identical."),args:zr(`\n string1 (string) ${r("The first string to compare.")}\n string2 (string) ${r("The second string to compare.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return Xr(e)===Xr(t)},isExported:!0},Od={description:r("First position of string found in text, case-sensitive."),args:zr(`\n search_for (string) ${r("The string to look for within text_to_search.")}\n text_to_search (string) ${r("The text to search for the first occurrence of search_for.")}\n starting_at (number, default=1) ${r("The character within text_to_search at which to start the search.")}\n `),returns:["NUMBER"],compute:function(e,t,o=1){const i=Xr(e),n=Xr(t),s=Zr(o);Gr((()=>""!==n),r("The text_to_search must be non-empty.")),Gr((()=>s>=1),r("The starting_at (%s) must be greater than or equal to 1.",s.toString()));const a=n.indexOf(i,s-1);return Gr((()=>a>=0),r("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i.toString(),n)),a+1},isExported:!0},Md={description:r("Concatenates elements of arrays with delimiter."),args:zr(`\n delimiter (string) ${r("The character or string to place between each concatenated value.")}\n value_or_array1 (string, range<string>) ${r("The value or values to be appended using delimiter.")}\n value_or_array2 (string, range<string>, repeating) ${r("More values to be appended using delimiter.")}\n `),returns:["STRING"],compute:function(e,...t){const o=Xr(e);return ns(t,((e,t)=>(e?e+o:"")+Xr(t)),"")}},Nd={description:r("Substring from beginning of specified string."),args:zr(`\n text (string) ${r("The string from which the left portion will be returned.")}\n number_of_characters (number, optional) ${r("The number of characters to return from the left side of string.")}\n `),returns:["STRING"],compute:function(e,...t){const o=t.length?Zr(t[0]):1;return Gr((()=>o>=0),r("The number_of_characters (%s) must be positive or null.",o.toString())),Xr(e).substring(0,o)},isExported:!0},_d={description:r("Length of a string."),args:zr(`\n text (string) ${r("The string whose length will be returned.")}\n `),returns:["NUMBER"],compute:function(e){return Xr(e).length},isExported:!0},Fd={description:r("Converts a specified string to lowercase."),args:zr(`\n text (string) ${r("The string to convert to lowercase.")}\n `),returns:["STRING"],compute:function(e){return Xr(e).toLowerCase()},isExported:!0},Dd={description:r("A segment of a string."),args:zr(`\n text (string) ${r("The string to extract a segment from.")}\n starting_at (number) ${r("The index from the left of string from which to begin extracting. The first character in string has the index 1.")}\n extract_length (number) ${r("The length of the segment to extract.")}\n `),returns:["STRING"],compute:function(e,t,o){const i=Xr(e),n=Zr(t),s=Zr(o);return Gr((()=>n>=1),r("The starting_at argument (%s) must be positive greater than one.",n.toString())),Gr((()=>s>=0),r("The extract_length argument (%s) must be positive or null.",s.toString())),i.slice(n-1,n+s-1)},isExported:!0},kd={description:r("Capitalizes each word in a specified string."),args:zr(`\n text_to_capitalize (string) ${r("The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase.")}\n `),returns:["STRING"],compute:function(e){return Xr(e).replace(xd,(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()))},isExported:!0},$d={description:r("Replaces part of a text string with different text."),args:zr(`\n text (string) ${r("The text, a part of which will be replaced.")}\n position (number) ${r("The position where the replacement will begin (starting from 1).")}\n length (number) ${r("The number of characters in the text to be replaced.")}\n new_text (string) ${r("The text which will be inserted into the original text.")}\n `),returns:["STRING"],compute:function(e,t,o,i){const n=Zr(t);Gr((()=>n>=1),r("The position (%s) must be greater than or equal to 1.",n.toString()));const s=Xr(e),a=Zr(o),l=Xr(i);return s.substring(0,n-1)+l+s.substring(n-1+a)},isExported:!0},Pd={description:r("A substring from the end of a specified string."),args:zr(`\n text (string) ${r("The string from which the right portion will be returned.")}\n number_of_characters (number, optional) ${r("The number of characters to return from the right side of string.")}\n `),returns:["STRING"],compute:function(e,...t){const o=t.length?Zr(t[0]):1;Gr((()=>o>=0),r("The number_of_characters (%s) must be positive or null.",o.toString()));const i=Xr(e),n=i.length;return i.substring(n-o,n)},isExported:!0},Ld={description:r("First position of string found in text, ignoring case."),args:zr(`\n search_for (string) ${r("The string to look for within text_to_search.")}\n text_to_search (string) ${r("The text to search for the first occurrence of search_for.")}\n starting_at (number, default=1) ${r("The character within text_to_search at which to start the search.")}\n `),returns:["NUMBER"],compute:function(e,t,o=1){const i=Xr(e).toLowerCase(),n=Xr(t).toLowerCase(),s=Zr(o);Gr((()=>""!==n),r("The text_to_search must be non-empty.")),Gr((()=>s>=1),r("The starting_at (%s) must be greater than or equal to 1.",s.toString()));const a=n.indexOf(i,s-1);return Gr((()=>a>=0),r("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i,n)),a+1},isExported:!0},Ud={description:r("Replaces existing text with new text in a string."),args:zr(`\n text_to_search (string) ${r("The text within which to search and replace.")}\n search_for (string) ${r("The string to search for within text_to_search.")}\n replace_with (string) ${r("The string that will replace search_for.")}\n occurrence_number (number, optional) ${r("The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i){const n=Zr(i);Gr((()=>n>=0),r("The occurrenceNumber (%s) must be positive or null.",n.toString()));const s=Xr(e),a=Xr(t);if(""===a)return s;const l=Xr(o),c=new RegExp(Oe(a),"g");if(0===n)return s.replace(c,l);let h=0;return s.replace(c,(e=>++h===n?l:e))},isExported:!0},Vd={description:r("Combines text from multiple strings and/or arrays."),args:zr(`\n delimiter (string) ${r(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")}\n ignore_empty (boolean) ${r("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")}\n text1 (string, range<string>) ${r("Any text item. This could be a string, or an array of strings in a range.")}\n text2 (string, range<string>, repeating) ${r("Additional text item(s).")}\n `),returns:["STRING"],compute:function(e,t,...o){const i=Xr(e),n=Qr(t);let r=0;return ns(o,((e,t)=>n&&""===Xr(t)?e:(r++?e+i:"")+Xr(t)),"")},isExported:!0},zd={description:r("Removes space characters."),args:zr(`\n text (string) ${r("The text or reference to a cell containing text to be trimmed.")}\n `),returns:["STRING"],compute:function(e){return Xr(e).trim()},isExported:!0},Bd={description:r("Converts a specified string to uppercase."),args:zr(`\n text (string) ${r("The string to convert to uppercase.")}\n `),returns:["STRING"],compute:function(e){return Xr(e).toUpperCase()},isExported:!0},Hd={description:r("Converts a number to text according to a specified format."),args:zr(`\n number (number) ${r("The number, date or time to format.")}\n format (string) ${r("The pattern by which to format the number, enclosed in quotation marks.")}\n `),returns:["STRING"],compute:function(e,t){return no(Zr(e),Xr(t))},isExported:!0};var Wd=Object.freeze({__proto__:null,CHAR:Id,CLEAN:Rd,CONCATENATE:Td,EXACT:Ad,FIND:Od,JOIN:Md,LEFT:Nd,LEN:_d,LOWER:Fd,MID:Dd,PROPER:kd,REPLACE:$d,RIGHT:Pd,SEARCH:Ld,SUBSTITUTE:Ud,TEXTJOIN:Vd,TRIM:zd,UPPER:Bd,TEXT:Hd});const Gd={description:r("Creates a hyperlink in a cell."),args:zr(`\n url (string) ${r("The full URL of the link enclosed in quotation marks.")}\n link_label (string, optional) ${r("The text to display in the cell, enclosed in quotation marks.")}\n `),returns:["STRING"],compute:function(e,t){const o=Xr(e).trim(),i=Xr(t)||o;return""===o?i:qe(i,o)},isExported:!0};const qd={database:Il,date:nc,financial:Ah,info:Lh,lookup:nd,logical:Zh,math:Sa,misc:vs,operators:yd,statistical:hl,text:Wd,engineering:sc,web:Object.freeze({__proto__:null,HYPERLINK:Gd})},Zd=/^[A-Z0-9\_\.]+$/;function jd(e){return e.map((e=>{if(void 0!==e)return"function"==typeof e?()=>Xd(e()):Xd(e)}))}function Xd(e){return Array.isArray(e)?e.map((e=>e.map((e=>null==e?void 0:e.value)))):null==e?void 0:e.value}const Yd=new class extends xn{constructor(){super(...arguments),this.mapping={}}add(e,t){if(!(e=e.toUpperCase()).match(Zd))throw new Error(r("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const o=Hr(t);return function(e){let t=!1,o=!1,i=!1;for(let n of e){if(n.type.includes("META")&&n.type.length>1)throw new Error(r("Function ${name} has an argument that has been declared with more than one type whose type 'META'. The 'META' type can only be declared alone."));if(t&&!n.repeating)throw new Error(r("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=o||t||i,s=!(n.optional||n.repeating||n.default);if(e&&s)throw new Error(r("Function ${name} has at mandatory arguments declared after optional ones. All optional arguments must be after all mandatory arguments."));t=n.repeating,o=n.optional,i=n.default}}(o.args),this.mapping[e]=function(...e){const t=o.compute.bind(this),i=o.computeFormat?o.computeFormat.bind(this):()=>{};return{value:t(...jd(e)),format:i(...e)}},super.add(e,o),this}};for(let e in qd){const t=qd[e];for(let o in t){const i=t[o];i.category=e,o=o.replace(/_/g,"."),Yd.add(o,{isExported:!1,...i})}}const Kd=Yd.content,Qd=["%"],Jd="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(Qd);function eu(e){const t=e.split(""),o=[];for(;t.length;){let e=du(t)||iu(t)||ru(t)||au(t)||tu(t)||uu(t)||su(t)||cu(t);e||(e={type:"UNKNOWN",value:t.shift()}),o.push(e)}return o}function tu(e){return"?"===e[0]?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const ou={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function iu(e){if(e[0]in ou){const t=e.shift();return{type:ou[t],value:t}}return null}function nu(e,t){for(let o=0;o<t.length;o++)if(t[o]!==e[o])return!1;return!0}function ru(e){for(let t of Jd)if(nu(e,t))return e.splice(0,t.length),{type:"OPERATOR",value:t};return null}function su(e){const t=tt(e).match(Vt);return t?(e.splice(0,t[0].length),{type:"NUMBER",value:t[0]}):null}function au(e){if('"'===e[0]){const t=e.shift();let o=t;for(;e[0]&&(e[0]!==t||"\\"===o[o.length-1]);)o+=e.shift();return'"'===e[0]&&(o+=e.shift()),{type:"STRING",value:o}}return null}const lu=/\w|\.|!|\$/;function cu(e){let t="";if("'"===e[0]){let o=e.shift();for(t+=o;e[0];)if(o=e.shift(),t+=o,"'"===o){if(!e[0]||"'"!==e[0])break;o=e.shift(),t+=o}if("'"!==o)return{type:"UNKNOWN",value:t}}for(;e[0]&&e[0].match(lu);)t+=e.shift();if(t.length){const e=t;if(e.toUpperCase()in Kd)return{type:"FUNCTION",value:e};return e.match(Rt)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}const hu=/\s/;function du(e){let t=0;for(;e[0]&&e[0].match(hu);)t++,e.shift();return t?{type:"SPACE",value:" ".repeat(t)}:null}function uu(e){return nu(e,X)?(e.splice(0,X.length),{type:"INVALID_REFERENCE",value:X}):null}const gu=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,pu=["-","+"],mu=["%"],fu=["*","+","&"],vu={"^":30,"%":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10},bu=6;function Cu(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 vu[e.value]||15}throw new h(r("Unknown token: %s",e.value))}function Su(e,t,o){if("OPERATOR"===t.type){const i=Cu(t);if(mu.includes(t.value))return{type:"UNARY_OPERATION",value:t.value,operand:e,postfix:!0};{const n=Eu(o,i);return{type:"BIN_OPERATION",value:t.value,left:e,right:n}}}throw new h(se)}function Eu(e,t){const o=e.shift();if(!o)throw new h(se);let i=function(e,t){var o,i,n,s;switch(e.type){case"DEBUGGER":const a=Eu(t,1e3);return a.debug=!0,a;case"NUMBER":return{type:"NUMBER",value:jt(e.value)};case"STRING":return{type:"STRING",value:Ae(e.value)};case"FUNCTION":if("LEFT_PAREN"!==t.shift().type)throw new h(r("Wrong function call"));{const i=[];if(t[0]&&"RIGHT_PAREN"!==t[0].type)for("COMMA"===t[0].type?i.push({type:"UNKNOWN",value:""}):i.push(Eu(t,bu));"COMMA"===(null===(o=t[0])||void 0===o?void 0:o.type);){t.shift();const e=t[0];if("RIGHT_PAREN"===(null==e?void 0:e.type)){i.push({type:"UNKNOWN",value:""});break}"COMMA"===(null==e?void 0:e.type)?i.push({type:"UNKNOWN",value:""}):i.push(Eu(t,bu))}const n=t.shift();if(!n||"RIGHT_PAREN"!==n.type)throw new h(r("Wrong function call"));return{type:"FUNCALL",value:e.value,args:i}}case"INVALID_REFERENCE":throw new u;case"REFERENCE":if(":"===(null===(i=t[0])||void 0===i?void 0:i.value)&&"REFERENCE"===(null===(n=t[1])||void 0===n?void 0:n.type)){t.shift();const o=t.shift();return{type:"REFERENCE",value:`${e.value}:${null==o?void 0:o.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(gu.test(e.value)&&"LEFT_PAREN"===(null===(s=t[0])||void 0===s?void 0:s.type))throw new p(e.value);throw new h(r("Invalid formula"))}return{type:"STRING",value:e.value};case"LEFT_PAREN":const l=Eu(t,5);if(!t.length||"RIGHT_PAREN"!==t[0].type)throw new h(r("Unmatched left parenthesis"));return t.shift(),l;default:if("OPERATOR"===e.type&&pu.includes(e.value))return{type:"UNARY_OPERATION",value:e.value,operand:Eu(t,vu[e.value])};throw new h(r("Unexpected token: %s",e.value))}}(o,e);for(;e[0]&&Cu(e[0])>t;)i=Su(i,e.shift(),e);return i}function wu(e){return yu(eu(e))}function yu(e){"OPERATOR"===(e=e.filter((e=>"SPACE"!==e.type)))[0].type&&"="===e[0].value&&e.splice(0,1);const t=Eu(e,0);if(e.length)throw new h(se);return t}function xu(e,t,o){switch(t===e.type&&(e=o(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>xu(e,t,o)))};case"UNARY_OPERATION":return{...e,operand:xu(e.operand,t,o)};case"BIN_OPERATION":return{...e,right:xu(e.right,t,o),left:xu(e.left,t,o)};default:return e}}function Iu(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>Iu(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?Ru(e)+e.value:e.value+Tu(e);case"BIN_OPERATION":return Ru(e)+e.value+Tu(e)}}function Ru(e){const t=e.value,o="left"in e?e.left:e.operand,i=o.value;return"BIN_OPERATION"===o.type&&vu[i]<vu[t]?`(${Iu(o)})`:Iu(o)}function Tu(e){const t=e.value,o="right"in e?e.right:e.operand,i=vu[o.value],n=vu[t];let r=!1;return"BIN_OPERATION"!==o.type?r=!1:i<n?r=!0:i!==n||fu.includes(t)||(r=!0),r?`(${Iu(o)})`:Iu(o)}var Au;!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"}(Au||(Au={}));const Ou=(e,t=(()=>!0))=>[{goTo:e,guard:t}],Mu=(e,t=(()=>!0))=>({goTo:e,guard:t}),Nu={[Au.LeftRef]:{REFERENCE:Ou(Au.Separator),NUMBER:Ou(Au.FullRowSeparator),SYMBOL:[Mu(Au.FullColumnSeparator,(e=>Tt(e.value))),Mu(Au.FullRowSeparator,(e=>At(e.value)))]},[Au.FullColumnSeparator]:{SPACE:Ou(Au.FullColumnSeparator),OPERATOR:Ou(Au.RightColumnRef,(e=>":"===e.value))},[Au.FullRowSeparator]:{SPACE:Ou(Au.FullRowSeparator),OPERATOR:Ou(Au.RightRowRef,(e=>":"===e.value))},[Au.Separator]:{SPACE:Ou(Au.Separator),OPERATOR:Ou(Au.RightRef,(e=>":"===e.value))},[Au.RightRef]:{SPACE:Ou(Au.RightRef),NUMBER:Ou(Au.Found),REFERENCE:Ou(Au.Found,(e=>Mt(e.value))),SYMBOL:Ou(Au.Found,(e=>Ot(e.value)))},[Au.RightColumnRef]:{SPACE:Ou(Au.RightColumnRef),SYMBOL:Ou(Au.Found,(e=>Ot(e.value))),REFERENCE:Ou(Au.Found,(e=>Mt(e.value)))},[Au.RightRowRef]:{SPACE:Ou(Au.RightRowRef),NUMBER:Ou(Au.Found),REFERENCE:Ou(Au.Found,(e=>Mt(e.value)))},[Au.Found]:{}};function _u(e){var t;let o=0,i=Nu[Au.LeftRef];const n=[];for(;void 0!==i;){const r=e[o++];if(!r)return null;const s=null===(t=i[r.type])||void 0===t?void 0:t.find((e=>e.guard(r))),a=s?s.goTo:void 0;switch(a){case void 0:return null;case Au.Found:return n.push(r),e.splice(0,o),{type:"REFERENCE",value:tt(n.map((e=>e.value)))};default:i=Nu[a],n.push(r)}}return null}function Fu(e){const t=eu(e),o=[];for(;t.length;)o.push(_u(t)||t.shift());return o}const Du=Yd.content,ku={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},$u={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"};function Pu(e){return e.join("\n").split("\n").filter((e=>""!==e.trim()))}const Lu={};function Uu(e){const t=Fu(e),{dependencies:o,constantValues:i}=function(e){const t={numbers:[],strings:[]},o=[];for(const i of e)switch(i.type){case"INVALID_REFERENCE":case"REFERENCE":o.push(i.value);break;case"STRING":const e=Ae(i.value);t.strings.includes(e)||t.strings.push(e);break;case"NUMBER":{const e=jt(i.value);t.numbers.includes(e)||t.numbers.push(e);break}}return{dependencies:o,constantValues:t}}(t),n=function(e,t,o){return tt(e.map((e=>{switch(e.type){case"STRING":const i=Ae(e.value);return`|S${o.strings.indexOf(i)}|`;case"NUMBER":return`|N${o.numbers.indexOf(jt(e.value))}|`;case"REFERENCE":case"INVALID_REFERENCE":return`|${t.indexOf(e.value)}|`;case"SPACE":return"";default:return e.value}})))}(t,o,i);if(!Lu[n]){const s=yu([...t]);let a=1;if("BIN_OPERATION"===s.type&&":"===s.value)throw new h(r("Invalid formula"));if("UNKNOWN"===s.type)throw new h(r("Invalid formula"));const l=g(s),c=Pu([`// ${n}`,l.code,`return ${l.id};`]).join("\n");let d=new Function("deps","ref","range","ctx",c);function u(e){const t=Du[e.value.toUpperCase()],o=e.args,i=o.length;if(i<t.minArgRequired)throw new h(r("Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.",e.value.toUpperCase(),t.minArgRequired.toString(),i.toString()));if(i>t.maxArgPossible)throw new h(r("Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.",e.value.toUpperCase(),t.maxArgPossible.toString(),i.toString()));const n=t.nbrArgRepeating;if(n>1){const o=t.args.length-n;if((i-o)%n!=0)throw new h(r("Invalid number of arguments for the %s function. Expected all arguments after position %s to be supplied by groups of %s arguments",e.value.toUpperCase(),o.toString(),n.toString()))}let s=[];for(let n=0;n<i;n++){const i=t.getArgToFocus(n+1)-1;if(0<=i&&i<t.args.length){const a=o[n],l=t.args[i],c=l.type||[],d=c.includes("META"),u=l.lazy,p=c.some((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e)),m=c.every((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e));if(m&&"REFERENCE"!==a.type)throw new h(r("Function %s expects the parameter %s to be reference to a cell or range, not a %s.",e.value.toUpperCase(),(n+1).toString(),a.type.toLowerCase()));const f=g(a,u,d,p,{functionName:e.value.toUpperCase(),paramIndex:n+1});s.push(f)}}return s}function g(e,t=!1,n=!1,s=!1,l={}){const c=[];let d,p,m;if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&n)throw new h(r("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:""};d=a++,m=`{ value: ${e.value} }`;break;case"NUMBER":d=a++,m=`{ value: this.constantValues.numbers[${i.numbers.indexOf(e.value)}] }`;break;case"STRING":d=a++,m=`{ value: this.constantValues.strings[${i.strings.indexOf(e.value)}] }`;break;case"REFERENCE":const r=o.indexOf(e.value);d=a++,m=s?`range(deps[${r}])`:`ref(deps[${r}], ${n?"true":"false"}, "${l.functionName||ku["="]}", ${l.paramIndex})`;break;case"FUNCALL":d=a++;const h=u(e);c.push(h.map((e=>e.code)).join("\n")),p=e.value.toUpperCase(),c.push(`ctx.__lastFnCalled = '${p}';`),m=`ctx['${p}'](${h.map((e=>e.id))})`;break;case"UNARY_OPERATION":{d=a++,p=$u[e.value];const t=g(e.operand,!1,!1,!1,{functionName:p});c.push(t.code),c.push(`ctx.__lastFnCalled = '${p}';`),m=`ctx['${p}'](${t.id})`;break}case"BIN_OPERATION":{d=a++,p=ku[e.value];const t=g(e.left,!1,!1,!1,{functionName:p}),o=g(e.right,!1,!1,!1,{functionName:p});c.push(t.code),c.push(o.code),c.push(`ctx.__lastFnCalled = '${p}';`),m=`ctx['${p}'](${t.id}, ${o.id})`;break}case"UNKNOWN":if(!t)return{id:"undefined",code:""};d=a++,m="undefined"}if(t){return{id:`_${d}`,code:`const _${d} = () => {\n\t${Pu(c).join("\n\t")}\n\treturn ${m};\n}`}}return c.push(`let _${d} = ${m};`),{id:`_${d}`,code:c.join("\n")}}Lu[n]={execute:d}}return{execute:Lu[n].execute,dependencies:o,constantValues:i,tokens:t}}function Vu(e){return function(e){let t=[],o="";return e.map(((e,i)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(o=""),e.type){case"FUNCTION":o=e.value;break;case"LEFT_PAREN":t.push({parent:o,argPosition:0}),o="";break;case"RIGHT_PAREN":t.pop();break;case"COMMA":t.length&&t[t.length-1].argPosition++}if(t.length){const o=t[t.length-1];o.parent&&(e.functionContext=Object.assign({},o))}return e}))}(function(e){let t=1;const o=[];return e.map((e=>("LEFT_PAREN"===e.type?(o.push(t),e.parenIndex=t,t++):"RIGHT_PAREN"===e.type&&(e.parenIndex=o.pop()),e)))}(function(e){let t=0;return e.map((e=>{const o=e.value.toString().length,i=Object.assign({},e,{start:t,end:t+o,length:o});return t=i.end,i}))}(Fu(e))))}function zu(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:o}=Nt(e.value),[i,n]=t.split(":"),r=o?`${_e(o)}!`:"",s=Bu(i),a=n?`:${Bu(n)}`:"";return{...e,value:r+s+a}}function Bu(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=Hu(e,"colrow");break;case"colrow":e=Hu(e,"row");break;case"row":e=Hu(e,"col");break;case"col":e=Hu(e,"none")}return e}function Hu(e,t){let o;switch(e=e.replace(/\$/g,""),t){case"col":return"$"+e;case"row":return o=e.search(/[0-9]/),e.slice(0,o)+"$"+e.slice(o);case"colrow":return o=e.search(/[0-9]/),"$"+(e=e.slice(0,o)+"$"+e.slice(o));case"none":return e}}class Wu{constructor(e,t){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t}exportForExcel(e){}allowDispatch(e){return 0}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map((e=>e.call(this,t))).flat()}chainValidations(...e){return t=>{for(const o of e){let e=o.call(this,t);Array.isArray(e)||(e=[e]);const i=e.filter((e=>0!==e));if(i.length)return i}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}Wu.getters=[];class Gu extends Wu{constructor({getters:e,stateObserver:t,dispatch:o,uiActions:i,selection:n}){super(t,o),this.getters=e,this.ui=i,this.selection=n}drawGrid(e,t){}}Gu.layers=[];const qu=r("The cell you are trying to edit has been deleted.");class Zu extends Gu{constructor(){super(...arguments),this.col=0,this.row=0,this.mode="inactive",this.sheetId="",this.currentContent="",this.currentTokens=[],this.selectionStart=0,this.selectionEnd=0,this.selectionInitialStart=0,this.initialContent="",this.previousRef="",this.previousRange=void 0,this.colorIndexByRange={}}allowDispatch(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":return this.validateSelection(this.currentContent.length,e.start,e.end);case"SET_CURRENT_CONTENT":return e.selection?this.validateSelection(e.content.length,e.selection.start,e.selection.end):0;case"START_EDITION":if(e.selection){const t=e.text||this.getComposerContent(this.getters.getActivePosition());return this.validateSelection(t.length,e.selection.start,e.selection.end)}return 0;default:return 0}}handleEvent(e){if("selecting"===this.mode)if("newAnchor"===e.mode)this.insertSelectedRange(e.anchor.zone);else this.replaceSelectedRanges(e.anchor.zone)}handle(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":this.selectionStart=e.start,this.selectionEnd=e.end;break;case"STOP_COMPOSER_RANGE_SELECTION":this.isSelectingForComposer()&&(this.mode="editing");break;case"START_EDITION":this.startEdition(e.text,e.selection),this.updateRangeColor();break;case"STOP_EDITION":e.cancel?(this.cancelEditionAndActivateSheet(),this.resetContent()):this.stopEdition(),this.colorIndexByRange={};break;case"SET_CURRENT_CONTENT":this.setContent(e.content,e.selection,!0),this.updateRangeColor();break;case"REPLACE_COMPOSER_CURSOR_SELECTION":this.replaceSelection(e.text);break;case"SELECT_FIGURE":this.cancelEditionAndActivateSheet(),this.resetContent();break;case"ADD_COLUMNS_ROWS":this.onAddElements(e);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case"START_CHANGE_HIGHLIGHT":this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const t=this.getters.getRangeFromRangeData(e.range),o=this.currentTokens.filter((e=>"REFERENCE"===e.type)).find((e=>{const{xc:o,sheetName:i}=Nt(e.value),n=i||this.getters.getSheetName(this.sheetId),r=this.getters.getActiveSheetId();if(this.getters.getSheetName(r)!==n)return!1;const s=this.getters.getRangeFromSheetXC(r,o);return Lo(this.getters.expandZone(r,s.zone),t.zone)}));this.previousRef=o.value,this.previousRange=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),this.previousRef),this.selectionInitialStart=o.start;break;case"CHANGE_HIGHLIGHT":const i=this.getters.getRangeFromRangeData(e.range),n=this.getRangeReference(i,this.previousRange.parts);this.selectionStart=this.selectionInitialStart,this.selectionEnd=this.selectionInitialStart+this.previousRef.length,this.replaceSelection(n),this.previousRef=n,this.selectionStart=this.currentContent.length,this.selectionEnd=this.currentContent.length;break;case"ACTIVATE_SHEET":if(this.currentContent.startsWith("=")||(this.cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){const t=this.getters.getActivePosition(),{col:o,row:i}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),n=this.getters.expandZone(e.sheetIdTo,Yo({col:o,row:i}));this.selection.resetAnchor(this,{cell:{col:o,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.cancelEditionAndActivateSheet(),this.resetContent(),this.ui.notifyUI({type:"ERROR",text:qu}));break;case"CYCLE_EDITION_REFERENCES":this.cycleReferences()}}unsubscribe(){this.mode="inactive"}getEditionMode(){return this.mode}getCurrentContent(){return"inactive"===this.mode?this.getComposerContent(this.getters.getActivePosition()):this.currentContent}getEditionSheet(){return this.sheetId}getComposerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}isSelectingForComposer(){return"selecting"===this.mode}showSelectionIndicator(){return this.isSelectingForComposer()&&this.canStartComposerRangeSelection()}getCurrentTokens(){return this.currentTokens}getTokenAtCursor(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return e===t&&0===t?void 0:this.currentTokens.find((o=>o.start<=e&&o.end>=t))}cycleReferences(){const e=this.getTokensInSelection(),t=e.filter((e=>"REFERENCE"===e.type));if(0===t.length)return;const o=e.map(zu).map((e=>e.value)).join(""),i=this.currentContent,n=e[0].start,r=e[e.length-1].end,s=i.slice(0,n)+o+i.slice(r),a=s.length-i.length,l={start:t[0].start,end:t[t.length-1].end+a};1===t.length&&this.selectionStart===this.selectionEnd&&(l.start=l.end),this.dispatch("SET_CURRENT_CONTENT",{content:s,selection:l})}validateSelection(e,t,o){return t>=0&&t<=e&&o>=0&&o<=e?0:46}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:qu});const{top:t,left:o}=Do({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",[...e.elements]);this.col=o,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:qu});const{top:t,left:o}=Do({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",[...e.elements]);this.col=o,this.row=t}onAddElements(e){const{top:t,left:o}=Fo({left:this.col,right:this.col,top:this.row,bottom:this.row},"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.col=o,this.row=t}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){const e=Yo({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 o;const i=this.getters.getActiveCell();e&&(null===(o=i.format)||void 0===o?void 0:o.includes("%"))&&qt(e)&&(t=t||{start:e.length,end:e.length},e=`${e}%`);const n=this.getters.getActiveSheetId(),{col:r,row:s}=this.getters.getActivePosition();this.col=r,this.sheetId=n,this.row=s,this.initialContent=this.getComposerContent({sheetId:n,col:r,row:s}),this.mode="editing",this.setContent(e||this.initialContent,t),this.colorIndexByRange={};const a=Yo({col:this.col,row:this.row});this.selection.capture(this,{cell:{col:this.col,row:this.row},zone:a},{handleEvent:this.handleEvent.bind(this),release:()=>{this.stopEdition()}})}stopEdition(){if("inactive"!==this.mode){this.cancelEditionAndActivateSheet();const e=this.col,t=this.row;let o=this.currentContent;if(!(this.initialContent!==o))return;if(o){const i=this.getters.getActiveSheetId(),n=this.getters.getEvaluatedCell({sheetId:i,col:this.col,row:this.row});if(o.startsWith("=")){const e=this.currentTokens.filter((e=>"LEFT_PAREN"===e.type)).length,t=this.currentTokens.filter((e=>"RIGHT_PAREN"===e.type)).length,i=e-t;i>0&&(o+=tt(new Array(i).fill(")")))}else n.link&&(o=qe(o,n.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,col:e,row:t,content:o})}else this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,content:"",col:e,row:t});this.setContent("")}}cancelEditionAndActivateSheet(){if("inactive"===this.mode)return;this.cancelEdition();this.getters.getActiveSheetId()!==this.sheetId&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}getComposerContent(e){const t=this.getters.getCell(e);if(null==t?void 0:t.isFormula)return t.content;const{format:o,value:i,type:n,formattedValue:r}=this.getters.getEvaluatedCell(e);switch(n){case mi.text:case mi.empty:return i;case mi.boolean:return r;case mi.error:return(null==t?void 0:t.content)||"";case mi.number:return o&&ho(o)?r:this.numberComposerContent(i,o)}}numberComposerContent(e,t){return(null==t?void 0:t.includes("%"))?100*e+"%":function(e){const{integerDigits:t,decimalDigits:o}=ao(e,20);return o?`${t}.${o}`:t}(e)}cancelEdition(){"inactive"!==this.mode&&(this.mode="inactive",this.selection.release(this))}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,o){e=e.replace(/[\r\n]/g,"");const i=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(i||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?Vu(e):[],this.currentTokens.length>100&&o&&this.ui.notifyUI({type:"ERROR",text:r("This formula has over 100 parts. It can't be processed properly, consider splitting it into multiple cells")})),this.canStartComposerRangeSelection()&&this.startComposerRangeSelection()}insertSelectedRange(e){const t=Math.min(this.selectionStart,this.selectionEnd),o=this.getZoneReference(e);this.canStartComposerRangeSelection()?(this.insertText(o,t),this.selectionInitialStart=t):(this.insertText(","+o,t),this.selectionInitialStart=t+1)}replaceSelectedRanges(e){const t=this.getZoneReference(e);this.replaceText(t,this.selectionInitialStart,this.selectionEnd)}getZoneReference(e,t=[{colFixed:!1,rowFixed:!1}]){const o=this.getters.getActiveSheetId();let i=this.getters.zoneToXC(o,e,t);if(this.getters.getEditionSheet()!==this.getters.getActiveSheetId()){i=`${_e(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${i}`}return i}getRangeReference(e,t=[{colFixed:!1,rowFixed:!1}]){let o=[...t];1===t.length&&Qo(e.zone)>1?o.push({...t[0]}):2===t.length&&1===Qo(e.zone)&&o.pop();const i=e.clone({parts:o});return this.getters.getSelectionRangeString(i,this.getters.getEditionSheet())}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),o=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,o)}replaceText(e,t,o){this.currentContent=this.currentContent.slice(0,t)+this.currentContent.slice(o,this.currentContent.length),this.insertText(e,t)}insertText(e,t){const o=this.currentContent.slice(0,t)+e+this.currentContent.slice(t),i=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:o,selection:{start:i,end:i}})}updateRangeColor(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return;const e=this.getters.getEditionSheet(),t=this.getReferencedRanges().map((t=>this.getters.getRangeString(t,e))),o={};for(const e of t)void 0!==this.colorIndexByRange[e]&&(o[e]=this.colorIndexByRange[e]);const i=new Set(Object.values(o));let n=0;const r=()=>{for(;i.has(n);)n++;return i.add(n),n};for(const e of t){const t=e in o?o[e]:r();o[e]=t}this.colorIndexByRange=o}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=this.getters.getEditionSheet(),t=e=>{const t=this.colorIndexByRange[e];return ht[t%ht.length]};return this.getReferencedRanges().map((o=>{const i=this.getters.getRangeString(o,e);return{zone:o.zone,color:t(i),sheetId:o.sheetId}}))}getReferencedRanges(){const e=this.getters.getEditionSheet();return this.currentTokens.filter((e=>"REFERENCE"===e.type)).map((t=>this.getters.getRangeFromSheetXC(e,t.value)))}canStartComposerRangeSelection(){if(this.currentContent.startsWith("=")){const e=this.getTokenAtCursor();if(!e)return!1;const t=this.currentTokens.map((e=>e.start)).indexOf(e.start);let o=t,i=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(i.type)||Qd.includes(i.value);){if("SPACE"!==i.type||o<1)return!1;o--,i=this.currentTokens[o]}for(o=t+1,i=this.currentTokens[o];i&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(i.type);){if("SPACE"!==i.type)return!1;o++,i=this.currentTokens[o]}return!0}return!1}getTokensInSelection(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return this.currentTokens.filter((o=>o.start<=e&&o.end>=e||o.start>=e&&o.start<t))}}Zu.getters=["getEditionMode","isSelectingForComposer","showSelectionIndicator","getCurrentContent","getEditionSheet","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights"];const ju={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function Xu(e,t){const o=ju[e.key];e.shiftKey?t.resizeAnchorZone(o,e.ctrlKey?"end":1):t.moveAnchorCell(o,e.ctrlKey?"end":1)}ii`
158
+ `;class Ur extends t.Component{get tagStyle(){const{col:e,row:t,color:o}=this.props,{height:i}=this.env.model.getters.getSheetViewDimensionWithHeaders(),{x:n,y:r}=this.env.model.getters.getVisibleRect({left:e,top:t,right:e,bottom:t});return`bottom: ${i-r+15}px;left: ${n-1}px;border: 1px solid ${o};background-color: ${o};${this.props.active?"opacity:1 !important":""}`}}Ur.template="o-spreadsheet-ClientTag",Ur.props={active:Boolean,name:String,color:String,col:Number,row:Number};const Vr=/(.*?)\((.*?)\)(.*)/,zr=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function Br(e){let t=e.split("\n");const o=[];for(let e of t)e=e.trim(),e&&o.push(Hr(e));return o}function Hr(e){let t,o=e.match(Vr),i=o[1].trim(),n=[],r=!1,s=!1,a=!1;for(let e of o[2].split(",")){const o=e.trim().toUpperCase();let i=zr.find((e=>o===e));i?n.push(i):"RANGE<ANY>"===o?n.push("RANGE"):"OPTIONAL"===o?r=!0:"REPEATING"===o?s=!0:"LAZY"===o?a=!0:o.startsWith("DEFAULT=")&&(t=e.trim().slice(8))}const l={name:i,description:o[3].trim(),type:n};return r&&(l.optional=!0),s&&(l.repeating=!0),a&&(l.lazy=!0),void 0!==t&&(l.default=!0,l.defaultValue=t),l}function Wr(e){let t=0,o=0,i=0;for(let n of e.args)t++,n.optional||n.repeating||n.default||o++,n.repeating&&i++;const n=e;return n.minArgRequired=o,n.maxArgPossible=i?1/0:t,n.nbrArgRepeating=i,n.getArgToFocus=function(e,t){if(!t)return e=>e;if(1===t)return t=>Math.min(t,e);const o=e-t;return e=>{if(e<=o)return e;return o+((e-o)%t||t)}}(t,i),n}const Gr=["number","string","boolean","undefined"];function qr(e,t){if(!e())throw new Error(t)}const Zr=e=>r("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function jr(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(Zt(e)||""===e)return Xt(e);const t=be(e);if(t)return t.value;throw new Error(Zr(e));default:return 0}}function Xr(e){if(""===e)throw new Error(Zr(e));return jr(e)}function Yr(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}function Kr(e){return"string"==typeof e?e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):e}const Qr=e=>r("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function Jr(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(Qr(e))}return!1;case"number":return!!e;default:return!1}}function es(e){return Se(jr(e))}function ts(e,t,o){for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let n=0;n<o;n++)for(let o=0;o<e;o++)t(i[o][n])}else o(i)}function os(e,t){ts(e,t,t)}function is(e,t){ts(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(Xr(e))}))}function ns(e,t,o,i){let n=i;for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let r=0;r<o;r++)for(let o=0;o<e;o++)n=t(n,i[o][r])}else n=o(n,i);return n}function rs(e,t,o){return ns(e,t,t,o)}function ss(e,t,o){return ns(e,((e,o)=>"number"==typeof o?t(e,o):e),((e,o)=>t(e,Xr(o))),o)}function as(e,t,o){return ns(e,((e,o)=>null!=o?t(e,"number"==typeof o?o:"boolean"==typeof o?jr(o):0):e),((e,o)=>t(e,jr(o))),o)}function ls(e,t){return function(e,t,o){for(let i of e)if(Array.isArray(i)){const e=i.length,o=i[0].length;for(let n=0;n<o;n++)for(let o=0;o<e;o++)if(!t(i[o][n]))return}else if(!o(i))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error(Qr(e));return Jr(e)}(e))))}function cs(e,t){let o,i,n=e.substring(0,2);"<="===n||">="===n||"<>"===n?(o=n,i=e.substring(2)):(n=e.substring(0,1),"<"===n||">"===n||"="===n?(o=n,i=e.substring(1)):(o="=",i=e)),Zt(i)?i=jr(i):"TRUE"!==i&&"FALSE"!==i||(i=Jr(i));const r={operator:o,operand:i};return"string"==typeof i&&(t&&(i+="*"),r.regexp=function(e){let t="",o="";for(let i of e)"?"===i&&"~"!==o?t+=".":"*"===i&&"~"!==o?t+=".*":("*"!==i&&"?"!==i||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(i)&&(t+="\\"),t+=i),o=i;return new RegExp("^"+t+"$","i")}(i)),r}function hs(e,t){const{operator:o,operand:i}=t;if(void 0===e||void 0===i)return!1;if("number"==typeof i&&"="===o)return Yr(e)===Yr(i);if("<>"===o||"="===o){let n;return n=typeof e==typeof i&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===i),"="===o?n:!n}if(typeof e==typeof i)switch(o){case"<":return e<i;case">":return e>i;case"<=":return e<=i;case">=":return e>=i}return!1}function ds(e,t,o=!1){const i=e.length;if(i%2==1)throw new Error(r("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const n=e[0].length,s=e[0][0].length;let a=[];for(let t=0;t<i-1;t+=2){const i=e[t];if(!Array.isArray(i)||i.length!==n||i[0].length!==s)throw new Error(r("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=Yr(e[t+1]);a.push(cs(l,o))}for(let o=0;o<n;o++)for(let n=0;n<s;n++){let r=!0;for(let t=0;t<i-1;t+=2){if(r=hs(e[t][o][n],a[t/2]),!r)break}r&&t(o,n)}}function us(e,t){return Kr(e[0][t])}function gs(e,t){return Kr(e[t][0])}function ps(e,t,o,i,n,r){if(null==t)return-1;const s=typeof t;let a,l,c,h,d,u,g=0,p=n-1;for(;p-g>=0;){for(c=Math.floor((g+p)/2),h=c,d=r(e,h),u=typeof d;g<h&&s!==u;)h--,d=r(e,h),u=typeof d;u===s&&void 0!==d?("strict"===o&&d===t?(a=d,l=h):"nextSmaller"===o&&d<=t?(void 0===a||a<d||a===d&&"asc"===i&&l<h||a===d&&"desc"===i&&l>h)&&(a=d,l=h):"nextGreater"===o&&d>=t&&(void 0===a||a>d||a===d&&"asc"===i&&l<h||a===d&&"desc"===i&&l>h)&&(a=d,l=h),"asc"===i&&d>t||"desc"===i&&d<=t?p=h-1:g=c+1):g=c+1}return void 0!==l?l:-1}function ms(e,t,o,i,n,r=!1){if(null==t)return-1;const s=r?(e,t)=>n(e,i-t-1):n;let a,l=-1;for(let n=0;n<i;n++){const c=s(e,n);if(c===t)return r?i-n-1:n;"nextSmaller"===o?(!a&&fs(t,c)>=0||fs(t,c)>=0&&fs(c,a)>0)&&(a=c,l=n):"nextGreater"===o&&(!a&&fs(t,c)<=0||fs(t,c)<=0&&fs(c,a)<0)&&(a=c,l=n)}return r?i-l-1:l}function fs(e,t){let o=Gr.indexOf(typeof e)-Gr.indexOf(typeof t);return 0===o&&("string"==typeof e&&"string"==typeof t?o=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?o=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(o=Number(e)-Number(t))),o}const vs={description:r("Apply a large number format"),args:Br(`\n value (number) ${r("The number.")}\n unit (string, optional) ${r("The formatting unit. Use 'k', 'm', or 'b' to force the unit")}\n `),returns:["NUMBER"],computeFormat:(e,t)=>{const o=Math.abs(jr(e.value)),i=e.format;if(void 0!==t){switch(null==t?void 0:t.value){case"k":return bo(i,1e3,"k");case"m":return bo(i,1e6,"m");case"b":return bo(i,1e9,"b");default:throw new Error(r("The formatting unit should be 'k', 'm' or 'b'."))}}return o<1e5?bo(i,0,""):o<1e8?bo(i,1e3,"k"):o<1e11?bo(i,1e6,"m"):bo(i,1e9,"b")},compute:function(e){return jr(e)}};var bs=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:vs});const Cs={description:r("Absolute value of a number."),args:Br(`\n value (number) ${r("The number of which to return the absolute value.")}\n `),returns:["NUMBER"],compute:function(e){return Math.abs(jr(e))},isExported:!0},Ss={description:r("Inverse cosine of a value, in radians."),args:Br(`\n value (number) ${r("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=jr(e);return qr((()=>Math.abs(t)<=1),r("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},Es={description:r("Inverse hyperbolic cosine of a number."),args:Br(`\n value (number) ${r("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=jr(e);return qr((()=>t>=1),r("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},ws={description:r("Inverse cotangent of a value."),args:Br(`\n value (number) ${r("The value for which to calculate the inverse cotangent.")}\n `),returns:["NUMBER"],compute:function(e){const t=jr(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},ys={description:r("Inverse hyperbolic cotangent of a value."),args:Br(`\n value (number) ${r("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=jr(e);return qr((()=>Math.abs(t)>1),r("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},xs={description:r("Inverse sine of a value, in radians."),args:Br(`\n value (number) ${r("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.")}\n `),returns:["NUMBER"],compute:function(e){const t=jr(e);return qr((()=>Math.abs(t)<=1),r("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},Is={description:r("Inverse hyperbolic sine of a number."),args:Br(`\n value (number) ${r("The value for which to calculate the inverse hyperbolic sine.")}\n `),returns:["NUMBER"],compute:function(e){return Math.asinh(jr(e))},isExported:!0},Rs={description:r("Inverse tangent of a value, in radians."),args:Br(`\n value (number) ${r("The value for which to calculate the inverse tangent.")}\n `),returns:["NUMBER"],compute:function(e){return Math.atan(jr(e))},isExported:!0},Ts={description:r("Angle from the X axis to a point (x,y), in radians."),args:Br(`\n x (number) ${r("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")}\n y (number) ${r("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 o=jr(e),i=jr(t);return qr((()=>0!==o||0!==i),r("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(i,o)},isExported:!0},As={description:r("Inverse hyperbolic tangent of a number."),args:Br(`\n value (number) ${r("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=jr(e);return qr((()=>Math.abs(t)<1),r("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},Os={description:r("Rounds number up to nearest multiple of factor."),args:Br(`\n value (number) ${r("The value to round up to the nearest integer multiple of factor.")}\n factor (number, default=1) ${r("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 o=jr(e),i=jr(t);return qr((()=>i>=0||o<=0),r("The factor (%s) must be positive when the value (%s) is positive.",i.toString(),o.toString())),i?Math.ceil(o/i)*i:0},isExported:!0},Ms={description:r("Rounds number up to nearest multiple of factor."),args:Br(`\n number (number) ${r("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${r("The number to whose multiples number will be rounded. The sign of significance will be ignored.")}\n mode (number, default=0) ${r("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1,o=0){let i=jr(t);if(0===i)return 0;const n=jr(e);if(i=Math.abs(i),n>=0)return Math.ceil(n/i)*i;return 0===jr(o)?-Math.floor(Math.abs(n)/i)*i:-Math.ceil(Math.abs(n)/i)*i},isExported:!0},Ns={description:r("Rounds number up to nearest multiple of factor."),args:Br(`\n number (number) ${r("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${r("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 Ms.compute(e,t,0)},isExported:!0},_s={description:r("Cosine of an angle provided in radians."),args:Br(`\n angle (number) ${r("The angle to find the cosine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cos(jr(e))},isExported:!0},Fs={description:r("Hyperbolic cosine of any real number."),args:Br(`\n value (number) ${r("Any real value to calculate the hyperbolic cosine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.cosh(jr(e))},isExported:!0},Ds={description:r("Cotangent of an angle provided in radians."),args:Br(`\n angle (number) ${r("The angle to find the cotangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=jr(e);return qr((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},ks={description:r("Hyperbolic cotangent of any real number."),args:Br(`\n value (number) ${r("Any real value to calculate the hyperbolic cotangent of.")}\n `),returns:["NUMBER"],compute:function(e){const t=jr(e);return qr((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},$s={description:r("Number of empty values."),args:Br(`\n value1 (any, range) ${r("The first value or range in which to count the number of blanks.")}\n value2 (any, range, repeating) ${r("Additional values or ranges in which to count the number of blanks.")}\n `),returns:["NUMBER"],compute:function(...e){return rs(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},Ps={description:r("A conditional count across a range."),args:Br(`\n range (range) ${r("The range that is tested against criterion.")}\n criterion (string) ${r("The pattern or test to apply to range.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;return ds(e,((e,o)=>{t+=1})),t},isExported:!0},Ls={description:r("Count values depending on multiple criteria."),args:Br(`\n criteria_range1 (range) ${r("The range to check against criterion1.")}\n criterion1 (string) ${r("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${r("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${r("Additional criteria to check.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;return ds(e,((e,o)=>{t+=1})),t},isExported:!0};function Us(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const Vs={description:r("Counts number of unique values in a range."),args:Br(`\n value1 (any, range) ${r("The first value or range to consider for uniqueness.")}\n value2 (any, range, repeating) ${r("Additional values or ranges to consider for uniqueness.")}\n `),returns:["NUMBER"],compute:function(...e){return rs(e,((e,t)=>Us(t)?e.add(t):e),new Set).size}},zs={description:r("Counts number of unique values in a range, filtered by a set of criteria."),args:Br(`\n range (range) ${r("The range of cells from which the number of unique values will be counted.")}\n criteria_range1 (range) ${r("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${r("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${r("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${r("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let o=new Set;return ds(t,((t,i)=>{const n=e[t][i];Us(n)&&o.add(n)})),o.size}},Bs={description:r("Cosecant of an angle provided in radians."),args:Br(`\n angle (number) ${r("The angle to find the cosecant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){const t=jr(e);return qr((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},Hs={description:r("Hyperbolic cosecant of any real number."),args:Br(`\n value (number) ${r("Any real value to calculate the hyperbolic cosecant of.")}\n `),returns:["NUMBER"],compute:function(e){const t=jr(e);return qr((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},Ws={description:r("Converts from another base to decimal."),args:Br(`\n value (string) ${r("The number to convert.")},\n base (number) ${r("The base to convert the value from.")},\n `),returns:["NUMBER"],compute:function(e,t){let o=jr(t);o=Math.floor(o),qr((()=>2<=o&&o<=36),r("The base (%s) must be between 2 and 36 inclusive.",o.toString()));const i=Yr(e);if(""===i)return 0;qr((()=>!!i.match(/^-?[a-z0-9]+$/i)),r("The value (%s) must be a valid base %s representation.",i,o.toString()));const n=parseInt(i,o);return qr((()=>!isNaN(n)),r("The value (%s) must be a valid base %s representation.",i,o.toString())),n},isExported:!0},Gs={description:r("Converts an angle value in radians to degrees."),args:Br(`\n angle (number) ${r("The angle to convert from radians to degrees.")}\n `),returns:["NUMBER"],compute:function(e){return 180*jr(e)/Math.PI},isExported:!0},qs={description:r("Euler's number, e (~2.718) raised to a power."),args:Br(`\n value (number) ${r("The exponent to raise e.")}\n `),returns:["NUMBER"],compute:function(e){return Math.exp(jr(e))},isExported:!0},Zs={description:r("Rounds number down to nearest multiple of factor."),args:Br(`\n value (number) ${r("The value to round down to the nearest integer multiple of factor.")}\n factor (number, default=1) ${r("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 o=jr(e),i=jr(t);return qr((()=>i>=0||o<=0),r("The factor (%s) must be positive when the value (%s) is positive.",i.toString(),o.toString())),i?Math.floor(o/i)*i:0},isExported:!0},js={description:r("Rounds number down to nearest multiple of factor."),args:Br(`\n number (number) ${r("The value to round down to the nearest integer multiple of significance.")}\n significance (number, default=1) ${r("The number to whose multiples number will be rounded. The sign of significance will be ignored.")}\n mode (number, default=0) ${r("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1,o=0){let i=jr(t);if(0===i)return 0;const n=jr(e);if(i=Math.abs(i),n>=0)return Math.floor(n/i)*i;return 0===jr(o)?-Math.ceil(Math.abs(n)/i)*i:-Math.floor(Math.abs(n)/i)*i},isExported:!0},Xs={description:r("Rounds number down to nearest multiple of factor."),args:Br(`\n number (number) ${r("The value to round down to the nearest integer multiple of significance.")}\n significance (number, default=1) ${r("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 js.compute(e,t,0)},isExported:!0},Ys={description:r("Whether the provided value is even."),args:Br(`\n value (number) ${r("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=Xr(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},Ks={description:r("Rounds number up to nearest multiple of factor."),args:Br(`\n number (number) ${r("The value to round up to the nearest integer multiple of significance.")}\n significance (number, default=1) ${r("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 Ms.compute(e,t,0)},isExported:!0},Qs={description:r("Whether the provided value is even."),args:Br(`\n value (number) ${r("The value to be verified as even.")}\n `),returns:["BOOLEAN"],compute:function(e){const t=Xr(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},Js={description:r("The logarithm of a number, base e (euler's number)."),args:Br(`\n value (number) ${r("The value for which to calculate the logarithm, base e.")}\n `),returns:["NUMBER"],compute:function(e){const t=jr(e);return qr((()=>t>0),r("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},ea={description:r("Modulo (remainder) operator."),args:Br(`\n dividend (number) ${r("The number to be divided to find the remainder.")}\n divisor (number) ${r("The number to divide by.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){const o=jr(t);qr((()=>0!==o),r("The divisor must be different from 0."));const i=jr(e)%o;return i>0&&o<0||i<0&&o>0?i+o:i},isExported:!0},ta={description:r("Rounds a number up to the nearest odd integer."),args:Br(`\n value (number) ${r("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=jr(e);let o=Math.ceil(Math.abs(t));return o=1&o?o:o+1,t<0?-o:o},isExported:!0},oa={description:r("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},ia={description:r("A number raised to a power."),args:Br(`\n base (number) ${r("The number to raise to the exponent power.")}\n exponent (number) ${r("The exponent to raise base to.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){const o=jr(e),i=jr(t);return qr((()=>o>=0||Number.isInteger(i)),r("The exponent (%s) must be an integer when the base is negative.",i.toString())),Math.pow(o,i)},isExported:!0},na={description:r("Result of multiplying a series of numbers together."),args:Br(`\n factor1 (number, range<number>) ${r("The first number or range to calculate for the product.")}\n factor2 (number, range<number>, repeating) ${r("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,o=1;for(let i of e)if(Array.isArray(i))for(let e of i)for(let i of e)"number"==typeof i&&(o*=i,t+=1);else null!=i&&(o*=Xr(i),t+=1);return 0===t?0:o},isExported:!0},ra={description:r("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},sa={description:r("Random integer between two values, inclusive."),args:Br(`\n low (number) ${r("The low end of the random range.")}\n high (number) ${r("The high end of the random range.")}\n `),returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){let o=jr(e);Number.isInteger(o)||(o=Math.ceil(o));let i=jr(t);return Number.isInteger(i)||(i=Math.floor(i)),qr((()=>o<=i),r("The high (%s) must be greater than or equal to the low (%s).",i.toString(),o.toString())),o+Math.ceil((i-o+1)*Math.random())-1},isExported:!0},aa={description:r("Rounds a number according to standard rules."),args:Br(`\n value (number) ${r("The value to round to places number of places.")}\n places (number, default=0) ${r("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 o=jr(e);let i=jr(t);const n=Math.abs(o);let r;return 0===i?r=Math.round(n):(Number.isInteger(i)||(i=Math.trunc(i)),r=Math.round(n*Math.pow(10,i))/Math.pow(10,i)),o>=0?r:-r},isExported:!0},la={description:r("Rounds down a number."),args:Br(`\n value (number) ${r("The value to round to places number of places, always rounding down.")}\n places (number, default=0) ${r("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 o=jr(e);let i=jr(t);const n=Math.abs(o);let r;return 0===i?r=Math.floor(n):(Number.isInteger(i)||(i=Math.trunc(i)),r=Math.floor(n*Math.pow(10,i))/Math.pow(10,i)),o>=0?r:-r},isExported:!0},ca={description:r("Rounds up a number."),args:Br(`\n value (number) ${r("The value to round to places number of places, always rounding up.")}\n places (number, default=0) ${r("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 o=jr(e);let i=jr(t);const n=Math.abs(o);let r;return 0===i?r=Math.ceil(n):(Number.isInteger(i)||(i=Math.trunc(i)),r=Math.ceil(n*Math.pow(10,i))/Math.pow(10,i)),o>=0?r:-r},isExported:!0},ha={description:r("Secant of an angle provided in radians."),args:Br(`\n angle (number) ${r("The angle to find the secant of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cos(jr(e))},isExported:!0},da={description:r("Hyperbolic secant of any real number."),args:Br(`\n value (number) ${r("Any real value to calculate the hyperbolic secant of.")}\n `),returns:["NUMBER"],compute:function(e){return 1/Math.cosh(jr(e))},isExported:!0},ua={description:r("Sine of an angle provided in radians."),args:Br(`\n angle (number) ${r("The angle to find the sine of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sin(jr(e))},isExported:!0},ga={description:r("Hyperbolic sine of any real number."),args:Br(`\n value (number) ${r("Any real value to calculate the hyperbolic sine of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.sinh(jr(e))},isExported:!0},pa={description:r("Positive square root of a positive number."),args:Br(`\n value (number) ${r("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=jr(e);return qr((()=>t>=0),r("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},ma={description:r("Sum of a series of numbers and/or cells."),args:Br(`\n value1 (number, range<number>) ${r("The first number or range to add together.")}\n value2 (number, range<number>, repeating) ${r("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 ss(e,((e,t)=>e+t),0)},isExported:!0},fa={description:r("A conditional sum across a range."),args:Br(`\n criteria_range (range) ${r("The range which is tested against criterion.")}\n criterion (string) ${r("The pattern or test to apply to range.")}\n sum_range (range, default=criteria_range) ${r("The range to be summed, if different from range.")}\n `),returns:["NUMBER"],compute:function(e,t,o){void 0===o&&(o=e);let i=0;return ds([e,t],((e,t)=>{const n=o[e][t];"number"==typeof n&&(i+=n)})),i},isExported:!0},va={description:r("Sums a range depending on multiple criteria."),args:Br(`\n sum_range (range) ${r("The range to sum.")}\n criteria_range1 (range) ${r("The range to check against criterion1.")}\n criterion1 (string) ${r("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${r("Additional ranges to check.")}\n criterion2 (string, repeating) ${r("Additional criteria to check.")}\n `),returns:["NUMBER"],compute:function(e,...t){let o=0;return ds(t,((t,i)=>{const n=e[t][i];"number"==typeof n&&(o+=n)})),o},isExported:!0},ba={description:r("Tangent of an angle provided in radians."),args:Br(`\n angle (number) ${r("The angle to find the tangent of, in radians.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tan(jr(e))},isExported:!0},Ca={description:r("Hyperbolic tangent of any real number."),args:Br(`\n value (number) ${r("Any real value to calculate the hyperbolic tangent of.")}\n `),returns:["NUMBER"],compute:function(e){return Math.tanh(jr(e))},isExported:!0},Sa={description:r("Truncates a number."),args:Br(`\n value (number) ${r("The value to be truncated.")}\n places (number, default=0) ${r("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 o=jr(e);let i=jr(t);return 0===i?Math.trunc(o):(Number.isInteger(i)||(i=Math.trunc(i)),Math.trunc(o*Math.pow(10,i))/Math.pow(10,i))},isExported:!0};var Ea=Object.freeze({__proto__:null,ABS:Cs,ACOS:Ss,ACOSH:Es,ACOT:ws,ACOTH:ys,ASIN:xs,ASINH:Is,ATAN:Rs,ATAN2:Ts,ATANH:As,CEILING:Os,CEILING_MATH:Ms,CEILING_PRECISE:Ns,COS:_s,COSH:Fs,COT:Ds,COTH:ks,COUNTBLANK:$s,COUNTIF:Ps,COUNTIFS:Ls,COUNTUNIQUE:Vs,COUNTUNIQUEIFS:zs,CSC:Bs,CSCH:Hs,DECIMAL:Ws,DEGREES:Gs,EXP:qs,FLOOR:Zs,FLOOR_MATH:js,FLOOR_PRECISE:Xs,ISEVEN:Ys,ISO_CEILING:Ks,ISODD:Qs,LN:Js,MOD:ea,ODD:ta,PI:oa,POWER:ia,PRODUCT:na,RAND:ra,RANDBETWEEN:sa,ROUND:aa,ROUNDDOWN:la,ROUNDUP:ca,SEC:ha,SECH:da,SIN:ua,SINH:ga,SQRT:pa,SUM:ma,SUMIF:fa,SUMIFS:va,TAN:ba,TANH:Ca,TRUNC:Sa});function wa(e,t,o){let i=[],n=[],s=0,a=0;os([e],(e=>{i.push(e),s+=1})),os([t],(e=>{n.push(e),a+=1})),qr((()=>s===a),r("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",s.toString(),a.toString()));let l=0,c=0,h=0;for(let e=0;e<s;e++){const t=i[e],o=n[e];"number"==typeof t&&"number"==typeof o&&(l+=1,c+=t,h+=o)}qr((()=>0!==l&&(!o||1!==l)),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const d=c/l,u=h/l;let g=0;for(let e=0;e<s;e++){const t=i[e],o=n[e];"number"==typeof t&&"number"==typeof o&&(g+=(t-d)*(o-u))}return g/(l-(o?1:0))}function ya(e,t,o){let i=0,n=0;const s=o?as:ss;n=s(e,((e,t)=>(i+=1,e+t)),0),qr((()=>0!==i&&(!t||1!==i)),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const a=n/i;return s(e,((e,t)=>e+Math.pow(t-a,2)),0)/(i-(t?1:0))}function xa(e,t,o){const i=jr(t);qr((()=>o?0<=i&&i<=1:0<i&&i<1),r("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let n,s=[],a=0;return os(e,(e=>{"number"==typeof e&&(n=ps(s,e,"nextSmaller","asc",s.length,((e,t)=>e[t])),s.splice(n+1,0,e),a++)})),qr((()=>0!==a),r("[[FUNCTION_NAME]] has no valid input data.")),o||qr((()=>1/(a+1)<=i&&i<=a/(a+1)),r("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),Yt(s,i,o)}const Ia={description:r("Average magnitude of deviations from mean."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;const o=ss(e,((e,o)=>(t+=1,e+o)),0);qr((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const i=o/t;return ss(e,((e,t)=>e+Math.abs(i-t)),0)/t},isExported:!0},Ra={description:r("Numerical average value in a dataset, ignoring text."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range to consider when calculating the average value.")}\n value2 (number, range<number>, repeating) ${r("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 o=ss(e,((e,o)=>(t+=1,e+o)),0);return qr((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/t},isExported:!0},Ta=r("[[FUNCTION_NAME]] has mismatched range sizes."),Aa=r("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),Oa={description:r("Weighted average."),args:Br(`\n values (number, range<number>) ${r("Values to average.")}\n weights (number, range<number>) ${r("Weights for each corresponding value.")}\n additional_values (number, range<number>, repeating) ${r("Additional values to average.")}\n additional_weights (number, range<number>, repeating) ${r("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,o,i=0,n=0;qr((()=>e.length%2==0),r("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let s=0;s<e.length-1;s+=2)if(t=e[s],o=e[s+1],Array.isArray(t)){qr((()=>Array.isArray(o)),Ta);let e=t.length,s=t[0].length;qr((()=>e===o.length&&s===o[0].length),Ta);for(let a=0;a<e;a++)for(let e=0;e<s;e++){let s=t[a][e],l=o[a][e],c="number"==typeof s,h="number"==typeof l;qr((()=>c===h),r("[[FUNCTION_NAME]] expects number values.")),h&&(qr((()=>l>=0),Aa),i+=s*l,n+=l)}}else o=jr(o),t=jr(t),qr((()=>o>=0),Aa),i+=t*o,n+=o;return qr((()=>0!==n),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/n}},Ma={description:r("Numerical average value in a dataset."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range to consider when calculating the average value.")}\n value2 (number, range<number>, repeating) ${r("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 o=as(e,((e,o)=>(t+=1,e+o)),0);return qr((()=>0!==t),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/t},isExported:!0},Na={description:r("Average of values depending on criteria."),args:Br(`\n criteria_range (range) ${r("The range to check against criterion.")}\n criterion (string) ${r("The pattern or test to apply to criteria_range.")}\n average_range (range, default=criteria_range) ${r("The range to average. If not included, criteria_range is used for the average instead.")}\n `),returns:["NUMBER"],compute:function(e,t,o){null==o&&(o=e);let i=0,n=0;return ds([e,t],((t,r)=>{const s=(o||e)[t][r];"number"==typeof s&&(i+=1,n+=s)})),qr((()=>0!==i),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),n/i},isExported:!0},_a={description:r("Average of values depending on multiple criteria."),args:Br(`\n average_range (range) ${r("The range to average.")}\n criteria_range1 (range) ${r("The range to check against criterion1.")}\n criterion1 (string) ${r("The pattern or test to apply to criteria_range1.")}\n criteria_range2 (any, range, repeating) ${r("Additional criteria_range and criterion to check.")}\n criterion2 (string, repeating) ${r("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let o=0,i=0;return ds(t,((t,n)=>{const r=e[t][n];"number"==typeof r&&(o+=1,i+=r)})),qr((()=>0!==o),r("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/o},isExported:!0},Fa={description:r("The number of numeric values in dataset."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range to consider when counting.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to consider when counting.")}\n `),returns:["NUMBER"],compute:function(...e){let t=0;for(let o of e)if(Array.isArray(o))for(let e of o)for(let o of e)"number"==typeof o&&(t+=1);else("string"!=typeof o||Zt(o)||be(o))&&(t+=1);return t},isExported:!0},Da={description:r("The number of values in a dataset."),args:Br(`\n value1 (any, range) ${r("The first value or range to consider when counting.")}\n value2 (any, range, repeating) ${r("Additional values or ranges to consider when counting.")}\n `),returns:["NUMBER"],compute:function(...e){return rs(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},ka={description:r("The covariance of a dataset."),args:Br(`\n data_y (any, range) ${r("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${r("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return wa(e,t,!1)},isExported:!0},$a={description:r("The covariance of a dataset."),args:Br(`\n data_y (any, range) ${r("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${r("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return wa(e,t,!1)},isExported:!0},Pa={description:r("The sample covariance of a dataset."),args:Br(`\n data_y (any, range) ${r("The range representing the array or matrix of dependent data.")}\n data_x (any, range) ${r("The range representing the array or matrix of independent data.")}\n `),returns:["NUMBER"],compute:function(e,t){return wa(e,t,!0)},isExported:!0},La={description:r("Nth largest element from a data set."),args:Br(`\n data (any, range) ${r("Array or range containing the dataset to consider.")}\n n (number) ${r("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 o=Math.trunc(jr(t));let i,n=[],s=0;os([e],(e=>{"number"==typeof e&&(i=ps(n,e,"nextSmaller","asc",n.length,((e,t)=>e[t])),n.splice(i+1,0,e),s++,s>o&&(n.shift(),s--))}));const a=n.shift();return qr((()=>void 0!==a),r("[[FUNCTION_NAME]] has no valid input data.")),qr((()=>s>=o),r("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",o.toString())),a},isExported:!0},Ua={description:r("Maximum value in a numeric dataset."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range to consider when calculating the maximum value.")}\n value2 (number, range<number>, repeating) ${r("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=ss(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},Va={description:r("Maximum numeric value in a dataset."),args:Br(`\n value1 (any, range) ${r("The first value or range to consider when calculating the maximum value.")}\n value2 (any, range, repeating) ${r("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=as(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},za={description:r("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:Br(`\n range (range) ${r("The range of cells from which the maximum will be determined.")}\n criteria_range1 (range) ${r("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${r("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${r("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${r("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let o=-1/0;return ds(t,((t,i)=>{const n=e[t][i];"number"==typeof n&&(o=o<n?n:o)})),o===-1/0?0:o},isExported:!0},Ba={description:r("Median value in a numeric dataset."),args:Br(`\n value1 (any, range) ${r("The first value or range to consider when calculating the median value.")}\n value2 (any, range, repeating) ${r("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 is(e,(e=>{t.push(e)})),xa(t,.5,!0)},isExported:!0},Ha={description:r("Minimum value in a numeric dataset."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range to consider when calculating the minimum value.")}\n value2 (number, range<number>, repeating) ${r("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=ss(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},Wa={description:r("Minimum numeric value in a dataset."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range to consider when calculating the minimum value.")}\n value2 (number, range<number>, repeating) ${r("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=as(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},Ga={description:r("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:Br(`\n range (range) ${r("The range of cells from which the minimum will be determined.")}\n criteria_range1 (range) ${r("The range of cells over which to evaluate criterion1.")}\n criterion1 (string) ${r("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")}\n criteria_range2 (any, range, repeating) ${r("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")}\n criterion2 (string, repeating) ${r("The pattern or test to apply to criteria_range2.")}\n `),returns:["NUMBER"],compute:function(e,...t){let o=1/0;return ds(t,((t,i)=>{const n=e[t][i];"number"==typeof n&&(o=o>n?n:o)})),o===1/0?0:o},isExported:!0},qa={description:r("Value at a given percentile of a dataset."),args:Br(`\n data (any, range) ${r("The array or range containing the dataset to consider.")}\n percentile (number) ${r("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 ja.compute(e,t)},isExported:!0},Za={description:r("Value at a given percentile of a dataset exclusive of 0 and 1."),args:Br(`\n data (any, range) ${r("The array or range containing the dataset to consider.")}\n percentile (number) ${r("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 xa([e],t,!1)},isExported:!0},ja={description:r("Value at a given percentile of a dataset."),args:Br(`\n data (any, range) ${r("The array or range containing the dataset to consider.")}\n percentile (number) ${r("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 xa([e],t,!0)},isExported:!0},Xa={description:r("Value nearest to a specific quartile of a dataset."),args:Br(`\n data (any, range) ${r("The array or range containing the dataset to consider.")}\n quartile_number (number) ${r("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 Ka.compute(e,t)},isExported:!0},Ya={description:r("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:Br(`\n data (any, range) ${r("The array or range containing the dataset to consider.")}\n quartile_number (number) ${r("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 xa([e],.25*Math.trunc(jr(t)),!1)},isExported:!0},Ka={description:r("Value nearest to a specific quartile of a dataset."),args:Br(`\n data (any, range) ${r("The array or range containing the dataset to consider.")}\n quartile_number (number) ${r("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 xa([e],.25*Math.trunc(jr(t)),!0)},isExported:!0},Qa={description:r("Nth smallest element in a data set."),args:Br(`\n data (any, range) ${r("The array or range containing the dataset to consider.")}\n n (number) ${r("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 o=Math.trunc(jr(t));let i,n=[],s=0;os([e],(e=>{"number"==typeof e&&(i=ps(n,e,"nextSmaller","asc",n.length,((e,t)=>e[t])),n.splice(i+1,0,e),s++,s>o&&(n.pop(),s--))}));const a=n.pop();return qr((()=>void 0!==a),r("[[FUNCTION_NAME]] has no valid input data.")),qr((()=>s>=o),r("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",o.toString())),a},isExported:!0},Ja={description:r("Standard deviation."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(rl.compute(...e))},isExported:!0},el={description:r("Standard deviation of entire population."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(sl.compute(...e))},isExported:!0},tl={description:r("Standard deviation."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(al.compute(...e))},isExported:!0},ol={description:r("Standard deviation of sample (text as 0)."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(ll.compute(...e))},isExported:!0},il={description:r("Standard deviation of entire population."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(cl.compute(...e))},isExported:!0},nl={description:r("Standard deviation of entire population (text as 0)."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return Math.sqrt(hl.compute(...e))},isExported:!0},rl={description:r("Variance."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return ya(e,!0,!1)},isExported:!0},sl={description:r("Variance of entire population."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return ya(e,!1,!1)},isExported:!0},al={description:r("Variance."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return ya(e,!0,!1)},isExported:!0},ll={description:r("Variance of sample (text as 0)."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range of the sample.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the sample.")}\n `),returns:["NUMBER"],compute:function(...e){return ya(e,!0,!0)},isExported:!0},cl={description:r("Variance of entire population."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return ya(e,!1,!1)},isExported:!0},hl={description:r("Variance of entire population (text as 0)."),args:Br(`\n value1 (number, range<number>) ${r("The first value or range of the population.")}\n value2 (number, range<number>, repeating) ${r("Additional values or ranges to include in the population.")}\n `),returns:["NUMBER"],compute:function(...e){return ya(e,!1,!0)},isExported:!0};var dl=Object.freeze({__proto__:null,AVEDEV:Ia,AVERAGE:Ra,AVERAGE_WEIGHTED:Oa,AVERAGEA:Ma,AVERAGEIF:Na,AVERAGEIFS:_a,COUNT:Fa,COUNTA:Da,COVAR:ka,COVARIANCE_P:$a,COVARIANCE_S:Pa,LARGE:La,MAX:Ua,MAXA:Va,MAXIFS:za,MEDIAN:Ba,MIN:Ha,MINA:Wa,MINIFS:Ga,PERCENTILE:qa,PERCENTILE_EXC:Za,PERCENTILE_INC:ja,QUARTILE:Xa,QUARTILE_EXC:Ya,QUARTILE_INC:Ka,SMALL:Qa,STDEV:Ja,STDEV_P:el,STDEV_S:tl,STDEVA:ol,STDEVP:il,STDEVPA:nl,VAR:rl,VAR_P:sl,VAR_S:al,VARA:ll,VARP:cl,VARPA:hl});function ul(e,t,o){var i;const n=new Map,s=e.length;for(let t=s-1;t>=0;t--)n.set(Yr(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(r("The field must be a number or a string"));let a;if("number"==typeof t){if(a=Math.trunc(t)-1,a<0||s-1<a)throw new Error(r("The field (%s) must be one of %s or must be a number between 1 and %s inclusive.",t.toString(),s.toString()))}else{const e=Yr(t).toUpperCase();if(a=null!==(i=n.get(e))&&void 0!==i?i:-1,-1===a)throw new Error(r("The field (%s) must be one of %s.",Yr(t),[...n.keys()].toString()))}const l=o[0].length;if(l<2)throw new Error(r("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const h=e[0].length;for(let t=1;t<l;t++){let i=[],r=!0;for(let s=0;s<o.length;s++){const a=Yr(o[s][0]).toUpperCase(),l=n.get(a),c=o[s][t];if(void 0!==c){if(void 0===l){r=!1;break}i.push([e[l].slice(1,h)]),i.push(c)}}if(r){if(!(i.length>0)){c=new Set(Array(h-1).keys());break}ds(i,((e,t)=>{c.add(t)}),!0)}}const d=e[a];return[...c].map((e=>d[e+1]))}const gl=Br(`\n database (range) ${r("The array or range containing the data to consider, structured in such a way that the first row contains the labels for each column's values.")}\n field (any) ${r("Indicates which column in database contains the values to be extracted and operated on.")}\n criteria (range) ${r("An array or range containing zero or more criteria to filter the database values by before operating.")}\n`),pl={description:r("Average of a set of values from a table-like range."),args:gl,returns:["NUMBER"],compute:function(e,t,o){const i=ul(e,t,o);return Ra.compute([i])},isExported:!0},ml={description:r("Counts values from a table-like range."),args:gl,returns:["NUMBER"],compute:function(e,t,o){const i=ul(e,t,o);return Fa.compute([i])},isExported:!0},fl={description:r("Counts values and text from a table-like range."),args:gl,returns:["NUMBER"],compute:function(e,t,o){const i=ul(e,t,o);return Da.compute([i])},isExported:!0},vl={description:r("Single value from a table-like range."),args:gl,returns:["NUMBER"],compute:function(e,t,o){const i=ul(e,t,o);return qr((()=>1===i.length),r("More than one match found in DGET evaluation.")),i[0]},isExported:!0},bl={description:r("Maximum of values from a table-like range."),args:gl,returns:["NUMBER"],compute:function(e,t,o){const i=ul(e,t,o);return Ua.compute([i])},isExported:!0},Cl={description:r("Minimum of values from a table-like range."),args:gl,returns:["NUMBER"],compute:function(e,t,o){const i=ul(e,t,o);return Ha.compute([i])},isExported:!0},Sl={description:r("Product of values from a table-like range."),args:gl,returns:["NUMBER"],compute:function(e,t,o){const i=ul(e,t,o);return na.compute([i])},isExported:!0},El={description:r("Standard deviation of population sample from table."),args:gl,returns:["NUMBER"],compute:function(e,t,o){const i=ul(e,t,o);return Ja.compute([i])},isExported:!0},wl={description:r("Standard deviation of entire population from table."),args:gl,returns:["NUMBER"],compute:function(e,t,o){const i=ul(e,t,o);return il.compute([i])},isExported:!0},yl={description:r("Sum of values from a table-like range."),args:gl,returns:["NUMBER"],compute:function(e,t,o){const i=ul(e,t,o);return ma.compute([i])},isExported:!0},xl={description:r("Variance of population sample from table-like range."),args:gl,returns:["NUMBER"],compute:function(e,t,o){const i=ul(e,t,o);return rl.compute([i])},isExported:!0},Il={description:r("Variance of a population from a table-like range."),args:gl,returns:["NUMBER"],compute:function(e,t,o){const i=ul(e,t,o);return cl.compute([i])},isExported:!0};var Rl=Object.freeze({__proto__:null,DAVERAGE:pl,DCOUNT:ml,DCOUNTA:fl,DGET:vl,DMAX:bl,DMIN:Cl,DPRODUCT:Sl,DSTDEV:El,DSTDEVP:wl,DSUM:yl,DVAR:xl,DVARP:Il});const Tl={description:r("Converts year/month/day into a date."),args:Br(`\n year (number) ${r("The year component of the date.")}\n month (number) ${r("The month component of the date.")}\n day (number) ${r("The day component of the date.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o){let i=Math.trunc(jr(e));const n=Math.trunc(jr(t)),s=Math.trunc(jr(o));qr((()=>0<=i&&i<=9999),r("The year (%s) must be between 0 and 9999 inclusive.",i.toString())),i<1900&&(i+=1900);const a=Ee(new Date(i,n-1,s));return qr((()=>a>=0),r("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),a},isExported:!0},Al={description:r("Converts a date string to a date value."),args:Br(`\n date_string (string) ${r("The string representing the date.")}\n `),returns:["NUMBER"],compute:function(e){const t=Yr(e),o=be(t);return qr((()=>null!==o),r("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(o.value)},isExported:!0},Ol={description:r("Day of the month that a specific date falls on."),args:Br(`\n date (string) ${r("The date from which to extract the day.")}\n `),returns:["NUMBER"],compute:function(e){return es(e).getDate()},isExported:!0},Ml={description:r("Number of days between two dates."),args:Br(`\n end_date (date) ${r("The end of the date range.")}\n start_date (date) ${r("The start of the date range.")}\n `),returns:["NUMBER"],compute:function(e,t){const o=es(e),i=es(t),n=o.getTime()-i.getTime();return Math.round(n/de)},isExported:!0},Nl={description:r("Number of days between two dates on a 360-day year (months of 30 days)."),args:Br(`\n start_date (date) ${r("The start date to consider in the calculation.")}\n end_date (date) ${r("The end date to consider in the calculation.")}\n method (number, default=0) ${r("An indicator of what day count method to use. (0) US NASD method (1) European method")}\n `),returns:["NUMBER"],compute:function(e,t,o=0){const i=jr(e),n=jr(t),r=Jr(o)?4:0,s=Kl.compute(e,t,r);return Math.sign(n-i)*Math.round(360*s)},isExported:!0},_l={description:r("Date a number of months before/after another date."),args:Br(`\n start_date (date) ${r("The date from which to calculate the result.")}\n months (number) ${r("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 Ee(xe(es(e),Math.trunc(jr(t)),!1))},isExported:!0},Fl={description:r("Last day of a month before or after a date."),args:Br(`\n start_date (date) ${r("The date from which to calculate the result.")}\n months (number) ${r("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 o=es(e),i=Math.trunc(jr(t)),n=o.getFullYear(),r=o.getMonth();return Ee(new Date(n,r+i+1,0))},isExported:!0},Dl={description:r("Hour component of a specific time."),args:Br(`\n time (date) ${r("The time from which to calculate the hour component.")}\n `),returns:["NUMBER"],compute:function(e){return es(e).getHours()},isExported:!0},kl={description:r("ISO week number of the year."),args:Br(`\n date (date) ${r("The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n `),returns:["NUMBER"],compute:function(e){const t=es(e),o=t.getFullYear();let i=1;for(;4!==new Date(o,0,i).getDay();)i+=1;const n=new Date(o,0,i-3);let r=31;for(;4!==new Date(o,11,r).getDay();)r-=1;const s=new Date(o,11,r+3);let a,l;switch(a=n.getTime()<=t.getTime()?t.getTime()<=s.getTime()?0:1:-1,a){case 0:l=n;break;case 1:l=new Date(o,11,r+3+1);break;case-1:let e=1;for(;4!==new Date(o-1,0,e).getDay();)e+=1;l=new Date(o-1,0,e-3)}const c=(t.getTime()-l.getTime())/de;return Math.floor(c/7)+1},isExported:!0},$l={description:r("Minute component of a specific time."),args:Br(`\n time (date) ${r("The time from which to calculate the minute component.")}\n `),returns:["NUMBER"],compute:function(e){return es(e).getMinutes()},isExported:!0},Pl={description:r("Month of the year a specific date falls in"),args:Br(`\n date (date) ${r("The date from which to extract the month.")}\n `),returns:["NUMBER"],compute:function(e){return es(e).getMonth()+1},isExported:!0},Ll={description:r("Net working days between two provided days."),args:Br(`\n start_date (date) ${r("The start date of the period from which to calculate the number of net working days.")}\n end_date (date) ${r("The end date of the period from which to calculate the number of net working days.")}\n holidays (date, range<date>, optional) ${r("A range or array constant containing the date serial numbers to consider holidays.")}\n `),returns:["NUMBER"],compute:function(e,t,o){return Vl.compute(e,t,1,o)},isExported:!0};function Ul(e){if("string"==typeof e){qr((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),r('When weekend is a string (%s) it must be composed of "0" or "1".',e));let t=[];for(let o=0;o<7;o++)"1"===e[o]&&t.push((o+1)%7);return t}if("number"==typeof e)return qr((()=>1<=e&&e<=7||11<=e&&e<=17),r("The weekend (%s) must be a string or a number in the range 1-7 or 11-17.",e.toString())),e<=7?[e-2==-1?6:e-2,e-1]:[e-11];throw Error(r("The weekend must be a number or a string."))}const Vl={description:r("Net working days between two dates (specifying weekends)."),args:Br(`\n start_date (date) ${r("The start date of the period from which to calculate the number of net working days.")}\n end_date (date) ${r("The end date of the period from which to calculate the number of net working days.")}\n weekend (any, default=1) ${r("A number or string representing which days of the week are considered weekends.")}\n holidays (date, range<date>, optional) ${r("A range or array constant containing the dates to consider as holidays.")}\n `),returns:["NUMBER"],compute:function(e,t,o=1,i){const n=es(e),r=es(t),s=Ul(o);let a=new Set;void 0!==i&&os([i],(e=>{const t=es(e);a.add(t.getTime())}));const l=n.getTime()>r.getTime(),c=new Date((l?n:r).getTime());let h=new Date((l?r:n).getTime());const d=c.getTime();let u=h.getTime(),g=0;for(;u<=d;)s.includes(h.getDay())||a.has(u)||(g+=1),h.setDate(h.getDate()+1),u=h.getTime();return l?-g:g},isExported:!0},zl={description:r("Current date and time as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy hh:mm:ss",compute:function(){let e=new Date;e.setMilliseconds(0);const t=e.getTime()-he.getTime(),o=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/de)+o},isExported:!0},Bl={description:r("Minute component of a specific time."),args:Br(`\n time (date) ${r("The time from which to calculate the second component.")}\n `),returns:["NUMBER"],compute:function(e){return es(e).getSeconds()},isExported:!0},Hl={description:r("Converts hour/minute/second into a time."),args:Br(`\n hour (number) ${r("The hour component of the time.")}\n minute (number) ${r("The minute component of the time.")}\n second (number) ${r("The second component of the time.")}\n `),returns:["DATE"],computeFormat:()=>"hh:mm:ss a",compute:function(e,t,o){let i=Math.trunc(jr(e)),n=Math.trunc(jr(t)),s=Math.trunc(jr(o));return n+=Math.floor(s/60),s=s%60+(s<0?60:0),i+=Math.floor(n/60),n=n%60+(n<0?60:0),i%=24,qr((()=>i>=0),r("The function [[FUNCTION_NAME]] result cannot be negative")),i/24+n/1440+s/86400},isExported:!0},Wl={description:r("Converts a time string into its serial number representation."),args:Br(`\n time_string (string) ${r("The string that holds the time representation.")}\n `),returns:["NUMBER"],compute:function(e){const t=Yr(e),o=be(t);qr((()=>null!==o),r("The time_string (%s) cannot be parsed to date/time.",t));const i=o.value-Math.trunc(o.value);return i<0?1+i:i},isExported:!0},Gl={description:r("Current date as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(){const e=new Date;return Ee(new Date(e.getFullYear(),e.getMonth(),e.getDate()))},isExported:!0},ql={description:r("Day of the week of the date provided (as number)."),args:Br(`\n date (date) ${r("The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n type (number, default=1) ${r("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 o=es(e),i=Math.round(jr(t)),n=o.getDay();return qr((()=>[1,2,3].includes(i)),r("The type (%s) must be 1, 2 or 3.",i.toString())),1===i?n+1:2===i?0===n?7:n:0===n?6:n-1},isExported:!0},Zl={description:r("Week number of the year."),args:Br(`\n date (date) ${r("The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n type (number, default=1) ${r("A number representing the day that a week starts on. Sunday = 1.")}\n `),returns:["NUMBER"],compute:function(e,t=1){const o=es(e),i=Math.round(jr(t));if(qr((()=>1===i||2===i||11<=i&&i<=17||21===i),r("The type (%s) is out of range.",i.toString())),21===i)return kl.compute(e);let n;n=1===i||2===i?i-1:i-10==7?0:i-10;const s=o.getFullYear();let a=1,l=new Date(s,0,a);for(;l.getDay()!==n;)a+=1,l=new Date(s,0,a);const c=(o.getTime()-l.getTime())/de;return c<0?1:Math.floor(c/7)+(1===a?1:2)},isExported:!0},jl={description:r("Date after a number of workdays."),args:Br(`\n start_date (date) ${r("The date from which to begin counting.")}\n num_days (number) ${r("The number of working days to advance from start_date. If negative, counts backwards.")}\n holidays (date, range<date>, optional) ${r("A range or array constant containing the dates to consider holidays.")}\n `),returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o){return Xl.compute(e,t,1,o)},isExported:!0},Xl={description:r("Date after a number of workdays (specifying weekends)."),args:Br(`\n start_date (date) ${r("The date from which to begin counting.")}\n num_days (number) ${r("The number of working days to advance from start_date. If negative, counts backwards.")}\n weekend (any, default=1) ${r("A number or string representing which days of the week are considered weekends.")}\n holidays (date, range<date>, optional) ${r("A range or array constant containing the dates to consider holidays.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o=1,i){let n=es(e),s=Math.trunc(jr(t));"string"==typeof o&&qr((()=>"1111111"!==o),r("The weekend (%s) must be different from '1111111'.",o));const a=Ul(o);let l=new Set;void 0!==i&&os([i],(e=>{const t=es(e);l.add(t.getTime())}));let c=new Date(n.getTime()),h=c.getTime();const d=Math.sign(s);let u=Math.abs(s);for(;u>0;)c.setDate(c.getDate()+d),h=c.getTime(),a.includes(c.getDay())||l.has(h)||(u-=1);const g=h-he.getTime();return Math.round(g/de)},isExported:!0},Yl={description:r("Year specified by a given date."),args:Br(`\n date (date) ${r("The date from which to extract the year.")}\n `),returns:["NUMBER"],compute:function(e){return es(e).getFullYear()},isExported:!0},Kl={description:r("Exact number of years between two dates."),args:Br(`\n start_date (date) ${r("The start date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n end_date (date) ${r("The end date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.")}\n day_count_convention (number, default=0) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o=0){let i=Math.trunc(jr(e)),n=Math.trunc(jr(t));const s=Math.trunc(jr(o));return qr((()=>i>=0),r("The start_date (%s) must be positive or null.",i.toString())),qr((()=>n>=0),r("The end_date (%s) must be positive or null.",n.toString())),qr((()=>0<=s&&s<=4),r("The day_count_convention (%s) must be between 0 and 4 inclusive.",s.toString())),Re(i,n,s)}},Ql={description:r("First day of the month preceding a date."),args:Br(`\n date (date) ${r("The date from which to calculate the result.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=es(e),o=t.getFullYear(),i=t.getMonth();return Ee(new Date(o,i,1))}},Jl={description:r("Last day of the month following a date."),args:Br(`\n date (date) ${r("The date from which to calculate the result.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){return Fl.compute(e,0)}},ec={description:r("Quarter of the year a specific date falls in"),args:Br(`\n date (date) ${r("The date from which to extract the quarter.")}\n `),returns:["NUMBER"],compute:function(e){return Math.ceil((es(e).getMonth()+1)/3)}},tc={description:r("First day of the quarter of the year a specific date falls in."),args:Br(`\n date (date) ${r("The date from which to calculate the start of quarter.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=ec.compute(e),o=Yl.compute(e);return Ee(new Date(o,3*(t-1),1))}},oc={description:r("Last day of the quarter of the year a specific date falls in."),args:Br(`\n date (date) ${r("The date from which to calculate the end of quarter.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=ec.compute(e),o=Yl.compute(e);return Ee(new Date(o,3*t,0))}},ic={description:r("First day of the year a specific date falls in."),args:Br(`\n date (date) ${r("The date from which to calculate the start of the year.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Yl.compute(e);return Ee(new Date(t,0,1))}},nc={description:r("Last day of the year a specific date falls in."),args:Br(`\n date (date) ${r("The date from which to calculate the end of the year.")}\n `),returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Yl.compute(e);return Ee(new Date(t+1,0,0))}};var rc=Object.freeze({__proto__:null,DATE:Tl,DATEVALUE:Al,DAY:Ol,DAYS:Ml,DAYS360:Nl,EDATE:_l,EOMONTH:Fl,HOUR:Dl,ISOWEEKNUM:kl,MINUTE:$l,MONTH:Pl,NETWORKDAYS:Ll,NETWORKDAYS_INTL:Vl,NOW:zl,SECOND:Bl,TIME:Hl,TIMEVALUE:Wl,TODAY:Gl,WEEKDAY:ql,WEEKNUM:Zl,WORKDAY:jl,WORKDAY_INTL:Xl,YEAR:Yl,YEARFRAC:Kl,MONTH_START:Ql,MONTH_END:Jl,QUARTER:ec,QUARTER_START:tc,QUARTER_END:oc,YEAR_START:ic,YEAR_END:nc});const sc={description:r("Compare two numeric values, returning 1 if they're equal."),args:Br(`\n number1 (number) ${r("The first number to compare.")}\n number2 (number, default=0) ${r("The second number to compare.")}\n `),returns:["NUMBER"],compute:function(e,t=0){return jr(e)===jr(t)?1:0},isExported:!0};var ac=Object.freeze({__proto__:null,DELTA:sc});function lc(e,t){qr((()=>e<t),r("The maturity (%s) must be strictly greater than the settlement (%s).",t.toString(),e.toString()))}function cc(e,t){qr((()=>t<e),r("The settlement date (%s) must be strictly greater than the issue date (%s).",e.toString(),t.toString()))}function hc(e){qr((()=>[1,2,4].includes(e)),r("The frequency (%s) must be one of %s",e.toString(),[1,2,4].toString()))}function dc(e){qr((()=>0<=e&&e<=4),r("The day_count_convention (%s) must be between 0 and 4 inclusive.",e.toString()))}function uc(e){qr((()=>e>0),r("The redemption (%s) must be strictly positive.",e.toString()))}function gc(e){qr((()=>e>0),r("The price (%s) must be strictly positive.",e.toString()))}function pc(e){qr((()=>e>0),r("The number_of_periods (%s) must be greater than 0.",e.toString()))}function mc(e){qr((()=>e>0),r("The rate (%s) must be strictly positive.",e.toString()))}function fc(e){qr((()=>e>0),r("The life (%s) must be strictly positive.",e.toString()))}function vc(e){qr((()=>e>=0),r("The cost (%s) must be positive or null.",e.toString()))}function bc(e){qr((()=>e>0),r("The period (%s) must be strictly positive.",e.toString()))}function Cc(e){qr((()=>e>=0),r("The salvage (%s) must be positive or null.",e.toString()))}function Sc(e){qr((()=>e>0),r("The present value (%s) must be strictly positive.",e.toString()))}function Ec(e,t){qr((()=>e<=t),r("The period (%s) must be less than or equal life (%s).",e.toString(),t.toString()))}function wc(e){qr((()=>e>0),r("The investment (%s) must be strictly positive.",e.toString()))}function yc(e){qr((()=>e>0),r("The discount (%s) must be strictly positive.",e.toString()))}function xc(e){qr((()=>e<1),r("The discount (%s) must be smaller than 1.",e.toString()))}function Ic(e){qr((()=>e>0),r("The depreciation factor (%s) must be strictly positive.",e.toString()))}function Rc(e,t){const o=es(e),i=es(t),n=new Date(o);n.setFullYear(o.getFullYear()+1),qr((()=>i.getTime()<=n.getTime()),r("The settlement date (%s) must at most one year after the maturity date (%s).",e.toString(),t.toString()))}function Tc(e,t,o){pc(o),qr((()=>e>0),r("The first_period (%s) must be strictly positive.",e.toString())),qr((()=>t>0),r("The last_period (%s) must be strictly positive.",t.toString())),qr((()=>e<=t),r("The first_period (%s) must be smaller or equal to the last_period (%s).",e.toString(),t.toString())),qr((()=>t<=o),r("The last_period (%s) must be smaller or equal to the number_of_periods (%s).",e.toString(),o.toString()))}function Ac(e){qr((()=>e>-1),r("The rate_guess (%s) must be strictly greater than -1.",e.toString()))}function Oc(e,t){qr((()=>e.length===t.length&&e[0].length===t[0].length),r("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."))}function Mc(e){qr((()=>e.every((t=>t>=e[0]))),r("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e[0].toString()))}const Nc=Br(`\nsettlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\nmaturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\nfrequency (number) ${r("The number of interest or coupon payments per year (1, 2, or 4).")}\nday_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n`);function _c(e,t,o,i,n=1e-10,s){let a,l,c,h,d=o,u=!1,g=0;do{c=e(d),isNaN(c)?(qr((()=>g<i&&void 0!==s),r("Function [[FUNCTION_NAME]] didn't find any result.")),g++,d=s(h),h=d):(a=d-c/t(d),l=Math.abs(a-d),d=a,u=l<n||Math.abs(c)<n,qr((()=>g<i),r("Function [[FUNCTION_NAME]] didn't find any result.")),g++)}while(!u);return d}const Fc={description:r("Accrued interest of security paying at maturity."),args:Br(`\n issue (date) ${r("The date the security was initially issued.")}\n maturity (date) ${r("The maturity date of the security.")}\n rate (number) ${r("The annualized rate of interest.")}\n redemption (number) ${r("The redemption amount per 100 face value, or par.")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n=0){n=n||0;const r=Math.trunc(jr(e)),s=Math.trunc(jr(t)),a=jr(i),l=jr(o),c=Math.trunc(jr(n));cc(s,r),dc(c),uc(a),mc(l);return a*l*Kl.compute(r,s,n)},isExported:!0},Dc={description:r("Depreciation for an accounting period."),args:Br(`\n cost (number) ${r("The initial cost of the asset.")}\n purchase_date (date) ${r("The date the asset was purchased.")}\n first_period_end (date) ${r("The date the first period ended.")}\n salvage (number) ${r("The value of the asset at the end of depreciation.")}\n period (number) ${r("The single period within life for which to calculate depreciation.")}\n rate (number) ${r("The deprecation rate.")}\n day_count_convention (number, optional) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,s,a=0){a=a||0;const l=jr(e),c=Math.trunc(jr(t)),h=Math.trunc(jr(o)),d=jr(i),u=jr(n),g=jr(s),p=Math.trunc(jr(a));!function(e){qr((()=>e>0),r("The cost (%s) must be strictly positive.",e.toString()))}(l),Cc(d),function(e,t){qr((()=>e<=t),r("The salvage (%s) must be smaller or equal than the cost (%s).",e.toString(),t.toString()))}(d,l),function(e){qr((()=>e>=0),r("The period (%s) must be positive or null.",e.toString()))}(u),mc(g),dc(p),qr((()=>c<=h),r("The purchase_date (%s) must be before the first_period_end (%s).",c.toString(),h.toString()));const m=u<1&&u>0?1:Math.trunc(u),f=l*g,v=Kl.compute(c,h,p),b=c===h?f:f*v,C=l-b-f*m;return C>=d?0===m?b:f:d-C<f?f-(d-C):0},isExported:!0},kc={description:r("Days in coupon period containing settlement date."),args:Nc,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const n=Math.trunc(jr(e)),r=Math.trunc(jr(t)),s=Math.trunc(jr(o)),a=Math.trunc(jr(i));if(lc(n,r),hc(s),dc(a),1===a){const n=Vc.compute(e,t,o,i);return Lc.compute(e,t,o,i)-n}return(3===a?365:360)/s},isExported:!0},$c={description:r("Days from settlement until next coupon."),args:Nc,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const n=Math.trunc(jr(e)),r=Math.trunc(jr(t)),s=Math.trunc(jr(o)),a=Math.trunc(jr(i));lc(n,r),hc(s),dc(a);const l=Vc.compute(n,r,o,i);if([1,2,3].includes(a))return n-l;if(4===a){const e=Re(l,n,a);return Math.round(360*e)}const c=es(n),h=es(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&&ye(h)&&ye(c)&&(f=30),31!==f||30!==m&&31!==m||(f=30),2===g&&ye(h)&&(m=30),31===m&&(m=30),360*(u-d)+30*(p-g)+(f-m)},isExported:!0},Pc={description:r("Days from settlement until next coupon."),args:Nc,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const n=Math.trunc(jr(e)),r=Math.trunc(jr(t)),s=Math.trunc(jr(o)),a=Math.trunc(jr(i));lc(n,r),hc(s),dc(a);const l=Lc.compute(n,r,o,i);if([1,2,3].includes(a))return l-n;if(4===a){const e=Re(n,l,a);return Math.round(360*e)}const c=$c.compute(e,t,o,a);return kc.compute(e,t,o,a)-c},isExported:!0},Lc={description:r("Next coupon date after the settlement date."),args:Nc,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o,i=0){i=i||0;const n=Math.trunc(jr(e)),r=Math.trunc(jr(t)),s=Math.trunc(jr(o)),a=Math.trunc(jr(i));lc(n,r),hc(s),dc(a);const l=12/s,c=Uc.compute(e,t,o,i);return Ee(xe(es(r),-(c-1)*l,!0))},isExported:!0},Uc={description:r("Number of coupons between settlement and maturity."),args:Nc,returns:["NUMBER"],compute:function(e,t,o,i=0){i=i||0;const n=Math.trunc(jr(e)),r=Math.trunc(jr(t)),s=Math.trunc(jr(o)),a=Math.trunc(jr(i));lc(n,r),hc(s),dc(a);let l=1,c=r;const h=12/s;for(;c>n;)c=Ee(xe(es(c),-h,!1)),l++;return l-1},isExported:!0},Vc={description:r("Last coupon date prior to or on the settlement date."),args:Nc,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,o,i=0){i=i||0;const n=Math.trunc(jr(e)),r=Math.trunc(jr(t)),s=Math.trunc(jr(o)),a=Math.trunc(jr(i));lc(n,r),hc(s),dc(a);const l=12/s,c=Uc.compute(e,t,o,i);return Ee(xe(es(r),-c*l,!0))},isExported:!0},zc={description:r("Cumulative interest paid over a set of periods."),args:Br(`\n rate (number) ${r("The interest rate.")}\n number_of_periods (number) ${r("The number of payments to be made.")}\n present_value (number) ${r("The current value of the annuity.")}\n first_period (number) ${r("The number of the payment period to begin the cumulative calculation.")}\n last_period (number) ${r("The number of the payment period to end the cumulative calculation.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,r=0){const s=jr(i),a=jr(n),l=jr(e),c=jr(o),h=jr(t);Tc(s,a,h),mc(l),Sc(c);let d=0;for(let t=s;t<=a;t++){d+=Jc.compute(e,t,h,o,0,r)}return d},isExported:!0},Bc={description:r("Cumulative principal paid over a set of periods."),args:Br(`\n rate (number) ${r("The interest rate.")}\n number_of_periods (number) ${r("The number of payments to be made.")}\n present_value (number) ${r("The current value of the annuity.")}\n first_period (number) ${r("The number of the payment period to begin the cumulative calculation.")}\n last_period (number) ${r("The number of the payment period to end the cumulative calculation.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,r=0){const s=jr(i),a=jr(n),l=jr(e),c=jr(o),h=jr(t);Tc(s,a,h),mc(l),Sc(c);let d=0;for(let t=s;t<=a;t++){d+=ch.compute(e,t,h,o,0,r)}return d},isExported:!0},Hc={description:r("Depreciation via declining balance method."),args:Br(`\n cost (number) ${r("The initial cost of the asset.")}\n salvage (number) ${r("The value of the asset at the end of depreciation.")}\n life (number) ${r("The number of periods over which the asset is depreciated.")}\n period (number) ${r("The single period within life for which to calculate depreciation.")}\n month (number, optional) ${r("The number of months in the first year of depreciation.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,...n){const s=jr(e),a=jr(t),l=jr(o),c=Math.trunc(jr(i)),h=n.length?Math.trunc(jr(n[0])):12,d=l+(12===h?0:1);vc(s),Cc(a),bc(c),fc(l),qr((()=>1<=h&&h<=12),r("The month (%s) must be between 1 and 12 inclusive.",h.toString())),qr((()=>c<=d),r("The period (%s) must be less than or equal to %s.",c.toString(),d.toString()));const u=h/12;let g=1-Math.pow(a/s,1/l);g=Math.round(1e3*g)/1e3;let p=s,m=s*(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},Wc={description:r("Depreciation via double-declining balance method."),args:Br(`\n cost (number) ${r("The initial cost of the asset.")}\n salvage (number) ${r("The value of the asset at the end of depreciation.")}\n life (number) ${r("The number of periods over which the asset is depreciated.")}\n period (number) ${r("The single period within life for which to calculate depreciation.")}\n factor (number, default=2) ${r("The factor by which depreciation decreases.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,n=2){n=n||0;const r=jr(e),s=jr(t),a=jr(o),l=jr(i),c=jr(n);if(vc(r),Cc(s),bc(l),fc(a),Ec(l,a),Ic(c),0===r||s>=r)return 0;const h=c/a;if(h>1)return 1===i?r-s:0;if(l<=1)return r*h;const d=r*Math.pow(1-h,l-1),u=r*Math.pow(1-h,l),g=u<s?d-s:d-u;return Math.max(g,0)},isExported:!0},Gc={description:r("Discount rate of a security based on price."),args:Br(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n price (number) ${r("The price at which the security is bought per 100 face value.")}\n redemption (number) ${r("The redemption amount per 100 face value, or par.")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n=0){n=n||0;const r=Math.trunc(jr(e)),s=Math.trunc(jr(t)),a=jr(o),l=jr(i),c=Math.trunc(jr(n));lc(r,s),dc(c),gc(a),uc(l);return(l-a)/l/Kl.compute(r,s,c)},isExported:!0},qc={description:r("Convert a decimal fraction to decimal value."),args:Br(`\n fractional_price (number) ${r("The price quotation given using fractional decimal conventions.")}\n unit (number) ${r("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.")}\n `),returns:["NUMBER"],compute:function(e,t){const o=jr(e),i=Math.trunc(jr(t));qr((()=>i>0),r("The unit (%s) must be strictly positive.",i.toString()));const n=Math.trunc(o);return n+(o-n)*(10**Math.ceil(Math.log10(i))/i)},isExported:!0},Zc={description:r("Convert a decimal value to decimal fraction."),args:Br(`\n decimal_price (number) ${r("The price quotation given as a decimal value.")}\n unit (number) ${r("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 o=jr(e),i=Math.trunc(jr(t));qr((()=>i>0),r("The unit (%s) must be strictly positive.",i.toString()));const n=Math.trunc(o);return n+(o-n)*(i/10**Math.ceil(Math.log10(i)))},isExported:!0},jc={description:r("Number of periods for an investment to reach a value."),args:Br(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${r("The annualized rate of interest.")}\n yield (number) ${r("The expected annual yield of the security.")}\n frequency (number) ${r("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,s=0){s=s||0;const a=Math.trunc(jr(e)),l=Math.trunc(jr(t)),c=jr(o),h=jr(i),d=Math.trunc(jr(n)),u=Math.trunc(jr(s));lc(a,l),hc(d),dc(u),qr((()=>c>=0),r("The rate (%s) must be positive or null.",c.toString())),qr((()=>h>=0),r("The yield (%s) must be positive or null.",h.toString()));const g=Kl.compute(a,l,u),p=g-Math.trunc(g)||1/d,m=Math.ceil(g*d),f=c/d,v=h/d;let b=0,C=0;for(let e=1;e<=m;e++){const t=(f+(e===m?1:0))/(1+v)**e;C+=(p+(e-1)/d)*t,b+=t}return 0===b?0:C/b},isExported:!0},Xc={description:r("Annual effective interest rate."),args:Br(`\n nominal_rate (number) ${r("The nominal interest rate per year.")}\n periods_per_year (number) ${r("The number of compounding periods per year.")}\n `),returns:["NUMBER"],compute:function(e,t){const o=jr(e),i=Math.trunc(jr(t));return qr((()=>o>0),r("The nominal rate (%s) must be strictly greater than 0.",o.toString())),qr((()=>i>0),r("The number of periods by year (%s) must strictly greater than 0.",i.toString())),Math.pow(1+o/i,i)-1},isExported:!0},Yc={description:r("Future value of an annuity investment."),args:Br(`\n rate (number) ${r("The interest rate.")}\n number_of_periods (number) ${r("The number of payments to be made.")}\n payment_amount (number) ${r("The amount per period to be paid.")}\n present_value (number, default=0) ${r("The current value of the annuity.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,n=0){i=i||0,n=n||0;const r=jr(e),s=jr(t),a=jr(o),l=jr(i),c=Jr(n)?1:0;return r?-l*(1+r)**s-a*(1+r*c)*((1+r)**s-1)/r:-(l+a*s)},isExported:!0},Kc={description:r("Future value of principal from series of rates."),args:Br(`\n principal (number) ${r("The amount of initial capital or value to compound against.")}\n rate_schedule (number, range<number>) ${r("A series of interest rates to compound against the principal.")}\n `),returns:["NUMBER"],compute:function(e,t){return rs([t],((e,t)=>e*(1+jr(t))),jr(e))},isExported:!0},Qc={description:r("Calculates effective interest rate."),args:Br(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n investment (number) ${r("The amount invested in the security.")}\n redemption (number) ${r("The amount to be received at maturity.")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n=0){const r=Math.trunc(jr(e)),s=Math.trunc(jr(t)),a=jr(i),l=jr(o);lc(r,s),wc(l),uc(a);return(a-l)/l/Kl.compute(r,s,n)},isExported:!0},Jc={description:r("Payment on the principal of an investment."),args:Br(`\n rate (number) ${r("The annualized rate of interest.")}\n period (number) ${r("The amortization period, in terms of number of periods.")}\n number_of_periods (number) ${r("The number of payments to be made.")}\n present_value (number) ${r("The current value of the annuity.")}\n future_value (number, default=0) ${r("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,n=0,r=0){return lh.compute(e,o,i,n,r)-ch.compute(e,t,o,i,n,r)},isExported:!0},eh={description:r("Internal rate of return given periodic cashflows."),args:Br(`\n cashflow_amounts (number, range<number>) ${r("An array or range containing the income or payments associated with the investment.")}\n rate_guess (number, default=0.1) ${r("An estimate for what the internal rate of return will be.")}\n `),returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t=.1){const o=jr(t);Ac(o);let i=!1,n=!1,s=[];is([e],(e=>{e>0&&(i=!0),e<0&&(n=!0),s.push(e)})),qr((()=>i&&n),r("The cashflow_amounts must include negative and positive values."));const a=s.shift();return _c((function(e){return function(e,t,o){const i=o.length;let n=0;return o.reduce(((t,o)=>(n++,t+o*e**(i-n))),t*e**i)}(e,a,s)}),(function(e){return function(e,t,o){const i=o.length;let n=0;return o.reduce(((t,o)=>(n++,t+o*(i-n)*e**(i-n-1))),t*i*e**(i-1))}(e,a,s)}),o+1,20,1e-5)-1},isExported:!0},th={description:r("Returns the interest paid at a particular period of an investment."),args:Br(`\n rate (number) ${r("The interest rate.")}\n period (number) ${r("The period for which you want to view the interest payment.")}\n number_of_periods (number) ${r("The number of payments to be made.")}\n present_value (number) ${r("The current value of the annuity.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i){const n=jr(e),s=jr(t),a=jr(o),l=jr(i);qr((()=>0!==a),r("The number of periods must be different than 0.",a.toString()));return-1*(l-l*(s/a))*n},isExported:!0},oh={description:r("Modified Macaulay duration."),args:Br(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${r("The annualized rate of interest.")}\n yield (number) ${r("The expected annual yield of the security.")}\n frequency (number) ${r("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,r=0){return jc.compute(e,t,o,i,n,r)/(1+jr(i)/Math.trunc(jr(n)))},isExported:!0},ih={description:r("Modified internal rate of return."),args:Br(`\n cashflow_amounts (range<number>) ${r("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")}\n financing_rate (number) ${r("The interest rate paid on funds invested.")}\n reinvestment_return_rate (number) ${r("The return (as a percentage) earned on reinvestment of income received from the investment.")}\n `),returns:["NUMBER"],compute:function(e,t,o){const i=jr(t),n=jr(o),s=(a=e,a.length?a[0].map(((e,t)=>a.map((e=>e[t])))):a).flat().filter(Je).map(jr);var a;const l=s.length;let c=0,h=0;for(const e of Ue(0,l)){const t=s[e];t>=0?c+=t*(n+1)**(l-e-1):h+=t/(i+1)**e}qr((()=>0!==h&&0!==c),r("There must be both positive and negative values in cashflow_amounts."));return(-c/h)**(1/(l-1))-1},isExported:!0},nh={description:r("Annual nominal interest rate."),args:Br(`\n effective_rate (number) ${r("The effective interest rate per year.")}\n periods_per_year (number) ${r("The number of compounding periods per year.")}\n `),returns:["NUMBER"],compute:function(e,t){const o=jr(e),i=Math.trunc(jr(t));return qr((()=>o>0),r("The effective rate (%s) must must strictly greater than 0.",o.toString())),qr((()=>i>0),r("The number of periods by year (%s) must strictly greater than 0.",i.toString())),(Math.pow(o+1,1/i)-1)*i},isExported:!0},rh={description:r("Number of payment periods for an investment."),args:Br(`\n rate (number) ${r("The interest rate.")}\n payment_amount (number) ${r("The amount of each payment made.")}\n present_value (number) ${r("The current value of the annuity.")}\n future_value (number, default=0) ${r("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i=0,n=0){i=i||0,n=n||0;const r=jr(e),s=jr(t),a=jr(o),l=jr(i),c=Jr(n)?1:0;if(0===r)return-(l+a)/s;const h=s*(1+r*c)/r;return Math.log((h-l)/(a+h))/Math.log(1+r)},isExported:!0};const sh={description:r("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:Br(`\n discount (number) ${r("The discount rate of the investment over one period.")}\n cashflow1 (number, range<number>) ${r("The first future cash flow.")}\n cashflow2 (number, range<number>, repeating) ${r("Additional future cash flows.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,...t){const o=jr(e);return qr((()=>-1!==o),r("The discount (%s) must be different from -1.",o.toString())),function(e,t,o){let i=0;return ss(o,((t,o)=>(i++,t+o/(1+e)**i)),t)}(o,0,t)},isExported:!0},ah={description:r("Computes the number of periods needed for an investment to reach a value."),args:Br(`\n rate (number) ${r("The rate at which the investment grows each period.")}\n present_value (number) ${r("The investment's current value.")}\n future_value (number) ${r("The investment's desired future value.")}\n `),returns:["NUMBER"],compute:function(e,t,o){const i=jr(e),n=jr(t),s=jr(o);return mc(i),qr((()=>n>0),r("The present_value (%s) must be strictly positive.",n.toString())),qr((()=>s>0),r("The future_value (%s) must be strictly positive.",s.toString())),(Math.log(s)-Math.log(n))/Math.log(1+i)},isExported:!0},lh={description:r("Periodic payment for an annuity investment."),args:Br(`\n rate (number) ${r("The annualized rate of interest.")}\n number_of_periods (number) ${r("The number of payments to be made.")}\n present_value (number) ${r("The current value of the annuity.")}\n future_value (number, default=0) ${r("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,n=0){i=i||0,n=n||0;const r=jr(t),s=jr(e),a=Jr(n)?1:0;let l=jr(i),c=jr(o);if(pc(r),0===s)return-(l+c)/r;let h=-(c*(1+s)**r+l);return h=h*s/((1+s*a)*((1+s)**r-1)),h},isExported:!0},ch={description:r("Payment on the principal of an investment."),args:Br(`\n rate (number) ${r("The annualized rate of interest.")}\n period (number) ${r("The amortization period, in terms of number of periods.")}\n number_of_periods (number) ${r("The number of payments to be made.")}\n present_value (number) ${r("The current value of the annuity.")}\n future_value (number, default=0) ${r("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i,n=0,s=0){n=n||0,s=s||0;const a=jr(o),l=jr(e),c=jr(t),h=Jr(s)?1:0,d=jr(n),u=jr(i);pc(a),qr((()=>c>0&&c<=a),r("The period must be between 1 and number_of_periods",a.toString()));const g=lh.compute(l,a,u,d,s);if(1===h&&1===c)return g;return g+-Yc.compute(l,0===h?c-1:c-2,g,u+g*h,0)*l},isExported:!0},hh={description:r("Present value of an annuity investment."),args:Br(`\n rate (number) ${r("The interest rate.")}\n number_of_periods (number) ${r("The number of payments to be made.")}\n payment_amount (number) ${r("The amount per period to be paid.")}\n future_value (number, default=0) ${r("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i=0,n=0){i=i||0,n=n||0;const r=jr(e),s=jr(t),a=jr(o),l=jr(i),c=Jr(n)?1:0;return r?-(a*(1+r*c)*((1+r)**s-1)/r+l)/(1+r)**s:-(l+a*s)},isExported:!0},dh={description:r("Price of a security paying periodic interest."),args:Br(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${r("The annualized rate of interest.")}\n yield (number) ${r("The expected annual yield of the security.")}\n redemption (number) ${r("The redemption amount per 100 face value, or par.")}\n frequency (number) ${r("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,s,a=0){a=a||0;const l=Math.trunc(jr(e)),c=Math.trunc(jr(t)),h=jr(o),d=jr(i),u=jr(n),g=Math.trunc(jr(s)),p=Math.trunc(jr(a));lc(l,c),hc(g),dc(p),qr((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),qr((()=>d>=0),r("The yield (%s) must be positive or null.",d.toString())),uc(u);const m=Kl.compute(l,c,p)*g,f=Math.ceil(m),v=m-Math.floor(m)||1,b=1+d/g,C=100*h/g;if(1===f)return(C+u)/(v*d/g+1)-C*(1-v);let S=0;for(let e=1;e<=f;e++)S+=C/b**(e-1+v);return u/b**(f-1+v)+S-C*(1-v)},isExported:!0},uh={description:r("Price of a discount security."),args:Br(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n discount (number) ${r("The discount rate of the security at time of purchase.")}\n redemption (number) ${r("The redemption amount per 100 face value, or par.")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n=0){n=n||0;const r=Math.trunc(jr(e)),s=Math.trunc(jr(t)),a=jr(o),l=jr(i),c=Math.trunc(jr(n));lc(r,s),dc(c),yc(a),uc(l);return l-a*l*Kl.compute(r,s,c)},isExported:!0},gh={description:r("Calculates the price of a security paying interest at maturity, based on expected yield."),args:Br(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n issue (date) ${r("The date the security was initially issued.")}\n rate (number) ${r("The annualized rate of interest.")}\n yield (number) ${r("The expected annual yield of the security.")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,s=0){s=s||0;const a=Math.trunc(jr(e)),l=Math.trunc(jr(t)),c=Math.trunc(jr(o)),h=jr(i),d=jr(n),u=Math.trunc(jr(s));cc(a,c),lc(a,l),dc(u),qr((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),qr((()=>d>=0),r("The yield (%s) must be positive or null.",d.toString()));const g=Kl.compute(a,l,u),p=Kl.compute(a,c,u);return(100+Kl.compute(c,l,u)*h*100)/(1+g*d)-p*h*100},isExported:!0},ph=.1,mh={description:r("Interest rate of an annuity investment."),args:Br(`\n number_of_periods (number) ${r("The number of payments to be made.")}\n payment_per_period (number) ${r("The amount per period to be paid.")}\n present_value (number) ${r("The current value of the annuity.")}\n future_value (number, default=0) ${r("The future value remaining after the final payment has been made.")}\n end_or_beginning (number, default=0) ${r("Whether payments are due at the end (0) or beginning (1) of each period.")}\n rate_guess (number, default=0.1) ${r("An estimate for what the interest rate will be.")}\n `),returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t,o,i=0,n=0,s=.1){i=i||0,n=n||0,s=s||ph;const a=jr(e),l=jr(t),c=Jr(n)?1:0,h=jr(s);let d=jr(i),u=jr(o);pc(a),qr((()=>[l,u,d].some((e=>e>0))&&[l,u,d].some((e=>e<0))),r("There must be both positive and negative values in [payment_amount, present_value, future_value].",a.toString())),Ac(h),d-=l*c,u+=l*c;return _c((e=>{const t=Math.pow(1+e,a);return d+u*t+l*((t-1)/e)}),(e=>{const t=Math.pow(1+e,a-1),o=Math.pow(1+e,a);return u*a*t+l*(a*t/e-(o-1)/e/e)}),h,40,1e-5)},isExported:!0},fh={description:r("Amount received at maturity for a security."),args:Br(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n investment (number) ${r("The amount invested (irrespective of face value of each security).")}\n discount (number) ${r("The discount rate of the security invested in.")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n=0){n=n||0;const r=Math.trunc(jr(e)),s=Math.trunc(jr(t)),a=jr(o),l=jr(i),c=Math.trunc(jr(n));lc(r,s),dc(c),wc(a),yc(l);return a/(1-l*Kl.compute(r,s,c))},isExported:!0},vh={description:r("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:Br(`\n number_of_periods (number) ${r("The number of periods.")}\n present_value (number) ${r("The present value of the investment.")}\n future_value (number) ${r("The future value of the investment.")}\n `),returns:["NUMBER"],compute:function(e,t,o){const i=jr(e),n=jr(t),r=jr(o);return pc(i),(r/n)**(1/i)-1},isExported:!0},bh={description:r("Depreciation of an asset using the straight-line method."),args:Br(`\n cost (number) ${r("The initial cost of the asset.")}\n salvage (number) ${r("The value of the asset at the end of depreciation.")}\n life (number) ${r("The number of periods over which the asset is depreciated.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o){return(jr(e)-jr(t))/jr(o)},isExported:!0},Ch={description:r("Depreciation via sum of years digit method."),args:Br(`\n cost (number) ${r("The initial cost of the asset.")}\n salvage (number) ${r("The value of the asset at the end of depreciation.")}\n life (number) ${r("The number of periods over which the asset is depreciated.")}\n period (number) ${r("The single period within life for which to calculate depreciation.")}\n `),returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,o,i){const n=jr(e),r=jr(t),s=jr(o),a=jr(i);bc(a),fc(s),Ec(a,s);return(s-a+1)/(s*(s+1)/2)*(n-r)},isExported:!0},Sh={description:r("Price of a US Treasury bill."),args:Br(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n discount (number) ${r("The discount rate of the bill at time of purchase.")}\n `),returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(jr(e)),n=Math.trunc(jr(t)),r=jr(o);lc(i,n),Rc(i,n),yc(r),xc(r);return 100*(1-r*Kl.compute(i,n,2))},isExported:!0},Eh={description:r("Equivalent rate of return for a US Treasury bill."),args:Br(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n discount (number) ${r("The discount rate of the bill at time of purchase.")}\n `),returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(jr(e)),n=Math.trunc(jr(t)),r=jr(o);lc(i,n),Rc(i,n),yc(r),xc(r);const s=Ml.compute(n,i);if(s<=182)return 365*r/(360-r*s);const a=Sh.compute(i,n,r)/100,l=s/(366===s?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},wh={description:r("The yield of a US Treasury bill based on price."),args:Br(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n price (number) ${r("The price at which the security is bought per 100 face value.")}\n `),returns:["NUMBER"],compute:function(e,t,o){const i=Math.trunc(jr(e)),n=Math.trunc(jr(t)),r=jr(o);lc(i,n),Rc(i,n),gc(r);return(100-r)/r*(1/Kl.compute(i,n,2))},isExported:!0},yh={description:r("Variable declining balance. WARNING : does not handle decimal periods."),args:Br(`\n cost (number) ${r("The initial cost of the asset.")}\n salvage (number) ${r("The value of the asset at the end of depreciation.")}\n life (number) ${r("The number of periods over which the asset is depreciated.")}\n start (number) ${r("Starting period to calculate depreciation.")}\n end (number) ${r("Ending period to calculate depreciation.")}\n factor (number, default=2) ${r("The number of months in the first year of depreciation.")}\n no_switch (number, default=false) ${r("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,s=2,a=false){s=s||0;const l=jr(e),c=jr(t),h=jr(o),d=Math.trunc(jr(i)),u=Math.trunc(jr(n)),g=jr(s),p=Jr(a);if(vc(l),Cc(c),function(e,t,o){fc(o),qr((()=>e>=0),r("The start_period (%s) must be greater or equal than 0.",e.toString())),qr((()=>t>=0),r("The end_period (%s) must be greater or equal than 0.",t.toString())),qr((()=>e<=t),r("The start_period (%s) must be smaller or equal to the end_period (%s).",e.toString(),t.toString())),qr((()=>t<=o),r("The end_period (%s) must be smaller or equal to the life (%s).",e.toString(),o.toString()))}(d,u,h),Ic(g),0===l)return 0;if(c>=l)return d<1?l-c:0;const m=g/h;if(m>=1)return d<1?l-c:0;let f=l,v=0,b=0,C=!1;for(let e=0;e<u;e++){if(!C||p){const t=f*m,o=(f-c)/(h-e);!p&&o>t?(C=!0,v=o):v=t}const t=Math.max(f-v,c);e>=d&&(b+=f-t),f=t}return b},isExported:!0},xh={description:r("Internal rate of return given non-periodic cash flows."),args:Br(`\n cashflow_amounts (range<number>) ${r("An range containing the income or payments associated with the investment.")}\n cashflow_dates (range<number>) ${r("An range with dates corresponding to the cash flows in cashflow_amounts.")}\n rate_guess (number, default=0.1) ${r("An estimate for what the internal rate of return will be.")}\n `),returns:["NUMBER"],compute:function(e,t,o=.1){const i=jr(o=o||0),n=e.flat().map(jr),s=t.flat().map(jr);var a;Oc(e,t),a=n,qr((()=>a.some((e=>e>0))&&a.some((e=>e<0))),r("There must be both positive and negative values in cashflow_amounts.")),Mc(s),Ac(i);const l=new Map;for(const e of Ue(0,s.length)){const t=s[e];l.has(t)?l.set(t,l.get(t)+n[e]):l.set(t,n[e])}const c=Array.from(l.keys()),h=c.map((e=>l.get(e)));return _c((e=>{let t=h[0];for(const o of Ue(1,h.length)){const i=(c[0]-c[o])/365;t+=h[o]*(1+e)**i}return t}),(e=>{let t=0;for(const o of Ue(1,h.length)){const i=(c[0]-c[o])/365;t+=i*h[o]*(1+e)**(i-1)}return t}),i,40,1e-5,(e=>e?e/10-.9:-.9))},isExported:!0},Ih={description:r("Net present value given to non-periodic cash flows.."),args:Br(`\n discount (number) ${r("The discount rate of the investment over one period.")}\n cashflow_amounts (number, range<number>) ${r("An range containing the income or payments associated with the investment.")}\n cashflow_dates (number, range<number>) ${r("An range with dates corresponding to the cash flows in cashflow_amounts.")}\n `),returns:["NUMBER"],compute:function(e,t,o){const i=jr(e),n=Array.isArray(t)?t.flat().map(Xr):[Xr(t)],s=Array.isArray(o)?o.flat().map(Xr):[Xr(o)];if(Array.isArray(o)&&Array.isArray(t)?Oc(t,o):qr((()=>n.length===s.length),r("There must be the same number of values in cashflow_amounts and cashflow_dates.")),Mc(s),mc(i),1===n.length)return n[0];const a=new Map;for(const e of Ue(0,s.length)){const t=s[e];a.has(t)?a.set(t,a.get(t)+n[e]):a.set(t,n[e])}const l=Array.from(a.keys()),c=l.map((e=>a.get(e)));let h=c[0];for(const e of Ue(1,c.length)){const t=(l[0]-l[e])/365;h+=c[e]*(1+i)**t}return h},isExported:!0},Rh={description:r("Annual yield of a security paying periodic interest."),args:Br(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n rate (number) ${r("The annualized rate of interest.")}\n price (number) ${r("The price at which the security is bought per 100 face value.")}\n redemption (number) ${r("The redemption amount per 100 face value, or par.")}\n frequency (number) ${r("The number of interest or coupon payments per year (1, 2, or 4).")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,s,a=0){a=a||0;const l=Math.trunc(jr(e)),c=Math.trunc(jr(t)),h=jr(o),d=jr(i),u=jr(n),g=Math.trunc(jr(s)),p=Math.trunc(jr(a));lc(l,c),hc(g),dc(p),qr((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),gc(d),uc(u);const m=Kl.compute(l,c,p)*g,f=Math.ceil(m),v=m-Math.floor(m)||1,b=100*h/g;if(1===f){const e=d+b*(1-v);return(u+b-e)*g*(1/v)/e}const C=_c((function(e){return function(e,t,o,i,n,r){let s=r-(e+n*(1-t))*i**(o-1+t);for(let e=1;e<=o;e++)s+=n*i**(e-1);return s}(d,v,f,e,b,u)}),(function(e){return function(e,t,o,i,n){let r=-(e+n*(1-t))*(o-1+t)*i**(o-2+t);for(let e=1;e<=o;e++)r+=n*(e-1)*i**(e-2);return r}(d,v,f,e,b)}),1+(h+1)/g,100,1e-5);return(C-1)*g},isExported:!0},Th={description:r("Annual yield of a discount security."),args:Br(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n price (number) ${r("The price at which the security is bought per 100 face value.")}\n redemption (number) ${r("The redemption amount per 100 face value, or par.")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n=0){n=n||0;const r=Math.trunc(jr(e)),s=Math.trunc(jr(t)),a=jr(o),l=jr(i),c=Math.trunc(jr(n));lc(r,s),dc(c),gc(a),uc(l);return(l/a-1)/Kl.compute(e,t,n)},isExported:!0},Ah={description:r("Annual yield of a security paying interest at maturity."),args:Br(`\n settlement (date) ${r("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")}\n maturity (date) ${r("The maturity or end date of the security, when it can be redeemed at face, or par value.")}\n issue (date) ${r("The date the security was initially issued.")}\n rate (number) ${r("The annualized rate of interest.")}\n price (number) ${r("The price at which the security is bought.")}\n day_count_convention (number, default=0 ) ${r("An indicator of what day count method to use.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i,n,s=0){s=s||0;const a=Math.trunc(jr(e)),l=Math.trunc(jr(t)),c=Math.trunc(jr(o)),h=jr(i),d=jr(n),u=Math.trunc(jr(s));lc(a,l),dc(u),qr((()=>a>=c),r("The settlement (%s) must be greater than or equal to the issue (%s).",a.toString(),c.toString())),qr((()=>h>=0),r("The rate (%s) must be positive or null.",h.toString())),gc(d);const g=Kl.compute(c,l,u),p=Kl.compute(c,a,u),m=Kl.compute(a,l,u);return(100*(1+h*g)/(d+100*h*p)-1)/m},isExported:!0};var Oh=Object.freeze({__proto__:null,ACCRINTM:Fc,AMORLINC:Dc,COUPDAYS:kc,COUPDAYBS:$c,COUPDAYSNC:Pc,COUPNCD:Lc,COUPNUM:Uc,COUPPCD:Vc,CUMIPMT:zc,CUMPRINC:Bc,DB:Hc,DDB:Wc,DISC:Gc,DOLLARDE:qc,DOLLARFR:Zc,DURATION:jc,EFFECT:Xc,FV:Yc,FVSCHEDULE:Kc,INTRATE:Qc,IPMT:Jc,IRR:eh,ISPMT:th,MDURATION:oh,MIRR:ih,NOMINAL:nh,NPER:rh,NPV:sh,PDURATION:ah,PMT:lh,PPMT:ch,PV:hh,PRICE:dh,PRICEDISC:uh,PRICEMAT:gh,RATE:mh,RECEIVED:fh,RRI:vh,SLN:bh,SYD:Ch,TBILLPRICE:Sh,TBILLEQ:Eh,TBILLYIELD:wh,VDB:yh,XIRR:xh,XNPV:Ih,YIELD:Rh,YIELDDISC:Th,YIELDMAT:Ah});const Mh={description:r("Whether a value is an error other than #N/A."),args:Br(`value (any, lazy) ${r("The value to be verified as an error type.")}`),returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return(null==e?void 0:e.errorType)!=a.NotAvailable}},isExported:!0},Nh={description:r("Whether a value is an error."),args:Br(`value (any, lazy) ${r("The value to be verified as an error type.")}`),returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},_h={description:r("Whether a value is `true` or `false`."),args:Br(`value (any, lazy) ${r("The value to be verified as a logical TRUE or FALSE.")}`),returns:["BOOLEAN"],compute:function(e){try{return"boolean"==typeof e()}catch(e){return!1}},isExported:!0},Fh={description:r("Whether a value is the error #N/A."),args:Br(`value (any, lazy) ${r("The value to be verified as an error type.")}`),returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return(null==e?void 0:e.errorType)==a.NotAvailable}},isExported:!0},Dh={description:r("Whether a value is non-textual."),args:Br(`value (any, lazy) ${r("The value to be checked.")}`),returns:["BOOLEAN"],compute:function(e){try{return"string"!=typeof e()}catch(e){return!0}},isExported:!0},kh={description:r("Whether a value is a number."),args:Br(`value (any, lazy) ${r("The value to be verified as a number.")}`),returns:["BOOLEAN"],compute:function(e){try{return"number"==typeof e()}catch(e){return!1}},isExported:!0},$h={description:r("Whether a value is text."),args:Br(`value (any, lazy) ${r("The value to be verified as text.")}`),returns:["BOOLEAN"],compute:function(e){try{return"string"==typeof e()}catch(e){return!1}},isExported:!0},Ph={description:r("Whether the referenced cell is empty"),args:Br(`value (any, lazy) ${r("Reference to the cell that will be checked for emptiness.")}`),returns:["BOOLEAN"],compute:function(e){try{return null===e()}catch(e){return!1}},isExported:!0},Lh={description:r("Returns the error value #N/A."),args:Br(""),returns:["BOOLEAN"],compute:function(e){throw new g},isExported:!0};var Uh=Object.freeze({__proto__:null,ISERR:Mh,ISERROR:Nh,ISLOGICAL:_h,ISNA:Fh,ISNONTEXT:Dh,ISNUMBER:kh,ISTEXT:$h,ISBLANK:Ph,NA:Lh});const Vh={description:r("Logical `and` operator."),args:Br(`\n logical_expression1 (boolean, range<boolean>) ${r("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${r("More expressions that represent logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!0;return ls(e,(e=>(t=!0,o=o&&e,o))),qr((()=>t),r("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0},zh={description:r("Returns value depending on logical expression."),args:Br(`\n logical_expression (boolean) ${r("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) ${r("The value the function returns if logical_expression is TRUE.")}\n value_if_false (any, lazy, default=FALSE) ${r("The value the function returns if logical_expression is FALSE.")}\n `),returns:["ANY"],compute:function(e,t,o=(()=>!1)){const i=Jr(e)?t():o();return null==i?"":i},isExported:!0},Bh={description:r("Value if it is not an error, otherwise 2nd argument."),args:Br(`\n value (any, lazy) ${r("The value to return if value itself is not an error.")}\n value_if_error (any, lazy, default=${r("An empty value")}) ${r("The value the function returns if value is an error.")}\n `),returns:["ANY"],computeFormat:(e,t=(()=>({value:""})))=>{var o;try{return e().format}catch(e){return null===(o=t())||void 0===o?void 0:o.format}},compute:function(e,t=(()=>"")){let o;try{o=e()}catch(e){o=t()}return null==o?"":o},isExported:!0},Hh={description:r("Value if it is not an #N/A error, otherwise 2nd argument."),args:Br(`\n value (any, lazy) ${r("The value to return if value itself is not #N/A an error.")}\n value_if_error (any, lazy, default=${r("An empty value")}) ${r("The value the function returns if value is an #N/A error.")}\n `),returns:["ANY"],compute:function(e,t=(()=>"")){let o;try{o=e()}catch(i){o=i.errorType===a.NotAvailable?t():e()}return null==o?"":o},isExported:!0},Wh={description:r("Returns a value depending on multiple logical expressions."),args:Br(`\n condition1 (boolean, lazy) ${r("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")}\n value1 (any, lazy) ${r("The returned value if condition1 is TRUE.")}\n condition2 (boolean, lazy, repeating) ${r("Additional conditions to be evaluated if the previous ones are FALSE.")}\n value2 (any, lazy, repeating) ${r("Additional values to be returned if their corresponding conditions are TRUE.")}\n `),returns:["ANY"],compute:function(...e){qr((()=>e.length%2==0),r("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(Jr(e[t]())){const o=e[t+1]();return null!==o?o:""}throw new Error(r("No match."))},isExported:!0},Gh={description:r("Returns opposite of provided logical value."),args:Br(`logical_expression (boolean) ${r("An expression or reference to a cell holding an expression that represents some logical value.")}\n `),returns:["BOOLEAN"],compute:function(e){return!Jr(e)},isExported:!0},qh={description:r("Logical `or` operator."),args:Br(`\n logical_expression1 (boolean, range<boolean>) ${r("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${r("More expressions that evaluate to logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!1;return ls(e,(e=>(t=!0,o=o||e,!o))),qr((()=>t),r("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0},Zh={description:r("Logical `xor` operator."),args:Br(`\n logical_expression1 (boolean, range<boolean>) ${r("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")}\n logical_expression2 (boolean, range<boolean>, repeating) ${r("More expressions that evaluate to logical values.")}\n `),returns:["BOOLEAN"],compute:function(...e){let t=!1,o=!1;return ls(e,(e=>(t=!0,o=o?!e:e,!0))),qr((()=>t),r("[[FUNCTION_NAME]] has no valid input data.")),o},isExported:!0};var jh=Object.freeze({__proto__:null,AND:Vh,IF:zh,IFERROR:Bh,IFNA:Hh,IFS:Wh,NOT:Gh,OR:qh,XOR:Zh});function Xh(e,t){if(void 0===e)throw new g(r("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",Yr(t)))}const Yh={description:r("Column number of a specified cell."),args:Br(`cell_reference (meta, default=${r("The cell in which the formula is entered")}) ${r("The cell whose column number will be returned. Column A corresponds to 1.")}\n `),returns:["NUMBER"],compute:function(e){var t;const o=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this));qr((()=>!!o),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Mo(o).left+1},isExported:!0},Kh={description:r("Number of columns in a specified array or range."),args:Br(`range (meta) ${r("The range whose column count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=Mo(e);return t.right-t.left+1},isExported:!0},Qh={description:r("Horizontal lookup"),args:Br(`\n search_key (any) ${r("The value to search for. For example, 42, 'Cats', or I24.")}\n range (range) ${r("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")}\n index (number) ${r("The row index of the value to be returned, where the first row in range is numbered 1.")}\n is_sorted (boolean, default=true) ${r("Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned.")}\n `),returns:["ANY"],compute:function(e,t,o,i=true){const n=Math.trunc(jr(o)),s=Kr(e);qr((()=>1<=n&&n<=t[0].length),r("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=Jr(i)?ps(t,s,"nextSmaller","asc",t.length,gs):ms(t,s,"strict",t.length,gs);const l=t[a];return Xh(l,e),l[n-1]},isExported:!0},Jh={description:r("Look up a value."),args:Br(`\n search_key (any) ${r("The value to search for. For example, 42, 'Cats', or I24.")}\n search_array (range) ${r("One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.")}\n result_range (range, optional) ${r("The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method.")}\n `),returns:["ANY"],compute:function(e,t,o){let i=t.length,n=t[0].length;const s=Kr(e),a=n>=i,l=ps(t,s,"nextSmaller","asc",a?n:i,a?us:gs);return-1===l&&Xh(void 0,e),Xh(a?t[0][l]:t[l][n-1],e),void 0===o?a?t[i-1][l]:t[l][n-1]:(i=o.length,n=o[0].length,qr((()=>1===i||1===n),r("The result_range must be a single row or a single column.")),i>1?(qr((()=>l<=i-1),r("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(l+1).toString())),o[l][0]):(qr((()=>l<=n-1),r("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(l+1).toString())),o[0][l]))},isExported:!0},ed={description:r("Position of item in range that matches value."),args:Br(`\n search_key (any) ${r("The value to search for. For example, 42, 'Cats', or I24.")}\n range (any, range) ${r("The one-dimensional array to be searched.")}\n search_type (number, default=1) ${r("The search method. 1 (default) finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order.")}\n `),returns:["NUMBER"],compute:function(e,t,o=1){let i=jr(o);const n=Kr(e),s=t.length,a=t[0].length;qr((()=>1===s||1===a),r("The range must be a single row or a single column."));let l=-1;const c=1===s?us:gs,h=1===s?t[0].length:t.length;switch(i=Math.sign(i),i){case 1:l=ps(t,n,"nextSmaller","asc",h,c);break;case 0:l=ms(t,n,"strict",h,c);break;case-1:l=ps(t,n,"nextGreater","desc",h,c)}return Xh(1===s?t[0][l]:t[l],e),l+1},isExported:!0},td={description:r("Row number of a specified cell."),args:Br(`cell_reference (meta, default=${r("The cell in which the formula is entered by default")}) ${r("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)),qr((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Mo(e).top+1},isExported:!0},od={description:r("Number of rows in a specified array or range."),args:Br(`range (meta) ${r("The range whose row count will be returned.")}`),returns:["NUMBER"],compute:function(e){const t=Mo(e);return t.bottom-t.top+1},isExported:!0},id={description:r("Vertical lookup."),args:Br(`\n search_key (any) ${r("The value to search for. For example, 42, 'Cats', or I24.")}\n range (any, range) ${r("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")}\n index (number) ${r("The column index of the value to be returned, where the first column in range is numbered 1.")}\n is_sorted (boolean, default=true) ${r("Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned.")}\n `),returns:["ANY"],compute:function(e,t,o,i=true){const n=Math.trunc(jr(o)),s=Kr(e);qr((()=>1<=n&&n<=t.length),r("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=Jr(i)?ps(t,s,"nextSmaller","asc",t[0].length,us):ms(t,s,"strict",t[0].length,us);const l=t[n-1][a];return Xh(l,e),l},isExported:!0},nd={description:r("Search a range for a match and return the corresponding item from a second range."),args:Br(`\n search_key (any) ${r("The value to search for.")}\n lookup_range (any, range) ${r("The range to consider for the search. Should be a single column or a single row.")}\n return_range (any, range) ${r("The range containing the return value. Should have the same dimensions as lookup_range.")}\n if_not_found (any, lazy, optional) ${r("If a valid match is not found, return this value.")}\n match_mode (any, default=0) ${r("(0) Exact match. (-1) Return next smaller item if no match. (1) Return next greater item if no match.")}\n search_mode (any, default=1) ${r("(1) Search starting at first item. (-1) Search starting at last item. (2) Perform a binary search that relies on lookup_array being sorted in ascending order. If not sorted, invalid results will be returned. (-2) Perform a binary search that relies on lookup_array being sorted in descending order. If not sorted, invalid results will be returned. ")}\n\n `),returns:["ANY"],compute:function(e,t,o,i,n=0,s=1){const a=Math.trunc(jr(n)),l=Math.trunc(jr(s)),c=Kr(e);qr((()=>1===t.length||1===t[0].length),r("lookup_range should be either a single row or single column.")),qr((()=>1===o.length||1===o[0].length),r("return_range should be either a single row or single column.")),qr((()=>o.length===t.length&&o[0].length===t[0].length),r("return_range should have the same dimensions as lookup_range.")),qr((()=>[-1,1,-2,2].includes(l)),r("searchMode should be a value in [-1, 1, -2, 2].")),qr((()=>[-1,0,1].includes(a)),r("matchMode should be a value in [-1, 0, 1]."));const h=1===t.length?us:gs,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=ps(t,c,u,2===l?"asc":"desc",d,h)}else p=ms(t,c,u,d,h,g);if(-1!==p)return 1===t.length?o[0][p]:o[p][0];const m=null==i?void 0:i();return Xh(m,e),m},isExported:!0};var rd=Object.freeze({__proto__:null,COLUMN:Yh,COLUMNS:Kh,HLOOKUP:Qh,LOOKUP:Jh,MATCH:ed,ROW:td,ROWS:od,VLOOKUP:id,XLOOKUP:nd});const sd={description:r("Sum of two numbers."),args:Br(`\n value1 (number) ${r("The first addend.")}\n value2 (number) ${r("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 jr(e)+jr(t)}},ad={description:r("Concatenation of two values."),args:Br(`\n value1 (string) ${r("The value to which value2 will be appended.")}\n value2 (string) ${r("The value to append to value1.")}\n `),returns:["STRING"],compute:function(e,t){return Yr(e)+Yr(t)},isExported:!0},ld={description:r("One number divided by another."),args:Br(`\n dividend (number) ${r("The number to be divided.")}\n divisor (number) ${r("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 o=jr(t);return qr((()=>0!==o),r("The divisor must be different from zero.")),jr(e)/o}};function cd(e){return null==e}const hd={number:0,string:"",boolean:!1},dd={description:r("Equal."),args:Br(`\n value1 (any) ${r("The first value.")}\n value2 (any) ${r("The value to test against value1 for equality.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return e=cd(e)?hd[typeof t]:e,t=cd(t)?hd[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function ud(e,t,o){e=cd(e)?hd[typeof t]:e,t=cd(t)?hd[typeof e]:t,"number"!=typeof e&&(e=Yr(e).toUpperCase()),"number"!=typeof t&&(t=Yr(t).toUpperCase());const i=typeof e,n=typeof t;return"string"===i&&"number"===n||("string"!==n||"number"!==i)&&o(e,t)}const gd={description:r("Strictly greater than."),args:Br(`\n value1 (any) ${r("The value to test as being greater than value2.")}\n value2 (any) ${r("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return ud(e,t,((e,t)=>e>t))}},pd={description:r("Greater than or equal to."),args:Br(`\n value1 (any) ${r("The value to test as being greater than or equal to value2.")}\n value2 (any) ${r("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return ud(e,t,((e,t)=>e>=t))}},md={description:r("Less than."),args:Br(`\n value1 (any) ${r("The value to test as being less than value2.")}\n value2 (any) ${r("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!pd.compute(e,t)}},fd={description:r("Less than or equal to."),args:Br(`\n value1 (any) ${r("The value to test as being less than or equal to value2.")}\n value2 (any) ${r("The second value.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!gd.compute(e,t)}},vd={description:r("Difference of two numbers."),args:Br(`\n value1 (number) ${r("The minuend, or number to be subtracted from.")}\n value2 (number) ${r("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 jr(e)-jr(t)}},bd={description:r("Product of two numbers"),args:Br(`\n factor1 (number) ${r("The first multiplicand.")}\n factor2 (number) ${r("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 jr(e)*jr(t)}},Cd={description:r("Not equal."),args:Br(`\n value1 (any) ${r("The first value.")}\n value2 (any) ${r("The value to test against value1 for inequality.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return!dd.compute(e,t)}},Sd={description:r("A number raised to a power."),args:Br(`\n base (number) ${r("The number to raise to the exponent power.")}\n exponent (number) ${r("The exponent to raise base to.")}\n `),returns:["NUMBER"],compute:function(e,t){return ia.compute(e,t)}},Ed={description:r("A number with the sign reversed."),args:Br(`\n value (number) ${r("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-jr(e)}},wd={description:r("Value interpreted as a percentage."),args:Br(`\n percentage (number) ${r("The value to interpret as a percentage.")}\n `),returns:["NUMBER"],compute:function(e){return jr(e)/100}},yd={description:r("A specified number, unchanged."),args:Br(`\n value (any) ${r("The number to return.")}\n `),returns:["ANY"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){return null===e?"":e}};var xd=Object.freeze({__proto__:null,ADD:sd,CONCAT:ad,DIVIDE:ld,EQ:dd,GT:gd,GTE:pd,LT:md,LTE:fd,MINUS:vd,MULTIPLY:bd,NE:Cd,POW:Sd,UMINUS:Ed,UNARY_PERCENT:wd,UPLUS:yd});const Id=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,Rd={description:r("Gets character associated with number."),args:Br(`\n table_number (number) ${r("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(jr(e));return qr((()=>t>=1),r("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},Td={description:r("Remove non-printable characters from a piece of text."),args:Br(`\n text (string) ${r("The text whose non-printable characters are to be removed.")}\n `),returns:["STRING"],compute:function(e){const t=Yr(e);let o="";for(const e of t)e&&e.charCodeAt(0)>31&&(o+=e);return o},isExported:!0},Ad={description:r("Appends strings to one another."),args:Br(`\n string1 (string, range<string>) ${r("The initial string.")}\n string2 (string, range<string>, repeating) ${r("More strings to append in sequence.")}\n `),returns:["STRING"],compute:function(...e){return rs(e,((e,t)=>e+Yr(t)),"")},isExported:!0},Od={description:r("Tests whether two strings are identical."),args:Br(`\n string1 (string) ${r("The first string to compare.")}\n string2 (string) ${r("The second string to compare.")}\n `),returns:["BOOLEAN"],compute:function(e,t){return Yr(e)===Yr(t)},isExported:!0},Md={description:r("First position of string found in text, case-sensitive."),args:Br(`\n search_for (string) ${r("The string to look for within text_to_search.")}\n text_to_search (string) ${r("The text to search for the first occurrence of search_for.")}\n starting_at (number, default=1) ${r("The character within text_to_search at which to start the search.")}\n `),returns:["NUMBER"],compute:function(e,t,o=1){const i=Yr(e),n=Yr(t),s=jr(o);qr((()=>""!==n),r("The text_to_search must be non-empty.")),qr((()=>s>=1),r("The starting_at (%s) must be greater than or equal to 1.",s.toString()));const a=n.indexOf(i,s-1);return qr((()=>a>=0),r("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i.toString(),n)),a+1},isExported:!0},Nd={description:r("Concatenates elements of arrays with delimiter."),args:Br(`\n delimiter (string) ${r("The character or string to place between each concatenated value.")}\n value_or_array1 (string, range<string>) ${r("The value or values to be appended using delimiter.")}\n value_or_array2 (string, range<string>, repeating) ${r("More values to be appended using delimiter.")}\n `),returns:["STRING"],compute:function(e,...t){const o=Yr(e);return rs(t,((e,t)=>(e?e+o:"")+Yr(t)),"")}},_d={description:r("Substring from beginning of specified string."),args:Br(`\n text (string) ${r("The string from which the left portion will be returned.")}\n number_of_characters (number, optional) ${r("The number of characters to return from the left side of string.")}\n `),returns:["STRING"],compute:function(e,...t){const o=t.length?jr(t[0]):1;return qr((()=>o>=0),r("The number_of_characters (%s) must be positive or null.",o.toString())),Yr(e).substring(0,o)},isExported:!0},Fd={description:r("Length of a string."),args:Br(`\n text (string) ${r("The string whose length will be returned.")}\n `),returns:["NUMBER"],compute:function(e){return Yr(e).length},isExported:!0},Dd={description:r("Converts a specified string to lowercase."),args:Br(`\n text (string) ${r("The string to convert to lowercase.")}\n `),returns:["STRING"],compute:function(e){return Yr(e).toLowerCase()},isExported:!0},kd={description:r("A segment of a string."),args:Br(`\n text (string) ${r("The string to extract a segment from.")}\n starting_at (number) ${r("The index from the left of string from which to begin extracting. The first character in string has the index 1.")}\n extract_length (number) ${r("The length of the segment to extract.")}\n `),returns:["STRING"],compute:function(e,t,o){const i=Yr(e),n=jr(t),s=jr(o);return qr((()=>n>=1),r("The starting_at argument (%s) must be positive greater than one.",n.toString())),qr((()=>s>=0),r("The extract_length argument (%s) must be positive or null.",s.toString())),i.slice(n-1,n+s-1)},isExported:!0},$d={description:r("Capitalizes each word in a specified string."),args:Br(`\n text_to_capitalize (string) ${r("The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase.")}\n `),returns:["STRING"],compute:function(e){return Yr(e).replace(Id,(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()))},isExported:!0},Pd={description:r("Replaces part of a text string with different text."),args:Br(`\n text (string) ${r("The text, a part of which will be replaced.")}\n position (number) ${r("The position where the replacement will begin (starting from 1).")}\n length (number) ${r("The number of characters in the text to be replaced.")}\n new_text (string) ${r("The text which will be inserted into the original text.")}\n `),returns:["STRING"],compute:function(e,t,o,i){const n=jr(t);qr((()=>n>=1),r("The position (%s) must be greater than or equal to 1.",n.toString()));const s=Yr(e),a=jr(o),l=Yr(i);return s.substring(0,n-1)+l+s.substring(n-1+a)},isExported:!0},Ld={description:r("A substring from the end of a specified string."),args:Br(`\n text (string) ${r("The string from which the right portion will be returned.")}\n number_of_characters (number, optional) ${r("The number of characters to return from the right side of string.")}\n `),returns:["STRING"],compute:function(e,...t){const o=t.length?jr(t[0]):1;qr((()=>o>=0),r("The number_of_characters (%s) must be positive or null.",o.toString()));const i=Yr(e),n=i.length;return i.substring(n-o,n)},isExported:!0},Ud={description:r("First position of string found in text, ignoring case."),args:Br(`\n search_for (string) ${r("The string to look for within text_to_search.")}\n text_to_search (string) ${r("The text to search for the first occurrence of search_for.")}\n starting_at (number, default=1) ${r("The character within text_to_search at which to start the search.")}\n `),returns:["NUMBER"],compute:function(e,t,o=1){const i=Yr(e).toLowerCase(),n=Yr(t).toLowerCase(),s=jr(o);qr((()=>""!==n),r("The text_to_search must be non-empty.")),qr((()=>s>=1),r("The starting_at (%s) must be greater than or equal to 1.",s.toString()));const a=n.indexOf(i,s-1);return qr((()=>a>=0),r("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",i,n)),a+1},isExported:!0},Vd={description:r("Replaces existing text with new text in a string."),args:Br(`\n text_to_search (string) ${r("The text within which to search and replace.")}\n search_for (string) ${r("The string to search for within text_to_search.")}\n replace_with (string) ${r("The string that will replace search_for.")}\n occurrence_number (number, optional) ${r("The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced.")}\n `),returns:["NUMBER"],compute:function(e,t,o,i){const n=jr(i);qr((()=>n>=0),r("The occurrenceNumber (%s) must be positive or null.",n.toString()));const s=Yr(e),a=Yr(t);if(""===a)return s;const l=Yr(o),c=new RegExp(Oe(a),"g");if(0===n)return s.replace(c,l);let h=0;return s.replace(c,(e=>++h===n?l:e))},isExported:!0},zd={description:r("Combines text from multiple strings and/or arrays."),args:Br(`\n delimiter (string) ${r(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")}\n ignore_empty (boolean) ${r("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")}\n text1 (string, range<string>) ${r("Any text item. This could be a string, or an array of strings in a range.")}\n text2 (string, range<string>, repeating) ${r("Additional text item(s).")}\n `),returns:["STRING"],compute:function(e,t,...o){const i=Yr(e),n=Jr(t);let r=0;return rs(o,((e,t)=>n&&""===Yr(t)?e:(r++?e+i:"")+Yr(t)),"")},isExported:!0},Bd={description:r("Removes space characters."),args:Br(`\n text (string) ${r("The text or reference to a cell containing text to be trimmed.")}\n `),returns:["STRING"],compute:function(e){return Yr(e).trim()},isExported:!0},Hd={description:r("Converts a specified string to uppercase."),args:Br(`\n text (string) ${r("The string to convert to uppercase.")}\n `),returns:["STRING"],compute:function(e){return Yr(e).toUpperCase()},isExported:!0},Wd={description:r("Converts a number to text according to a specified format."),args:Br(`\n number (number) ${r("The number, date or time to format.")}\n format (string) ${r("The pattern by which to format the number, enclosed in quotation marks.")}\n `),returns:["STRING"],compute:function(e,t){return ro(jr(e),Yr(t))},isExported:!0};var Gd=Object.freeze({__proto__:null,CHAR:Rd,CLEAN:Td,CONCATENATE:Ad,EXACT:Od,FIND:Md,JOIN:Nd,LEFT:_d,LEN:Fd,LOWER:Dd,MID:kd,PROPER:$d,REPLACE:Pd,RIGHT:Ld,SEARCH:Ud,SUBSTITUTE:Vd,TEXTJOIN:zd,TRIM:Bd,UPPER:Hd,TEXT:Wd});const qd={description:r("Creates a hyperlink in a cell."),args:Br(`\n url (string) ${r("The full URL of the link enclosed in quotation marks.")}\n link_label (string, optional) ${r("The text to display in the cell, enclosed in quotation marks.")}\n `),returns:["STRING"],compute:function(e,t){const o=Yr(e).trim(),i=Yr(t)||o;return""===o?i:Ze(i,o)},isExported:!0};const Zd={database:Rl,date:rc,financial:Oh,info:Uh,lookup:rd,logical:jh,math:Ea,misc:bs,operators:xd,statistical:dl,text:Gd,engineering:ac,web:Object.freeze({__proto__:null,HYPERLINK:qd})},jd=/^[A-Z0-9\_\.]+$/;function Xd(e){return e.map((e=>{if(void 0!==e)return"function"==typeof e?()=>Yd(e()):Yd(e)}))}function Yd(e){return Array.isArray(e)?e.map((e=>e.map((e=>null==e?void 0:e.value)))):null==e?void 0:e.value}const Kd=new class extends In{constructor(){super(...arguments),this.mapping={}}add(e,t){if(!(e=e.toUpperCase()).match(jd))throw new Error(r("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const o=Wr(t);return function(e){let t=!1,o=!1,i=!1;for(let n of e){if(n.type.includes("META")&&n.type.length>1)throw new Error(r("Function ${name} has an argument that has been declared with more than one type whose type 'META'. The 'META' type can only be declared alone."));if(t&&!n.repeating)throw new Error(r("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=o||t||i,s=!(n.optional||n.repeating||n.default);if(e&&s)throw new Error(r("Function ${name} has at mandatory arguments declared after optional ones. All optional arguments must be after all mandatory arguments."));t=n.repeating,o=n.optional,i=n.default}}(o.args),this.mapping[e]=function(...e){const t=o.compute.bind(this),i=o.computeFormat?o.computeFormat.bind(this):()=>{};return{value:t(...Xd(e)),format:i(...e)}},super.add(e,o),this}};for(let e in Zd){const t=Zd[e];for(let o in t){const i=t[o];i.category=e,o=o.replace(/_/g,"."),Kd.add(o,{isExported:!1,...i})}}const Qd=Kd.content,Jd=["%"],eu="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(Jd);function tu(e){const t=e.split(""),o=[];for(;t.length;){let e=uu(t)||nu(t)||su(t)||lu(t)||ou(t)||gu(t)||au(t)||hu(t);e||(e={type:"UNKNOWN",value:t.shift()}),o.push(e)}return o}function ou(e){return"?"===e[0]?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const iu={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function nu(e){if(e[0]in iu){const t=e.shift();return{type:iu[t],value:t}}return null}function ru(e,t){for(let o=0;o<t.length;o++)if(t[o]!==e[o])return!1;return!0}function su(e){for(let t of eu)if(ru(e,t))return e.splice(0,t.length),{type:"OPERATOR",value:t};return null}function au(e){const t=ot(e).match(zt);return t?(e.splice(0,t[0].length),{type:"NUMBER",value:t[0]}):null}function lu(e){if('"'===e[0]){const t=e.shift();let o=t;for(;e[0]&&(e[0]!==t||"\\"===o[o.length-1]);)o+=e.shift();return'"'===e[0]&&(o+=e.shift()),{type:"STRING",value:o}}return null}const cu=/\w|\.|!|\$/;function hu(e){let t="";if("'"===e[0]){let o=e.shift();for(t+=o;e[0];)if(o=e.shift(),t+=o,"'"===o){if(!e[0]||"'"!==e[0])break;o=e.shift(),t+=o}if("'"!==o)return{type:"UNKNOWN",value:t}}for(;e[0]&&e[0].match(cu);)t+=e.shift();if(t.length){const e=t;if(e.toUpperCase()in Qd)return{type:"FUNCTION",value:e};return e.match(Tt)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}const du=/\s/;function uu(e){let t=0;for(;e[0]&&e[0].match(du);)t++,e.shift();return t?{type:"SPACE",value:" ".repeat(t)}:null}function gu(e){return ru(e,X)?(e.splice(0,X.length),{type:"INVALID_REFERENCE",value:X}):null}const pu=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,mu=["-","+"],fu=["%"],vu=["*","+","&"],bu={"^":30,"%":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10},Cu=6;function Su(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 bu[e.value]||15}throw new h(r("Unknown token: %s",e.value))}function Eu(e,t,o){if("OPERATOR"===t.type){const i=Su(t);if(fu.includes(t.value))return{type:"UNARY_OPERATION",value:t.value,operand:e,postfix:!0};{const n=wu(o,i);return{type:"BIN_OPERATION",value:t.value,left:e,right:n}}}throw new h(se)}function wu(e,t){const o=e.shift();if(!o)throw new h(se);let i=function(e,t){var o,i,n,s;switch(e.type){case"DEBUGGER":const a=wu(t,1e3);return a.debug=!0,a;case"NUMBER":return{type:"NUMBER",value:Xt(e.value)};case"STRING":return{type:"STRING",value:Ae(e.value)};case"FUNCTION":if("LEFT_PAREN"!==t.shift().type)throw new h(r("Wrong function call"));{const i=[];if(t[0]&&"RIGHT_PAREN"!==t[0].type)for("COMMA"===t[0].type?i.push({type:"UNKNOWN",value:""}):i.push(wu(t,Cu));"COMMA"===(null===(o=t[0])||void 0===o?void 0:o.type);){t.shift();const e=t[0];if("RIGHT_PAREN"===(null==e?void 0:e.type)){i.push({type:"UNKNOWN",value:""});break}"COMMA"===(null==e?void 0:e.type)?i.push({type:"UNKNOWN",value:""}):i.push(wu(t,Cu))}const n=t.shift();if(!n||"RIGHT_PAREN"!==n.type)throw new h(r("Wrong function call"));return{type:"FUNCALL",value:e.value,args:i}}case"INVALID_REFERENCE":throw new u;case"REFERENCE":if(":"===(null===(i=t[0])||void 0===i?void 0:i.value)&&"REFERENCE"===(null===(n=t[1])||void 0===n?void 0:n.type)){t.shift();const o=t.shift();return{type:"REFERENCE",value:`${e.value}:${null==o?void 0:o.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(pu.test(e.value)&&"LEFT_PAREN"===(null===(s=t[0])||void 0===s?void 0:s.type))throw new p(e.value);throw new h(r("Invalid formula"))}return{type:"STRING",value:e.value};case"LEFT_PAREN":const l=wu(t,5);if(!t.length||"RIGHT_PAREN"!==t[0].type)throw new h(r("Unmatched left parenthesis"));return t.shift(),l;default:if("OPERATOR"===e.type&&mu.includes(e.value))return{type:"UNARY_OPERATION",value:e.value,operand:wu(t,bu[e.value])};throw new h(r("Unexpected token: %s",e.value))}}(o,e);for(;e[0]&&Su(e[0])>t;)i=Eu(i,e.shift(),e);return i}function yu(e){return xu(tu(e))}function xu(e){"OPERATOR"===(e=e.filter((e=>"SPACE"!==e.type)))[0].type&&"="===e[0].value&&e.splice(0,1);const t=wu(e,0);if(e.length)throw new h(se);return t}function Iu(e,t,o){switch(t===e.type&&(e=o(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>Iu(e,t,o)))};case"UNARY_OPERATION":return{...e,operand:Iu(e.operand,t,o)};case"BIN_OPERATION":return{...e,right:Iu(e.right,t,o),left:Iu(e.left,t,o)};default:return e}}function Ru(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>Ru(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?Tu(e)+e.value:e.value+Au(e);case"BIN_OPERATION":return Tu(e)+e.value+Au(e)}}function Tu(e){const t=e.value,o="left"in e?e.left:e.operand,i=o.value;return"BIN_OPERATION"===o.type&&bu[i]<bu[t]?`(${Ru(o)})`:Ru(o)}function Au(e){const t=e.value,o="right"in e?e.right:e.operand,i=bu[o.value],n=bu[t];let r=!1;return"BIN_OPERATION"!==o.type?r=!1:i<n?r=!0:i!==n||vu.includes(t)||(r=!0),r?`(${Ru(o)})`:Ru(o)}var Ou;!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"}(Ou||(Ou={}));const Mu=(e,t=(()=>!0))=>[{goTo:e,guard:t}],Nu=(e,t=(()=>!0))=>({goTo:e,guard:t}),_u={[Ou.LeftRef]:{REFERENCE:Mu(Ou.Separator),NUMBER:Mu(Ou.FullRowSeparator),SYMBOL:[Nu(Ou.FullColumnSeparator,(e=>At(e.value))),Nu(Ou.FullRowSeparator,(e=>Ot(e.value)))]},[Ou.FullColumnSeparator]:{SPACE:Mu(Ou.FullColumnSeparator),OPERATOR:Mu(Ou.RightColumnRef,(e=>":"===e.value))},[Ou.FullRowSeparator]:{SPACE:Mu(Ou.FullRowSeparator),OPERATOR:Mu(Ou.RightRowRef,(e=>":"===e.value))},[Ou.Separator]:{SPACE:Mu(Ou.Separator),OPERATOR:Mu(Ou.RightRef,(e=>":"===e.value))},[Ou.RightRef]:{SPACE:Mu(Ou.RightRef),NUMBER:Mu(Ou.Found),REFERENCE:Mu(Ou.Found,(e=>Nt(e.value))),SYMBOL:Mu(Ou.Found,(e=>Mt(e.value)))},[Ou.RightColumnRef]:{SPACE:Mu(Ou.RightColumnRef),SYMBOL:Mu(Ou.Found,(e=>Mt(e.value))),REFERENCE:Mu(Ou.Found,(e=>Nt(e.value)))},[Ou.RightRowRef]:{SPACE:Mu(Ou.RightRowRef),NUMBER:Mu(Ou.Found),REFERENCE:Mu(Ou.Found,(e=>Nt(e.value)))},[Ou.Found]:{}};function Fu(e){var t;let o=0,i=_u[Ou.LeftRef];const n=[];for(;void 0!==i;){const r=e[o++];if(!r)return null;const s=null===(t=i[r.type])||void 0===t?void 0:t.find((e=>e.guard(r))),a=s?s.goTo:void 0;switch(a){case void 0:return null;case Ou.Found:return n.push(r),e.splice(0,o),{type:"REFERENCE",value:ot(n.map((e=>e.value)))};default:i=_u[a],n.push(r)}}return null}function Du(e){const t=tu(e),o=[];for(;t.length;)o.push(Fu(t)||t.shift());return o}const ku=Kd.content,$u={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},Pu={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"};function Lu(e){return e.join("\n").split("\n").filter((e=>""!==e.trim()))}const Uu={};function Vu(e){const t=Du(e),{dependencies:o,constantValues:i}=function(e){const t={numbers:[],strings:[]},o=[];for(const i of e)switch(i.type){case"INVALID_REFERENCE":case"REFERENCE":o.push(i.value);break;case"STRING":const e=Ae(i.value);t.strings.includes(e)||t.strings.push(e);break;case"NUMBER":{const e=Xt(i.value);t.numbers.includes(e)||t.numbers.push(e);break}}return{dependencies:o,constantValues:t}}(t),n=function(e,t,o){return ot(e.map((e=>{switch(e.type){case"STRING":const i=Ae(e.value);return`|S${o.strings.indexOf(i)}|`;case"NUMBER":return`|N${o.numbers.indexOf(Xt(e.value))}|`;case"REFERENCE":case"INVALID_REFERENCE":return`|${t.indexOf(e.value)}|`;case"SPACE":return"";default:return e.value}})))}(t,o,i);if(!Uu[n]){const s=xu([...t]);let a=1;if("BIN_OPERATION"===s.type&&":"===s.value)throw new h(r("Invalid formula"));if("UNKNOWN"===s.type)throw new h(r("Invalid formula"));const l=g(s),c=Lu([`// ${n}`,l.code,`return ${l.id};`]).join("\n");let d=new Function("deps","ref","range","ctx",c);function u(e){const t=ku[e.value.toUpperCase()],o=e.args,i=o.length;if(i<t.minArgRequired)throw new h(r("Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.",e.value.toUpperCase(),t.minArgRequired.toString(),i.toString()));if(i>t.maxArgPossible)throw new h(r("Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.",e.value.toUpperCase(),t.maxArgPossible.toString(),i.toString()));const n=t.nbrArgRepeating;if(n>1){const o=t.args.length-n;if((i-o)%n!=0)throw new h(r("Invalid number of arguments for the %s function. Expected all arguments after position %s to be supplied by groups of %s arguments",e.value.toUpperCase(),o.toString(),n.toString()))}let s=[];for(let n=0;n<i;n++){const i=t.getArgToFocus(n+1)-1;if(0<=i&&i<t.args.length){const a=o[n],l=t.args[i],c=l.type||[],d=c.includes("META"),u=l.lazy,p=c.some((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e)),m=c.every((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e));if(m&&"REFERENCE"!==a.type)throw new h(r("Function %s expects the parameter %s to be reference to a cell or range, not a %s.",e.value.toUpperCase(),(n+1).toString(),a.type.toLowerCase()));const f=g(a,u,d,p,{functionName:e.value.toUpperCase(),paramIndex:n+1});s.push(f)}}return s}function g(e,t=!1,n=!1,s=!1,l={}){const c=[];let d,p,m;if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&n)throw new h(r("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:""};d=a++,m=`{ value: ${e.value} }`;break;case"NUMBER":d=a++,m=`{ value: this.constantValues.numbers[${i.numbers.indexOf(e.value)}] }`;break;case"STRING":d=a++,m=`{ value: this.constantValues.strings[${i.strings.indexOf(e.value)}] }`;break;case"REFERENCE":const r=o.indexOf(e.value);d=a++,m=s?`range(deps[${r}])`:`ref(deps[${r}], ${n?"true":"false"}, "${l.functionName||$u["="]}", ${l.paramIndex})`;break;case"FUNCALL":d=a++;const h=u(e);c.push(h.map((e=>e.code)).join("\n")),p=e.value.toUpperCase(),c.push(`ctx.__lastFnCalled = '${p}';`),m=`ctx['${p}'](${h.map((e=>e.id))})`;break;case"UNARY_OPERATION":{d=a++,p=Pu[e.value];const t=g(e.operand,!1,!1,!1,{functionName:p});c.push(t.code),c.push(`ctx.__lastFnCalled = '${p}';`),m=`ctx['${p}'](${t.id})`;break}case"BIN_OPERATION":{d=a++,p=$u[e.value];const t=g(e.left,!1,!1,!1,{functionName:p}),o=g(e.right,!1,!1,!1,{functionName:p});c.push(t.code),c.push(o.code),c.push(`ctx.__lastFnCalled = '${p}';`),m=`ctx['${p}'](${t.id}, ${o.id})`;break}case"UNKNOWN":if(!t)return{id:"undefined",code:""};d=a++,m="undefined"}if(t){return{id:`_${d}`,code:`const _${d} = () => {\n\t${Lu(c).join("\n\t")}\n\treturn ${m};\n}`}}return c.push(`let _${d} = ${m};`),{id:`_${d}`,code:c.join("\n")}}Uu[n]={execute:d}}return{execute:Uu[n].execute,dependencies:o,constantValues:i,tokens:t}}function zu(e){return function(e){let t=[],o="";return e.map(((e,i)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(o=""),e.type){case"FUNCTION":o=e.value;break;case"LEFT_PAREN":t.push({parent:o,argPosition:0}),o="";break;case"RIGHT_PAREN":t.pop();break;case"COMMA":t.length&&t[t.length-1].argPosition++}if(t.length){const o=t[t.length-1];o.parent&&(e.functionContext=Object.assign({},o))}return e}))}(function(e){let t=1;const o=[];return e.map((e=>("LEFT_PAREN"===e.type?(o.push(t),e.parenIndex=t,t++):"RIGHT_PAREN"===e.type&&(e.parenIndex=o.pop()),e)))}(function(e){let t=0;return e.map((e=>{const o=e.value.toString().length,i=Object.assign({},e,{start:t,end:t+o,length:o});return t=i.end,i}))}(Du(e))))}function Bu(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:o}=_t(e.value),[i,n]=t.split(":"),r=o?`${_e(o)}!`:"",s=Hu(i),a=n?`:${Hu(n)}`:"";return{...e,value:r+s+a}}function Hu(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=Wu(e,"colrow");break;case"colrow":e=Wu(e,"row");break;case"row":e=Wu(e,"col");break;case"col":e=Wu(e,"none")}return e}function Wu(e,t){let o;switch(e=e.replace(/\$/g,""),t){case"col":return"$"+e;case"row":return o=e.search(/[0-9]/),e.slice(0,o)+"$"+e.slice(o);case"colrow":return o=e.search(/[0-9]/),"$"+(e=e.slice(0,o)+"$"+e.slice(o));case"none":return e}}class Gu{constructor(e,t){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t}exportForExcel(e){}allowDispatch(e){return 0}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map((e=>e.call(this,t))).flat()}chainValidations(...e){return t=>{for(const o of e){let e=o.call(this,t);Array.isArray(e)||(e=[e]);const i=e.filter((e=>0!==e));if(i.length)return i}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}Gu.getters=[];class qu extends Gu{constructor({getters:e,stateObserver:t,dispatch:o,uiActions:i,selection:n}){super(t,o),this.getters=e,this.ui=i,this.selection=n}drawGrid(e,t){}}qu.layers=[];const Zu=r("The cell you are trying to edit has been deleted.");class ju extends qu{constructor(){super(...arguments),this.col=0,this.row=0,this.mode="inactive",this.sheetId="",this.currentContent="",this.currentTokens=[],this.selectionStart=0,this.selectionEnd=0,this.selectionInitialStart=0,this.initialContent="",this.previousRef="",this.previousRange=void 0,this.colorIndexByRange={}}allowDispatch(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":return this.validateSelection(this.currentContent.length,e.start,e.end);case"SET_CURRENT_CONTENT":return e.selection?this.validateSelection(e.content.length,e.selection.start,e.selection.end):0;case"START_EDITION":if(e.selection){const t=e.text||this.getComposerContent(this.getters.getActivePosition());return this.validateSelection(t.length,e.selection.start,e.selection.end)}return 0;default:return 0}}handleEvent(e){if("selecting"===this.mode)if("newAnchor"===e.mode)this.insertSelectedRange(e.anchor.zone);else this.replaceSelectedRanges(e.anchor.zone)}handle(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":this.selectionStart=e.start,this.selectionEnd=e.end;break;case"STOP_COMPOSER_RANGE_SELECTION":this.isSelectingForComposer()&&(this.mode="editing");break;case"START_EDITION":this.startEdition(e.text,e.selection),this.updateRangeColor();break;case"STOP_EDITION":e.cancel?(this.cancelEditionAndActivateSheet(),this.resetContent()):this.stopEdition(),this.colorIndexByRange={};break;case"SET_CURRENT_CONTENT":this.setContent(e.content,e.selection,!0),this.updateRangeColor();break;case"REPLACE_COMPOSER_CURSOR_SELECTION":this.replaceSelection(e.text);break;case"SELECT_FIGURE":this.cancelEditionAndActivateSheet(),this.resetContent();break;case"ADD_COLUMNS_ROWS":this.onAddElements(e);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case"START_CHANGE_HIGHLIGHT":this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const t=this.getters.getRangeFromRangeData(e.range),o=this.currentTokens.filter((e=>"REFERENCE"===e.type)).find((e=>{const{xc:o,sheetName:i}=_t(e.value),n=i||this.getters.getSheetName(this.sheetId),r=this.getters.getActiveSheetId();if(this.getters.getSheetName(r)!==n)return!1;const s=this.getters.getRangeFromSheetXC(r,o);return Uo(this.getters.expandZone(r,s.zone),t.zone)}));this.previousRef=o.value,this.previousRange=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),this.previousRef),this.selectionInitialStart=o.start;break;case"CHANGE_HIGHLIGHT":const i=this.getters.getRangeFromRangeData(e.range),n=this.getRangeReference(i,this.previousRange.parts);this.selectionStart=this.selectionInitialStart,this.selectionEnd=this.selectionInitialStart+this.previousRef.length,this.replaceSelection(n),this.previousRef=n,this.selectionStart=this.currentContent.length,this.selectionEnd=this.currentContent.length;break;case"ACTIVATE_SHEET":if(this.currentContent.startsWith("=")||(this.cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){const t=this.getters.getActivePosition(),{col:o,row:i}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),n=this.getters.expandZone(e.sheetIdTo,Ko({col:o,row:i}));this.selection.resetAnchor(this,{cell:{col:o,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.cancelEditionAndActivateSheet(),this.resetContent(),this.ui.notifyUI({type:"ERROR",text:Zu}));break;case"CYCLE_EDITION_REFERENCES":this.cycleReferences()}}unsubscribe(){this.mode="inactive"}getEditionMode(){return this.mode}getCurrentContent(){return"inactive"===this.mode?this.getComposerContent(this.getters.getActivePosition()):this.currentContent}getEditionSheet(){return this.sheetId}getComposerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}isSelectingForComposer(){return"selecting"===this.mode}showSelectionIndicator(){return this.isSelectingForComposer()&&this.canStartComposerRangeSelection()}getCurrentTokens(){return this.currentTokens}getTokenAtCursor(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return e===t&&0===t?void 0:this.currentTokens.find((o=>o.start<=e&&o.end>=t))}cycleReferences(){const e=this.getTokensInSelection(),t=e.filter((e=>"REFERENCE"===e.type));if(0===t.length)return;const o=e.map(Bu).map((e=>e.value)).join(""),i=this.currentContent,n=e[0].start,r=e[e.length-1].end,s=i.slice(0,n)+o+i.slice(r),a=s.length-i.length,l={start:t[0].start,end:t[t.length-1].end+a};1===t.length&&this.selectionStart===this.selectionEnd&&(l.start=l.end),this.dispatch("SET_CURRENT_CONTENT",{content:s,selection:l})}validateSelection(e,t,o){return t>=0&&t<=e&&o>=0&&o<=e?0:46}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:Zu});const{top:t,left:o}=ko({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",[...e.elements]);this.col=o,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:Zu});const{top:t,left:o}=ko({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",[...e.elements]);this.col=o,this.row=t}onAddElements(e){const{top:t,left:o}=Do({left:this.col,right:this.col,top:this.row,bottom:this.row},"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.col=o,this.row=t}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){const e=Ko({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 o;const i=this.getters.getActiveCell();e&&(null===(o=i.format)||void 0===o?void 0:o.includes("%"))&&Zt(e)&&(t=t||{start:e.length,end:e.length},e=`${e}%`);const n=this.getters.getActiveSheetId(),{col:r,row:s}=this.getters.getActivePosition();this.col=r,this.sheetId=n,this.row=s,this.initialContent=this.getComposerContent({sheetId:n,col:r,row:s}),this.mode="editing",this.setContent(e||this.initialContent,t),this.colorIndexByRange={};const a=Ko({col:this.col,row:this.row});this.selection.capture(this,{cell:{col:this.col,row:this.row},zone:a},{handleEvent:this.handleEvent.bind(this),release:()=>{this.stopEdition()}})}stopEdition(){if("inactive"!==this.mode){this.cancelEditionAndActivateSheet();const e=this.col,t=this.row;let o=this.currentContent;if(!(this.initialContent!==o))return;if(o){const i=this.getters.getActiveSheetId(),n=this.getters.getEvaluatedCell({sheetId:i,col:this.col,row:this.row});if(o.startsWith("=")){const e=this.currentTokens.filter((e=>"LEFT_PAREN"===e.type)).length,t=this.currentTokens.filter((e=>"RIGHT_PAREN"===e.type)).length,i=e-t;i>0&&(o+=ot(new Array(i).fill(")")))}else n.link&&(o=Ze(o,n.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,col:e,row:t,content:o})}else this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,content:"",col:e,row:t});this.setContent("")}}cancelEditionAndActivateSheet(){if("inactive"===this.mode)return;this.cancelEdition();this.getters.getActiveSheetId()!==this.sheetId&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}getComposerContent(e){const t=this.getters.getCell(e);if(null==t?void 0:t.isFormula)return t.content;const{format:o,value:i,type:n,formattedValue:r}=this.getters.getEvaluatedCell(e);switch(n){case fi.text:case fi.empty:return i;case fi.boolean:return r;case fi.error:return(null==t?void 0:t.content)||"";case fi.number:return o&&uo(o)?r:this.numberComposerContent(i,o)}}numberComposerContent(e,t){return(null==t?void 0:t.includes("%"))?100*e+"%":function(e){const{integerDigits:t,decimalDigits:o}=lo(e,20);return o?`${t}.${o}`:t}(e)}cancelEdition(){"inactive"!==this.mode&&(this.mode="inactive",this.selection.release(this))}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,o){e=e.replace(/[\r\n]/g,"");const i=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(i||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?zu(e):[],this.currentTokens.length>100&&o&&this.ui.notifyUI({type:"ERROR",text:r("This formula has over 100 parts. It can't be processed properly, consider splitting it into multiple cells")})),this.canStartComposerRangeSelection()&&this.startComposerRangeSelection()}insertSelectedRange(e){const t=Math.min(this.selectionStart,this.selectionEnd),o=this.getZoneReference(e);this.canStartComposerRangeSelection()?(this.insertText(o,t),this.selectionInitialStart=t):(this.insertText(","+o,t),this.selectionInitialStart=t+1)}replaceSelectedRanges(e){const t=this.getZoneReference(e);this.replaceText(t,this.selectionInitialStart,this.selectionEnd)}getZoneReference(e,t=[{colFixed:!1,rowFixed:!1}]){const o=this.getters.getActiveSheetId();let i=this.getters.zoneToXC(o,e,t);if(this.getters.getEditionSheet()!==this.getters.getActiveSheetId()){i=`${_e(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${i}`}return i}getRangeReference(e,t=[{colFixed:!1,rowFixed:!1}]){let o=[...t];1===t.length&&Jo(e.zone)>1?o.push({...t[0]}):2===t.length&&1===Jo(e.zone)&&o.pop();const i=e.clone({parts:o});return this.getters.getSelectionRangeString(i,this.getters.getEditionSheet())}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),o=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,o)}replaceText(e,t,o){this.currentContent=this.currentContent.slice(0,t)+this.currentContent.slice(o,this.currentContent.length),this.insertText(e,t)}insertText(e,t){const o=this.currentContent.slice(0,t)+e+this.currentContent.slice(t),i=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:o,selection:{start:i,end:i}})}updateRangeColor(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return;const e=this.getters.getEditionSheet(),t=this.getReferencedRanges().map((t=>this.getters.getRangeString(t,e))),o={};for(const e of t)void 0!==this.colorIndexByRange[e]&&(o[e]=this.colorIndexByRange[e]);const i=new Set(Object.values(o));let n=0;const r=()=>{for(;i.has(n);)n++;return i.add(n),n};for(const e of t){const t=e in o?o[e]:r();o[e]=t}this.colorIndexByRange=o}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=this.getters.getEditionSheet(),t=e=>{const t=this.colorIndexByRange[e];return dt[t%dt.length]};return this.getReferencedRanges().map((o=>{const i=this.getters.getRangeString(o,e);return{zone:o.zone,color:t(i),sheetId:o.sheetId}}))}getReferencedRanges(){const e=this.getters.getEditionSheet();return this.currentTokens.filter((e=>"REFERENCE"===e.type)).map((t=>this.getters.getRangeFromSheetXC(e,t.value)))}canStartComposerRangeSelection(){if(this.currentContent.startsWith("=")){const e=this.getTokenAtCursor();if(!e)return!1;const t=this.currentTokens.map((e=>e.start)).indexOf(e.start);let o=t,i=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(i.type)||Jd.includes(i.value);){if("SPACE"!==i.type||o<1)return!1;o--,i=this.currentTokens[o]}for(o=t+1,i=this.currentTokens[o];i&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(i.type);){if("SPACE"!==i.type)return!1;o++,i=this.currentTokens[o]}return!0}return!1}getTokensInSelection(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return this.currentTokens.filter((o=>o.start<=e&&o.end>=e||o.start>=e&&o.start<t))}}ju.getters=["getEditionMode","isSelectingForComposer","showSelectionIndicator","getCurrentContent","getEditionSheet","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights"];const Xu={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function Yu(e,t){const o=Xu[e.key];e.shiftKey?t.resizeAnchorZone(o,e.ctrlKey?"end":1):t.moveAnchorCell(o,e.ctrlKey?"end":1)}ni`
159
159
  .o-autocomplete-dropdown {
160
160
  pointer-events: auto;
161
161
  background-color: #fff;
@@ -179,7 +179,7 @@
179
179
  }
180
180
  }
181
181
  }
182
- `;class Yu extends t.Component{}Yu.template="o-spreadsheet-TextValueProvider",Yu.props={values:Array,selectedIndex:Number,onValueSelected:Function};class Ku{constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){let o=window.getSelection();this.removeSelection();let i=document.createRange();if(e==t&&0===e)i.setStart(this.el,0),i.setEnd(this.el,0),o.addRange(i);else{(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 n=this.findChildAtCharacterIndex(e),r=this.findChildAtCharacterIndex(t);i.setStart(n.node,n.offset),o.addRange(i),o.extend(r.node,r.offset)}}findChildAtCharacterIndex(e){let t,o,i=this.iterateChildren(this.el),n=e;do{t=i.next(),t.done||t.value.hasChildNodes()||(t.value.textContent&&t.value.textContent.length<n?n-=t.value.textContent.length:i.return(t.value),o=t.value)}while(!t.done);return t.value?{node:t.value,offset:n}:{node:o,offset:n}}*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:o,endSelectionOffset:i}=this.getStartAndEndSelection();return{start:this.findSelectionIndex(e,o),end:this.findSelectionIndex(t,i)}}findSelectionIndex(e,t){let o=this.iterateChildren(this.el),i=0,n=o.next();for(;!n.done&&n.value!==e;)n.value.hasChildNodes()||n.value.textContent&&(i+=n.value.textContent.length),n=o.next();if(n.value===e)if(n.value.hasChildNodes()){const e=[...n.value.childNodes].slice(0,t);for(const t of e)t.textContent&&(i+=t.textContent.length)}else i+=t;return i}getStartAndEndSelection(){const e=document.getSelection();return{startElement:e.anchorNode||this.el,startSelectionOffset:e.anchorOffset,endElement:e.focusNode||this.el,endSelectionOffset:e.focusOffset}}}ii`
182
+ `;class Ku extends t.Component{}Ku.template="o-spreadsheet-TextValueProvider",Ku.props={values:Array,selectedIndex:Number,onValueSelected:Function};class Qu{constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){let o=window.getSelection();this.removeSelection();let i=document.createRange();if(e==t&&0===e)i.setStart(this.el,0),i.setEnd(this.el,0),o.addRange(i);else{(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 n=this.findChildAtCharacterIndex(e),r=this.findChildAtCharacterIndex(t);i.setStart(n.node,n.offset),o.addRange(i),o.extend(r.node,r.offset)}}findChildAtCharacterIndex(e){let t,o,i=this.iterateChildren(this.el),n=e;do{t=i.next(),t.done||t.value.hasChildNodes()||(t.value.textContent&&t.value.textContent.length<n?n-=t.value.textContent.length:i.return(t.value),o=t.value)}while(!t.done);return t.value?{node:t.value,offset:n}:{node:o,offset:n}}*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:o,endSelectionOffset:i}=this.getStartAndEndSelection();return{start:this.findSelectionIndex(e,o),end:this.findSelectionIndex(t,i)}}findSelectionIndex(e,t){let o=this.iterateChildren(this.el),i=0,n=o.next();for(;!n.done&&n.value!==e;)n.value.hasChildNodes()||n.value.textContent&&(i+=n.value.textContent.length),n=o.next();if(n.value===e)if(n.value.hasChildNodes()){const e=[...n.value.childNodes].slice(0,t);for(const t of e)t.textContent&&(i+=t.textContent.length)}else i+=t;return i}getStartAndEndSelection(){const e=document.getSelection();return{startElement:e.anchorNode||this.el,startSelectionOffset:e.anchorOffset,endElement:e.focusNode||this.el,endSelectionOffset:e.focusOffset}}}ni`
183
183
  .o-formula-assistant {
184
184
  white-space: normal;
185
185
  background-color: #fff;
@@ -226,7 +226,7 @@
226
226
  .o-formula-assistant-transparency {
227
227
  opacity: 0.3;
228
228
  }
229
- `;class Qu 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)}}Qu.template="o-spreadsheet-FunctionDescriptionProvider",Qu.props={functionName:String,functionDescription:Object,argToFocus:Number};const Ju=Yd.content,eg="#4a4e4d",tg="#3da4ab",og="#02c39a",ig="selector-flag",ng={OPERATOR:tg,NUMBER:og,STRING:"#00a82d",FUNCTION:eg,DEBUGGER:tg,LEFT_PAREN:eg,RIGHT_PAREN:eg,COMMA:eg};ii`
229
+ `;class Ju 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)}}Ju.template="o-spreadsheet-FunctionDescriptionProvider",Ju.props={functionName:String,functionDescription:Object,argToFocus:Number};const eg=Kd.content,tg="#4a4e4d",og="#3da4ab",ig="#02c39a",ng="selector-flag",rg={OPERATOR:og,NUMBER:ig,STRING:"#00a82d",FUNCTION:tg,DEBUGGER:og,LEFT_PAREN:tg,RIGHT_PAREN:tg,COMMA:tg};ni`
230
230
  .o-composer-container {
231
231
  padding: 0;
232
232
  margin: 0;
@@ -247,7 +247,7 @@
247
247
  }
248
248
  span {
249
249
  white-space: pre;
250
- &.${ig}:after {
250
+ &.${ng}:after {
251
251
  content: "${"␣"}";
252
252
  color: ${"darkgrey"};
253
253
  }
@@ -273,14 +273,14 @@
273
273
  .o-topbar-toolbar .o-composer-container {
274
274
  z-index: ${ae.TopBarComposer};
275
275
  }
276
- `;class rg extends t.Component{constructor(){super(...arguments),this.composerRef=t.useRef("o_composer"),this.contentHelper=new Ku(this.composerRef.el),this.composerState=t.useState({positionStart:0,positionEnd:0}),this.autoCompleteState=t.useState({showProvider:!1,values:[],selectedIndex:0}),this.functionDescriptionState=t.useState({showDescription:!1,functionName:"",functionDescription:{},argToFocus:0}),this.isKeyStillDown=!1,this.compositionActive=!1,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(){if(this.props.delimitation&&this.props.rect){const{x:e,y:t,height:o}=this.props.rect;let i="";return t>this.props.delimitation.height-(t+o)&&(i+="\n top: -8px;\n transform: translate(0, -100%);\n "),e+300>this.props.delimitation.width&&(i+="right:0px;"),i+="width:300px;"}return"width:300px;"}setup(){t.onMounted((()=>{const e=this.composerRef.el;this.contentHelper.updateEl(e),this.processContent()})),t.onWillUnmount((()=>{var e,t;null===(t=(e=this.props).onComposerUnmounted)||void 0===t||t.call(e)})),t.onPatched((()=>{this.isKeyStillDown||this.processContent()}))}processArrowKeys(e){if(this.env.model.getters.isSelectingForComposer())return this.functionDescriptionState.showDescription=!1,e.preventDefault(),e.stopPropagation(),void Xu(e,this.env.model.selection);const t=this.env.model.getters.getCurrentContent();"cellFocus"!==this.props.focus||this.autoCompleteState.showProvider||t.startsWith("=")?(e.stopPropagation(),this.handleArrowKeysForAutocomplete(e)):this.env.model.dispatch("STOP_EDITION")}handleArrowKeysForAutocomplete(e){["ArrowUp","ArrowDown"].includes(e.key)&&this.autoCompleteState.showProvider&&(e.preventDefault(),"ArrowUp"===e.key?(this.autoCompleteState.selectedIndex--,this.autoCompleteState.selectedIndex<0&&(this.autoCompleteState.selectedIndex=this.autoCompleteState.values.length-1)):this.autoCompleteState.selectedIndex=(this.autoCompleteState.selectedIndex+1)%this.autoCompleteState.values.length),this.updateCursorIfNeeded()}processTabKey(e){var t;if(e.preventDefault(),e.stopPropagation(),this.autoCompleteState.showProvider){const e=null===(t=this.autoCompleteState.values[this.autoCompleteState.selectedIndex])||void 0===t?void 0:t.text;if(e)return void this.autoComplete(e)}else this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION");const o=e.shiftKey?"left":"right";this.env.model.dispatch("STOP_EDITION"),this.env.model.selection.moveAnchorCell(o,1)}processEnterKey(e){var t;if(e.preventDefault(),e.stopPropagation(),this.isKeyStillDown=!1,this.autoCompleteState.showProvider){const e=null===(t=this.autoCompleteState.values[this.autoCompleteState.selectedIndex])||void 0===t?void 0:t.text;if(e)return void this.autoComplete(e)}this.env.model.dispatch("STOP_EDITION");const o=e.shiftKey?"up":"down";this.env.model.selection.moveAnchorCell(o,1)}processEscapeKey(){this.env.model.dispatch("STOP_EDITION",{cancel:!0})}processF4Key(){this.env.model.dispatch("CYCLE_EDITION_REFERENCES"),this.processContent()}onCompositionStart(){this.compositionActive=!0}onCompositionEnd(){this.compositionActive=!1}onKeydown(e){let t=this.keyMapping[e.key];t?t.call(this,e):(e.stopPropagation(),this.updateCursorIfNeeded())}updateCursorIfNeeded(){if(!this.env.model.getters.isSelectingForComposer()){const{start:e,end:t}=this.contentHelper.getCurrentSelection();this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:e,end:t}),this.isKeyStillDown=!0}}onInput(){if("inactive"===this.props.focus||!this.shouldProcessInputEvents)return;this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION");const e=this.composerRef.el;this.env.model.dispatch("SET_CURRENT_CONTENT",{content:e.childNodes.length?e.textContent:"",selection:this.contentHelper.getCurrentSelection()})}onKeyup(e){if(this.isKeyStillDown=!1,"inactive"===this.props.focus||["Control","Shift","Tab","Enter","F4"].includes(e.key))return;if(this.autoCompleteState.showProvider&&["ArrowUp","ArrowDown"].includes(e.key))return;if(this.env.model.getters.isSelectingForComposer()&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return;if(e.preventDefault(),e.stopPropagation(),this.autoCompleteState.showProvider=!1,e.ctrlKey&&" "===e.key)return this.showAutocomplete(""),void this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION");const{start:t,end:o}=this.env.model.getters.getComposerSelection(),{start:i,end:n}=this.contentHelper.getCurrentSelection();i===t&&n===o||this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",this.contentHelper.getCurrentSelection()),this.processTokenAtCursor(),this.processContent()}showAutocomplete(e){this.autoCompleteState.showProvider=!0;let t=Object.entries(Yd.content).map((([e,{description:t}])=>({text:e,description:t})));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.autoCompleteState.values=t.slice(0,10),this.autoCompleteState.selectedIndex=0}onMousedown(e){e.button>0||this.contentHelper.removeSelection()}onClick(){if(this.env.model.getters.isReadonly())return;const e=this.contentHelper.getCurrentSelection();this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION"),"inactive"===this.props.focus&&this.props.onComposerContentFocused(e),this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",e),this.processTokenAtCursor()}onBlur(){this.isKeyStillDown=!1}processContent(){if(this.compositionActive)return;this.contentHelper.removeAll(),this.shouldProcessInputEvents=!1,"inactive"!==this.props.focus&&this.contentHelper.selectRange(0,0);const e=this.getContent();if(0!==e.length){this.contentHelper.setText(e);const{start:t,end:o}=this.env.model.getters.getComposerSelection();"inactive"!==this.props.focus&&this.contentHelper.selectRange(t,o)}this.shouldProcessInputEvents=!0}getContent(){let e;const t=this.env.model.getters.getCurrentContent(),o=t.startsWith("=")&&this.env.model.getters.getCurrentTokens().length>0;return e=""===t?[]:o&&"inactive"!==this.props.focus?this.getColoredTokens():[{value:t}],e}getColoredTokens(){const e=this.env.model.getters.getCurrentTokens(),t=this.env.model.getters.getTokenAtCursor(),o=[],{start:i,end:n}=this.env.model.getters.getComposerSelection();for(const r of e){switch(r.type){case"OPERATOR":case"NUMBER":case"FUNCTION":case"COMMA":case"STRING":o.push({value:r.value,color:ng[r.type]||"#000"});break;case"REFERENCE":const{xc:e,sheetName:i}=Nt(r.value);o.push({value:r.value,color:this.rangeColor(e,i)||"#000"});break;case"SYMBOL":let n=r.value;["TRUE","FALSE"].includes(n.toUpperCase())?o.push({value:r.value,color:og}):o.push({value:r.value,color:"#000"});break;case"LEFT_PAREN":case"RIGHT_PAREN":t&&["LEFT_PAREN","RIGHT_PAREN"].includes(t.type)&&t.parenIndex&&t.parenIndex===r.parenIndex?o.push({value:r.value,color:"black"}):o.push({value:r.value,color:ng[r.type]||"#000"});break;default:o.push({value:r.value,color:"#000"})}this.env.model.getters.showSelectionIndicator()&&n===i&&n===r.end&&(o[o.length-1].class=ig)}return o}rangeColor(e,t){if("inactive"===this.props.focus)return;const o=this.env.model.getters.getHighlights(),i=t?this.env.model.getters.getSheetIdByName(t):this.env.model.getters.getEditionSheet(),n=o.find((t=>{if(t.sheetId!==i)return!1;let o=this.env.model.getters.getRangeFromSheetXC(i,e).zone;const{height:n,width:r}=Wo(o);return o=n*r==1?this.env.model.getters.expandZone(i,o):o,Lo(o,t.zone)}));return n&&n.color?n.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}=Nt(e.value);if("FUNCTION"===e.type||"SYMBOL"===e.type&&!Rt.test(t))this.showAutocomplete(e.value);else if(e.functionContext&&"UNKNOWN"!==e.type){const t=e.functionContext,o=t.parent.toUpperCase(),i=Ju[o],n=t.argPosition;this.functionDescriptionState.functionName=o,this.functionDescriptionState.functionDescription=i,this.functionDescriptionState.argToFocus=i.getArgToFocus(n+1)-1,this.functionDescriptionState.showDescription=!0}}}}autoComplete(e){if(e){const t=this.env.model.getters.getTokenAtCursor();if(t){let o=t.end,i=t.end;["SYMBOL","FUNCTION"].includes(t.type)&&(o=t.start);const n=this.env.model.getters.getCurrentTokens();if(n.length){e+="(";const o=n.map((e=>e.start)).indexOf(t.start);if(o+1<n.length){"LEFT_PAREN"===n[o+1].type&&i++}}this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:o,end:i})}this.env.model.dispatch("REPLACE_COMPOSER_CURSOR_SELECTION",{text:e})}this.processTokenAtCursor()}}rg.template="o-spreadsheet-Composer",rg.components={TextValueProvider:Yu,FunctionDescriptionProvider:Qu},rg.defaultProps={inputStyle:""},rg.props={inputStyle:{type:String,optional:!0},rect:{type:Object,optional:!0},delimitation:{type:Object,optional:!0},focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerUnmounted:{type:Function,optional:!0},onComposerContentFocused:Function};const sg=3*.4*window.devicePixelRatio||1;ii`
276
+ `;class sg extends t.Component{constructor(){super(...arguments),this.composerRef=t.useRef("o_composer"),this.contentHelper=new Qu(this.composerRef.el),this.composerState=t.useState({positionStart:0,positionEnd:0}),this.autoCompleteState=t.useState({showProvider:!1,values:[],selectedIndex:0}),this.functionDescriptionState=t.useState({showDescription:!1,functionName:"",functionDescription:{},argToFocus:0}),this.isKeyStillDown=!1,this.compositionActive=!1,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(){if(this.props.delimitation&&this.props.rect){const{x:e,y:t,height:o}=this.props.rect;let i="";return t>this.props.delimitation.height-(t+o)&&(i+="\n top: -8px;\n transform: translate(0, -100%);\n "),e+300>this.props.delimitation.width&&(i+="right:0px;"),i+="width:300px;"}return"width:300px;"}setup(){t.onMounted((()=>{const e=this.composerRef.el;this.contentHelper.updateEl(e),this.processContent()})),t.onWillUnmount((()=>{var e,t;null===(t=(e=this.props).onComposerUnmounted)||void 0===t||t.call(e)})),t.onPatched((()=>{this.isKeyStillDown||this.processContent()}))}processArrowKeys(e){if(this.env.model.getters.isSelectingForComposer())return this.functionDescriptionState.showDescription=!1,e.preventDefault(),e.stopPropagation(),void Yu(e,this.env.model.selection);const t=this.env.model.getters.getCurrentContent();"cellFocus"!==this.props.focus||this.autoCompleteState.showProvider||t.startsWith("=")?(e.stopPropagation(),this.handleArrowKeysForAutocomplete(e)):this.env.model.dispatch("STOP_EDITION")}handleArrowKeysForAutocomplete(e){["ArrowUp","ArrowDown"].includes(e.key)&&this.autoCompleteState.showProvider&&(e.preventDefault(),"ArrowUp"===e.key?(this.autoCompleteState.selectedIndex--,this.autoCompleteState.selectedIndex<0&&(this.autoCompleteState.selectedIndex=this.autoCompleteState.values.length-1)):this.autoCompleteState.selectedIndex=(this.autoCompleteState.selectedIndex+1)%this.autoCompleteState.values.length),this.updateCursorIfNeeded()}processTabKey(e){var t;if(e.preventDefault(),e.stopPropagation(),this.autoCompleteState.showProvider){const e=null===(t=this.autoCompleteState.values[this.autoCompleteState.selectedIndex])||void 0===t?void 0:t.text;if(e)return void this.autoComplete(e)}else this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION");const o=e.shiftKey?"left":"right";this.env.model.dispatch("STOP_EDITION"),this.env.model.selection.moveAnchorCell(o,1)}processEnterKey(e){var t;if(e.preventDefault(),e.stopPropagation(),this.isKeyStillDown=!1,this.autoCompleteState.showProvider){const e=null===(t=this.autoCompleteState.values[this.autoCompleteState.selectedIndex])||void 0===t?void 0:t.text;if(e)return void this.autoComplete(e)}this.env.model.dispatch("STOP_EDITION");const o=e.shiftKey?"up":"down";this.env.model.selection.moveAnchorCell(o,1)}processEscapeKey(){this.env.model.dispatch("STOP_EDITION",{cancel:!0})}processF4Key(){this.env.model.dispatch("CYCLE_EDITION_REFERENCES"),this.processContent()}onCompositionStart(){this.compositionActive=!0}onCompositionEnd(){this.compositionActive=!1}onKeydown(e){let t=this.keyMapping[e.key];t?t.call(this,e):(e.stopPropagation(),this.updateCursorIfNeeded())}updateCursorIfNeeded(){if(!this.env.model.getters.isSelectingForComposer()){const{start:e,end:t}=this.contentHelper.getCurrentSelection();this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:e,end:t}),this.isKeyStillDown=!0}}onInput(){if("inactive"===this.props.focus||!this.shouldProcessInputEvents)return;this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION");const e=this.composerRef.el;this.env.model.dispatch("SET_CURRENT_CONTENT",{content:e.childNodes.length?e.textContent:"",selection:this.contentHelper.getCurrentSelection()})}onKeyup(e){if(this.isKeyStillDown=!1,"inactive"===this.props.focus||["Control","Shift","Tab","Enter","F4"].includes(e.key))return;if(this.autoCompleteState.showProvider&&["ArrowUp","ArrowDown"].includes(e.key))return;if(this.env.model.getters.isSelectingForComposer()&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return;if(e.preventDefault(),e.stopPropagation(),this.autoCompleteState.showProvider=!1,e.ctrlKey&&" "===e.key)return this.showAutocomplete(""),void this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION");const{start:t,end:o}=this.env.model.getters.getComposerSelection(),{start:i,end:n}=this.contentHelper.getCurrentSelection();i===t&&n===o||this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",this.contentHelper.getCurrentSelection()),this.processTokenAtCursor(),this.processContent()}showAutocomplete(e){this.autoCompleteState.showProvider=!0;let t=Object.entries(Kd.content).map((([e,{description:t}])=>({text:e,description:t})));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.autoCompleteState.values=t.slice(0,10),this.autoCompleteState.selectedIndex=0}onMousedown(e){e.button>0||this.contentHelper.removeSelection()}onClick(){if(this.env.model.getters.isReadonly())return;const e=this.contentHelper.getCurrentSelection();this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION"),"inactive"===this.props.focus&&this.props.onComposerContentFocused(e),this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",e),this.processTokenAtCursor()}onBlur(){this.isKeyStillDown=!1}processContent(){if(this.compositionActive)return;this.contentHelper.removeAll(),this.shouldProcessInputEvents=!1,"inactive"!==this.props.focus&&this.contentHelper.selectRange(0,0);const e=this.getContent();if(0!==e.length){this.contentHelper.setText(e);const{start:t,end:o}=this.env.model.getters.getComposerSelection();"inactive"!==this.props.focus&&this.contentHelper.selectRange(t,o)}this.shouldProcessInputEvents=!0}getContent(){let e;const t=this.env.model.getters.getCurrentContent(),o=t.startsWith("=")&&this.env.model.getters.getCurrentTokens().length>0;return e=""===t?[]:o&&"inactive"!==this.props.focus?this.getColoredTokens():[{value:t}],e}getColoredTokens(){const e=this.env.model.getters.getCurrentTokens(),t=this.env.model.getters.getTokenAtCursor(),o=[],{start:i,end:n}=this.env.model.getters.getComposerSelection();for(const r of e){switch(r.type){case"OPERATOR":case"NUMBER":case"FUNCTION":case"COMMA":case"STRING":o.push({value:r.value,color:rg[r.type]||"#000"});break;case"REFERENCE":const{xc:e,sheetName:i}=_t(r.value);o.push({value:r.value,color:this.rangeColor(e,i)||"#000"});break;case"SYMBOL":let n=r.value;["TRUE","FALSE"].includes(n.toUpperCase())?o.push({value:r.value,color:ig}):o.push({value:r.value,color:"#000"});break;case"LEFT_PAREN":case"RIGHT_PAREN":t&&["LEFT_PAREN","RIGHT_PAREN"].includes(t.type)&&t.parenIndex&&t.parenIndex===r.parenIndex?o.push({value:r.value,color:"black"}):o.push({value:r.value,color:rg[r.type]||"#000"});break;default:o.push({value:r.value,color:"#000"})}this.env.model.getters.showSelectionIndicator()&&n===i&&n===r.end&&(o[o.length-1].class=ng)}return o}rangeColor(e,t){if("inactive"===this.props.focus)return;const o=this.env.model.getters.getHighlights(),i=t?this.env.model.getters.getSheetIdByName(t):this.env.model.getters.getEditionSheet(),n=o.find((t=>{if(t.sheetId!==i)return!1;let o=this.env.model.getters.getRangeFromSheetXC(i,e).zone;const{height:n,width:r}=Go(o);return o=n*r==1?this.env.model.getters.expandZone(i,o):o,Uo(o,t.zone)}));return n&&n.color?n.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&&!Tt.test(t))this.showAutocomplete(e.value);else if(e.functionContext&&"UNKNOWN"!==e.type){const t=e.functionContext,o=t.parent.toUpperCase(),i=eg[o],n=t.argPosition;this.functionDescriptionState.functionName=o,this.functionDescriptionState.functionDescription=i,this.functionDescriptionState.argToFocus=i.getArgToFocus(n+1)-1,this.functionDescriptionState.showDescription=!0}}}}autoComplete(e){if(e){const t=this.env.model.getters.getTokenAtCursor();if(t){let o=t.end,i=t.end;["SYMBOL","FUNCTION"].includes(t.type)&&(o=t.start);const n=this.env.model.getters.getCurrentTokens();if(n.length){e+="(";const o=n.map((e=>e.start)).indexOf(t.start);if(o+1<n.length){"LEFT_PAREN"===n[o+1].type&&i++}}this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:o,end:i})}this.env.model.dispatch("REPLACE_COMPOSER_CURSOR_SELECTION",{text:e})}this.processTokenAtCursor()}}sg.template="o-spreadsheet-Composer",sg.components={TextValueProvider:Ku,FunctionDescriptionProvider:Ju},sg.defaultProps={inputStyle:""},sg.props={inputStyle:{type:String,optional:!0},rect:{type:Object,optional:!0},delimitation:{type:Object,optional:!0},focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerUnmounted:{type:Function,optional:!0},onComposerContentFocused:Function};const ag=3*.4*window.devicePixelRatio||1;ni`
277
277
  div.o-grid-composer {
278
278
  z-index: ${ae.GridComposer};
279
279
  box-sizing: border-box;
280
280
  position: absolute;
281
- border: ${sg}px solid ${E};
281
+ border: ${ag}px solid ${E};
282
282
  }
283
- `;class ag extends t.Component{setup(){this.gridComposerRef=t.useRef("gridComposer"),this.composerState=t.useState({rect:void 0,delimitation:void 0});const{sheetId:e,col:o,row:i}=this.env.model.getters.getActivePosition();this.zone=this.env.model.getters.expandZone(e,Yo({col:o,row:i})),this.rect=this.env.model.getters.getVisibleRect(this.zone),t.onMounted((()=>{const e=this.gridComposerRef.el,t=e.parentElement.clientHeight-this.rect.y-15;e.style.maxHeight=t+"px";const o=e.parentElement.clientWidth-this.rect.x-14;e.style.maxWidth=o+"px",this.composerState.rect={x:this.rect.x,y:this.rect.y,width:e.clientWidth,height:e.clientHeight},this.composerState.delimitation={width:e.parentElement.clientWidth,height:e.parentElement.clientHeight}}))}get containerStyle(){const e=this.env.model.getters.getCurrentContent().startsWith("="),t=this.env.model.getters.getActiveCell(),o=this.env.model.getters.getActivePosition(),i=this.env.model.getters.getCellComputedStyle(o),{x:n,y:r,width:s,height:a}=this.rect,l=!e&&i.fillColor||"#ffffff",c=!e&&i.textColor||"#000000",h=!e&&i.fontSize||10,d=!e&&i.bold?"bold":500,u=!e&&i.italic?"italic":"normal",g=e?"none":ni(i);let p="left";return e||(p=i.align||t.defaultAlign),`\n left: ${n-1}px;\n top: ${r}px;\n min-width: ${s+2}px;\n min-height: ${a+1}px;\n\n background: ${l};\n color: ${c};\n\n font-size: ${ce[h]}px;\n font-weight: ${d};\n font-style: ${u};\n text-decoration: ${g};\n\n text-align: ${p};\n `}get composerStyle(){return`\n line-height: ${_}px;\n max-height: inherit;\n overflow: hidden;\n `}}ag.template="o-spreadsheet-GridComposer",ag.components={Composer:rg},ag.props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerUnmounted:Function,onComposerContentFocused:Function};const lg=ii`
283
+ `;class lg extends t.Component{setup(){this.gridComposerRef=t.useRef("gridComposer"),this.composerState=t.useState({rect:void 0,delimitation:void 0});const{sheetId:e,col:o,row:i}=this.env.model.getters.getActivePosition();this.zone=this.env.model.getters.expandZone(e,Ko({col:o,row:i})),this.rect=this.env.model.getters.getVisibleRect(this.zone),t.onMounted((()=>{const e=this.gridComposerRef.el,t=e.parentElement.clientHeight-this.rect.y-15;e.style.maxHeight=t+"px";const o=e.parentElement.clientWidth-this.rect.x-14;e.style.maxWidth=o+"px",this.composerState.rect={x:this.rect.x,y:this.rect.y,width:e.clientWidth,height:e.clientHeight},this.composerState.delimitation={width:e.parentElement.clientWidth,height:e.parentElement.clientHeight}}))}get containerStyle(){const e=this.env.model.getters.getCurrentContent().startsWith("="),t=this.env.model.getters.getActiveCell(),o=this.env.model.getters.getActivePosition(),i=this.env.model.getters.getCellComputedStyle(o),{x:n,y:r,width:s,height:a}=this.rect,l=!e&&i.fillColor||"#ffffff",c=!e&&i.textColor||"#000000",h=!e&&i.fontSize||10,d=!e&&i.bold?"bold":500,u=!e&&i.italic?"italic":"normal",g=e?"none":ri(i);let p="left";return e||(p=i.align||t.defaultAlign),`\n left: ${n-1}px;\n top: ${r}px;\n min-width: ${s+2}px;\n min-height: ${a+1}px;\n\n background: ${l};\n color: ${c};\n\n font-size: ${ce[h]}px;\n font-weight: ${d};\n font-style: ${u};\n text-decoration: ${g};\n\n text-align: ${p};\n `}get composerStyle(){return`\n line-height: ${_}px;\n max-height: inherit;\n overflow: hidden;\n `}}lg.template="o-spreadsheet-GridComposer",lg.components={Composer:sg},lg.props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerUnmounted:Function,onComposerContentFocused:Function};const cg=ni`
284
284
  .o-filter-icon {
285
285
  color: ${I};
286
286
  position: absolute;
@@ -304,7 +304,7 @@
304
304
  }
305
305
  }
306
306
  }
307
- `;class cg extends t.Component{get style(){const{x:e,y:t}=this.props.position;return`top:${t}px;left:${e}px`}}cg.style=lg,cg.template="o-spreadsheet-FilterIcon",cg.props={position:Object,isActive:Boolean,onClick:Function};const hg=ii``;class dg 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(),o=this.env.model.getters.getRowDimensionsInViewport(t,e.row),i=this.env.model.getters.getColDimensionsInViewport(t,e.col),n=Math.floor((o.size-V)/2);return{x:i.end-V+this.props.gridPosition.x-2-1,y:o.end-V+this.props.gridPosition.y-n}}isFilterActive(e){const t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.isFilterActive({sheetId:t,...e})}toggleFilterMenu(e){const t=this.env.model.getters.getPersistentPopoverTypeAtPosition(e);if(t&&"FilterMenu"===t)return void this.env.model.dispatch("CLOSE_CELL_POPOVER");const{col:o,row:i}=e;this.env.model.dispatch("OPEN_CELL_POPOVER",{col:o,row:i,popoverType:"FilterMenu"})}isPositionVisible(e,t){const o=this.env.model.getters.getVisibleRect({left:e,right:e,top:t,bottom:t});return!(0===o.width||0===o.height)}}function ug(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}dg.style=hg,dg.template="o-spreadsheet-FilterIconsOverlay",dg.components={FilterIcon:cg},dg.defaultProps={gridPosition:{x:0,y:0}},dg.props={gridPosition:{type:Object,optional:!0}};const gg=new xn;function pg(e,t){return{url:e=ug(e),label:t||e,isExternal:!0,isUrlEditable:!0}}gg.add("sheet_URL",{match:e=>Xe(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){const o=Ke(e);return t.tryGetSheetName(o)||r("Invalid sheet")},open(e,t){const o=Ke(e);t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:o})},sequence:0});const mg={createLink:pg,match:e=>Ge(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function fg(e){return gg.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((t=>t.match(e)))||mg}function vg(e,t){return fg(e.url).urlRepresentation(e.url,t)}function bg(e,t){fg(e.url).open(e.url,t)}function Cg(e){if("string"==typeof e){if(We(e)){const{label:t,url:o}=Ze(e);return fg(o).createLink(o,t)}return Ge(e)?pg(e):void 0}}function Sg(e,t){return wg(Eg(e||""),t)}function Eg(e){if(e.startsWith("="))throw new Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);return qt(e)||ze(e)?Zr(e):function(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}(e)?"TRUE"===e.toUpperCase():e}function wg(e,t){const o=Cg(e);return o?{...yg(Eg(o.label),t||fo(o.label)),link:o}:yg(e,t)}function yg(e,t){try{for(const o of Tg){const i=o(e,t);if(i)return i}return function(e,t){return{type:mi.text,value:e,format:t,isAutoSummable:!0,defaultAlign:"left",formattedValue:no(e,t)}}((e||"").toString(),t)}catch(t){return Rg((e||"").toString(),new c(a.GenericError,t.message||se))}}function xg(e,t){return{type:mi.number,value:e||0,format:t,isAutoSummable:!0,defaultAlign:"right",formattedValue:no(e,t)}}const Ig={type:mi.empty,value:"",format:void 0,isAutoSummable:!0,defaultAlign:"left",formattedValue:""};function Rg(e,t){return{type:mi.error,value:t.errorType,error:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:t.errorType}}const Tg=[function(e,t){if(""===e)return function(e){return void 0===e?Ig:{type:mi.empty,value:"",format:e,isAutoSummable:!0,defaultAlign:"left",formattedValue:""}}(t)},function(e,t){if(t&&"number"==typeof e&&ho(t))return function(e,t){const o=no(e,t);return{type:mi.number,value:e,format:t,isAutoSummable:!1,defaultAlign:"right",formattedValue:o}}(e,t)},function(e,t){return"number"==typeof e?xg(e,t):null===e?xg(0,t):void 0},function(e,t){if("boolean"==typeof e)return function(e,t){const o=e?"TRUE":"FALSE";return{type:mi.boolean,value:e,format:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:o}}(e,t)}],Ag=new xn;Ag.add("INCREMENT_MODIFIER",{apply:(e,t)=>{var o;e.current+=e.increment;const i=e.current.toString(),n=no(e.current,null===(o=t.cell)||void 0===o?void 0:o.format);return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i},tooltip:i?{props:{content:n}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,o)=>{var i,n,r;const s=(null===(i=t.cell)||void 0===i?void 0:i.content)||"";return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:s},tooltip:s?{props:{content:Sg(null===(n=t.cell)||void 0===n?void 0:n.content,null===(r=t.cell)||void 0===r?void 0:r.format).formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,o,i)=>{e.current+=e.increment;let n=0,r=0;switch(i){case"up":n=0,r=-e.current;break;case"down":n=0,r=e.current;break;case"left":n=-e.current,r=0;break;case"right":n=e.current,r=0}const s=t.cell;if(!s||!s.isFormula)return{cellData:{}};const a=t.sheetId,l=o.createAdaptedRanges(s.dependencies,n,r,a),c=o.buildFormulaContent(a,s,l);return{cellData:{border:t.border,style:s.style,format:s.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});const Og=new xn;Og.add("simple_value_copy",{condition:(e,t)=>{var o;return 1===t.length&&!e.isFormula&&!(null===(o=e.format)||void 0===o?void 0:o.match(j))},generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("copy_text",{condition:e=>!e.isFormula&&Sg(e.content).type===mi.text,generateRule:()=>({type:"COPY_MODIFIER"}),sequence:20}).add("update_formula",{condition:e=>e.isFormula,generateRule:(e,t)=>({type:"FORMULA_MODIFIER",increment:t.length,current:0}),sequence:30}).add("increment_number",{condition:e=>!e.isFormula&&Sg(e.content).type===mi.number,generateRule:(e,t)=>{const o=function(e,t){let o=[],i=!1;for(let n of t){n===e&&(i=!0);const t=Sg(null==n?void 0:n.content);if(t.type===mi.number)o.push(t.value);else{if(i)return o;o=[]}}return o}(e,t);let i=1;2==o.length?i=2*(o[1]-o[0]):o.length>2&&(i=function(e){const t=[];let o=e[0];for(let i=1;i<e.length;i++){const n=e[i];t.push(n-o),o=n}return t.reduce(((e,t)=>e+t),0)/t.length}(o)*o.length);const n=Sg(e.content);return{type:"INCREMENT_MODIFIER",increment:i,current:n.type===mi.number?n.value:0}},sequence:40});ii`
307
+ `;class hg extends t.Component{get style(){const{x:e,y:t}=this.props.position;return`top:${t}px;left:${e}px`}}hg.style=cg,hg.template="o-spreadsheet-FilterIcon",hg.props={position:Object,isActive:Boolean,onClick:Function};const dg=ni``;class ug 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(),o=this.env.model.getters.getRowDimensionsInViewport(t,e.row),i=this.env.model.getters.getColDimensionsInViewport(t,e.col),n=Math.floor((o.size-V)/2);return{x:i.end-V+this.props.gridPosition.x-2-1,y:o.end-V+this.props.gridPosition.y-n}}isFilterActive(e){const t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.isFilterActive({sheetId:t,...e})}toggleFilterMenu(e){const t=this.env.model.getters.getPersistentPopoverTypeAtPosition(e);if(t&&"FilterMenu"===t)return void this.env.model.dispatch("CLOSE_CELL_POPOVER");const{col:o,row:i}=e;this.env.model.dispatch("OPEN_CELL_POPOVER",{col:o,row:i,popoverType:"FilterMenu"})}isPositionVisible(e,t){const o=this.env.model.getters.getVisibleRect({left:e,right:e,top:t,bottom:t});return!(0===o.width||0===o.height)}}function gg(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}ug.style=dg,ug.template="o-spreadsheet-FilterIconsOverlay",ug.components={FilterIcon:hg},ug.defaultProps={gridPosition:{x:0,y:0}},ug.props={gridPosition:{type:Object,optional:!0}};const pg=new In;function mg(e,t){return{url:e=gg(e),label:t||e,isExternal:!0,isUrlEditable:!0}}pg.add("sheet_URL",{match:e=>Ye(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){const o=Qe(e);return t.tryGetSheetName(o)||r("Invalid sheet")},open(e,t){const o=Qe(e);t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:o})},sequence:0});const fg={createLink:mg,match:e=>qe(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function vg(e){return pg.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((t=>t.match(e)))||fg}function bg(e,t){return vg(e.url).urlRepresentation(e.url,t)}function Cg(e,t){vg(e.url).open(e.url,t)}function Sg(e){if("string"==typeof e){if(Ge(e)){const{label:t,url:o}=je(e);return vg(o).createLink(o,t)}return qe(e)?mg(e):void 0}}function Eg(e,t){return yg(wg(e||""),t)}function wg(e){if(e.startsWith("="))throw new Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);return Zt(e)||Be(e)?jr(e):function(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}(e)?"TRUE"===e.toUpperCase():e}function yg(e,t){const o=Sg(e);return o?{...xg(wg(o.label),t||vo(o.label)),link:o}:xg(e,t)}function xg(e,t){try{for(const o of Ag){const i=o(e,t);if(i)return i}return function(e,t){return{type:fi.text,value:e,format:t,isAutoSummable:!0,defaultAlign:"left",formattedValue:ro(e,t)}}((e||"").toString(),t)}catch(t){return Tg((e||"").toString(),new c(a.GenericError,t.message||se))}}function Ig(e,t){return{type:fi.number,value:e||0,format:t,isAutoSummable:!0,defaultAlign:"right",formattedValue:ro(e,t)}}const Rg={type:fi.empty,value:"",format:void 0,isAutoSummable:!0,defaultAlign:"left",formattedValue:""};function Tg(e,t){return{type:fi.error,value:t.errorType,error:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:t.errorType}}const Ag=[function(e,t){if(""===e)return function(e){return void 0===e?Rg:{type:fi.empty,value:"",format:e,isAutoSummable:!0,defaultAlign:"left",formattedValue:""}}(t)},function(e,t){if(t&&"number"==typeof e&&uo(t))return function(e,t){const o=ro(e,t);return{type:fi.number,value:e,format:t,isAutoSummable:!1,defaultAlign:"right",formattedValue:o}}(e,t)},function(e,t){return"number"==typeof e?Ig(e,t):null===e?Ig(0,t):void 0},function(e,t){if("boolean"==typeof e)return function(e,t){const o=e?"TRUE":"FALSE";return{type:fi.boolean,value:e,format:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:o}}(e,t)}],Og=new In;Og.add("INCREMENT_MODIFIER",{apply:(e,t)=>{var o;e.current+=e.increment;const i=e.current.toString(),n=ro(e.current,null===(o=t.cell)||void 0===o?void 0:o.format);return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i},tooltip:i?{props:{content:n}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,o)=>{var i,n,r;const s=(null===(i=t.cell)||void 0===i?void 0:i.content)||"";return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:s},tooltip:s?{props:{content:Eg(null===(n=t.cell)||void 0===n?void 0:n.content,null===(r=t.cell)||void 0===r?void 0:r.format).formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,o,i)=>{e.current+=e.increment;let n=0,r=0;switch(i){case"up":n=0,r=-e.current;break;case"down":n=0,r=e.current;break;case"left":n=-e.current,r=0;break;case"right":n=e.current,r=0}const s=t.cell;if(!s||!s.isFormula)return{cellData:{}};const a=t.sheetId,l=o.createAdaptedRanges(s.dependencies,n,r,a),c=o.buildFormulaContent(a,s,l);return{cellData:{border:t.border,style:s.style,format:s.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});const Mg=new In;Mg.add("simple_value_copy",{condition:(e,t)=>{var o;return 1===t.length&&!e.isFormula&&!(null===(o=e.format)||void 0===o?void 0:o.match(j))},generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("copy_text",{condition:e=>!e.isFormula&&Eg(e.content).type===fi.text,generateRule:()=>({type:"COPY_MODIFIER"}),sequence:20}).add("update_formula",{condition:e=>e.isFormula,generateRule:(e,t)=>({type:"FORMULA_MODIFIER",increment:t.length,current:0}),sequence:30}).add("increment_number",{condition:e=>!e.isFormula&&Eg(e.content).type===fi.number,generateRule:(e,t)=>{const o=function(e,t){let o=[],i=!1;for(let n of t){n===e&&(i=!0);const t=Eg(null==n?void 0:n.content);if(t.type===fi.number)o.push(t.value);else{if(i)return o;o=[]}}return o}(e,t);let i=1;2==o.length?i=2*(o[1]-o[0]):o.length>2&&(i=function(e){const t=[];let o=e[0];for(let i=1;i<e.length;i++){const n=e[i];t.push(n-o),o=n}return t.reduce(((e,t)=>e+t),0)/t.length}(o)*o.length);const n=Eg(e.content);return{type:"INCREMENT_MODIFIER",increment:i,current:n.type===fi.number?n.value:0}},sequence:40});ni`
308
308
  .o-error-tooltip {
309
309
  font-size: 13px;
310
310
  background-color: white;
@@ -313,7 +313,7 @@
313
313
  width: ${180}px;
314
314
  box-sizing: border-box !important;
315
315
  }
316
- `;class Mg extends t.Component{}Mg.maxSize={maxHeight:80},Mg.template="o-spreadsheet-ErrorToolTip",Mg.components={},Mg.props={text:String,onClosed:{type:Function,optional:!0}};const Ng={onHover:(e,t)=>{const o=t.getEvaluatedCell(e);return o.type===mi.error&&o.error.logLevel>l.silent?{isOpen:!0,props:{text:o.error.message},Component:Mg,cellCorner:"TopRight"}:{isOpen:!1}}};class _g 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"}))}}_g.template="o-spreadsheet-FilterMenuValueItem",_g.props={value:String,isChecked:Boolean,isSelected:Boolean,onMouseMove:Function,onClick:Function,scrolledTo:{type:String,optional:!0}};const Fg=ii`
316
+ `;class Ng extends t.Component{}Ng.maxSize={maxHeight:80},Ng.template="o-spreadsheet-ErrorToolTip",Ng.components={},Ng.props={text:String,onClosed:{type:Function,optional:!0}};const _g={onHover:(e,t)=>{const o=t.getEvaluatedCell(e);return o.type===fi.error&&o.error.logLevel>l.silent?{isOpen:!0,props:{text:o.error.message},Component:Ng,cellCorner:"TopRight"}:{isOpen:!1}}};class Fg 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"}))}}Fg.template="o-spreadsheet-FilterMenuValueItem",Fg.props={value:String,isChecked:Boolean,isSelected:Boolean,onMouseMove:Function,onClick:Function,scrolledTo:{type:String,optional:!0}};const Dg=ni`
317
317
  .o-filter-menu {
318
318
  box-sizing: border-box;
319
319
  padding: 8px 16px;
@@ -415,7 +415,7 @@
415
415
  }
416
416
  }
417
417
  }
418
- `;class Dg extends t.Component{constructor(){super(...arguments),this.state=t.useState({values:[],textFilter:"",selectedValue:void 0}),this.searchBar=t.useRef("filterMenuSearchBar")}setup(){t.onWillUpdateProps((e=>{rt(e.filterPosition,this.props.filterPosition)||(this.state.values=this.getFilterValues(e.filterPosition))})),this.state.values=this.getFilterValues(this.props.filterPosition)}getFilterValues(e){const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getFilter({sheetId:t,...e});if(!o)return[];const i=(o.filteredZone?qo(o.filteredZone):[]).filter((({row:e})=>!this.env.model.getters.isRowHidden(t,e))).map((({col:e,row:o})=>this.env.model.getters.getEvaluatedCell({sheetId:t,col:e,row:o}).formattedValue)),n=this.env.model.getters.getFilterValues({sheetId:t,...e}),r=[...i,...n],s=n.map(at);return[...new Set(r.map(at))].sort(((e,t)=>e.localeCompare(t,void 0,{numeric:!0,sensitivity:"base"}))).map((e=>({checked:-1===s.findIndex((t=>t===e)),string:r.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({sheetId:e,...t})}get displayedValues(){return this.state.textFilter?function(e,t,o){const i=[];return t.forEach((t=>{const n=function(e,t){e=e.toLocaleLowerCase();let o=0,i=0,n=(t=t.toLocaleLowerCase()).length,r=0;for(let s=0;s<n;s++)t[s]===e[r]?(r++,i+=100+i-s/200):i=0,o+=i;return r===e.length?o:0}(e,o(t));n>0&&i.push({score:n,elem:t})})),i.sort(((e,t)=>t.score-e.score)),i.map((e=>e.elem))}(this.state.textFilter,this.state.values,(e=>e.string)):this.state.values}confirm(){var e,t;const o=this.props.filterPosition;this.env.model.dispatch("UPDATE_FILTER",{...o,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 o;if(void 0!==this.state.selectedValue){const e=t.findIndex((e=>e.string===this.state.selectedValue));o=-1===e?void 0:e}switch(e.key){case"ArrowDown":o=void 0===o?0:Math.min(o+1,t.length-1),e.preventDefault(),e.stopPropagation();break;case"ArrowUp":o=void 0===o?t.length-1:Math.max(o-1,0),e.preventDefault(),e.stopPropagation();break;case"Enter":void 0!==o&&this.checkValue(t[o]),e.stopPropagation(),e.preventDefault()}this.state.selectedValue=void 0!==o?t[o].string:void 0,"ArrowUp"!==e.key&&"ArrowDown"!==e.key||this.scrollListToSelectedValue(e.key)}clearScrolledToValue(){this.state.values.forEach((e=>e.scrolledTo=void 0))}scrollListToSelectedValue(e){this.clearScrolledToValue();const t=this.state.values.find((e=>e.string===this.state.selectedValue));t&&(t.scrolledTo="ArrowUp"===e?"top":"bottom")}sortFilterZone(e){var t,o;const i=this.props.filterPosition,n=this.filterTable;if(!i||!n||!n.contentZone)return;const r=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("SORT_CELLS",{sheetId:r,col:i.col,row:n.contentZone.top,zone:n.contentZone,sortDirection:e,sortOptions:{emptyCellAsZero:!0,sortHeaders:!0}}),null===(o=(t=this.props).onClosed)||void 0===o||o.call(t)}}Dg.size={width:z,height:295},Dg.template="o-spreadsheet-FilterMenu",Dg.style=Fg,Dg.components={FilterMenuValueItem:_g},Dg.props={filterPosition:Object,onClosed:{type:Function,optional:!0}};const kg={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:Dg,cellCorner:"BottomLeft"})};ii`
418
+ `;class kg extends t.Component{constructor(){super(...arguments),this.state=t.useState({values:[],textFilter:"",selectedValue:void 0}),this.searchBar=t.useRef("filterMenuSearchBar")}setup(){t.onWillUpdateProps((e=>{st(e.filterPosition,this.props.filterPosition)||(this.state.values=this.getFilterValues(e.filterPosition))})),this.state.values=this.getFilterValues(this.props.filterPosition)}getFilterValues(e){const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getFilter({sheetId:t,...e});if(!o)return[];const i=(o.filteredZone?Zo(o.filteredZone):[]).filter((({row:e})=>!this.env.model.getters.isRowHidden(t,e))).map((({col:e,row:o})=>this.env.model.getters.getEvaluatedCell({sheetId:t,col:e,row:o}).formattedValue)),n=this.env.model.getters.getFilterValues({sheetId:t,...e}),r=[...i,...n],s=n.map(lt);return[...new Set(r.map(lt))].sort(((e,t)=>e.localeCompare(t,void 0,{numeric:!0,sensitivity:"base"}))).map((e=>({checked:-1===s.findIndex((t=>t===e)),string:r.find((t=>lt(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({sheetId:e,...t})}get displayedValues(){return this.state.textFilter?function(e,t,o){const i=[];return t.forEach((t=>{const n=function(e,t){e=e.toLocaleLowerCase();let o=0,i=0,n=(t=t.toLocaleLowerCase()).length,r=0;for(let s=0;s<n;s++)t[s]===e[r]?(r++,i+=100+i-s/200):i=0,o+=i;return r===e.length?o:0}(e,o(t));n>0&&i.push({score:n,elem:t})})),i.sort(((e,t)=>t.score-e.score)),i.map((e=>e.elem))}(this.state.textFilter,this.state.values,(e=>e.string)):this.state.values}confirm(){var e,t;const o=this.props.filterPosition;this.env.model.dispatch("UPDATE_FILTER",{...o,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 o;if(void 0!==this.state.selectedValue){const e=t.findIndex((e=>e.string===this.state.selectedValue));o=-1===e?void 0:e}switch(e.key){case"ArrowDown":o=void 0===o?0:Math.min(o+1,t.length-1),e.preventDefault(),e.stopPropagation();break;case"ArrowUp":o=void 0===o?t.length-1:Math.max(o-1,0),e.preventDefault(),e.stopPropagation();break;case"Enter":void 0!==o&&this.checkValue(t[o]),e.stopPropagation(),e.preventDefault()}this.state.selectedValue=void 0!==o?t[o].string:void 0,"ArrowUp"!==e.key&&"ArrowDown"!==e.key||this.scrollListToSelectedValue(e.key)}clearScrolledToValue(){this.state.values.forEach((e=>e.scrolledTo=void 0))}scrollListToSelectedValue(e){this.clearScrolledToValue();const t=this.state.values.find((e=>e.string===this.state.selectedValue));t&&(t.scrolledTo="ArrowUp"===e?"top":"bottom")}sortFilterZone(e){var t,o;const i=this.props.filterPosition,n=this.filterTable;if(!i||!n||!n.contentZone)return;const r=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("SORT_CELLS",{sheetId:r,col:i.col,row:n.contentZone.top,zone:n.contentZone,sortDirection:e,sortOptions:{emptyCellAsZero:!0,sortHeaders:!0}}),null===(o=(t=this.props).onClosed)||void 0===o||o.call(t)}}kg.size={width:z,height:295},kg.template="o-spreadsheet-FilterMenu",kg.style=Dg,kg.components={FilterMenuValueItem:Fg},kg.props={filterPosition:Object,onClosed:{type:Function,optional:!0}};const $g={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:kg,cellCorner:"BottomLeft"})};ni`
419
419
  .o-link-tool {
420
420
  font-size: 13px;
421
421
  background-color: white;
@@ -462,7 +462,7 @@
462
462
  cursor: pointer;
463
463
  color: #000;
464
464
  }
465
- `;class $g extends t.Component{get cell(){const{col:e,row:t}=this.props.cellPosition,o=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getEvaluatedCell({sheetId:o,col:e,row:t})}get link(){if(this.cell.link)return this.cell.link;const{col:e,row:t}=this.props.cellPosition;throw new Error(`LinkDisplay Component can only be used with link cells. ${kt(e,t)} is not a link.`)}getUrlRepresentation(e){return vg(e,this.env.model.getters)}openLink(){bg(this.link,this.env)}edit(){const{col:e,row:t}=this.props.cellPosition;this.env.model.dispatch("OPEN_CELL_POPOVER",{col:e,row:t,popoverType:"LinkEditor"})}unlink(){const e=this.env.model.getters.getActiveSheetId(),{col:t,row:o}=this.props.cellPosition,i=this.env.model.getters.getCellComputedStyle({sheetId:e,col:t,row:o}),n=(null==i?void 0:i.textColor)===x||null==i?void 0:i.textColor;this.env.model.dispatch("UPDATE_CELL",{col:t,row:o,sheetId:e,content:this.link.label,style:{...i,textColor:n,underline:void 0}})}}$g.components={Menu:Bn},$g.template="o-spreadsheet-LinkDisplay";const Pg={onHover:(e,t)=>{const o=t.getEvaluatedCell(e);return!t.isDashboard()&&o.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:$g,props:{cellPosition:e},cellCorner:"BottomLeft"}:{isOpen:!1}}};$g.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const Lg=new Mn;Lg.add("sheet",{name:r("Link sheet"),sequence:10}).addChild("sheet_list",["sheet"],(e=>e.model.getters.getSheetIds().map((t=>e.model.getters.getSheet(t))).map(((e,t)=>An(e.id,{name:e.name,sequence:t,action:()=>qe(e.name,Ye(e.id))})))));ii`
465
+ `;class Pg extends t.Component{get cell(){const{col:e,row:t}=this.props.cellPosition,o=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getEvaluatedCell({sheetId:o,col:e,row:t})}get link(){if(this.cell.link)return this.cell.link;const{col:e,row:t}=this.props.cellPosition;throw new Error(`LinkDisplay Component can only be used with link cells. ${$t(e,t)} is not a link.`)}getUrlRepresentation(e){return bg(e,this.env.model.getters)}openLink(){Cg(this.link,this.env)}edit(){const{col:e,row:t}=this.props.cellPosition;this.env.model.dispatch("OPEN_CELL_POPOVER",{col:e,row:t,popoverType:"LinkEditor"})}unlink(){const e=this.env.model.getters.getActiveSheetId(),{col:t,row:o}=this.props.cellPosition,i=this.env.model.getters.getCellComputedStyle({sheetId:e,col:t,row:o}),n=(null==i?void 0:i.textColor)===x||null==i?void 0:i.textColor;this.env.model.dispatch("UPDATE_CELL",{col:t,row:o,sheetId:e,content:this.link.label,style:{...i,textColor:n,underline:void 0}})}}Pg.components={Menu:Hn},Pg.template="o-spreadsheet-LinkDisplay";const Lg={onHover:(e,t)=>{const o=t.getEvaluatedCell(e);return!t.isDashboard()&&o.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:Pg,props:{cellPosition:e},cellCorner:"BottomLeft"}:{isOpen:!1}}};Pg.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const Ug=new Nn;Ug.add("sheet",{name:r("Link sheet"),sequence:10}).addChild("sheet_list",["sheet"],(e=>e.model.getters.getSheetIds().map((t=>e.model.getters.getSheet(t))).map(((e,t)=>On(e.id,{name:e.name,sequence:t,action:()=>Ze(e.name,Ke(e.id))})))));ni`
466
466
  .o-link-editor {
467
467
  font-size: 13px;
468
468
  background-color: white;
@@ -535,7 +535,7 @@
535
535
  }
536
536
  }
537
537
  }
538
- `;class Ug extends t.Component{constructor(){super(...arguments),this.menuItems=Lg.getAll(),this.link=t.useState(this.defaultState),this.menu=t.useState({isOpen:!1}),this.linkEditorRef=t.useRef("linkEditor"),this.position=_n(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,o=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getEvaluatedCell({sheetId:o,col:e,row:t});return i.link?{url:i.link.url,label:i.formattedValue,isUrlEditable:i.link.isUrlEditable}:{label:i.formattedValue,url:"",isUrlEditable:!0}}get menuPosition(){return{x:this.position.x+320-12-2,y:this.position.y+100}}onSpecialLink(e){const{detail:t}=e,o=Cg(t);o&&(this.link.url=o.url,this.link.label=o.label,this.link.isUrlEditable=o.isUrlEditable)}getUrlRepresentation(e){return vg(e,this.env.model.getters)}openMenu(){this.menu.isOpen=!0}removeLink(){this.link.url="",this.link.isUrlEditable=!0}save(){var e,t;const{col:o,row:i}=this.props.cellPosition,n=this.link.label||this.link.url;this.env.model.dispatch("UPDATE_CELL",{col:o,row:i,sheetId:this.env.model.getters.getActiveSheetId(),content:qe(n,this.link.url)}),null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}cancel(){var e,t;null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}onKeyDown(e){switch(e.key){case"Enter":this.link.url&&this.save(),e.stopPropagation();break;case"Escape":this.cancel(),e.stopPropagation()}}}Ug.template="o-spreadsheet-LinkEditor",Ug.components={Menu:Bn};const Vg={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:Ug,cellCorner:"BottomLeft"})};Ug.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const zg=new xn;zg.add("ErrorToolTip",Ng).add("LinkCell",Pg).add("LinkEditor",Vg).add("FilterMenu",kg);const Bg=new xn;class Hg extends t.Component{constructor(){super(...arguments),this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.imageContainerRef=t.useRef("o-image"),this.menuButtonRef=t.useRef("menuButton"),this.menuButtonRect=_n(this.menuButtonRef),this.position=_n(this.imageContainerRef)}getMenuItemRegistry(){const e=new Mn;return e.add("copy",{name:r("Copy"),description:"Ctrl+C",sequence:1,action:async()=>{this.env.model.dispatch("SELECT_FIGURE",{id:this.figureId}),this.env.model.dispatch("COPY"),await this.env.clipboard.write(this.env.model.getters.getClipboardContent())}}),e.add("cut",{name:r("Cut"),description:"Ctrl+X",sequence:2,action:async()=>{this.env.model.dispatch("SELECT_FIGURE",{id:this.figureId}),this.env.model.dispatch("CUT"),await this.env.clipboard.write(this.env.model.getters.getClipboardContent())}}),e.add("reset_size",{name:r("Reset size"),sequence:3,action:()=>{const e=this.env.model.getters.getImageSize(this.figureId),{height:t,width:o}=Kn(this.env.model.getters,e);this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:this.figureId,height:t,width:o})}}),e.add("delete",{name:r("Delete image"),description:"delete",sequence:5,action:()=>{this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:this.figureId})}}),e}onContextMenu(e){const t={x:this.position.x+e.offsetX,y:this.position.y+e.offsetY};this.openContextMenu(t)}showMenu(){const{x:e,y:t,width:o}=this.menuButtonRect,i={x:e>=z?e-z:e+o,y:t};this.openContextMenu(i)}openContextMenu(e){const t=this.getMenuItemRegistry();this.menuState.isOpen=!0,this.menuState.menuItems=t.getAll().filter((e=>e.isVisible(this.env))),this.menuState.position=e}get figureId(){return this.props.figure.id}get getImagePath(){return this.env.model.getters.getImagePath(this.figureId)}}Hg.template="o-spreadsheet-ImageFigure",Hg.components={Menu:Bn},Hg.props={figure:Object,onFigureDeleted:Function};const Wg=new xn;Wg.add("chart",{Component:Hn,SidePanelComponent:"ChartPanel"}),Wg.add("image",{Component:Hg,keepRatio:!0,minFigSize:20,borderWidth:0});const Gg=(new xn).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let o=e.base;"after"===e.position&&o++;for(let i=0;i<e.quantity;i++)t.push(i+o);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],o=[...e.elements].sort(((e,t)=>e-t));for(let i of Ue(o)){const o=0===i[0]?0:i[0]-1,n=0===i[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:i.length,base:o,sheetId:e.sheetId,position:n})}return t})).add("ADD_MERGE",(function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]})).add("REMOVE_MERGE",(function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]})).add("CREATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId}]})).add("DELETE_SHEET",(function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1}]})).add("DUPLICATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo}]})).add("CREATE_FIGURE",(function(e){return[{type:"DELETE_FIGURE",id:e.figure.id,sheetId:e.sheetId}]})).add("CREATE_CHART",(function(e){return[{type:"DELETE_FIGURE",id:e.id,sheetId:e.sheetId}]})).add("HIDE_COLUMNS_ROWS",(function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("UNHIDE_COLUMNS_ROWS",(function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}));for(const e of Si.values())Gg.contains(e)||Gg.add(e,qg);function qg(e){return[e]}function Zg(e,t,o){const i=e.model.getters.getSheetName(t),n=r("Rename Sheet");e.editText(n,(o=>{if(null===o||o===i)return;""===o&&Zg(e,t,r("The sheet name cannot be empty."));const n=e.model.dispatch("RENAME_SHEET",{sheetId:t,name:o});n.isSuccessful||(n.reasons.includes(11)&&Zg(e,t,r("A sheet with the name %s already exists. Please select another name.",o)),n.reasons.includes(13)&&Zg(e,t,r("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",ie.join(" "))))}),{placeholder:i,error:o})}const jg=new Mn;function Xg(e,t,o){const i=e.model.getters.getActiveSheetId(),n="COL"===t?"FREEZE_COLUMNS":"FREEZE_ROWS";e.model.dispatch(n,{sheetId:i,quantity:o}).isCancelledBecause(65)&&e.raiseError(Zi)}jg.add("delete",{name:r("Delete"),sequence:10,isVisible:e=>e.model.getters.getSheetIds().length>1,action:e=>e.askConfirmation(r("Are you sure you want to delete this sheet ?"),(()=>{e.model.dispatch("DELETE_SHEET",{sheetId:e.model.getters.getActiveSheetId()})}))}).add("duplicate",{name:r("Duplicate"),sequence:20,action:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.uuidGenerator.uuidv4();e.model.dispatch("DUPLICATE_SHEET",{sheetId:t,sheetIdTo:o}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})}}).add("rename",{name:r("Rename"),sequence:30,action:e=>Zg(e,e.model.getters.getActiveSheetId())}).add("move_right",{name:r("Move right"),sequence:40,isVisible:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getVisibleSheetIds();return o.indexOf(t)!==o.length-1},action:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),direction:"right"})}).add("move_left",{name:r("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:r("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 Yg=new Mn;Yg.add("file",{name:r("File"),sequence:10}).add("edit",{name:r("Edit"),sequence:20}).add("view",{name:r("View"),sequence:30}).add("insert",{name:r("Insert"),sequence:40}).add("format",{name:r("Format"),sequence:50}).add("data",{name:r("Data"),sequence:60}).addChild("save",["file"],{name:r("Save"),description:"Ctrl+S",sequence:10,action:()=>console.log("Not implemented")}).addChild("undo",["edit"],{name:r("Undo"),description:"Ctrl+Z",sequence:10,action:e=>e.model.dispatch("REQUEST_UNDO")}).addChild("redo",["edit"],{name:r("Redo"),description:"Ctrl+Y",sequence:20,action:e=>e.model.dispatch("REQUEST_REDO"),separator:!0}).addChild("copy",["edit"],{name:r("Copy"),description:"Ctrl+C",sequence:30,isReadonlyAllowed:!0,action:sr}).addChild("cut",["edit"],{name:r("Cut"),description:"Ctrl+X",sequence:40,action:ar}).addChild("paste",["edit"],{name:r("Paste"),description:"Ctrl+V",sequence:50,action:lr}).addChild("paste_special",["edit"],{name:r("Paste special"),sequence:60,separator:!0,isVisible:ur}).addChild("paste_special_value",["edit","paste_special"],{name:r("Paste value only"),sequence:10,action:cr}).addChild("paste_special_format",["edit","paste_special"],{name:r("Paste format only"),sequence:20,action:dr}).addChild("sort_range",["data"],{name:r("Sort range"),sequence:20,isVisible:Mr,separator:!0}).addChild("sort_ascending",["data","sort_range"],{name:r("Ascending (A ⟶ Z)"),sequence:10,action:Ar}).addChild("sort_descending",["data","sort_range"],{name:r("Descending (Z ⟶ A)"),sequence:20,action:Or}).addChild("find_and_replace",["edit"],{name:r("Find and replace"),description:"Ctrl+H",sequence:65,isReadonlyAllowed:!0,action:e=>{e.openSidePanel("FindAndReplace",{})},separator:!0}).addChild("edit_delete_cell_values",["edit"],{name:r("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:gr,sequence:80,action:pr}).addChild("edit_delete_column",["edit"],{name:mr,sequence:90,action:fr}).addChild("edit_delete_cell_shift_up",["edit"],{name:r("Delete cell and shift up"),sequence:93,action:Cr}).addChild("edit_delete_cell_shift_left",["edit"],{name:r("Delete cell and shift left"),sequence:97,action:Sr}).addChild("edit_unhide_columns",["edit"],{name:r("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:r("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=ir(e);return 1===t?r("Row above"):r("%s Rows above",t.toString())},sequence:10,action:Er,isVisible:e=>0===e.model.getters.getActiveCols().size}).addChild("insert_row_after",["insert"],{name:e=>{const t=ir(e);return 1===t?r("Row below"):r("%s Rows below",t.toString())},sequence:20,action:wr,isVisible:e=>0===e.model.getters.getActiveCols().size,separator:!0}).addChild("insert_column_before",["insert"],{name:e=>{const t=or(e);return 1===t?r("Column left"):r("%s Columns left",t.toString())},sequence:30,action:yr,isVisible:e=>0===e.model.getters.getActiveRows().size}).addChild("insert_column_after",["insert"],{name:e=>{const t=or(e);return 1===t?r("Column right"):r("%s Columns right",t.toString())},sequence:40,action:xr,isVisible:e=>0===e.model.getters.getActiveRows().size,separator:!0}).addChild("insert_insert_cell_shift_down",["insert"],{name:r("Insert cells and shift down"),sequence:43,action:vr}).addChild("insert_insert_cell_shift_right",["insert"],{name:r("Insert cells and shift right"),sequence:47,action:br,separator:!0}).addChild("insert_chart",["insert"],{name:r("Chart"),sequence:50,action:e=>{const t=e.model.getters,o=e.model.uuidGenerator.uuidv4(),i=t.getActiveSheetId();1===Qo(e.model.getters.getSelectedZone())&&e.model.selection.selectTableAroundSelection();const n={width:536,height:335},r=function(e,t){const{x:o,y:i}=e.getMainViewportCoordinates(),{scrollX:n,scrollY:r}=e.getActiveSheetScrollInfo(),{width:s,height:a}=e.getVisibleRect(e.getActiveMainViewport());return{x:o+n+Math.max(0,(s-t.width)/2),y:i+r+Math.max(0,(a-t.height)/2)}}(t,n);e.model.dispatch("CREATE_CHART",{sheetId:i,id:o,position:r,size:n,definition:Yn(e.model.getters.getSelectedZone(),e.model.getters)}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{id:o}),e.openSidePanel("ChartPanel"))}}).addChild("insert_image",["insert"],{name:r("Image"),sequence:55,action:async e=>{if(e.imageProvider){const t=e.model.getters.getActiveSheetId(),o=e.model.uuidGenerator.uuidv4(),i=await async function(e){try{return await e.imageProvider.requestImage()}catch{return void e.raiseError(r("An unexpected error occurred during the image transfer"))}}(e);if(!i)throw new Error("No image provider was given to the environment");const n=Kn(e.model.getters,i.size),s=function(e,t){const{x:o,y:i}=e.getMainViewportCoordinates(),{scrollX:n,scrollY:r}=e.getActiveSheetScrollInfo(),s=e.getSheetViewDimension(),a=e.getVisibleRect(e.getActiveMainViewport()),l=Math.min(a.width,s.width-o),c=Math.min(a.height,s.height-i);return{x:o+n+Math.max(0,(l-t.width)/2),y:i+r+Math.max(0,(c-t.height)/2)}}(e.model.getters,n);e.model.dispatch("CREATE_IMAGE",{sheetId:t,figureId:o,position:s,size:n,definition:i})}},isVisible:e=>void 0!==e.imageProvider}).addChild("insert_link",["insert"],{name:r("Link"),separator:!0,sequence:60,action:Rr}).addChild("insert_sheet",["insert"],{name:r("New sheet"),sequence:70,action:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSheetIds().indexOf(t)+1,i=e.model.uuidGenerator.uuidv4();e.model.dispatch("CREATE_SHEET",{sheetId:i,position:o}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:i})},separator:!0}).addChild("unfreeze_panes",["view"],{name:r("Unfreeze"),sequence:4,isVisible:e=>{const{xSplit:t,ySplit:o}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+o>0},action:e=>e.model.dispatch("UNFREEZE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId()})}).addChild("freeze_panes",["view"],{name:r("Freeze"),sequence:5,separator:!0}).addChild("unfreeze_rows",["view","freeze_panes"],{name:r("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:r("1 row"),action:e=>Xg(e,"ROW",1),isReadonlyAllowed:!0,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{name:r("2 rows"),action:e=>Xg(e,"ROW",2),isReadonlyAllowed:!0,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{name:r("Up to current row"),action:e=>{const{bottom:t}=e.model.getters.getSelectedZone();Xg(e,"ROW",t+1)},isReadonlyAllowed:!0,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{name:r("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:r("1 column"),action:e=>Xg(e,"COL",1),isReadonlyAllowed:!0,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{name:r("2 columns"),action:e=>Xg(e,"COL",2),isReadonlyAllowed:!0,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{name:r("Up to current column"),action:e=>{const{right:t}=e.model.getters.getSelectedZone();Xg(e,"COL",t+1)},isReadonlyAllowed:!0,sequence:40}).addChild("view_gridlines",["view"],{name:e=>e.model.getters.getGridLinesVisibility(e.model.getters.getActiveSheetId())?r("Hide gridlines"):r("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()?r("Hide formulas"):r("Show formulas"),action:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,sequence:15}).addChild("format_number",["format"],{name:r("Numbers"),sequence:10,separator:!0}).addChild("format_number_automatic",["format","format_number"],{name:Gi.Automatic,sequence:10,separator:!0,action:e=>nr(e,"")}).addChild("format_number_number",["format","format_number"],{name:Gi.Number,description:"1,000.12",sequence:20,action:e=>nr(e,"#,##0.00")}).addChild("format_number_percent",["format","format_number"],{name:Gi.Percent,description:"10.12%",sequence:30,separator:!0,action:e=>nr(e,"0.00%")}).addChild("format_number_currency",["format","format_number"],{name:Gi.Currency,description:"$1,000.12",sequence:37,action:e=>nr(e,"[$$]#,##0.00")}).addChild("format_number_currency_rounded",["format","format_number"],{name:Gi.CurrencyRounded,description:"$1,000",sequence:38,action:e=>nr(e,"[$$]#,##0")}).addChild("format_custom_currency",["format","format_number"],{name:Gi.CustomCurrency,sequence:39,separator:!0,isVisible:e=>void 0!==e.loadCurrencies,action:e=>{e.openSidePanel("CustomCurrency",{})}}).addChild("format_number_date",["format","format_number"],{name:Gi.Date,description:"9/26/2008",sequence:40,action:e=>nr(e,"m/d/yyyy")}).addChild("format_number_time",["format","format_number"],{name:Gi.Time,description:"10:43:00 PM",sequence:50,action:e=>nr(e,"hh:mm:ss a")}).addChild("format_number_date_time",["format","format_number"],{name:Gi.DateTime,description:"9/26/2008 22:43:00",sequence:60,action:e=>nr(e,"m/d/yyyy hh:mm:ss")}).addChild("format_number_duration",["format","format_number"],{name:Gi.Duration,description:"27:51:38",sequence:70,separator:!0,action:e=>nr(e,"hhhh:mm:ss")}).addChild("format_bold",["format"],{name:r("Bold"),sequence:20,description:"Ctrl+B",action:e=>rr(e,{bold:!e.model.getters.getCurrentStyle().bold})}).addChild("format_italic",["format"],{name:r("Italic"),sequence:30,description:"Ctrl+I",action:e=>rr(e,{italic:!e.model.getters.getCurrentStyle().italic})}).addChild("format_underline",["format"],{name:r("Underline"),description:"Ctrl+U",sequence:40,action:e=>rr(e,{underline:!e.model.getters.getCurrentStyle().underline})}).addChild("format_strikethrough",["format"],{name:r("Strikethrough"),sequence:50,action:e=>rr(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),separator:!0}).addChild("format_font_size",["format"],{name:r("Font size"),sequence:60,separator:!0}).addChild("format_alignment",["format"],{name:r("Alignment"),sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{name:"Left",sequence:10,action:e=>rr(e,{align:"left"})}).addChild("format_alignment_center",["format","format_alignment"],{name:"Center",sequence:20,action:e=>rr(e,{align:"center"})}).addChild("format_alignment_right",["format","format_alignment"],{name:"Right",sequence:30,action:e=>rr(e,{align:"right"}),separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{name:"Top",sequence:40,action:e=>rr(e,{verticalAlign:"top"})}).addChild("format_alignment_middle",["format","format_alignment"],{name:"Middle",sequence:50,action:e=>rr(e,{verticalAlign:"middle"})}).addChild("format_alignment_bottom",["format","format_alignment"],{name:"Bottom",sequence:60,action:e=>rr(e,{verticalAlign:"bottom"}),separator:!0}).addChild("format_wrapping",["format"],{name:r("Wrapping"),sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{name:r("Overflow"),sequence:10,action:e=>rr(e,{wrapping:"overflow"})}).addChild("format_wrapping_wrap",["format","format_wrapping"],{name:r("Wrap"),sequence:20,action:e=>rr(e,{wrapping:"wrap"})}).addChild("format_wrapping_clip",["format","format_wrapping"],{name:r("Clip"),sequence:30,action:e=>rr(e,{wrapping:"clip"})}).addChild("format_cf",["format"],{name:r("Conditional formatting"),sequence:90,action:Ir,separator:!0}).addChild("format_clearFormat",["format"],{name:r("Clear formatting"),sequence:100,action:e=>{e.model.dispatch("CLEAR_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},separator:!0}).addChild("add_data_filter",["data"],{name:r("Create filter"),sequence:10,action:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelection().zones;tr(e,t,o)},isVisible:e=>!Tr(e),isEnabled:e=>(e=>Jo(...e.model.getters.getSelectedZones()))(e)}).addChild("remove_data_filter",["data"],{name:r("Remove filter"),sequence:10,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:t,target:e.model.getters.getSelectedZones()})},isVisible:Tr});for(let e of le)Yg.addChild(`format_font_size_${e.pt}`,["format","format_font_size"],{name:e.pt.toString(),sequence:e.pt,action:t=>rr(t,{fontSize:e.pt})});const Kg=new class extends xn{addTransformation(e,t,o){for(let i of t)this.content[i]||(this.content[i]=new Map),this.content[i].set(e,o);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},Qg=new To;ii`
538
+ `;class Vg extends t.Component{constructor(){super(...arguments),this.menuItems=Ug.getAll(),this.link=t.useState(this.defaultState),this.menu=t.useState({isOpen:!1}),this.linkEditorRef=t.useRef("linkEditor"),this.position=Fn(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,o=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getEvaluatedCell({sheetId:o,col:e,row:t});return i.link?{url:i.link.url,label:i.formattedValue,isUrlEditable:i.link.isUrlEditable}:{label:i.formattedValue,url:"",isUrlEditable:!0}}get menuPosition(){return{x:this.position.x+320-12-2,y:this.position.y+100}}onSpecialLink(e){const{detail:t}=e,o=Sg(t);o&&(this.link.url=o.url,this.link.label=o.label,this.link.isUrlEditable=o.isUrlEditable)}getUrlRepresentation(e){return bg(e,this.env.model.getters)}openMenu(){this.menu.isOpen=!0}removeLink(){this.link.url="",this.link.isUrlEditable=!0}save(){var e,t;const{col:o,row:i}=this.props.cellPosition,n=this.link.label||this.link.url;this.env.model.dispatch("UPDATE_CELL",{col:o,row:i,sheetId:this.env.model.getters.getActiveSheetId(),content:Ze(n,this.link.url)}),null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}cancel(){var e,t;null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}onKeyDown(e){switch(e.key){case"Enter":this.link.url&&this.save(),e.stopPropagation();break;case"Escape":this.cancel(),e.stopPropagation()}}}Vg.template="o-spreadsheet-LinkEditor",Vg.components={Menu:Hn};const zg={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:Vg,cellCorner:"BottomLeft"})};Vg.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const Bg=new In;Bg.add("ErrorToolTip",_g).add("LinkCell",Lg).add("LinkEditor",zg).add("FilterMenu",$g);const Hg=new In;class Wg extends t.Component{constructor(){super(...arguments),this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.imageContainerRef=t.useRef("o-image"),this.menuButtonRef=t.useRef("menuButton"),this.menuButtonRect=Fn(this.menuButtonRef),this.position=Fn(this.imageContainerRef)}getMenuItemRegistry(){const e=new Nn;return e.add("copy",{name:r("Copy"),description:"Ctrl+C",sequence:1,action:async()=>{this.env.model.dispatch("SELECT_FIGURE",{id:this.figureId}),this.env.model.dispatch("COPY"),await this.env.clipboard.write(this.env.model.getters.getClipboardContent())}}),e.add("cut",{name:r("Cut"),description:"Ctrl+X",sequence:2,action:async()=>{this.env.model.dispatch("SELECT_FIGURE",{id:this.figureId}),this.env.model.dispatch("CUT"),await this.env.clipboard.write(this.env.model.getters.getClipboardContent())}}),e.add("reset_size",{name:r("Reset size"),sequence:3,action:()=>{const e=this.env.model.getters.getImageSize(this.figureId),{height:t,width:o}=Qn(this.env.model.getters,e);this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:this.figureId,height:t,width:o})}}),e.add("delete",{name:r("Delete image"),description:"delete",sequence:5,action:()=>{this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:this.figureId})}}),e}onContextMenu(e){const t={x:this.position.x+e.offsetX,y:this.position.y+e.offsetY};this.openContextMenu(t)}showMenu(){const{x:e,y:t,width:o}=this.menuButtonRect,i={x:e>=z?e-z:e+o,y:t};this.openContextMenu(i)}openContextMenu(e){const t=this.getMenuItemRegistry();this.menuState.isOpen=!0,this.menuState.menuItems=t.getAll().filter((e=>e.isVisible(this.env))),this.menuState.position=e}get figureId(){return this.props.figure.id}get getImagePath(){return this.env.model.getters.getImagePath(this.figureId)}}Wg.template="o-spreadsheet-ImageFigure",Wg.components={Menu:Hn},Wg.props={figure:Object,onFigureDeleted:Function};const Gg=new In;Gg.add("chart",{Component:Wn,SidePanelComponent:"ChartPanel"}),Gg.add("image",{Component:Wg,keepRatio:!0,minFigSize:20,borderWidth:0});const qg=(new In).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let o=e.base;"after"===e.position&&o++;for(let i=0;i<e.quantity;i++)t.push(i+o);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],o=[...e.elements].sort(((e,t)=>e-t));for(let i of Ve(o)){const o=0===i[0]?0:i[0]-1,n=0===i[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:i.length,base:o,sheetId:e.sheetId,position:n})}return t})).add("ADD_MERGE",(function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]})).add("REMOVE_MERGE",(function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]})).add("CREATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId}]})).add("DELETE_SHEET",(function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1}]})).add("DUPLICATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo}]})).add("CREATE_FIGURE",(function(e){return[{type:"DELETE_FIGURE",id:e.figure.id,sheetId:e.sheetId}]})).add("CREATE_CHART",(function(e){return[{type:"DELETE_FIGURE",id:e.id,sheetId:e.sheetId}]})).add("HIDE_COLUMNS_ROWS",(function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("UNHIDE_COLUMNS_ROWS",(function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}));for(const e of Ei.values())qg.contains(e)||qg.add(e,Zg);function Zg(e){return[e]}function jg(e,t,o){const i=e.model.getters.getSheetName(t),n=r("Rename Sheet");e.editText(n,(o=>{if(null===o||o===i)return;""===o&&jg(e,t,r("The sheet name cannot be empty."));const n=e.model.dispatch("RENAME_SHEET",{sheetId:t,name:o});n.isSuccessful||(n.reasons.includes(11)&&jg(e,t,r("A sheet with the name %s already exists. Please select another name.",o)),n.reasons.includes(13)&&jg(e,t,r("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",ie.join(" "))))}),{placeholder:i,error:o})}const Xg=new Nn;function Yg(e,t,o){const i=e.model.getters.getActiveSheetId(),n="COL"===t?"FREEZE_COLUMNS":"FREEZE_ROWS";e.model.dispatch(n,{sheetId:i,quantity:o}).isCancelledBecause(65)&&e.raiseError(ji)}Xg.add("delete",{name:r("Delete"),sequence:10,isVisible:e=>e.model.getters.getSheetIds().length>1,action:e=>e.askConfirmation(r("Are you sure you want to delete this sheet ?"),(()=>{e.model.dispatch("DELETE_SHEET",{sheetId:e.model.getters.getActiveSheetId()})}))}).add("duplicate",{name:r("Duplicate"),sequence:20,action:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.uuidGenerator.uuidv4();e.model.dispatch("DUPLICATE_SHEET",{sheetId:t,sheetIdTo:o}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})}}).add("rename",{name:r("Rename"),sequence:30,action:e=>jg(e,e.model.getters.getActiveSheetId())}).add("move_right",{name:r("Move right"),sequence:40,isVisible:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getVisibleSheetIds();return o.indexOf(t)!==o.length-1},action:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),direction:"right"})}).add("move_left",{name:r("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:r("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 Kg=new Nn;Kg.add("file",{name:r("File"),sequence:10}).add("edit",{name:r("Edit"),sequence:20}).add("view",{name:r("View"),sequence:30}).add("insert",{name:r("Insert"),sequence:40}).add("format",{name:r("Format"),sequence:50}).add("data",{name:r("Data"),sequence:60}).addChild("save",["file"],{name:r("Save"),description:"Ctrl+S",sequence:10,action:()=>console.log("Not implemented")}).addChild("undo",["edit"],{name:r("Undo"),description:"Ctrl+Z",sequence:10,action:e=>e.model.dispatch("REQUEST_UNDO")}).addChild("redo",["edit"],{name:r("Redo"),description:"Ctrl+Y",sequence:20,action:e=>e.model.dispatch("REQUEST_REDO"),separator:!0}).addChild("copy",["edit"],{name:r("Copy"),description:"Ctrl+C",sequence:30,isReadonlyAllowed:!0,action:ar}).addChild("cut",["edit"],{name:r("Cut"),description:"Ctrl+X",sequence:40,action:lr}).addChild("paste",["edit"],{name:r("Paste"),description:"Ctrl+V",sequence:50,action:cr}).addChild("paste_special",["edit"],{name:r("Paste special"),sequence:60,separator:!0,isVisible:gr}).addChild("paste_special_value",["edit","paste_special"],{name:r("Paste value only"),sequence:10,action:hr}).addChild("paste_special_format",["edit","paste_special"],{name:r("Paste format only"),sequence:20,action:ur}).addChild("sort_range",["data"],{name:r("Sort range"),sequence:20,isVisible:Nr,separator:!0}).addChild("sort_ascending",["data","sort_range"],{name:r("Ascending (A ⟶ Z)"),sequence:10,action:Or}).addChild("sort_descending",["data","sort_range"],{name:r("Descending (Z ⟶ A)"),sequence:20,action:Mr}).addChild("find_and_replace",["edit"],{name:r("Find and replace"),description:"Ctrl+H",sequence:65,isReadonlyAllowed:!0,action:e=>{e.openSidePanel("FindAndReplace",{})},separator:!0}).addChild("edit_delete_cell_values",["edit"],{name:r("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:pr,sequence:80,action:mr}).addChild("edit_delete_column",["edit"],{name:fr,sequence:90,action:vr}).addChild("edit_delete_cell_shift_up",["edit"],{name:r("Delete cell and shift up"),sequence:93,action:Sr}).addChild("edit_delete_cell_shift_left",["edit"],{name:r("Delete cell and shift left"),sequence:97,action:Er}).addChild("edit_unhide_columns",["edit"],{name:r("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:r("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=nr(e);return 1===t?r("Row above"):r("%s Rows above",t.toString())},sequence:10,action:wr,isVisible:e=>0===e.model.getters.getActiveCols().size}).addChild("insert_row_after",["insert"],{name:e=>{const t=nr(e);return 1===t?r("Row below"):r("%s Rows below",t.toString())},sequence:20,action:yr,isVisible:e=>0===e.model.getters.getActiveCols().size,separator:!0}).addChild("insert_column_before",["insert"],{name:e=>{const t=ir(e);return 1===t?r("Column left"):r("%s Columns left",t.toString())},sequence:30,action:xr,isVisible:e=>0===e.model.getters.getActiveRows().size}).addChild("insert_column_after",["insert"],{name:e=>{const t=ir(e);return 1===t?r("Column right"):r("%s Columns right",t.toString())},sequence:40,action:Ir,isVisible:e=>0===e.model.getters.getActiveRows().size,separator:!0}).addChild("insert_insert_cell_shift_down",["insert"],{name:r("Insert cells and shift down"),sequence:43,action:br}).addChild("insert_insert_cell_shift_right",["insert"],{name:r("Insert cells and shift right"),sequence:47,action:Cr,separator:!0}).addChild("insert_chart",["insert"],{name:r("Chart"),sequence:50,action:e=>{const t=e.model.getters,o=e.model.uuidGenerator.uuidv4(),i=t.getActiveSheetId();1===Jo(e.model.getters.getSelectedZone())&&e.model.selection.selectTableAroundSelection();const n={width:536,height:335},r=function(e,t){const{x:o,y:i}=e.getMainViewportCoordinates(),{scrollX:n,scrollY:r}=e.getActiveSheetScrollInfo(),{width:s,height:a}=e.getVisibleRect(e.getActiveMainViewport());return{x:o+n+Math.max(0,(s-t.width)/2),y:i+r+Math.max(0,(a-t.height)/2)}}(t,n);e.model.dispatch("CREATE_CHART",{sheetId:i,id:o,position:r,size:n,definition:Kn(e.model.getters.getSelectedZone(),e.model.getters)}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{id:o}),e.openSidePanel("ChartPanel"))}}).addChild("insert_image",["insert"],{name:r("Image"),sequence:55,action:async e=>{if(e.imageProvider){const t=e.model.getters.getActiveSheetId(),o=e.model.uuidGenerator.uuidv4(),i=await async function(e){try{return await e.imageProvider.requestImage()}catch{return void e.raiseError(r("An unexpected error occurred during the image transfer"))}}(e);if(!i)throw new Error("No image provider was given to the environment");const n=Qn(e.model.getters,i.size),s=function(e,t){const{x:o,y:i}=e.getMainViewportCoordinates(),{scrollX:n,scrollY:r}=e.getActiveSheetScrollInfo(),s=e.getSheetViewDimension(),a=e.getVisibleRect(e.getActiveMainViewport()),l=Math.min(a.width,s.width-o),c=Math.min(a.height,s.height-i);return{x:o+n+Math.max(0,(l-t.width)/2),y:i+r+Math.max(0,(c-t.height)/2)}}(e.model.getters,n);e.model.dispatch("CREATE_IMAGE",{sheetId:t,figureId:o,position:s,size:n,definition:i})}},isVisible:e=>void 0!==e.imageProvider}).addChild("insert_link",["insert"],{name:r("Link"),separator:!0,sequence:60,action:Tr}).addChild("insert_sheet",["insert"],{name:r("New sheet"),sequence:70,action:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSheetIds().indexOf(t)+1,i=e.model.uuidGenerator.uuidv4();e.model.dispatch("CREATE_SHEET",{sheetId:i,position:o}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:i})},separator:!0}).addChild("unfreeze_panes",["view"],{name:r("Unfreeze"),sequence:4,isVisible:e=>{const{xSplit:t,ySplit:o}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+o>0},action:e=>e.model.dispatch("UNFREEZE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId()})}).addChild("freeze_panes",["view"],{name:r("Freeze"),sequence:5,separator:!0}).addChild("unfreeze_rows",["view","freeze_panes"],{name:r("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:r("1 row"),action:e=>Yg(e,"ROW",1),isReadonlyAllowed:!0,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{name:r("2 rows"),action:e=>Yg(e,"ROW",2),isReadonlyAllowed:!0,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{name:r("Up to current row"),action:e=>{const{bottom:t}=e.model.getters.getSelectedZone();Yg(e,"ROW",t+1)},isReadonlyAllowed:!0,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{name:r("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:r("1 column"),action:e=>Yg(e,"COL",1),isReadonlyAllowed:!0,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{name:r("2 columns"),action:e=>Yg(e,"COL",2),isReadonlyAllowed:!0,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{name:r("Up to current column"),action:e=>{const{right:t}=e.model.getters.getSelectedZone();Yg(e,"COL",t+1)},isReadonlyAllowed:!0,sequence:40}).addChild("view_gridlines",["view"],{name:e=>e.model.getters.getGridLinesVisibility(e.model.getters.getActiveSheetId())?r("Hide gridlines"):r("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()?r("Hide formulas"):r("Show formulas"),action:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,sequence:15}).addChild("format_number",["format"],{name:r("Numbers"),sequence:10,separator:!0}).addChild("format_number_automatic",["format","format_number"],{name:qi.Automatic,sequence:10,separator:!0,action:e=>rr(e,"")}).addChild("format_number_number",["format","format_number"],{name:qi.Number,description:"1,000.12",sequence:20,action:e=>rr(e,"#,##0.00")}).addChild("format_number_percent",["format","format_number"],{name:qi.Percent,description:"10.12%",sequence:30,separator:!0,action:e=>rr(e,"0.00%")}).addChild("format_number_currency",["format","format_number"],{name:qi.Currency,description:"$1,000.12",sequence:37,action:e=>rr(e,"[$$]#,##0.00")}).addChild("format_number_currency_rounded",["format","format_number"],{name:qi.CurrencyRounded,description:"$1,000",sequence:38,action:e=>rr(e,"[$$]#,##0")}).addChild("format_custom_currency",["format","format_number"],{name:qi.CustomCurrency,sequence:39,separator:!0,isVisible:e=>void 0!==e.loadCurrencies,action:e=>{e.openSidePanel("CustomCurrency",{})}}).addChild("format_number_date",["format","format_number"],{name:qi.Date,description:"9/26/2008",sequence:40,action:e=>rr(e,"m/d/yyyy")}).addChild("format_number_time",["format","format_number"],{name:qi.Time,description:"10:43:00 PM",sequence:50,action:e=>rr(e,"hh:mm:ss a")}).addChild("format_number_date_time",["format","format_number"],{name:qi.DateTime,description:"9/26/2008 22:43:00",sequence:60,action:e=>rr(e,"m/d/yyyy hh:mm:ss")}).addChild("format_number_duration",["format","format_number"],{name:qi.Duration,description:"27:51:38",sequence:70,separator:!0,action:e=>rr(e,"hhhh:mm:ss")}).addChild("format_bold",["format"],{name:r("Bold"),sequence:20,description:"Ctrl+B",action:e=>sr(e,{bold:!e.model.getters.getCurrentStyle().bold})}).addChild("format_italic",["format"],{name:r("Italic"),sequence:30,description:"Ctrl+I",action:e=>sr(e,{italic:!e.model.getters.getCurrentStyle().italic})}).addChild("format_underline",["format"],{name:r("Underline"),description:"Ctrl+U",sequence:40,action:e=>sr(e,{underline:!e.model.getters.getCurrentStyle().underline})}).addChild("format_strikethrough",["format"],{name:r("Strikethrough"),sequence:50,action:e=>sr(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),separator:!0}).addChild("format_font_size",["format"],{name:r("Font size"),sequence:60,separator:!0}).addChild("format_alignment",["format"],{name:r("Alignment"),sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{name:"Left",sequence:10,action:e=>sr(e,{align:"left"})}).addChild("format_alignment_center",["format","format_alignment"],{name:"Center",sequence:20,action:e=>sr(e,{align:"center"})}).addChild("format_alignment_right",["format","format_alignment"],{name:"Right",sequence:30,action:e=>sr(e,{align:"right"}),separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{name:"Top",sequence:40,action:e=>sr(e,{verticalAlign:"top"})}).addChild("format_alignment_middle",["format","format_alignment"],{name:"Middle",sequence:50,action:e=>sr(e,{verticalAlign:"middle"})}).addChild("format_alignment_bottom",["format","format_alignment"],{name:"Bottom",sequence:60,action:e=>sr(e,{verticalAlign:"bottom"}),separator:!0}).addChild("format_wrapping",["format"],{name:r("Wrapping"),sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{name:r("Overflow"),sequence:10,action:e=>sr(e,{wrapping:"overflow"})}).addChild("format_wrapping_wrap",["format","format_wrapping"],{name:r("Wrap"),sequence:20,action:e=>sr(e,{wrapping:"wrap"})}).addChild("format_wrapping_clip",["format","format_wrapping"],{name:r("Clip"),sequence:30,action:e=>sr(e,{wrapping:"clip"})}).addChild("format_cf",["format"],{name:r("Conditional formatting"),sequence:90,action:Rr,separator:!0}).addChild("format_clearFormat",["format"],{name:r("Clear formatting"),sequence:100,action:e=>{e.model.dispatch("CLEAR_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},separator:!0}).addChild("add_data_filter",["data"],{name:r("Create filter"),sequence:10,action:e=>{const t=e.model.getters.getActiveSheetId(),o=e.model.getters.getSelection().zones;or(e,t,o)},isVisible:e=>!Ar(e),isEnabled:e=>(e=>ei(...e.model.getters.getSelectedZones()))(e)}).addChild("remove_data_filter",["data"],{name:r("Remove filter"),sequence:10,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:t,target:e.model.getters.getSelectedZones()})},isVisible:Ar});for(let e of le)Kg.addChild(`format_font_size_${e.pt}`,["format","format_font_size"],{name:e.pt.toString(),sequence:e.pt,action:t=>sr(t,{fontSize:e.pt})});const Qg=new class extends In{addTransformation(e,t,o){for(let i of t)this.content[i]||(this.content[i]=new Map),this.content[i].set(e,o);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},Jg=new Ao;ni`
539
539
  .o-selection {
540
540
  .o-selection-input {
541
541
  display: flex;
@@ -585,7 +585,7 @@
585
585
  font-size: calc(100% + 4px);
586
586
  }
587
587
  }
588
- `;class Jg extends t.Component{constructor(){super(...arguments),this.id=Qg.uuidv4(),this.previousRanges=this.props.ranges||[],this.originSheet=this.env.model.getters.getActiveSheetId(),this.state=t.useState({isMissing:!1,mode:"select-range"})}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 o=this.env.model.getters.getSelectionInputValue(this.id);null===(t=(e=this.props).onSelectionChanged)||void 0===t||t.call(e,o),this.previousRanges=o}onKeydown(e){"F2"===e.key?(e.preventDefault(),e.stopPropagation(),this.state.mode="select-range"===this.state.mode?"text-edit":"select-range"):e.key.startsWith("Arrow")&&(e.stopPropagation(),"select-range"===this.state.mode&&(e.preventDefault(),Xu(e,this.env.model.selection)))}extractRanges(e){return this.props.hasSingleRange?e.split(",")[0]:e}focus(e){this.state.isMissing=!1,this.state.mode="select-range",this.env.model.dispatch("FOCUS_RANGE",{id:this.id,rangeId:e})}addEmptyInput(){this.env.model.dispatch("ADD_EMPTY_RANGE",{id:this.id})}removeInput(e){var t,o;this.env.model.dispatch("REMOVE_RANGE",{id:this.id,rangeId:e}),this.triggerChange(),null===(o=(t=this.props).onSelectionConfirmed)||void 0===o||o.call(t)}onInputChanged(e,t){const o=t.target,i=this.extractRanges(o.value);this.env.model.dispatch("CHANGE_RANGE",{id:this.id,rangeId:e,value:i}),o.blur(),this.triggerChange()}confirm(){var e,t;this.env.model.dispatch("UNFOCUS_SELECTION_INPUT");const o=this.env.model.getters.getSelectionInputValue(this.id);this.props.required&&0===o.length&&(this.state.isMissing=!0);const i=this.env.model.getters.getActiveSheetId();this.originSheet!==i&&this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:i,sheetIdTo:this.originSheet}),null===(t=(e=this.props).onSelectionConfirmed)||void 0===t||t.call(e)}}Jg.template="o-spreadsheet-SelectionInput",Jg.props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},required:{type:Boolean,optional:!0},isInvalid:{type:Boolean,optional:!0},class:{type:String,optional:!0},onSelectionChanged:{type:Function,optional:!0},onSelectionConfirmed:{type:Function,optional:!0}};class ep 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=>Wi.Errors[e]||Wi.Errors.Unexpected))}get isDatasetInvalid(){var e;return!!(null===(e=this.state.datasetDispatchResult)||void 0===e?void 0:e.isCancelledBecause(32))}get isLabelInvalid(){var e;return!!(null===(e=this.state.labelsDispatchResult)||void 0===e?void 0:e.isCancelledBecause(33))}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.figureId,{dataSetsHaveTitle:e.target.checked})}onDataSeriesRangesChanged(e){this.dataSeriesRanges=e}onDataSeriesConfirmed(){this.state.datasetDispatchResult=this.props.updateChart(this.props.figureId,{dataSets:this.dataSeriesRanges})}onLabelRangeChanged(e){this.labelRange=e[0]}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.figureId,{labelRange:this.labelRange})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}}ep.template="o-spreadsheet-LineBarPieConfigPanel",ep.components={SelectionInput:Jg},ep.props={figureId:String,definition:Object,updateChart:Function};class tp extends ep{onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e.target.checked})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}}tp.template="o-spreadsheet-BarConfigPanel";const op=218,ip=182;function np(e){return vt(Ct({h:360*e.offsetX/op,s:100,l:100*e.offsetY/ip,a:1}))}ii`
588
+ `;class ep extends t.Component{constructor(){super(...arguments),this.id=Jg.uuidv4(),this.previousRanges=this.props.ranges||[],this.originSheet=this.env.model.getters.getActiveSheetId(),this.state=t.useState({isMissing:!1,mode:"select-range"})}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 o=this.env.model.getters.getSelectionInputValue(this.id);null===(t=(e=this.props).onSelectionChanged)||void 0===t||t.call(e,o),this.previousRanges=o}onKeydown(e){"F2"===e.key?(e.preventDefault(),e.stopPropagation(),this.state.mode="select-range"===this.state.mode?"text-edit":"select-range"):e.key.startsWith("Arrow")&&(e.stopPropagation(),"select-range"===this.state.mode&&(e.preventDefault(),Yu(e,this.env.model.selection)))}extractRanges(e){return this.props.hasSingleRange?e.split(",")[0]:e}focus(e){this.state.isMissing=!1,this.state.mode="select-range",this.env.model.dispatch("FOCUS_RANGE",{id:this.id,rangeId:e})}addEmptyInput(){this.env.model.dispatch("ADD_EMPTY_RANGE",{id:this.id})}removeInput(e){var t,o;this.env.model.dispatch("REMOVE_RANGE",{id:this.id,rangeId:e}),this.triggerChange(),null===(o=(t=this.props).onSelectionConfirmed)||void 0===o||o.call(t)}onInputChanged(e,t){const o=t.target,i=this.extractRanges(o.value);this.env.model.dispatch("CHANGE_RANGE",{id:this.id,rangeId:e,value:i}),o.blur(),this.triggerChange()}confirm(){var e,t;this.env.model.dispatch("UNFOCUS_SELECTION_INPUT");const o=this.env.model.getters.getSelectionInputValue(this.id);this.props.required&&0===o.length&&(this.state.isMissing=!0);const i=this.env.model.getters.getActiveSheetId();this.originSheet!==i&&this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:i,sheetIdTo:this.originSheet}),null===(t=(e=this.props).onSelectionConfirmed)||void 0===t||t.call(e)}}ep.template="o-spreadsheet-SelectionInput",ep.props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},required:{type:Boolean,optional:!0},isInvalid:{type:Boolean,optional:!0},class:{type:String,optional:!0},onSelectionChanged:{type:Function,optional:!0},onSelectionConfirmed:{type:Function,optional:!0}};class tp 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=>Gi.Errors[e]||Gi.Errors.Unexpected))}get isDatasetInvalid(){var e;return!!(null===(e=this.state.datasetDispatchResult)||void 0===e?void 0:e.isCancelledBecause(32))}get isLabelInvalid(){var e;return!!(null===(e=this.state.labelsDispatchResult)||void 0===e?void 0:e.isCancelledBecause(33))}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.figureId,{dataSetsHaveTitle:e.target.checked})}onDataSeriesRangesChanged(e){this.dataSeriesRanges=e}onDataSeriesConfirmed(){this.state.datasetDispatchResult=this.props.updateChart(this.props.figureId,{dataSets:this.dataSeriesRanges})}onLabelRangeChanged(e){this.labelRange=e[0]}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.figureId,{labelRange:this.labelRange})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}}tp.template="o-spreadsheet-LineBarPieConfigPanel",tp.components={SelectionInput:ep},tp.props={figureId:String,definition:Object,updateChart:Function};class op extends tp{onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e.target.checked})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}}op.template="o-spreadsheet-BarConfigPanel";const ip=218,np=182;function rp(e){return bt(St({h:360*e.offsetX/ip,s:100,l:100*e.offsetY/np,a:1}))}ni`
589
589
  .o-color-picker {
590
590
  position: absolute;
591
591
  top: calc(100% + 5px);
@@ -596,7 +596,7 @@
596
596
  line-height: 1.2;
597
597
  overflow-y: auto;
598
598
  overflow-x: hidden;
599
- width: ${op+12}px;
599
+ width: ${ip+12}px;
600
600
 
601
601
  .o-color-picker-section-name {
602
602
  margin: 0px ${1}px;
@@ -697,8 +697,8 @@
697
697
  hsl(1turn 100% 50%) 100%
698
698
  );
699
699
  border: ${1}px solid #c0c0c0;
700
- width: ${op}px;
701
- height: ${ip}px;
700
+ width: ${ip}px;
701
+ height: ${np}px;
702
702
  &:hover {
703
703
  cursor: crosshair;
704
704
  }
@@ -734,7 +734,7 @@
734
734
  width: 30px;
735
735
  height: 30px;
736
736
  }
737
- `;class rp extends t.Component{constructor(){super(...arguments),this.COLORS=A,this.state=t.useState({showGradient:!1,currentColor:gt(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?ai({display:"none"}):ai({"max-height":`${this.props.maxHeight}px`})}onColorClick(e){e&&this.props.onColorPicked(ut(e))}getCheckMarkColor(){return $i(this.props.currentColor)}resetColor(){this.props.onColorPicked("")}setCustomColor(e){if(!gt(this.state.currentColor))return e.stopPropagation(),void(this.state.isCurrentColorInvalid=!0);const t=ut(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=np(e)}hideMagnifier(e){this.state.style.display="none"}showMagnifier(e){this.state.style.display="block"}moveMagnifier(e){this.state.style.background=np(e);this.state.style.left=`${e.offsetX+10}px`,this.state.style.top=`${e.offsetY+10}px`}get magnifyingGlassStyle(){const{display:e,background:t,left:o,top:i}=this.state.style;return`display:${e};${"block"===e?`background-color:${t};left:${o};top:${i};`:""}`}isSameColor(e,t){return function(e,t){return gt(e)&&gt(t)&&ut(e)===ut(t)}(e,t)}}rp.template="o-spreadsheet-ColorPicker",rp.defaultProps={currentColor:""},rp.props={dropdownDirection:{type:String,optional:!0},onColorPicked:Function,currentColor:{type:String,optional:!0},maxHeight:{type:Number,optional:!0}};class sp 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})}}sp.template="o-spreadsheet-LineBarPieDesignPanel",sp.components={ColorPicker:rp},sp.props={figureId:String,definition:Object,updateChart:Function};class ap extends sp{}ap.template="o-spreadsheet-BarChartDesignPanel";class lp 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=>Wi.Errors[e]||Wi.Errors.Unexpected))}get isDataRangeInvalid(){var e;return!!(null===(e=this.state.dataRangeDispatchResult)||void 0===e?void 0:e.isCancelledBecause(36))}onDataRangeChanged(e){this.dataRange=e[0]}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.figureId,{dataRange:this.dataRange})}}lp.template="o-spreadsheet-GaugeChartConfigPanel",lp.components={SelectionInput:Jg},lp.props={figureId:String,definition:Object,updateChart:Function},ii`
737
+ `;class sp extends t.Component{constructor(){super(...arguments),this.COLORS=A,this.state=t.useState({showGradient:!1,currentColor:pt(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?li({display:"none"}):li({"max-height":`${this.props.maxHeight}px`})}onColorClick(e){e&&this.props.onColorPicked(gt(e))}getCheckMarkColor(){return Pi(this.props.currentColor)}resetColor(){this.props.onColorPicked("")}setCustomColor(e){if(!pt(this.state.currentColor))return e.stopPropagation(),void(this.state.isCurrentColorInvalid=!0);const t=gt(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=rp(e)}hideMagnifier(e){this.state.style.display="none"}showMagnifier(e){this.state.style.display="block"}moveMagnifier(e){this.state.style.background=rp(e);this.state.style.left=`${e.offsetX+10}px`,this.state.style.top=`${e.offsetY+10}px`}get magnifyingGlassStyle(){const{display:e,background:t,left:o,top:i}=this.state.style;return`display:${e};${"block"===e?`background-color:${t};left:${o};top:${i};`:""}`}isSameColor(e,t){return function(e,t){return pt(e)&&pt(t)&&gt(e)===gt(t)}(e,t)}}sp.template="o-spreadsheet-ColorPicker",sp.defaultProps={currentColor:""},sp.props={dropdownDirection:{type:String,optional:!0},onColorPicked:Function,currentColor:{type:String,optional:!0},maxHeight:{type:Number,optional:!0}};class ap 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})}}ap.template="o-spreadsheet-LineBarPieDesignPanel",ap.components={ColorPicker:sp},ap.props={figureId:String,definition:Object,updateChart:Function};class lp extends ap{}lp.template="o-spreadsheet-BarChartDesignPanel";class cp 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=>Gi.Errors[e]||Gi.Errors.Unexpected))}get isDataRangeInvalid(){var e;return!!(null===(e=this.state.dataRangeDispatchResult)||void 0===e?void 0:e.isCancelledBecause(36))}onDataRangeChanged(e){this.dataRange=e[0]}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.figureId,{dataRange:this.dataRange})}}cp.template="o-spreadsheet-GaugeChartConfigPanel",cp.components={SelectionInput:ep},cp.props={figureId:String,definition:Object,updateChart:Function},ni`
738
738
  .o-gauge-color-set {
739
739
  .o-gauge-color-set-color-button {
740
740
  display: inline-block;
@@ -774,7 +774,7 @@
774
774
  box-sizing: border-box;
775
775
  }
776
776
  }
777
- `;class cp 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=>Wi.Errors[e]||Wi.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,o;return!!((null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(37))||(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(38))||(null===(o=this.state.sectionRuleDispatchResult)||void 0===o?void 0:o.isCancelledBecause(41)))}isRangeMaxInvalid(){var e,t,o;return!!((null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(39))||(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(40))||(null===(o=this.state.sectionRuleDispatchResult)||void 0===o?void 0:o.isCancelledBecause(41)))}get isLowerInflectionPointInvalid(){var e,t;return!(!(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(42))&&!(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(44)))}get isUpperInflectionPointInvalid(){var e,t;return!(!(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(43))&&!(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(44)))}updateInflectionPointValue(e,t){const o=Me(this.props.definition.sectionRule);o[e].value=t.target.value,this.updateSectionRule(o)}updateInflectionPointType(e,t){const o=Me(this.props.definition.sectionRule);o[e].type=t.target.value,this.updateSectionRule(o)}updateSectionColor(e,t){const o=Me(this.props.definition.sectionRule);o.colors[e]=t,this.updateSectionRule(o),this.closeMenus()}updateRangeMin(e){let t=Me(this.props.definition.sectionRule);t={...t,rangeMin:e.target.value},this.updateSectionRule(t)}updateRangeMax(e){let t=Me(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}}cp.template="o-spreadsheet-GaugeChartDesignPanel",cp.components={ColorPicker:rp},cp.props={figureId:String,definition:Object,updateChart:Function};class hp extends ep{get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.figureId);return!!(e&&e instanceof pn)&&mn(e.labelRange,this.env.model.getters)}onUpdateLabelsAsText(e){this.props.updateChart(this.props.figureId,{labelsAsText:e.target.checked})}onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e.target.checked})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}}hp.template="o-spreadsheet-LineConfigPanel";class dp extends sp{}dp.template="o-spreadsheet-LineChartDesignPanel";class up 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=>Wi.Errors[e]||Wi.Errors.Unexpected))}get isKeyValueInvalid(){var e;return!!(null===(e=this.state.keyValueDispatchResult)||void 0===e?void 0:e.isCancelledBecause(34))}get isBaselineInvalid(){var e;return!!(null===(e=this.state.keyValueDispatchResult)||void 0===e?void 0:e.isCancelledBecause(35))}onKeyValueRangeChanged(e){this.keyValue=e[0]}updateKeyValueRange(){this.state.keyValueDispatchResult=this.props.updateChart(this.props.figureId,{keyValue:this.keyValue})}onBaselineRangeChanged(e){this.baseline=e[0]}updateBaselineRange(){this.state.baselineDispatchResult=this.props.updateChart(this.props.figureId,{baseline:this.baseline})}updateBaselineMode(e){this.props.updateChart(this.props.figureId,{baselineMode:e.target.value})}}up.template="o-spreadsheet-ScorecardChartConfigPanel",up.components={SelectionInput:Jg},up.props={figureId:String,definition:Object,updateChart:Function};class gp 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}}gp.template="o-spreadsheet-ScorecardChartDesignPanel",gp.components={ColorPicker:rp},gp.props={figureId:String,definition:Object,updateChart:Function};const pp=new xn;pp.add("line",{configuration:hp,design:dp}).add("bar",{configuration:tp,design:ap}).add("pie",{configuration:ep,design:sp}).add("gauge",{configuration:lp,design:cp}).add("scorecard",{configuration:up,design:gp}),ii`
777
+ `;class hp 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=>Gi.Errors[e]||Gi.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,o;return!!((null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(37))||(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(38))||(null===(o=this.state.sectionRuleDispatchResult)||void 0===o?void 0:o.isCancelledBecause(41)))}isRangeMaxInvalid(){var e,t,o;return!!((null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(39))||(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(40))||(null===(o=this.state.sectionRuleDispatchResult)||void 0===o?void 0:o.isCancelledBecause(41)))}get isLowerInflectionPointInvalid(){var e,t;return!(!(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(42))&&!(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(44)))}get isUpperInflectionPointInvalid(){var e,t;return!(!(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(43))&&!(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(44)))}updateInflectionPointValue(e,t){const o=Me(this.props.definition.sectionRule);o[e].value=t.target.value,this.updateSectionRule(o)}updateInflectionPointType(e,t){const o=Me(this.props.definition.sectionRule);o[e].type=t.target.value,this.updateSectionRule(o)}updateSectionColor(e,t){const o=Me(this.props.definition.sectionRule);o.colors[e]=t,this.updateSectionRule(o),this.closeMenus()}updateRangeMin(e){let t=Me(this.props.definition.sectionRule);t={...t,rangeMin:e.target.value},this.updateSectionRule(t)}updateRangeMax(e){let t=Me(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}}hp.template="o-spreadsheet-GaugeChartDesignPanel",hp.components={ColorPicker:sp},hp.props={figureId:String,definition:Object,updateChart:Function};class dp extends tp{get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.figureId);return!!(e&&e instanceof mn)&&fn(e.labelRange,this.env.model.getters)}onUpdateLabelsAsText(e){this.props.updateChart(this.props.figureId,{labelsAsText:e.target.checked})}onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e.target.checked})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}}dp.template="o-spreadsheet-LineConfigPanel";class up extends ap{}up.template="o-spreadsheet-LineChartDesignPanel";class gp 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=>Gi.Errors[e]||Gi.Errors.Unexpected))}get isKeyValueInvalid(){var e;return!!(null===(e=this.state.keyValueDispatchResult)||void 0===e?void 0:e.isCancelledBecause(34))}get isBaselineInvalid(){var e;return!!(null===(e=this.state.keyValueDispatchResult)||void 0===e?void 0:e.isCancelledBecause(35))}onKeyValueRangeChanged(e){this.keyValue=e[0]}updateKeyValueRange(){this.state.keyValueDispatchResult=this.props.updateChart(this.props.figureId,{keyValue:this.keyValue})}onBaselineRangeChanged(e){this.baseline=e[0]}updateBaselineRange(){this.state.baselineDispatchResult=this.props.updateChart(this.props.figureId,{baseline:this.baseline})}updateBaselineMode(e){this.props.updateChart(this.props.figureId,{baselineMode:e.target.value})}}gp.template="o-spreadsheet-ScorecardChartConfigPanel",gp.components={SelectionInput:ep},gp.props={figureId:String,definition:Object,updateChart:Function};class pp 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}}pp.template="o-spreadsheet-ScorecardChartDesignPanel",pp.components={ColorPicker:sp},pp.props={figureId:String,definition:Object,updateChart:Function};const mp=new In;mp.add("line",{configuration:dp,design:up}).add("bar",{configuration:op,design:lp}).add("pie",{configuration:tp,design:ap}).add("gauge",{configuration:cp,design:hp}).add("scorecard",{configuration:gp,design:pp}),ni`
778
778
  .o-chart {
779
779
  .o-panel {
780
780
  display: flex;
@@ -804,7 +804,7 @@
804
804
  border-bottom: 4px solid;
805
805
  }
806
806
  }
807
- `;class mp extends t.Component{get figureId(){return this.state.figureId}setup(){const e=this.env.model.getters.getSelectedFigureId();if(!e)throw new Error(r("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 o={...this.getChartDefinition(),...t};return this.env.model.dispatch("UPDATE_CHART",{definition:o,id:e,sheetId:this.env.model.getters.getFigureSheetId(e)})}onTypeChange(e){const t=this.env.model.getters.getContextCreationChart(this.figureId);if(!t)throw new Error("Chart not defined.");const o=function(e,t){return In.get(t).getChartDefinitionFromContextCreation(e)}(t,e);this.env.model.dispatch("UPDATE_CHART",{definition:o,id:this.figureId,sheetId:this.env.model.getters.getFigureSheetId(this.figureId)})}get chartPanel(){const e=this.env.model.getters.getChartType(this.figureId);if(!e)throw new Error("Chart not defined.");const t=pp.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 In.getKeys())e[t]=In.get(t).name;return e}()}activatePanel(e){this.state.panel=e}}mp.template="o-spreadsheet-ChartPanel",mp.props={onCloseSidePanel:Function};function fp(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 vp={arrowGood:{template:"ARROW_UP",img:fp('<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:fp('<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:fp('<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:fp('<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:fp('<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:fp('<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:fp('<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:fp('<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:fp('<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>')}},bp={arrows:{good:"arrowGood",neutral:"arrowNeutral",bad:"arrowBad"},smiley:{good:"smileyGood",neutral:"smileyNeutral",bad:"smileyBad"},dots:{good:"dotGood",neutral:"dotNeutral",bad:"dotBad"}};ii`
807
+ `;class fp extends t.Component{get figureId(){return this.state.figureId}setup(){const e=this.env.model.getters.getSelectedFigureId();if(!e)throw new Error(r("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 o={...this.getChartDefinition(),...t};return this.env.model.dispatch("UPDATE_CHART",{definition:o,id:e,sheetId:this.env.model.getters.getFigureSheetId(e)})}onTypeChange(e){const t=this.env.model.getters.getContextCreationChart(this.figureId);if(!t)throw new Error("Chart not defined.");const o=function(e,t){return Rn.get(t).getChartDefinitionFromContextCreation(e)}(t,e);this.env.model.dispatch("UPDATE_CHART",{definition:o,id:this.figureId,sheetId:this.env.model.getters.getFigureSheetId(this.figureId)})}get chartPanel(){const e=this.env.model.getters.getChartType(this.figureId);if(!e)throw new Error("Chart not defined.");const t=mp.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}}fp.template="o-spreadsheet-ChartPanel",fp.props={onCloseSidePanel:Function};function vp(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 bp={arrowGood:{template:"ARROW_UP",img:vp('<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:vp('<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:vp('<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:vp('<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:vp('<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:vp('<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:vp('<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:vp('<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:vp('<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>')}},Cp={arrows:{good:"arrowGood",neutral:"arrowNeutral",bad:"arrowBad"},smiley:{good:"smileyGood",neutral:"smileyNeutral",bad:"smileyBad"},dots:{good:"dotGood",neutral:"dotNeutral",bad:"dotBad"}};ni`
808
808
  .o-icon-picker {
809
809
  position: absolute;
810
810
  z-index: ${ae.IconPicker};
@@ -823,7 +823,7 @@
823
823
  outline: 1px solid gray;
824
824
  }
825
825
  }
826
- `;class Cp extends t.Component{constructor(){super(...arguments),this.icons=vp,this.iconSets=bp}onIconClick(e){e&&this.props.onIconPicked(e)}}Cp.template="o-spreadsheet-IconPicker",Cp.props={onIconPicked:Function},ii`
826
+ `;class Sp extends t.Component{constructor(){super(...arguments),this.icons=bp,this.iconSets=Cp}onIconClick(e){e&&this.props.onIconPicked(e)}}Sp.template="o-spreadsheet-IconPicker",Sp.props={onIconPicked:Function},ni`
827
827
  label {
828
828
  vertical-align: middle;
829
829
  }
@@ -1090,13 +1090,13 @@
1090
1090
  }
1091
1091
  }
1092
1092
  }
1093
- `;class Sp extends t.Component{constructor(){super(...arguments),this.icons=vp,this.cellIsOperators=Hi,this.iconSets=bp,this.getTextDecoration=ni,this.colorNumberString=dt}setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId(),this.state=t.useState({mode:"list",errors:[],rules:this.getDefaultRules()});const e=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(1===o.length){const e=this.conditionalFormats.find((e=>e.id===o[0]));e&&this.editConditionalFormat(e)}t.onWillUpdateProps((e=>{const t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(1===o.length){const e=this.conditionalFormats.find((e=>e.id===o[0]));e&&this.editConditionalFormat(e)}else this.switchToList()}})),t.useExternalListener(window,"click",this.closeMenus)}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId())}get isRangeValid(){return this.state.errors.includes(24)}errorMessage(e){return Bi.Errors[e]||Bi.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:${ni(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=dt(e.minimum.color),o=e.midpoint?dt(e.midpoint.color):null,i=dt(e.maximum.color),n="background-image: linear-gradient(to right, ";return o?n+t+", "+o+", "+i+")":n+t+", "+i+")"}return""}getDescription(e){switch(e.rule.type){case"CellIsRule":const t=Hi[e.rule.operator];return 1===e.rule.values.length?`${t} ${e.rule.values[0]}`:2===e.rule.values.length?n("%s %s and %s",t,e.rule.values[0],e.rule.values[1]):t;case"ColorScaleRule":return Bi.ColorScale;case"IconSetRule":return Bi.IconSet;default:return""}}saveConditionalFormat(){if(this.state.currentCF){if(this.state.currentCF.ranges.some((e=>!e.match(Rt))))return void(this.state.errors=[25]);const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{rule:this.getEditorRule(),id:"edit"===this.state.mode?this.state.currentCF.id:this.env.model.uuidGenerator.uuidv4()},ranges:this.state.currentCF.ranges.map((t=>this.env.model.getters.getRangeDataFromXc(e,t))),sheetId:e});t.isSuccessful?this.switchToList():this.state.errors=t.reasons}}getEditorRule(){switch(this.state.currentCFType){case"CellIsRule":return this.state.rules.cellIs;case"ColorScaleRule":return this.state.rules.colorScale;case"IconSetRule":return this.state.rules.iconSet}throw new Error(`Invalid cf type: ${this.state.currentCFType}`)}getDefaultRules(){return{cellIs:{type:"CellIsRule",operator:"IsNotEmpty",values:[],style:{fillColor:"#b6d7a8"}},colorScale:{type:"ColorScaleRule",minimum:{type:"value",color:16777215},midpoint:void 0,maximum:{type:"value",color:6989903}},iconSet:{type:"IconSetRule",icons:{upper:"arrowGood",middle:"arrowNeutral",lower:"arrowBad"},upperInflectionPoint:{type:"percentage",value:"66",operator:"gt"},lowerInflectionPoint:{type:"percentage",value:"33",operator:"gt"}}}}addConditionalFormat(){this.state.mode="add",this.state.currentCFType="CellIsRule",this.state.currentCF={id:this.env.model.uuidGenerator.uuidv4(),ranges:this.env.model.getters.getSelectedZones().map((e=>this.env.model.getters.zoneToXC(this.env.model.getters.getActiveSheetId(),e)))}}deleteConditionalFormat(e){this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:e.id,sheetId:this.env.model.getters.getActiveSheetId()})}editConditionalFormat(e){if("reorder"!==this.state.mode)switch(this.state.mode="edit",this.state.currentCF=e,this.state.currentCFType=e.rule.type,e.rule.type){case"CellIsRule":this.state.rules.cellIs=e.rule;break;case"ColorScaleRule":this.state.rules.colorScale=e.rule;break;case"IconSetRule":this.state.rules.iconSet=e.rule}}reorderConditionalFormats(){this.state.mode="reorder"}reorderRule(e,t){this.env.model.dispatch("MOVE_CONDITIONAL_FORMAT",{cfId:e.id,direction:t,sheetId:this.env.model.getters.getActiveSheetId()})}changeRuleType(e){this.state.currentCFType!==e&&this.state.rules&&(this.state.errors=[],this.state.currentCFType=e)}onRangesChanged(e){this.state.currentCF&&(this.state.currentCF.ranges=e)}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(51))}get isValue2Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(52))}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.closeMenus()}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.closeMenus()}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes(58)||this.state.errors.includes(50)||this.state.errors.includes(47)||this.state.errors.includes(53);case"midpoint":return this.state.errors.includes(59)||this.state.errors.includes(54)||this.state.errors.includes(49);case"maximum":return this.state.errors.includes(60)||this.state.errors.includes(55);default:return!1}}setColorScaleColor(e,t){const o=this.state.rules.colorScale[e];o&&(o.color=Number.parseInt(t.substr(1),16)),this.closeMenus()}getPreviewGradient(){var e;const t=this.state.rules.colorScale,o=dt(t.minimum.color),i=dt((null===(e=t.midpoint)||void 0===e?void 0:e.color)||y),n=dt(t.maximum.color),r="background-image: linear-gradient(to right, ";return void 0===t.midpoint?r+o+", "+n+")":r+o+", "+i+", "+n+")"}getThresholdColor(e){return dt(e?e.color:y)}onMidpointChange(e){const t=e.target.value,o=this.state.rules.colorScale;o.midpoint="none"===t?void 0:{color:y,value:"",...o.midpoint,type:t}}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes(57)||this.state.errors.includes(62)||this.state.errors.includes(48);case"upperInflectionPoint":return this.state.errors.includes(56)||this.state.errors.includes(61)||this.state.errors.includes(48);default:return!0}}reverseIcons(){const e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t}setIconSet(e){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad}setIcon(e,t){this.state.rules.iconSet.icons[e]=t}}Sp.template="o-spreadsheet-ConditionalFormattingPanel",Sp.components={SelectionInput:Jg,IconPicker:Cp,ColorPicker:rp},Sp.props={selection:{type:Object,optional:!0},onCloseSidePanel:Function},ii`
1093
+ `;class Ep extends t.Component{constructor(){super(...arguments),this.icons=bp,this.cellIsOperators=Wi,this.iconSets=Cp,this.getTextDecoration=ri,this.colorNumberString=ut}setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId(),this.state=t.useState({mode:"list",errors:[],rules:this.getDefaultRules()});const e=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(1===o.length){const e=this.conditionalFormats.find((e=>e.id===o[0]));e&&this.editConditionalFormat(e)}t.onWillUpdateProps((e=>{const t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(1===o.length){const e=this.conditionalFormats.find((e=>e.id===o[0]));e&&this.editConditionalFormat(e)}else this.switchToList()}})),t.useExternalListener(window,"click",this.closeMenus)}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId())}get isRangeValid(){return this.state.errors.includes(24)}errorMessage(e){return Hi.Errors[e]||Hi.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:${ri(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=ut(e.minimum.color),o=e.midpoint?ut(e.midpoint.color):null,i=ut(e.maximum.color),n="background-image: linear-gradient(to right, ";return o?n+t+", "+o+", "+i+")":n+t+", "+i+")"}return""}getDescription(e){switch(e.rule.type){case"CellIsRule":const t=Wi[e.rule.operator];return 1===e.rule.values.length?`${t} ${e.rule.values[0]}`:2===e.rule.values.length?n("%s %s and %s",t,e.rule.values[0],e.rule.values[1]):t;case"ColorScaleRule":return Hi.ColorScale;case"IconSetRule":return Hi.IconSet;default:return""}}saveConditionalFormat(){if(this.state.currentCF){if(this.state.currentCF.ranges.some((e=>!e.match(Tt))))return void(this.state.errors=[25]);const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{rule:this.getEditorRule(),id:"edit"===this.state.mode?this.state.currentCF.id:this.env.model.uuidGenerator.uuidv4()},ranges:this.state.currentCF.ranges.map((t=>this.env.model.getters.getRangeDataFromXc(e,t))),sheetId:e});t.isSuccessful?this.switchToList():this.state.errors=t.reasons}}getEditorRule(){switch(this.state.currentCFType){case"CellIsRule":return this.state.rules.cellIs;case"ColorScaleRule":return this.state.rules.colorScale;case"IconSetRule":return this.state.rules.iconSet}throw new Error(`Invalid cf type: ${this.state.currentCFType}`)}getDefaultRules(){return{cellIs:{type:"CellIsRule",operator:"IsNotEmpty",values:[],style:{fillColor:"#b6d7a8"}},colorScale:{type:"ColorScaleRule",minimum:{type:"value",color:16777215},midpoint:void 0,maximum:{type:"value",color:6989903}},iconSet:{type:"IconSetRule",icons:{upper:"arrowGood",middle:"arrowNeutral",lower:"arrowBad"},upperInflectionPoint:{type:"percentage",value:"66",operator:"gt"},lowerInflectionPoint:{type:"percentage",value:"33",operator:"gt"}}}}addConditionalFormat(){this.state.mode="add",this.state.currentCFType="CellIsRule",this.state.currentCF={id:this.env.model.uuidGenerator.uuidv4(),ranges:this.env.model.getters.getSelectedZones().map((e=>this.env.model.getters.zoneToXC(this.env.model.getters.getActiveSheetId(),e)))}}deleteConditionalFormat(e){this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:e.id,sheetId:this.env.model.getters.getActiveSheetId()})}editConditionalFormat(e){if("reorder"!==this.state.mode)switch(this.state.mode="edit",this.state.currentCF=e,this.state.currentCFType=e.rule.type,e.rule.type){case"CellIsRule":this.state.rules.cellIs=e.rule;break;case"ColorScaleRule":this.state.rules.colorScale=e.rule;break;case"IconSetRule":this.state.rules.iconSet=e.rule}}reorderConditionalFormats(){this.state.mode="reorder"}reorderRule(e,t){this.env.model.dispatch("MOVE_CONDITIONAL_FORMAT",{cfId:e.id,direction:t,sheetId:this.env.model.getters.getActiveSheetId()})}changeRuleType(e){this.state.currentCFType!==e&&this.state.rules&&(this.state.errors=[],this.state.currentCFType=e)}onRangesChanged(e){this.state.currentCF&&(this.state.currentCF.ranges=e)}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(51))}get isValue2Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(52))}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.closeMenus()}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.closeMenus()}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes(58)||this.state.errors.includes(50)||this.state.errors.includes(47)||this.state.errors.includes(53);case"midpoint":return this.state.errors.includes(59)||this.state.errors.includes(54)||this.state.errors.includes(49);case"maximum":return this.state.errors.includes(60)||this.state.errors.includes(55);default:return!1}}setColorScaleColor(e,t){const o=this.state.rules.colorScale[e];o&&(o.color=Number.parseInt(t.substr(1),16)),this.closeMenus()}getPreviewGradient(){var e;const t=this.state.rules.colorScale,o=ut(t.minimum.color),i=ut((null===(e=t.midpoint)||void 0===e?void 0:e.color)||y),n=ut(t.maximum.color),r="background-image: linear-gradient(to right, ";return void 0===t.midpoint?r+o+", "+n+")":r+o+", "+i+", "+n+")"}getThresholdColor(e){return ut(e?e.color:y)}onMidpointChange(e){const t=e.target.value,o=this.state.rules.colorScale;o.midpoint="none"===t?void 0:{color:y,value:"",...o.midpoint,type:t}}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes(57)||this.state.errors.includes(62)||this.state.errors.includes(48);case"upperInflectionPoint":return this.state.errors.includes(56)||this.state.errors.includes(61)||this.state.errors.includes(48);default:return!0}}reverseIcons(){const e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t}setIconSet(e){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad}setIcon(e,t){this.state.rules.iconSet.icons[e]=t}}Ep.template="o-spreadsheet-ConditionalFormattingPanel",Ep.components={SelectionInput:ep,IconPicker:Sp,ColorPicker:sp},Ep.props={selection:{type:Object,optional:!0},onCloseSidePanel:Function},ni`
1094
1094
  .o-custom-currency {
1095
1095
  .o-format-proposals {
1096
1096
  color: black;
1097
1097
  }
1098
1098
  }
1099
- `;class Ep 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),o=e.position,i="before"===e.position?"after":"before",n=this.state.currencySymbol.trim()?this.state.currencySymbol:"",r=this.state.currencyCode.trim()?this.state.currencyCode:"";return r||n?[...this.createFormatProposals(t,n,r,o),...this.createFormatProposals(t,n,r,i)]:[]}get isSameFormat(){const e=this.formatProposals[this.state.selectedFormatIndex];return!!e&&e.format===this.getCommonFormat()}async updateAvailableCurrencies(){var e,t;if(0===Bg.getAll().length){(await(null===(t=(e=this.env).loadCurrencies)||void 0===t?void 0:t.call(e))||[]).forEach(((e,t)=>{Bg.add(t.toString(),e)}))}const o={name:this.env._t(qi.Custom),code:"",symbol:"",decimalPlaces:2,position:"after"};this.availableCurrencies=[o,...Bg.getAll()]}updateSelectCurrency(e){const t=e.target;this.state.selectedCurrencyIndex=parseInt(t.value,10);const o=this.availableCurrencies[this.state.selectedCurrencyIndex];this.state.currencyCode=o.code,this.state.currencySymbol=o.symbol}updateCode(e){const t=e.target;this.state.currencyCode=t.value,this.initAvailableCurrencies()}updateSymbol(e){const t=e.target;this.state.currencySymbol=t.value,this.initAvailableCurrencies()}updateSelectFormat(e){const t=e.target;this.state.selectedFormatIndex=parseInt(t.value,10)}apply(){const e=this.formatProposals[this.state.selectedFormatIndex];this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),format:e.format})}initAvailableCurrencies(){this.state.selectedCurrencyIndex=0}initProposalBases(e){const t=[{format:"#,##0",example:"1,000"}],o=e?"."+"0".repeat(e):"";return o&&t.push({format:"#,##0"+o,example:"1,000"+o}),t}createFormatProposals(e,t,o,i){let n=[];if(t)for(let o of e)n.push(this.createFormatProposal(i,o.example,o.format,t));if(o)for(let r of e){const e=("after"===i?" ":"")+o+" "+t;n.push(this.createFormatProposal(i,r.example,r.format,e))}return n}createFormatProposal(e,t,o,i){const n="[$"+i+"]";return{example:"before"===e?i+t:t+i,format:"before"===e?n+o:o+n}}getCommonFormat(){const e=this.env.model.getters.getSelectedZones(),t=this.env.model.getters.getActiveSheetId(),o=e.map((e=>this.env.model.getters.getEvaluatedCellsInZone(t,e))).flat(),i=o[0].format;return o.every((e=>e.format===i))?i:void 0}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:"")}}Ep.template="o-spreadsheet-CustomCurrencyPanel",Ep.props={onCloseSidePanel:Function},ii`
1099
+ `;class wp 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),o=e.position,i="before"===e.position?"after":"before",n=this.state.currencySymbol.trim()?this.state.currencySymbol:"",r=this.state.currencyCode.trim()?this.state.currencyCode:"";return r||n?[...this.createFormatProposals(t,n,r,o),...this.createFormatProposals(t,n,r,i)]:[]}get isSameFormat(){const e=this.formatProposals[this.state.selectedFormatIndex];return!!e&&e.format===this.getCommonFormat()}async updateAvailableCurrencies(){var e,t;if(0===Hg.getAll().length){(await(null===(t=(e=this.env).loadCurrencies)||void 0===t?void 0:t.call(e))||[]).forEach(((e,t)=>{Hg.add(t.toString(),e)}))}const o={name:this.env._t(Zi.Custom),code:"",symbol:"",decimalPlaces:2,position:"after"};this.availableCurrencies=[o,...Hg.getAll()]}updateSelectCurrency(e){const t=e.target;this.state.selectedCurrencyIndex=parseInt(t.value,10);const o=this.availableCurrencies[this.state.selectedCurrencyIndex];this.state.currencyCode=o.code,this.state.currencySymbol=o.symbol}updateCode(e){const t=e.target;this.state.currencyCode=t.value,this.initAvailableCurrencies()}updateSymbol(e){const t=e.target;this.state.currencySymbol=t.value,this.initAvailableCurrencies()}updateSelectFormat(e){const t=e.target;this.state.selectedFormatIndex=parseInt(t.value,10)}apply(){const e=this.formatProposals[this.state.selectedFormatIndex];this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),format:e.format})}initAvailableCurrencies(){this.state.selectedCurrencyIndex=0}initProposalBases(e){const t=[{format:"#,##0",example:"1,000"}],o=e?"."+"0".repeat(e):"";return o&&t.push({format:"#,##0"+o,example:"1,000"+o}),t}createFormatProposals(e,t,o,i){let n=[];if(t)for(let o of e)n.push(this.createFormatProposal(i,o.example,o.format,t));if(o)for(let r of e){const e=("after"===i?" ":"")+o+" "+t;n.push(this.createFormatProposal(i,r.example,r.format,e))}return n}createFormatProposal(e,t,o,i){const n="[$"+i+"]";return{example:"before"===e?i+t:t+i,format:"before"===e?n+o:o+n}}getCommonFormat(){const e=this.env.model.getters.getSelectedZones(),t=this.env.model.getters.getActiveSheetId(),o=e.map((e=>this.env.model.getters.getEvaluatedCellsInZone(t,e))).flat(),i=o[0].format;return o.every((e=>e.format===i))?i:void 0}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:"")}}wp.template="o-spreadsheet-CustomCurrencyPanel",wp.props={onCloseSidePanel:Function},ni`
1100
1100
  .o-find-and-replace {
1101
1101
  .o-far-item {
1102
1102
  display: block;
@@ -1129,7 +1129,7 @@
1129
1129
  }
1130
1130
  }
1131
1131
  }
1132
- `;class wp 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()}get pendingSearch(){return void 0!==this.debounceTimeoutId}setup(){this.showFormulaState=this.env.model.getters.shouldShowFormulas(),t.onMounted((()=>this.focusInput())),t.onWillUnmount((()=>{this.env.model.dispatch("CLEAR_SEARCH"),this.env.model.dispatch("SET_FORMULA_VISIBILITY",{show:this.showFormulaState})}))}onInput(e){this.state.toSearch=e.target.value,this.debouncedUpdateSearch()}onKeydownSearch(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),this.onSelectNextCell())}onKeydownReplace(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),this.replace())}onFocusSidePanel(){this.state.searchOptions.searchFormulas=this.env.model.getters.shouldShowFormulas(),this.env.model.dispatch("REFRESH_SEARCH")}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}),400)}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}}}}wp.template="o-spreadsheet-FindAndReplacePanel",wp.props={onCloseSidePanel:Function};const yp=new xn;yp.add("ConditionalFormatting",{title:r("Conditional formatting"),Body:Sp}),yp.add("ChartPanel",{title:r("Chart"),Body:mp}),yp.add("FindAndReplace",{title:r("Find and Replace"),Body:wp}),yp.add("CustomCurrency",{title:r("Custom currency format"),Body:Ep});const xp=new class extends xn{constructor(){super(...arguments),this.mapping={},this.uuidGenerator=new To}add(e,t){const o={...t,id:this.uuidGenerator.uuidv4()};return super.add(e,o)}};ii`
1132
+ `;class yp 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()}get pendingSearch(){return void 0!==this.debounceTimeoutId}setup(){this.showFormulaState=this.env.model.getters.shouldShowFormulas(),t.onMounted((()=>this.focusInput())),t.onWillUnmount((()=>{this.env.model.dispatch("CLEAR_SEARCH"),this.env.model.dispatch("SET_FORMULA_VISIBILITY",{show:this.showFormulaState})}))}onInput(e){this.state.toSearch=e.target.value,this.debouncedUpdateSearch()}onKeydownSearch(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),this.onSelectNextCell())}onKeydownReplace(e){"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),this.replace())}onFocusSidePanel(){this.state.searchOptions.searchFormulas=this.env.model.getters.shouldShowFormulas(),this.env.model.dispatch("REFRESH_SEARCH")}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}),400)}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}}}}yp.template="o-spreadsheet-FindAndReplacePanel",yp.props={onCloseSidePanel:Function};const xp=new In;xp.add("ConditionalFormatting",{title:r("Conditional formatting"),Body:Ep}),xp.add("ChartPanel",{title:r("Chart"),Body:fp}),xp.add("FindAndReplace",{title:r("Find and Replace"),Body:yp}),xp.add("CustomCurrency",{title:r("Custom currency format"),Body:wp});const Ip=new class extends In{constructor(){super(...arguments),this.mapping={},this.uuidGenerator=new Ao}add(e,t){const o={...t,id:this.uuidGenerator.uuidv4()};return super.add(e,o)}};ni`
1133
1133
  div.o-figure {
1134
1134
  box-sizing: border-box;
1135
1135
  position: absolute;
@@ -1203,7 +1203,7 @@
1203
1203
  }
1204
1204
  }
1205
1205
  }
1206
- `;class Ip extends t.Component{constructor(){super(...arguments),this.figureRef=t.useRef("figure")}get isSelected(){return this.env.model.getters.getSelectedFigureId()===this.props.figure.id}get figureRegistry(){return Wg}getBorderWidth(){return this.env.isDashboard()?0:this.isSelected?2:this.borderWidth}get borderStyle(){return`border: ${this.getBorderWidth()}px solid ${this.isSelected?E:"#c9ccd2"};`}get wrapperStyle(){const{x:e,y:t,width:o,height:i}=this.props.figure;return ai({left:`${e}px`,top:`${t}px`,width:`${o}px`,height:`${i}px`,"z-index":String(ae.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(){const e=Wg.get(this.props.figure.tag).borderWidth;this.borderWidth=void 0!==e?e:1,t.useEffect(((e,t,o)=>{e===t&&(null==o||o.focus({preventScroll:!0}))}),(()=>[this.env.model.getters.getSelectedFigureId(),this.props.figure.id,this.figureRef.el]))}clickAnchor(e,t,o){this.props.onClickAnchor(e,t,o)}onMouseDown(e){this.props.onMouseDown(e)}onKeyDown(e){const t=this.props.figure;switch(e.key){case"Delete":this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:t.id}),this.props.onFigureDeleted(),e.stopPropagation(),e.preventDefault();break;case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":const o={ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1]}[e.key];this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:t.id,x:t.x+o[0],y:t.y+o[1]}),e.stopPropagation(),e.preventDefault()}}}Ip.template="o-spreadsheet-FigureComponent",Ip.components={},Ip.defaultProps={onFigureDeleted:()=>{},onMouseDown:()=>{},onClickAnchor:()=>{}},Ip.props={figure:Object,style:{type:String,optional:!0},onFigureDeleted:{type:Function,optional:!0},onMouseDown:{type:Function,optional:!0},onClickAnchor:{type:Function,optional:!0}};class Rp extends t.Component{constructor(){super(...arguments),this.dnd=t.useState({figId:void 0,x:0,y:0,width:0,height:0})}setup(){t.onMounted((()=>{this.render()}))}getVisibleFigures(){const e=this.env.model.getters.getVisibleFigures();return this.dnd.figId&&!e.some((e=>e.id===this.dnd.figId))&&e.push(this.env.model.getters.getFigure(this.env.model.getters.getActiveSheetId(),this.dnd.figId)),e}get containers(){const e=this.getVisibleFigures(),t=[];for(const o of["topLeft","topRight","bottomLeft","bottomRight"]){const i=e.filter((e=>this.getFigureContainer(e)===o));i.length>0&&t.push({type:o,figures:i,style:this.getContainerStyle(o),inverseViewportStyle:this.getInverseViewportPositionStyle(o)})}return this.dnd.figId&&t.push({type:"dnd",figures:[this.getDndFigure()],style:this.getContainerStyle("dnd"),inverseViewportStyle:this.getInverseViewportPositionStyle("dnd")}),t}getContainerStyle(e){const{width:t,height:o}=this.env.model.getters.getMainViewportRect(),{x:i,y:n}=this.env.model.getters.getMainViewportCoordinates(),r=["bottomRight","topRight"].includes(e)?i:0,s=t-r,a=["bottomRight","bottomLeft"].includes(e)?n:0;return ai({left:`${r}px`,top:`${a}px`,width:`${s}px`,height:`${o-a}px`})}getInverseViewportPositionStyle(e){const{scrollX:t,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo(),{x:i,y:n}=this.env.model.getters.getMainViewportCoordinates();return ai({left:`${["bottomRight","topRight"].includes(e)?-(i+t):0}px`,top:`${["bottomRight","bottomLeft"].includes(e)?-(n+o):0}px`})}getFigureContainer(e){const{x:t,y:o}=this.env.model.getters.getMainViewportCoordinates();return e.id===this.dnd.figId?"dnd":e.x<t&&e.y<o?"topLeft":e.x<t?"bottomLeft":e.y<o?"topRight":"bottomRight"}startDraggingFigure(e,t){if(t.button>0||this.env.model.getters.isReadonly())return;if(!this.env.model.dispatch("SELECT_FIGURE",{id:e.id}).isSuccessful)return;const o=this.env.model.getters.getActiveSheetId(),i=t.clientX,n=t.clientY,{x:r,y:s}=this.internalToScreenCoordinates(e);this.dnd.x=r,this.dnd.y=s,this.dnd.width=e.width,this.dnd.height=e.height;Dr((t=>{const{x:o,y:a}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:l,scrollY:c}=this.env.model.getters.getActiveSheetScrollInfo(),h=o?0:-l,d=a?0:-c;this.dnd.figId=e.id;let u=t.clientX-i;this.dnd.x=Math.max(r+u,h);let g=t.clientY-n;this.dnd.y=Math.max(s+g,d)}),(t=>{if(!this.dnd.figId)return;let{x:i,y:n}=this.screenCoordinatesToInternal(this.dnd);this.dnd.figId=void 0,this.env.model.dispatch("UPDATE_FIGURE",{sheetId:o,id:e.id,x:i,y:n})}))}startResize(e,t,o,i){i.stopPropagation();const n=i.clientX,r=i.clientY,{x:s,y:a}=this.internalToScreenCoordinates(e);this.dnd.x=s,this.dnd.y=a,this.dnd.width=e.width,this.dnd.height=e.height;const l=Wg.get(e.tag).keepRatio||!1,c=Wg.get(e.tag).minFigSize||80;let h;h=l&&0!=t&&0!=o?i=>{this.dnd.figId=e.id;const l=Math.min(t*(n-i.clientX),e.width-c),h=Math.min(o*(r-i.clientY),e.height-c),d=Math.min(l/e.width,h/e.height);this.dnd.width=e.width*(1-d),this.dnd.height=e.height*(1-d),t<0&&(this.dnd.x=s+e.width*d),o<0&&(this.dnd.y=a+e.height*d)}:i=>{this.dnd.figId=e.id;const l=Math.max(t*(i.clientX-n),c-e.width),h=Math.max(o*(i.clientY-r),c-e.height);this.dnd.width=e.width+l,this.dnd.height=e.height+h,t<0&&(this.dnd.x=s-l),o<0&&(this.dnd.y=a-h)};Dr(h,(i=>{if(!this.dnd.figId)return;this.dnd.figId=void 0;let{x:n,y:r}=this.screenCoordinatesToInternal(this.dnd);const s={x:n,y:r};t&&(s.width=this.dnd.width),o&&(s.height=this.dnd.height),this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:e.id,...s})}))}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?"":ai({opacity:"0.9",cursor:"grabbing"})}internalToScreenCoordinates({x:e,y:t}){const{x:o,y:i}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();return{x:e=e<o?e:e-n,y:t=t<i?t:t-r}}screenCoordinatesToInternal({x:e,y:t}){const{x:o,y:i}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();return{x:e=o&&e<o?e:e+n,y:t=i&&t<i?t:t+r}}}function Tp(e,o,i){let n={col:void 0,row:void 0};const{Date:r}=window;let s=0,a=0,l=0;function c(){return{col:e.model.getters.getColIndex(s),row:e.model.getters.getRowIndex(a)}}const{pause:h,resume:d}=function(e,o){let i;const{setInterval:n,clearInterval:r}=window;return t.useEffect((()=>(i=n(e,o),()=>r(i))),(()=>[o])),{pause:()=>{r(i),i=void 0},resume:()=>{void 0===i&&(i=n(e,o))}}}((function(){const{col:e,row:t}=c(),o=r.now()-l;o>300&&(e!==n.col||t!==n.row)&&p(void 0,void 0);if(o>300){if(e<0||t<0)return;p(e,t)}}),200);function u(e){s=e.offsetX,a=e.offsetY,l=r.now()}function g(){const{col:e,row:t}=c();e===n.col&&t===n.row||p(void 0,void 0)}function p(e,t){e===n.col&&t===n.row||(n.col=e,n.row=t,i({col:e,row:t}))}return t.onMounted((()=>{const e=o.el;e.addEventListener("mousemove",u),e.addEventListener("mouseleave",h),e.addEventListener("mouseenter",d),e.addEventListener("mousedown",g)})),t.onWillUnmount((()=>{const e=o.el;e.removeEventListener("mousemove",u),e.removeEventListener("mouseleave",h),e.removeEventListener("mouseenter",d),e.removeEventListener("mousedown",g)})),n}Rp.template="o-spreadsheet-FiguresContainer",Rp.components={FigureComponent:Ip},Rp.props={onFigureDeleted:Function};class Ap extends t.Component{setup(){this.gridOverlay=t.useRef("gridOverlay"),Tp(this.env,this.gridOverlay,this.props.onCellHovered);const e=new ResizeObserver((()=>{this.props.onGridResized({height:this.gridOverlayEl.clientHeight,width:this.gridOverlayEl.clientWidth})}));t.onMounted((()=>{e.observe(this.gridOverlayEl)})),t.onWillUnmount((()=>{e.disconnect()})),function(e,o,i){let n=null,r=null;function s(e){1===e.touches.length&&(n=e.touches[0].clientX,r=e.touches[0].clientY)}function a(){n=null,r=null}function l(e){if(1!==e.touches.length)return;i()&&(e.preventDefault(),e.stopPropagation());const t=e.touches[0].clientX,s=e.touches[0].clientY;o(n-t,r-s),n=t,r=s}t.onMounted((()=>{e.el.addEventListener("touchstart",s),e.el.addEventListener("touchend",a),e.el.addEventListener("touchmove",l)})),t.onWillUnmount((()=>{e.el.removeEventListener("touchstart",s),e.el.removeEventListener("touchend",a),e.el.removeEventListener("touchmove",l)}))}(this.gridOverlay,this.props.onGridMoved,(()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetDOMScrollInfo();return e>0}))}get gridOverlayEl(){if(!this.gridOverlay.el)throw new Error("GridOverlay el is not defined.");return this.gridOverlay.el}onMouseDown(e){if(e.button>0)return;const[t,o]=this.getCartesianCoordinates(e);this.props.onCellClicked(t,o,{shiftKey:e.shiftKey,ctrlKey:e.ctrlKey})}onDoubleClick(e){const[t,o]=this.getCartesianCoordinates(e);this.props.onCellDoubleClicked(t,o)}onContextMenu(e){e.preventDefault();const[t,o]=this.getCartesianCoordinates(e);this.props.onCellRightClicked(t,o,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){return[this.env.model.getters.getColIndex(e.offsetX),this.env.model.getters.getRowIndex(e.offsetY)]}}Ap.template="o-spreadsheet-GridOverlay",Ap.components={FiguresContainer:Rp},Ap.defaultProps={onCellHovered:()=>{},onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{},onFigureDeleted:()=>{}},Ap.props={onCellHovered:{type:Function,optional:!0},onCellDoubleClicked:{type:Function,optional:!0},onCellClicked:{type:Function,optional:!0},onCellRightClicked:{type:Function,optional:!0},onGridResized:{type:Function,optional:!0},onFigureDeleted:{type:Function,optional:!0},onGridMoved:Function,gridOverlayDimensions:String};class Op extends t.Component{constructor(){super(...arguments),this.zIndex=ae.GridPopover}get cellPopover(){const e=this.env.model.getters.getCellPopover(this.props.hoveredCell);if(!e.isOpen)return{isOpen:!1};const t=e.anchorRect;return{...e,anchorRect:{...t,x:t.x+this.props.gridRect.x,y:t.y+this.props.gridRect.y}}}}Op.template="o-spreadsheet-GridPopover",Op.components={Popover:Ln},Op.props={hoveredCell:Object,onClosePopover:Function,onMouseWheel:Function,gridRect:Object};class Mp 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})}_computeHandleDisplay(e){const t=this._getEvOffset(e),o=this._getElementIndex(t);if(o<0)return;const i=this._getDimensionsInViewport(o);t-i.start<this.PADDING&&o!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=i.start,this.state.activeElement=this._getPreviousVisibleElement(o)):i.end-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=i.end,this.state.activeElement=o):this.state.resizerIsActive=!1}_computeGrabDisplay(e){const t=this._getElementIndex(this._getEvOffset(e)),o=this._getActiveElements(),i=this._getSelectedZoneStart(),n=this._getSelectedZoneEnd();o.has(i)&&i<=t&&t<=n?this.state.waitingForMove=!0:this.state.waitingForMove=!1}onMouseMove(e){this.state.isResizing||this.state.isMoving||this.state.isSelecting||(this._computeHandleDisplay(e),this._computeGrabDisplay(e))}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(e){this._fitElementSize(this.state.activeElement),this.state.isResizing=!1,this._computeHandleDisplay(e),this._computeGrabDisplay(e)}onMouseDown(e){this.state.isResizing=!0,this.state.delta=0;const t=this._getClientPosition(e),o=this.state.draggerLinePosition,i=this._getElementSize(this.state.activeElement),n=o-i+this.MIN_ELEMENT_SIZE,r=this._getMaxSize();Dr((e=>{this.state.delta=this._getClientPosition(e)-t,this.state.draggerLinePosition=o+this.state.delta,this.state.draggerLinePosition<n&&(this.state.draggerLinePosition=n,this.state.delta=this.MIN_ELEMENT_SIZE-i),this.state.draggerLinePosition>r&&(this.state.draggerLinePosition=r,this.state.delta=r-o)}),(e=>{this.state.isResizing=!1,0!==this.state.delta&&this._updateSize()}))}select(e){if(e.button>0)return;const t=this._getElementIndex(this._getEvOffset(e));t<0||(!0!==this.state.waitingForMove?("editing"===this.env.model.getters.getEditionMode()&&this.env.model.selection.getBackToDefault(),this.startSelection(e,t)):this.startMovement(e))}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;const t=this._getDimensionsInViewport(this._getSelectedZoneStart()),o=this._getDimensionsInViewport(this._getSelectedZoneEnd()),i=t.start;this.state.draggerLinePosition=i,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=i,this.state.draggerShadowThickness=o.end-t.start;kr(this.env,((e,o)=>{let i="COL"===this._getType()?e:o;if(i>=0){const e=this._getDimensionsInViewport(i);i<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=e.start,this.state.draggerShadowPosition=e.start,this.state.base=i):this._getSelectedZoneEnd()<i?(this.state.draggerLinePosition=e.end,this.state.draggerShadowPosition=e.end-this.state.draggerShadowThickness,this.state.base=i+1):(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,e.ctrlKey),this.lastSelectedElementIndex=t;kr(this.env,((e,t)=>{let o="COL"===this._getType()?e:t;o!==this.lastSelectedElementIndex&&-1!==o&&(this._increaseSelection(o),this.lastSelectedElementIndex=o)}),(()=>{this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this.env.model.dispatch(e.ctrlKey?"PREPARE_SELECTION_INPUT_EXPANSION":"STOP_SELECTION_INPUT"),this._computeGrabDisplay(e)}))}onMouseUp(e){this.lastSelectedElementIndex=null}onContextMenu(e){e.preventDefault();const t=this._getElementIndex(this._getEvOffset(e));if(t<0)return;this._getActiveElements().has(t)||this._selectElement(t,!1);const o=this._getType();this.props.onOpenContextMenu(o,e.clientX,e.clientY)}}ii`
1206
+ `;class Rp extends t.Component{constructor(){super(...arguments),this.figureRef=t.useRef("figure")}get isSelected(){return this.env.model.getters.getSelectedFigureId()===this.props.figure.id}get figureRegistry(){return Gg}getBorderWidth(){return this.env.isDashboard()?0:this.isSelected?2:this.borderWidth}get borderStyle(){return`border: ${this.getBorderWidth()}px solid ${this.isSelected?E:"#c9ccd2"};`}get wrapperStyle(){const{x:e,y:t,width:o,height:i}=this.props.figure;return li({left:`${e}px`,top:`${t}px`,width:`${o}px`,height:`${i}px`,"z-index":String(ae.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(){const e=Gg.get(this.props.figure.tag).borderWidth;this.borderWidth=void 0!==e?e:1,t.useEffect(((e,t,o)=>{e===t&&(null==o||o.focus({preventScroll:!0}))}),(()=>[this.env.model.getters.getSelectedFigureId(),this.props.figure.id,this.figureRef.el]))}clickAnchor(e,t,o){this.props.onClickAnchor(e,t,o)}onMouseDown(e){this.props.onMouseDown(e)}onKeyDown(e){const t=this.props.figure;switch(e.key){case"Delete":this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:t.id}),this.props.onFigureDeleted(),e.stopPropagation(),e.preventDefault();break;case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":const o={ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1]}[e.key];this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:t.id,x:t.x+o[0],y:t.y+o[1]}),e.stopPropagation(),e.preventDefault()}}}Rp.template="o-spreadsheet-FigureComponent",Rp.components={},Rp.defaultProps={onFigureDeleted:()=>{},onMouseDown:()=>{},onClickAnchor:()=>{}},Rp.props={figure:Object,style:{type:String,optional:!0},onFigureDeleted:{type:Function,optional:!0},onMouseDown:{type:Function,optional:!0},onClickAnchor:{type:Function,optional:!0}};class Tp extends t.Component{constructor(){super(...arguments),this.dnd=t.useState({figId:void 0,x:0,y:0,width:0,height:0})}setup(){t.onMounted((()=>{this.render()}))}getVisibleFigures(){const e=this.env.model.getters.getVisibleFigures();return this.dnd.figId&&!e.some((e=>e.id===this.dnd.figId))&&e.push(this.env.model.getters.getFigure(this.env.model.getters.getActiveSheetId(),this.dnd.figId)),e}get containers(){const e=this.getVisibleFigures(),t=[];for(const o of["topLeft","topRight","bottomLeft","bottomRight"]){const i=e.filter((e=>this.getFigureContainer(e)===o));i.length>0&&t.push({type:o,figures:i,style:this.getContainerStyle(o),inverseViewportStyle:this.getInverseViewportPositionStyle(o)})}return this.dnd.figId&&t.push({type:"dnd",figures:[this.getDndFigure()],style:this.getContainerStyle("dnd"),inverseViewportStyle:this.getInverseViewportPositionStyle("dnd")}),t}getContainerStyle(e){const{width:t,height:o}=this.env.model.getters.getMainViewportRect(),{x:i,y:n}=this.env.model.getters.getMainViewportCoordinates(),r=["bottomRight","topRight"].includes(e)?i:0,s=t-r,a=["bottomRight","bottomLeft"].includes(e)?n:0;return li({left:`${r}px`,top:`${a}px`,width:`${s}px`,height:`${o-a}px`})}getInverseViewportPositionStyle(e){const{scrollX:t,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo(),{x:i,y:n}=this.env.model.getters.getMainViewportCoordinates();return li({left:`${["bottomRight","topRight"].includes(e)?-(i+t):0}px`,top:`${["bottomRight","bottomLeft"].includes(e)?-(n+o):0}px`})}getFigureContainer(e){const{x:t,y:o}=this.env.model.getters.getMainViewportCoordinates();return e.id===this.dnd.figId?"dnd":e.x<t&&e.y<o?"topLeft":e.x<t?"bottomLeft":e.y<o?"topRight":"bottomRight"}startDraggingFigure(e,t){if(t.button>0||this.env.model.getters.isReadonly())return;if(!this.env.model.dispatch("SELECT_FIGURE",{id:e.id}).isSuccessful)return;const o=this.env.model.getters.getActiveSheetId(),i=t.clientX,n=t.clientY,{x:r,y:s}=this.internalToScreenCoordinates(e);this.dnd.x=r,this.dnd.y=s,this.dnd.width=e.width,this.dnd.height=e.height;kr((t=>{const{x:o,y:a}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:l,scrollY:c}=this.env.model.getters.getActiveSheetScrollInfo(),h=o?0:-l,d=a?0:-c;this.dnd.figId=e.id;let u=t.clientX-i;this.dnd.x=Math.max(r+u,h);let g=t.clientY-n;this.dnd.y=Math.max(s+g,d)}),(t=>{if(!this.dnd.figId)return;let{x:i,y:n}=this.screenCoordinatesToInternal(this.dnd);this.dnd.figId=void 0,this.env.model.dispatch("UPDATE_FIGURE",{sheetId:o,id:e.id,x:i,y:n})}))}startResize(e,t,o,i){i.stopPropagation();const n=i.clientX,r=i.clientY,{x:s,y:a}=this.internalToScreenCoordinates(e);this.dnd.x=s,this.dnd.y=a,this.dnd.width=e.width,this.dnd.height=e.height;const l=Gg.get(e.tag).keepRatio||!1,c=Gg.get(e.tag).minFigSize||80;let h;h=l&&0!=t&&0!=o?i=>{this.dnd.figId=e.id;const l=Math.min(t*(n-i.clientX),e.width-c),h=Math.min(o*(r-i.clientY),e.height-c),d=Math.min(l/e.width,h/e.height);this.dnd.width=e.width*(1-d),this.dnd.height=e.height*(1-d),t<0&&(this.dnd.x=s+e.width*d),o<0&&(this.dnd.y=a+e.height*d)}:i=>{this.dnd.figId=e.id;const l=Math.max(t*(i.clientX-n),c-e.width),h=Math.max(o*(i.clientY-r),c-e.height);this.dnd.width=e.width+l,this.dnd.height=e.height+h,t<0&&(this.dnd.x=s-l),o<0&&(this.dnd.y=a-h)};kr(h,(i=>{if(!this.dnd.figId)return;this.dnd.figId=void 0;let{x:n,y:r}=this.screenCoordinatesToInternal(this.dnd);const s={x:n,y:r};t&&(s.width=this.dnd.width),o&&(s.height=this.dnd.height),this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:e.id,...s})}))}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?"":li({opacity:"0.9",cursor:"grabbing"})}internalToScreenCoordinates({x:e,y:t}){const{x:o,y:i}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();return{x:e=e<o?e:e-n,y:t=t<i?t:t-r}}screenCoordinatesToInternal({x:e,y:t}){const{x:o,y:i}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();return{x:e=o&&e<o?e:e+n,y:t=i&&t<i?t:t+r}}}function Ap(e,o,i){let n={col:void 0,row:void 0};const{Date:r}=window;let s=0,a=0,l=0;function c(){return{col:e.model.getters.getColIndex(s),row:e.model.getters.getRowIndex(a)}}const{pause:h,resume:d}=function(e,o){let i;const{setInterval:n,clearInterval:r}=window;return t.useEffect((()=>(i=n(e,o),()=>r(i))),(()=>[o])),{pause:()=>{r(i),i=void 0},resume:()=>{void 0===i&&(i=n(e,o))}}}((function(){const{col:e,row:t}=c(),o=r.now()-l;o>300&&(e!==n.col||t!==n.row)&&p(void 0,void 0);if(o>300){if(e<0||t<0)return;p(e,t)}}),200);function u(e){s=e.offsetX,a=e.offsetY,l=r.now()}function g(){const{col:e,row:t}=c();e===n.col&&t===n.row||p(void 0,void 0)}function p(e,t){e===n.col&&t===n.row||(n.col=e,n.row=t,i({col:e,row:t}))}return t.onMounted((()=>{const e=o.el;e.addEventListener("mousemove",u),e.addEventListener("mouseleave",h),e.addEventListener("mouseenter",d),e.addEventListener("mousedown",g)})),t.onWillUnmount((()=>{const e=o.el;e.removeEventListener("mousemove",u),e.removeEventListener("mouseleave",h),e.removeEventListener("mouseenter",d),e.removeEventListener("mousedown",g)})),n}Tp.template="o-spreadsheet-FiguresContainer",Tp.components={FigureComponent:Rp},Tp.props={onFigureDeleted:Function};class Op extends t.Component{setup(){this.gridOverlay=t.useRef("gridOverlay"),Ap(this.env,this.gridOverlay,this.props.onCellHovered);const e=new ResizeObserver((()=>{this.props.onGridResized({height:this.gridOverlayEl.clientHeight,width:this.gridOverlayEl.clientWidth})}));t.onMounted((()=>{e.observe(this.gridOverlayEl)})),t.onWillUnmount((()=>{e.disconnect()})),function(e,o,i){let n=null,r=null;function s(e){1===e.touches.length&&(n=e.touches[0].clientX,r=e.touches[0].clientY)}function a(){n=null,r=null}function l(e){if(1!==e.touches.length)return;i()&&(e.preventDefault(),e.stopPropagation());const t=e.touches[0].clientX,s=e.touches[0].clientY;o(n-t,r-s),n=t,r=s}t.onMounted((()=>{e.el.addEventListener("touchstart",s),e.el.addEventListener("touchend",a),e.el.addEventListener("touchmove",l)})),t.onWillUnmount((()=>{e.el.removeEventListener("touchstart",s),e.el.removeEventListener("touchend",a),e.el.removeEventListener("touchmove",l)}))}(this.gridOverlay,this.props.onGridMoved,(()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetDOMScrollInfo();return e>0}))}get gridOverlayEl(){if(!this.gridOverlay.el)throw new Error("GridOverlay el is not defined.");return this.gridOverlay.el}onMouseDown(e){if(e.button>0)return;const[t,o]=this.getCartesianCoordinates(e);this.props.onCellClicked(t,o,{shiftKey:e.shiftKey,ctrlKey:e.ctrlKey})}onDoubleClick(e){const[t,o]=this.getCartesianCoordinates(e);this.props.onCellDoubleClicked(t,o)}onContextMenu(e){e.preventDefault();const[t,o]=this.getCartesianCoordinates(e);this.props.onCellRightClicked(t,o,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){return[this.env.model.getters.getColIndex(e.offsetX),this.env.model.getters.getRowIndex(e.offsetY)]}}Op.template="o-spreadsheet-GridOverlay",Op.components={FiguresContainer:Tp},Op.defaultProps={onCellHovered:()=>{},onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{},onFigureDeleted:()=>{}},Op.props={onCellHovered:{type:Function,optional:!0},onCellDoubleClicked:{type:Function,optional:!0},onCellClicked:{type:Function,optional:!0},onCellRightClicked:{type:Function,optional:!0},onGridResized:{type:Function,optional:!0},onFigureDeleted:{type:Function,optional:!0},onGridMoved:Function,gridOverlayDimensions:String};class Mp extends t.Component{constructor(){super(...arguments),this.zIndex=ae.GridPopover}get cellPopover(){const e=this.env.model.getters.getCellPopover(this.props.hoveredCell);if(!e.isOpen)return{isOpen:!1};const t=e.anchorRect;return{...e,anchorRect:{...t,x:t.x+this.props.gridRect.x,y:t.y+this.props.gridRect.y}}}}Mp.template="o-spreadsheet-GridPopover",Mp.components={Popover:Un},Mp.props={hoveredCell:Object,onClosePopover:Function,onMouseWheel:Function,gridRect:Object};class Np 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})}_computeHandleDisplay(e){const t=this._getEvOffset(e),o=this._getElementIndex(t);if(o<0)return;const i=this._getDimensionsInViewport(o);t-i.start<this.PADDING&&o!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=i.start,this.state.activeElement=this._getPreviousVisibleElement(o)):i.end-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=i.end,this.state.activeElement=o):this.state.resizerIsActive=!1}_computeGrabDisplay(e){const t=this._getElementIndex(this._getEvOffset(e)),o=this._getActiveElements(),i=this._getSelectedZoneStart(),n=this._getSelectedZoneEnd();o.has(i)&&i<=t&&t<=n?this.state.waitingForMove=!0:this.state.waitingForMove=!1}onMouseMove(e){this.state.isResizing||this.state.isMoving||this.state.isSelecting||(this._computeHandleDisplay(e),this._computeGrabDisplay(e))}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(e){this._fitElementSize(this.state.activeElement),this.state.isResizing=!1,this._computeHandleDisplay(e),this._computeGrabDisplay(e)}onMouseDown(e){this.state.isResizing=!0,this.state.delta=0;const t=this._getClientPosition(e),o=this.state.draggerLinePosition,i=this._getElementSize(this.state.activeElement),n=o-i+this.MIN_ELEMENT_SIZE,r=this._getMaxSize();kr((e=>{this.state.delta=this._getClientPosition(e)-t,this.state.draggerLinePosition=o+this.state.delta,this.state.draggerLinePosition<n&&(this.state.draggerLinePosition=n,this.state.delta=this.MIN_ELEMENT_SIZE-i),this.state.draggerLinePosition>r&&(this.state.draggerLinePosition=r,this.state.delta=r-o)}),(e=>{this.state.isResizing=!1,0!==this.state.delta&&this._updateSize()}))}select(e){if(e.button>0)return;const t=this._getElementIndex(this._getEvOffset(e));t<0||(!0!==this.state.waitingForMove?("editing"===this.env.model.getters.getEditionMode()&&this.env.model.selection.getBackToDefault(),this.startSelection(e,t)):this.startMovement(e))}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;const t=this._getDimensionsInViewport(this._getSelectedZoneStart()),o=this._getDimensionsInViewport(this._getSelectedZoneEnd()),i=t.start;this.state.draggerLinePosition=i,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=i,this.state.draggerShadowThickness=o.end-t.start;$r(this.env,((e,o)=>{let i="COL"===this._getType()?e:o;if(i>=0){const e=this._getDimensionsInViewport(i);i<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=e.start,this.state.draggerShadowPosition=e.start,this.state.base=i):this._getSelectedZoneEnd()<i?(this.state.draggerLinePosition=e.end,this.state.draggerShadowPosition=e.end-this.state.draggerShadowThickness,this.state.base=i+1):(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,e.ctrlKey),this.lastSelectedElementIndex=t;$r(this.env,((e,t)=>{let o="COL"===this._getType()?e:t;o!==this.lastSelectedElementIndex&&-1!==o&&(this._increaseSelection(o),this.lastSelectedElementIndex=o)}),(()=>{this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this.env.model.dispatch(e.ctrlKey?"PREPARE_SELECTION_INPUT_EXPANSION":"STOP_SELECTION_INPUT"),this._computeGrabDisplay(e)}))}onMouseUp(e){this.lastSelectedElementIndex=null}onContextMenu(e){e.preventDefault();const t=this._getElementIndex(this._getEvOffset(e));if(t<0)return;this._getActiveElements().has(t)||this._selectElement(t,!1);const o=this._getType();this.props.onOpenContextMenu(o,e.clientX,e.clientY)}}ni`
1207
1207
  .o-col-resizer {
1208
1208
  position: absolute;
1209
1209
  top: 0;
@@ -1262,7 +1262,7 @@
1262
1262
  top: calc(${k}px / 2 - ${D}px / 2);
1263
1263
  }
1264
1264
  }
1265
- `,Mp.props={onOpenContextMenu:Function};class Np extends Mp{setup(){super.setup(),this.colResizerRef=t.useRef("colResizer"),this.PADDING=15,this.MAX_SIZE_MARGIN=90,this.MIN_ELEMENT_SIZE=5}_getEvOffset(e){return e.offsetX}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().left}_getClientPosition(e){return e.clientX}_getElementIndex(e){return this.env.model.getters.getColIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().left}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().right}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollCol(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getColDimensionsInViewport(this.env.model.getters.getActiveSheetId(),e)}_getElementSize(e){return this.env.model.getters.getColSize(this.env.model.getters.getActiveSheetId(),e)}_getMaxSize(){return this.colResizerRef.el.clientWidth}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),o=this.env.model.getters.getActiveCols();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"COL",sheetId:this.env.model.getters.getActiveSheetId(),elements:o.has(e)?[...o]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),o=this._getSelectedZoneEnd();for(let i=t;i<=o;i++)e.push(i);const i=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"COL",base:this.state.base,elements:e});!i.isSuccessful&&i.reasons.includes(2)&&this.env.raiseError(Zi)}_selectElement(e,t){this.env.model.selection.selectColumn(e,t?"newAnchor":"overrideSelection")}_increaseSelection(e){this.env.model.selection.selectColumn(e,"updateAnchor")}_fitElementSize(e){const t=this.env.model.getters.getActiveCols();this.env.model.dispatch("AUTORESIZE_COLUMNS",{sheetId:this.env.model.getters.getActiveSheetId(),cols:t.has(e)?[...t]:[e]})}_getType(){return"COL"}_getActiveElements(){return this.env.model.getters.getActiveCols()}_getPreviousVisibleElement(e){const t=this.env.model.getters.getActiveSheetId();let o;for(o=e-1;o>=0&&this.env.model.getters.isColHidden(t,o);o--);return o}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),elements:e,dimension:"COL"})}unhideStyleValue(e){return this._getDimensionsInViewport(e).start}}Np.template="o-spreadsheet-ColResizer",ii`
1265
+ `,Np.props={onOpenContextMenu:Function};class _p extends Np{setup(){super.setup(),this.colResizerRef=t.useRef("colResizer"),this.PADDING=15,this.MAX_SIZE_MARGIN=90,this.MIN_ELEMENT_SIZE=5}_getEvOffset(e){return e.offsetX}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().left}_getClientPosition(e){return e.clientX}_getElementIndex(e){return this.env.model.getters.getColIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().left}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().right}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollCol(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getColDimensionsInViewport(this.env.model.getters.getActiveSheetId(),e)}_getElementSize(e){return this.env.model.getters.getColSize(this.env.model.getters.getActiveSheetId(),e)}_getMaxSize(){return this.colResizerRef.el.clientWidth}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),o=this.env.model.getters.getActiveCols();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"COL",sheetId:this.env.model.getters.getActiveSheetId(),elements:o.has(e)?[...o]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),o=this._getSelectedZoneEnd();for(let i=t;i<=o;i++)e.push(i);const i=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"COL",base:this.state.base,elements:e});!i.isSuccessful&&i.reasons.includes(2)&&this.env.raiseError(ji)}_selectElement(e,t){this.env.model.selection.selectColumn(e,t?"newAnchor":"overrideSelection")}_increaseSelection(e){this.env.model.selection.selectColumn(e,"updateAnchor")}_fitElementSize(e){const t=this.env.model.getters.getActiveCols();this.env.model.dispatch("AUTORESIZE_COLUMNS",{sheetId:this.env.model.getters.getActiveSheetId(),cols:t.has(e)?[...t]:[e]})}_getType(){return"COL"}_getActiveElements(){return this.env.model.getters.getActiveCols()}_getPreviousVisibleElement(e){const t=this.env.model.getters.getActiveSheetId();let o;for(o=e-1;o>=0&&this.env.model.getters.isColHidden(t,o);o--);return o}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),elements:e,dimension:"COL"})}unhideStyleValue(e){return this._getDimensionsInViewport(e).start}}_p.template="o-spreadsheet-ColResizer",ni`
1266
1266
  .o-row-resizer {
1267
1267
  position: absolute;
1268
1268
  top: ${O}px;
@@ -1323,7 +1323,7 @@
1323
1323
  background-color: lightgrey;
1324
1324
  }
1325
1325
  }
1326
- `,Np.props={onOpenContextMenu:Function};class _p extends Mp{setup(){super.setup(),this.rowResizerRef=t.useRef("rowResizer"),this.PADDING=5,this.MAX_SIZE_MARGIN=60,this.MIN_ELEMENT_SIZE=10}_getEvOffset(e){return e.offsetY}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().top}_getClientPosition(e){return e.clientY}_getElementIndex(e){return this.env.model.getters.getRowIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().top}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().bottom}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollRow(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getRowDimensionsInViewport(this.env.model.getters.getActiveSheetId(),e)}_getElementSize(e){return this.env.model.getters.getRowSize(this.env.model.getters.getActiveSheetId(),e)}_getMaxSize(){return this.rowResizerRef.el.clientHeight}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),o=this.env.model.getters.getActiveRows();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"ROW",sheetId:this.env.model.getters.getActiveSheetId(),elements:o.has(e)?[...o]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),o=this._getSelectedZoneEnd();for(let i=t;i<=o;i++)e.push(i);const i=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",base:this.state.base,elements:e});!i.isSuccessful&&i.reasons.includes(2)&&this.env.raiseError(Zi)}_selectElement(e,t){this.env.model.selection.selectRow(e,t?"newAnchor":"overrideSelection")}_increaseSelection(e){this.env.model.selection.selectRow(e,"updateAnchor")}_fitElementSize(e){const t=this.env.model.getters.getActiveRows();this.env.model.dispatch("AUTORESIZE_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),rows:t.has(e)?[...t]:[e]})}_getType(){return"ROW"}_getActiveElements(){return this.env.model.getters.getActiveRows()}_getPreviousVisibleElement(e){const t=this.env.model.getters.getActiveSheetId();let o;for(o=e-1;o>=0&&this.env.model.getters.isRowHidden(t,o);o--);return o}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",elements:e})}unhideStyleValue(e){return this._getDimensionsInViewport(e).start}}_p.template="o-spreadsheet-RowResizer",ii`
1326
+ `,_p.props={onOpenContextMenu:Function};class Fp extends Np{setup(){super.setup(),this.rowResizerRef=t.useRef("rowResizer"),this.PADDING=5,this.MAX_SIZE_MARGIN=60,this.MIN_ELEMENT_SIZE=10}_getEvOffset(e){return e.offsetY}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().top}_getClientPosition(e){return e.clientY}_getElementIndex(e){return this.env.model.getters.getRowIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().top}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().bottom}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollRow(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getRowDimensionsInViewport(this.env.model.getters.getActiveSheetId(),e)}_getElementSize(e){return this.env.model.getters.getRowSize(this.env.model.getters.getActiveSheetId(),e)}_getMaxSize(){return this.rowResizerRef.el.clientHeight}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),o=this.env.model.getters.getActiveRows();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"ROW",sheetId:this.env.model.getters.getActiveSheetId(),elements:o.has(e)?[...o]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),o=this._getSelectedZoneEnd();for(let i=t;i<=o;i++)e.push(i);const i=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",base:this.state.base,elements:e});!i.isSuccessful&&i.reasons.includes(2)&&this.env.raiseError(ji)}_selectElement(e,t){this.env.model.selection.selectRow(e,t?"newAnchor":"overrideSelection")}_increaseSelection(e){this.env.model.selection.selectRow(e,"updateAnchor")}_fitElementSize(e){const t=this.env.model.getters.getActiveRows();this.env.model.dispatch("AUTORESIZE_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),rows:t.has(e)?[...t]:[e]})}_getType(){return"ROW"}_getActiveElements(){return this.env.model.getters.getActiveRows()}_getPreviousVisibleElement(e){const t=this.env.model.getters.getActiveSheetId();let o;for(o=e-1;o>=0&&this.env.model.getters.isRowHidden(t,o);o--);return o}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",elements:e})}unhideStyleValue(e){return this._getDimensionsInViewport(e).start}}Fp.template="o-spreadsheet-RowResizer",ni`
1327
1327
  .o-overlay {
1328
1328
  .all {
1329
1329
  position: absolute;
@@ -1334,7 +1334,7 @@
1334
1334
  height: ${O}px;
1335
1335
  }
1336
1336
  }
1337
- `,_p.props={onOpenContextMenu:Function};class Fp extends t.Component{selectAll(){this.env.model.selection.selectAll()}}function Dp(e,o,i){const n=t.useRef(e);t.useEffect((function(){const e=n.el,t=window.devicePixelRatio||1,r=e.getContext("2d",{alpha:!1}),s={ctx:r,dpr:t,thinLineWidth:.4*t},{width:a,height:l}=i();e.style.width=`${a}px`,e.style.height=`${l}px`,e.width=a*t,e.height=l*t,e.setAttribute("style",`width:${a}px;height:${l}px;`),r.translate(-m,-m),r.scale(t,t),o.drawGrid(s)}))}function kp(e){function t(e,t){return e*(0===t?1:_)}return o=>{const i=t(o.shiftKey?o.deltaY:o.deltaX,o.deltaMode),n=t(o.shiftKey?o.deltaX:o.deltaY,o.deltaMode);e(i,n)}}Fp.template="o-spreadsheet-HeadersOverlay",Fp.components={ColResizer:Np,RowResizer:_p},Fp.props={onOpenContextMenu:Function},ii`
1337
+ `,Fp.props={onOpenContextMenu:Function};class Dp extends t.Component{selectAll(){this.env.model.selection.selectAll()}}function kp(e,o,i){const n=t.useRef(e);t.useEffect((function(){const e=n.el,t=window.devicePixelRatio||1,r=e.getContext("2d",{alpha:!1}),s={ctx:r,dpr:t,thinLineWidth:.4*t},{width:a,height:l}=i();e.style.width=`${a}px`,e.style.height=`${l}px`,e.width=a*t,e.height=l*t,e.setAttribute("style",`width:${a}px;height:${l}px;`),r.translate(-m,-m),r.scale(t,t),o.drawGrid(s)}))}function $p(e){function t(e,t){return e*(0===t?1:_)}return o=>{const i=t(o.shiftKey?o.deltaY:o.deltaX,o.deltaMode),n=t(o.shiftKey?o.deltaX:o.deltaY,o.deltaMode);e(i,n)}}Dp.template="o-spreadsheet-HeadersOverlay",Dp.components={ColResizer:_p,RowResizer:Fp},Dp.props={onOpenContextMenu:Function},ni`
1338
1338
  .o-border {
1339
1339
  position: absolute;
1340
1340
  &:hover {
@@ -1344,7 +1344,7 @@
1344
1344
  .o-moving {
1345
1345
  cursor: grabbing;
1346
1346
  }
1347
- `;class $p extends t.Component{get style(){const e=["n","w","e"].includes(this.props.orientation),t=["n","w","s"].includes(this.props.orientation),o=["n","s"].includes(this.props.orientation),i=["w","e"].includes(this.props.orientation),n=this.props.zone,r=this.env.model.getters.getVisibleRect(n),s=r.x,a=r.x+r.width-4,l=r.y,c=r.y+r.height-4;return`\n left:${t?s:a}px;\n top:${e?l:c}px;\n width:${o?a-s:4}px;\n height:${i?c-l:4}px;\n `}onMouseDown(e){this.props.onMoveHighlight(e.clientX,e.clientY)}}$p.template="o-spreadsheet-Border",$p.props={zone:Object,orientation:String,isMoving:Boolean,onMoveHighlight:Function},ii`
1347
+ `;class Pp extends t.Component{get style(){const e=["n","w","e"].includes(this.props.orientation),t=["n","w","s"].includes(this.props.orientation),o=["n","s"].includes(this.props.orientation),i=["w","e"].includes(this.props.orientation),n=this.props.zone,r=this.env.model.getters.getVisibleRect(n),s=r.x,a=r.x+r.width-4,l=r.y,c=r.y+r.height-4;return`\n left:${t?s:a}px;\n top:${e?l:c}px;\n width:${o?a-s:4}px;\n height:${i?c-l:4}px;\n `}onMouseDown(e){this.props.onMoveHighlight(e.clientX,e.clientY)}}Pp.template="o-spreadsheet-Border",Pp.props={zone:Object,orientation:String,isMoving:Boolean,onMoveHighlight:Function},ni`
1348
1348
  .o-corner {
1349
1349
  position: absolute;
1350
1350
  height: 6px;
@@ -1366,11 +1366,11 @@
1366
1366
  .o-resizing {
1367
1367
  cursor: grabbing;
1368
1368
  }
1369
- `;class Pp 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,o=this.isTop?e.top:e.bottom,i=this.env.model.getters.getVisibleRect({left:t,right:t,top:o,bottom:o});if(i.width*i.height==0)return"display:none";return`\n left:${(this.isLeft?i.x:i.x+i.width)-4}px;\n top:${(this.isTop?i.y:i.y+i.height)-4}px;\n background-color:${this.props.color};\n `}onMouseDown(e){this.props.onResizeHighlight(this.isLeft,this.isTop)}}Pp.template="o-spreadsheet-Corner",Pp.props={zone:Object,color:String,orientation:String,isResizing:Boolean,onResizeHighlight:Function},ii`
1369
+ `;class Lp 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,o=this.isTop?e.top:e.bottom,i=this.env.model.getters.getVisibleRect({left:t,right:t,top:o,bottom:o});if(i.width*i.height==0)return"display:none";return`\n left:${(this.isLeft?i.x:i.x+i.width)-4}px;\n top:${(this.isTop?i.y:i.y+i.height)-4}px;\n background-color:${this.props.color};\n `}onMouseDown(e){this.props.onResizeHighlight(this.isLeft,this.isTop)}}Lp.template="o-spreadsheet-Corner",Lp.props={zone:Object,color:String,orientation:String,isResizing:Boolean,onResizeHighlight:Function},ni`
1370
1370
  .o-highlight {
1371
1371
  z-index: ${ae.Highlight};
1372
1372
  }
1373
- `;class Lp extends t.Component{constructor(){super(...arguments),this.highlightState=t.useState({shiftingMode:"none"})}onResizeHighlight(e,t){const o=this.env.model.getters.getActiveSheet();this.highlightState.shiftingMode="isResizing";const i=this.props.zone,n=e?i.right:i.left,r=t?i.bottom:i.top;let s=e?i.left:i.right,a=t?i.top:i.bottom,l=i;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(o.id,l)});kr(this.env,((e,t)=>{if(s!==e||a!==t){const i=this.env.model.getters.getActiveSheetId();s=Fe(-1===e?s:e,0,this.env.model.getters.getNumberCols(i)-1),a=Fe(-1===t?a:t,0,this.env.model.getters.getNumberRows(i)-1);let c={left:Math.min(n,s),top:Math.min(r,a),right:Math.max(n,s),bottom:Math.max(r,a)};c=this.env.model.getters.expandZone(i,c),Lo(c,l)||(this.env.model.dispatch("CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(o.id,c)}),l=c)}}),(()=>{this.highlightState.shiftingMode="none",this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION")}))}onMoveHighlight(e,t){this.highlightState.shiftingMode="isMoving";const o=this.props.zone,i=kn(),n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getColIndex(e-i.left),s=this.env.model.getters.getRowIndex(t-i.top),a=-o.left,l=this.env.model.getters.getNumberCols(n)-o.right-1,c=-o.top,h=this.env.model.getters.getNumberRows(n)-o.bottom-1;let d=o;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(n,d)});let u=r,g=s;kr(this.env,((e,t)=>{if(u!==e||g!==t){u=-1===e?u:e,g=-1===t?g:t;const i=Fe(u-r,a,l),p=Fe(g-s,c,h);let m={left:o.left+i,top:o.top+p,right:o.right+i,bottom:o.bottom+p};m=this.env.model.getters.expandZone(n,m),Lo(m,d)||(this.env.model.dispatch("CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(n,m)}),d=m)}}),(()=>{this.highlightState.shiftingMode="none",this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION")}))}}Lp.template="o-spreadsheet-Highlight",Lp.components={Corner:Pp,Border:$p},Lp.props={zone:Object,color:String};class Up{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}}ii`
1373
+ `;class Up extends t.Component{constructor(){super(...arguments),this.highlightState=t.useState({shiftingMode:"none"})}onResizeHighlight(e,t){const o=this.env.model.getters.getActiveSheet();this.highlightState.shiftingMode="isResizing";const i=this.props.zone,n=e?i.right:i.left,r=t?i.bottom:i.top;let s=e?i.left:i.right,a=t?i.top:i.bottom,l=i;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(o.id,l)});$r(this.env,((e,t)=>{if(s!==e||a!==t){const i=this.env.model.getters.getActiveSheetId();s=Fe(-1===e?s:e,0,this.env.model.getters.getNumberCols(i)-1),a=Fe(-1===t?a:t,0,this.env.model.getters.getNumberRows(i)-1);let c={left:Math.min(n,s),top:Math.min(r,a),right:Math.max(n,s),bottom:Math.max(r,a)};c=this.env.model.getters.expandZone(i,c),Uo(c,l)||(this.env.model.dispatch("CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(o.id,c)}),l=c)}}),(()=>{this.highlightState.shiftingMode="none",this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION")}))}onMoveHighlight(e,t){this.highlightState.shiftingMode="isMoving";const o=this.props.zone,i=$n(),n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getColIndex(e-i.left),s=this.env.model.getters.getRowIndex(t-i.top),a=-o.left,l=this.env.model.getters.getNumberCols(n)-o.right-1,c=-o.top,h=this.env.model.getters.getNumberRows(n)-o.bottom-1;let d=o;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(n,d)});let u=r,g=s;$r(this.env,((e,t)=>{if(u!==e||g!==t){u=-1===e?u:e,g=-1===t?g:t;const i=Fe(u-r,a,l),p=Fe(g-s,c,h);let m={left:o.left+i,top:o.top+p,right:o.right+i,bottom:o.bottom+p};m=this.env.model.getters.expandZone(n,m),Uo(m,d)||(this.env.model.dispatch("CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(n,m)}),d=m)}}),(()=>{this.highlightState.shiftingMode="none",this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION")}))}}Up.template="o-spreadsheet-Highlight",Up.components={Corner:Lp,Border:Pp},Up.props={zone:Object,color:String};class Vp{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}}ni`
1374
1374
  .o-scrollbar {
1375
1375
  position: absolute;
1376
1376
  overflow: auto;
@@ -1386,7 +1386,7 @@
1386
1386
  border-left: 1px solid #e2e3e3;
1387
1387
  }
1388
1388
  }
1389
- `;class Vp extends t.Component{setup(){this.scrollbarRef=t.useRef("scrollbar"),this.scrollbar=new Up(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 ai({width:`${this.props.width}px`,height:`${this.props.height}px`})}get positionCss(){return ai(this.props.position)}onScroll(e){this.props.offset!==this.scrollbar.scroll&&this.props.onScroll(this.scrollbar.scroll)}}Vp.template=t.xml`
1389
+ `;class zp extends t.Component{setup(){this.scrollbarRef=t.useRef("scrollbar"),this.scrollbar=new Vp(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 li({width:`${this.props.width}px`,height:`${this.props.height}px`})}get positionCss(){return li(this.props.position)}onScroll(e){this.props.offset!==this.scrollbar.scroll&&this.props.onScroll(this.scrollbar.scroll)}}zp.template=t.xml`
1390
1390
  <div
1391
1391
  t-attf-class="o-scrollbar {{props.direction}}"
1392
1392
  t-on-scroll="onScroll"
@@ -1394,7 +1394,7 @@
1394
1394
  t-att-style="positionCss">
1395
1395
  <div t-att-style="sizeCss"/>
1396
1396
  </div>
1397
- `,Vp.defaultProps={width:1,height:1},Vp.props={width:{type:Number,optional:!0},height:{type:Number,optional:!0},direction:String,position:Object,offset:Number,onScroll:Function};class zp 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.leftOffset+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})}}zp.components={ScrollBar:Vp},zp.template=t.xml`
1397
+ `,zp.defaultProps={width:1,height:1},zp.props={width:{type:Number,optional:!0},height:{type:Number,optional:!0},direction:String,position:Object,offset:Number,onScroll:Function};class Bp 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.leftOffset+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})}}Bp.components={ScrollBar:zp},Bp.template=t.xml`
1398
1398
  <ScrollBar
1399
1399
  t-if="isDisplayed"
1400
1400
  width="width"
@@ -1402,7 +1402,7 @@
1402
1402
  offset="offset"
1403
1403
  direction="'horizontal'"
1404
1404
  onScroll.bind="onScroll"
1405
- />`,zp.defaultProps={leftOffset:0},zp.props={leftOffset:{type:Number,optional:!0}};class Bp 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.topOffset+e}px`,right:"0px",width:"15px",bottom:"0px"}}onScroll(e){const{scrollX:t}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:t,offsetY:e})}}Bp.components={ScrollBar:Vp},Bp.template=t.xml`
1405
+ />`,Bp.defaultProps={leftOffset:0},Bp.props={leftOffset:{type:Number,optional:!0}};class Hp 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.topOffset+e}px`,right:"0px",width:"15px",bottom:"0px"}}onScroll(e){const{scrollX:t}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:t,offsetY:e})}}Hp.components={ScrollBar:zp},Hp.template=t.xml`
1406
1406
  <ScrollBar
1407
1407
  t-if="isDisplayed"
1408
1408
  height="height"
@@ -1410,9 +1410,9 @@
1410
1410
  offset="offset"
1411
1411
  direction="'vertical'"
1412
1412
  onScroll.bind="onScroll"
1413
- />`,Bp.defaultProps={topOffset:0},Bp.props={topOffset:{type:Number,optional:!0}};const Hp={ROW:Fr,COL:_r,CELL:Nr};class Wp extends t.Component{constructor(){super(...arguments),this.HEADER_HEIGHT=O,this.HEADER_WIDTH=M,this.keyDownMapping={ENTER:()=>{this.env.model.getters.getActiveCell().type===mi.empty?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()},TAB:()=>this.env.model.selection.moveAnchorCell("right",1),"SHIFT+TAB":()=>this.env.model.selection.moveAnchorCell("left",1),F2:()=>{this.env.model.getters.getActiveCell().type===mi.empty?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()},DELETE:()=>{this.env.model.dispatch("DELETE_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},BACKSPACE:()=>{this.env.model.dispatch("DELETE_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},ESCAPE:()=>{this.env.model.getters.hasOpenedPopover()?this.closeOpenedPopover():this.menuState.isOpen?this.closeMenu():this.env.model.dispatch("CLEAN_CLIPBOARD_HIGHLIGHT")},"CTRL+A":()=>this.env.model.selection.loopSelection(),"CTRL+Z":()=>this.env.model.dispatch("REQUEST_UNDO"),"CTRL+Y":()=>this.env.model.dispatch("REQUEST_REDO"),"CTRL+B":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"CTRL+I":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"CTRL+U":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"ALT+=":()=>{var e;const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSelectedZone(),{anchor:i}=this.env.model.getters.getSelection(),n=this.env.model.getters.getAutomaticSums(t,o,i.cell);if(this.env.model.getters.isSingleCellOrMerge(t,o)||this.env.model.getters.isEmpty(t,o)&&n.length<=1){const o=(null===(e=n[0])||void 0===e?void 0:e.zone)?this.env.model.getters.zoneToXC(t,n[0].zone):"",i=`=SUM(${o})`;this.props.onGridComposerCellFocused(i,{start:5,end:5+o.length})}else this.env.model.dispatch("SUM_SELECTION")},"CTRL+HOME":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:o}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,o)},"CTRL+END":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,"COL",this.env.model.getters.getNumberCols(e)-1,0),o=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,o)},"SHIFT+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},o=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:o,zone:t})},"CTRL+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},o=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:o,zone:t})},"CTRL+SHIFT+ ":()=>{this.env.model.selection.selectAll()},"SHIFT+PAGEDOWN":()=>{this.env.model.dispatch("ACTIVATE_NEXT_SHEET")},"SHIFT+PAGEUP":()=>{this.env.model.dispatch("ACTIVATE_PREVIOUS_SHEET")},PAGEDOWN:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PAGEUP:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP"),"CTRL+K":()=>Rr(this.env)}}setup(){this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.hiddenInput=t.useRef("hiddenInput"),this.canvasPosition=_n(this.gridRef),this.hoveredCell=t.useState({col:void 0,row:void 0}),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),t.useExternalListener(document.body,"cut",this.copy.bind(this,!0)),t.useExternalListener(document.body,"copy",this.copy.bind(this,!1)),t.useExternalListener(document.body,"paste",this.paste),t.onMounted((()=>this.focus())),this.props.exposeFocus((()=>this.focus())),Dp("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimensionWithHeaders())),t.useEffect((()=>this.focus()),(()=>[this.env.model.getters.getActiveSheetId()])),this.onMouseWheel=kp(((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.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.focus()}focus(){var e;this.env.model.getters.getSelectedFigureId()||"inactive"!==this.env.model.getters.getEditionMode()||null===(e=this.hiddenInput.el)||void 0===e||e.focus()}get gridEl(){if(!this.gridRef.el)throw new Error("Grid el is not defined.");return this.gridRef.el}getAutofillPosition(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{left:t.x+t.width-4,top:t.y+t.height-4}}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:o,scrollY:i}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o+e,offsetY:i+t})}getClientPositionKey(e){var t,o,i;return`${e.id}-${null===(t=e.position)||void 0===t?void 0:t.sheetId}-${null===(o=e.position)||void 0===o?void 0:o.col}-${null===(i=e.position)||void 0===i?void 0:i.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,{ctrlKey:o,shiftKey:i}){o&&this.env.model.dispatch("PREPARE_SELECTION_INPUT_EXPANSION"),this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),"editing"===this.env.model.getters.getEditionMode()&&this.env.model.dispatch("STOP_EDITION"),i?this.env.model.selection.setAnchorCorner(e,t):o?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t);let n=e,r=t;kr(this.env,((e,t)=>{(e!==n&&-1!=e||t!==r&&-1!=t)&&(n=-1===e?n:e,r=-1===t?r:t,this.env.model.selection.setAnchorCorner(n,r))}),(()=>{this.env.model.dispatch("STOP_SELECTION_INPUT"),this.env.model.getters.isPaintingFormat()&&this.env.model.dispatch("PASTE",{target:this.env.model.getters.getSelectedZones()})}))}onCellDoubleClicked(e,t){const o=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:o,col:e,row:t}));this.env.model.getters.getEvaluatedCell({sheetId:o,col:e,row:t}).type===mi.empty?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()}closeOpenedPopover(){this.env.model.dispatch("CLOSE_CELL_POPOVER")}processArrows(e){e.preventDefault(),e.stopPropagation(),this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),Xu(e,this.env.model.selection),this.env.model.getters.isPaintingFormat()&&this.env.model.dispatch("PASTE",{target:this.env.model.getters.getSelectedZones()})}onKeydown(e){if(e.key.startsWith("Arrow"))return void this.processArrows(e);let t="";e.ctrlKey&&(t+="CTRL+"),e.metaKey&&(t+="CTRL+"),e.altKey&&(t+="ALT+"),e.shiftKey&&(t+="SHIFT+"),t+=e.key.toUpperCase();let o=this.keyDownMapping[t];return o?(e.preventDefault(),e.stopPropagation(),void o()):void 0}onInput(e){(e.isComposing||"insertFromPaste"!==e.inputType)&&e.data&&(e.preventDefault(),e.stopPropagation(),this.props.onGridComposerCellFocused(e.data))}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:o,top:i}=t;let n="CELL";this.env.model.dispatch("STOP_EDITION"),this.env.model.getters.getActiveCols().has(o)?n="COL":this.env.model.getters.getActiveRows().has(i)&&(n="ROW");const{x:r,y:s,width:a,height:l}=this.env.model.getters.getVisibleRect(t);this.toggleContextMenu(n,r+a,s+l)}onCellRightClicked(e,t,{x:o,y:i}){const n=this.env.model.getters.getSelectedZones();let r="CELL";Vo(e,t,n[n.length-1])?this.env.model.getters.getActiveCols().has(e)?r="COL":this.env.model.getters.getActiveRows().has(t)&&(r="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(r,o,i)}toggleContextMenu(e,t,o){this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:o},this.menuState.menuItems=Hp[e].getAll()}copy(e,t){if(!this.gridEl.contains(document.activeElement))return;const o=t.clipboardData;if(!o)return void this.displayWarningCopyPasteNotSupported();if("inactive"!==this.env.model.getters.getEditionMode())return;e?Wn(this.env):this.env.model.dispatch("COPY");const i=this.env.model.getters.getClipboardContent();for(const e in i)o.setData(e,i[e]);t.preventDefault()}paste(e){if(!this.gridEl.contains(document.activeElement))return;const t=e.clipboardData;if(t){if(t.types.indexOf(fi.PlainText)>-1){const e=t.getData(fi.PlainText),o=this.env.model.getters.getSelectedZones();this.env.model.getters.getClipboardTextContent()===e?Zn(this.env,o):jn(this.env,o,e)}}else this.displayWarningCopyPasteNotSupported()}displayWarningCopyPasteNotSupported(){this.env.raiseError(r("Copy/Paste is not supported in this browser."))}closeMenu(){this.menuState.isOpen=!1,this.focus()}}Wp.template="o-spreadsheet-Grid",Wp.components={GridComposer:ag,GridOverlay:Ap,GridPopover:Op,HeadersOverlay:Fp,Menu:Bn,Autofill:$r,ClientTag:Lr,Highlight:Lp,Popover:Ln,VerticalScrollBar:Bp,HorizontalScrollBar:zp,FilterIconsOverlay:dg},Wp.props={sidePanelIsOpen:Boolean,exposeFocus:Function,focusComposer:String,onComposerContentFocused:Function,onGridComposerCellFocused:Function};class Gp{constructor(e){this.xmlString=e}toString(){return this.xmlString}}const qp=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart"],Zp="000000",jp={arrow:"3Arrows",smiley:"3Symbols",dot:"3TrafficLights1"},Xp={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"},Yp="http://schemas.openxmlformats.org/drawingml/2006/main",Kp="http://schemas.openxmlformats.org/drawingml/2006/chart",Qp={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"},Jp={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"},em="http://schemas.openxmlformats.org/officeDocument/2006/relationships",tm=.75,om=.1317,im=8.43,nm=12.75,rm=30,sm=100,am=164,lm={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}]},cm=["ACOT","ACOTH","AGGREGATE","ARABIC","BASE","BETA.DIST","BETA.INV","BINOM.DIST","BINOM.DIST.RANGE","BINOM.INV","BITAND","BITLSHIFT","BITOR","BITRSHIFT","BITXOR","CEILING.MATH","CEILING.PRECISE","CHISQ.DIST","CHISQ.DIST.RT","CHISQ.INV","CHISQ.INV.RT","CHISQ.TEST","COMBINA","CONCAT","CONFIDENCE.NORM","CONFIDENCE.T","COT","COTH","COVARIANCE.P","COVARIANCE.S","CSC","CSCH","DAYS","DECIMAL","ERF.PRECISE","ERFC.PRECISE","EXPON.DIST","F.DIST","F.DIST.RT","F.INV","F.INV.RT","F.TEST","FILTERXML","FLOOR.MATH","FLOOR.PRECISE","FORECAST.ETS","FORECAST.ETS.CONFINT","FORECAST.ETS.SEASONALITY","FORECAST.ETS.STAT","FORECAST.LINEAR","FORMULATEXT","GAMMA","GAMMA.DIST","GAMMA.INV","GAMMALN.PRECISE","GAUSS","HYPGEOM.DIST","IFNA","IFS","IMCOSH","IMCOT","IMCSC","IMCSCH","IMSEC","IMSECH","IMSINH","IMTAN","ISFORMULA","ISOWEEKNUM","LOGNORM.DIST","LOGNORM.INV","MAXIFS","MINIFS","MODE.MULT","MODE.SNGL","MUNIT","NEGBINOM.DIST","NORM.DIST","NORM.INV","NORM.S.DIST","NORM.S.INV","NUMBERVALUE","PDURATION","PERCENTILE.EXC","PERCENTILE.INC","PERCENTRANK.EXC","PERCENTRANK.INC","PERMUTATIONA","PHI","POISSON.DIST","QUARTILE.EXC","QUARTILE.INC","QUERYSTRING","RANK.AVG","RANK.EQ","RRI","SEC","SECH","SHEET","SHEETS","SKEW.P","STDEV.P","STDEV.S","SWITCH","T.DIST","T.DIST.2T","T.DIST.RT","T.INV","T.INV.2T","T.TEST","TEXTJOIN","UNICHAR","UNICODE","VAR.P","VAR.S","WEBSERVICE","WEIBULL.DIST","XOR","Z.TEST"],hm="[Content_Types].xml";var dm;!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"}(dm||(dm={}));class um{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,o){let i=`${e} ${t?'"'+t+'" is':"are"} not yet supported. `;o&&(i+=`Only ${o.join(", ")} are currently supported.`),this._conversionWarnings.has(i)||this._conversionWarnings.add(i)}}const gm=["thin"],pm=["general","left","center","right"],mm=["Arial"],fm=["solid"],vm=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWith","containsBlanks","notContainsBlanks"],bm={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},Cm={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"},Sm={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"};const Em={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},wm={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},ym={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"},xm={b:"bottom",t:"top",l:"left",r:"right",tr:"right"},Im={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},Rm={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"},Tm={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},Am={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},Om={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 Mm(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=Zp;else{if(!e.indexed)return;t=Om[e.indexed]}var o;return t=6===(o=t).length?"#"+o+"FF":"#"+o.slice(2)+o.slice(0,2),e.tint&&(t=function(e,t){const o=bt(e),i=St(o);t<0&&(i.l=i.l*(1+t));t>0&&(i.l=i.l*(1-t)+(100-100*(1-t)));return vt(Ct(i))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function Nm(e,t){const o=e.split("/"),i=t.split("/");let n="",r=0;for(let e=0;e<o.length-1;e++)o[e]===i[e]?r++:n+="../";return n+=i.slice(r).join("/"),n}function _m(e,t=0){const o={};for(let i=0;i<e.length;i++)e[i]&&(o[i+t]=e[i]);return o}function Fm(e){const t=[];for(let o of Object.keys(e).map(Number))t[o]=e[o];return t}function Dm(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,((e,t)=>String.fromCharCode(parseInt(t,16))))}const km=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function $m(e,t,o){var i,n,r;if(0===e)return;let s=Tm[e]||(null===(i=t.find((t=>t.id===e)))||void 0===i?void 0:i.format);if(s)try{let e=s.replace(/(.*?);.*/,"$1");e=e.replace(/\[(.*)-[A-Z0-9]{3}\]/g,"[$1]"),e=e.replace(/\[\$\]/g,"");const t=(null===(n=e.match(/"/g))||void 0===n?void 0:n.length)||0;if(t/2+((null===(r=e.match(/\[/g))||void 0===r?void 0:r.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(km)}(e)&&(e=function(e){return e=e.toLowerCase(),e=e.replace(/mmmmm/g,"mmm"),e=e.replace(/am\/pm|a\/m/g,"a"),e=e.replace(/hhhh/g,"hh"),e=e.replace(/\bh\b/g,"hh"),e}(e)),function(e){try{return no(0,e),!0}catch(e){return!1}}(e))return e}catch(e){}o.generateNotSupportedWarning(dm.NumFmtIdNotSupported,s||`nmFmtId ${e}`)}function Pm(e,t){const o=e.borders.map((e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(dm.DiagonalBorderNotSupported)}(e,t);const o={top:Lm(e.top,t),bottom:Lm(e.bottom,t),left:Lm(e.left,t),right:Lm(e.right,t)};return Object.keys(o).forEach((e=>void 0===o[e]&&delete o[e])),o}));return _m(o,1)}function Lm(e,t){if(!e)return;!function(e,t){gm.includes(e.style)||t.generateNotSupportedWarning(dm.BorderStyleNotSupported,e.style,gm)}(e,t);const o=Cm[e.style];return o?[o,Mm(e.color)]:void 0}function Um(e,t){return _m(e.styles.map((o=>Vm({fontStyle:e.fonts[o.fontId],fillStyle:e.fills[o.fillId],alignment:o.alignment},t))),1)}function Vm(e,t){var o,i,n,r,s,a,l,c,h,d,u,g;return function(e,t,o){e&&e.name&&!mm.includes(e.name)&&o.generateNotSupportedWarning(dm.FontNotSupported,e.name,mm);t&&t.patternType&&!fm.includes(t.patternType)&&o.generateNotSupportedWarning(dm.FillStyleNotSupported,t.patternType,fm)}(null==e?void 0:e.fontStyle,null==e?void 0:e.fillStyle,t),function(e,t){e&&!pm.includes(e)&&t.generateNotSupportedWarning(dm.HorizontalAlignmentNotSupported,e,pm)}(null===(o=null==e?void 0:e.alignment)||void 0===o?void 0:o.horizontal,t),function(e,t){e&&t.generateNotSupportedWarning(dm.VerticalAlignmentNotSupported)}(null===(i=null==e?void 0:e.alignment)||void 0===i?void 0:i.vertical,t),{bold:null===(n=e.fontStyle)||void 0===n?void 0:n.bold,italic:null===(r=e.fontStyle)||void 0===r?void 0:r.italic,strikethrough:null===(s=e.fontStyle)||void 0===s?void 0:s.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)?Sm[e.alignment.horizontal]:void 0,fillColor:"solid"===(null===(c=e.fillStyle)||void 0===c?void 0:c.patternType)?Mm(null===(h=e.fillStyle)||void 0===h?void 0:h.fgColor):Mm(null===(d=e.fillStyle)||void 0===d?void 0:d.bgColor),textColor:Mm(null===(u=e.fontStyle)||void 0===u?void 0:u.color),fontSize:(null===(g=e.fontStyle)||void 0===g?void 0:g.size)?Bm(e.fontStyle.size):void 0}}function zm(e,t){const o=[];for(let i of e.styles){const n=$m(i.numFmtId,e.numFmts,t);n&&(o[i.numFmtId]=n)}return _m(o,1)}function Bm(e){return Object.keys(ce).map(Number).reduce(((t,o)=>Math.abs(o-e)<Math.abs(t-e)?o:t))}function Hm(e,t,o){const i=[];let n=1;for(let s of e){if(0===s.cfRules.length)continue;Zm(s,t,o);const e=s.cfRules[0];let a;const l=[];if(void 0!==e.dxfId||"colorScale"===e.type||"iconSet"===e.type){switch(e.type){case"aboveAverage":case"containsErrors":case"notContainsErrors":case"dataBar":case"duplicateValues":case"expression":case"top10":case"uniqueValues":case"timePeriod":continue;case"colorScale":const t=Wm(n++,s);t&&i.push(t);continue;case"iconSet":const c=Gm(n++,s,o);c&&i.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;a=Em[e.type],l.push(e.text);break;case"containsBlanks":case"notContainsBlanks":a=Em[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;a=(r=e.operator).slice(0,1).toUpperCase()+r.slice(1),l.push(e.formula[0]),2===e.formula.length&&l.push(e.formula[1])}a&&void 0!==e.dxfId&&i.push({id:(n++).toString(),ranges:s.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:a,values:l,style:Vm({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},o)}})}}var r;return i}function Wm(e,t){const o=t.cfRules[0].colorScale;if(!o||o.cfvos.length!==o.colors.length||o.cfvos.length<2||o.cfvos.length>3)return;const i=[];for(let e=0;e<o.cfvos.length;e++)i.push({color:(n=Mm(o.colors[e])||"#FFFFFF",9===n.length&&(n=n.slice(0,7)),parseInt(n.replace("#",""),16)),type:wm[o.cfvos[e].type],value:o.cfvos[e].value});var n;const r=i[0],s=2===i.length?i[1]:i[2],a=3===i.length?i[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"ColorScaleRule",minimum:r,midpoint:a,maximum:s}}}function Gm(e,t,o){const i=t.cfRules[0].iconSet;if(!i)return;let n=i.cfvos,r=i.cfIcons;if(n.length<3||r&&r.length<3)return;n.length>3&&(n=[n[0],n[Math.floor(n.length/2)],n[n.length-1]]),r&&r.length>3&&(r=[r[0],r[Math.floor(r.length/2)],r[r.length-1]]);const s=[];for(let e=1;e<=2;e++){const t=wm[n[e].type];if("value"===t)return;s.push({value:n[e].value||"",operator:n[e].gte?"ge":"gt",type:t})}let a={lower:r?qm(r[0].iconSet,r[0].iconId):qm(i.iconSet,0),middle:r?qm(r[1].iconSet,r[1].iconId):qm(i.iconSet,1),upper:r?qm(r[2].iconSet,r[2].iconId):qm(i.iconSet,2)};i.reverse&&(a={upper:a.lower,middle:a.middle,lower:a.upper});for(let e of Object.keys(a))if(!a[e])switch(o.generateNotSupportedWarning(dm.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=bp.dots.good;break;case"middle":a[e]=bp.dots.neutral;break;case"lower":a[e]=bp.dots.bad}return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"IconSetRule",icons:a,upperInflectionPoint:s[1],lowerInflectionPoint:s[0]}}}function qm(e,t){const o=ym[e];return o?0===t?bp[o].bad:1===t?bp[o].neutral:bp[o].good:""}function Zm(e,t,o){if(e.cfRules.length>1&&o.generateNotSupportedWarning(dm.MultipleRulesCfNotSupported),vm.includes(e.cfRules[0].type)||o.generateNotSupportedWarning(dm.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const i=t[e.cfRules[0].dxfId];i.border&&o.generateNotSupportedWarning(dm.CfFormatBorderNotSupported),i.alignment&&o.generateNotSupportedWarning(dm.CfFormatAlignmentNotSupported),i.numFmt&&o.generateNotSupportedWarning(dm.CfFormatNumFmtNotSupported)}}function jm(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function Xm(e){return Math.round(tm*e*window.devicePixelRatio*100)/100}function Ym(e){return Math.round(om*e*100)/100}function Km(e){if(e)return{style:e[0],color:{rgb:e[1]}}}function Qm(e,t){let o={};e.style&&(o=t.styles[e.style]);const i=function(e,t){if(e.format)return t.formats[e.format];if(e.isFormula){const t=eu(e.content||""),o=Yd.content;if(!t.filter((e=>"FUNCTION"===e.type)).every((e=>o[e.value.toUpperCase()].isExported)))return e.computedFormat}return}(e,t),n={};if(e.border){const o=t.borders[e.border];n.left=Km(o.left),n.right=Km(o.right),n.bottom=Km(o.bottom),n.top=Km(o.top)}const r={font:{size:(null==o?void 0:o.fontSize)||W,color:{rgb:(null==o?void 0:o.textColor)?o.textColor:"000000"},family:2,name:"Arial"},fill:(null==o?void 0:o.fillColor)?{fgColor:{rgb:o.fillColor}}:{reservedAttribute:"none"},numFmt:i?{format:i,id:0}:void 0,border:n||{},alignment:{vertical:"center",horizontal:o.align}};return r.font.strike=!!(null==o?void 0:o.strikethrough)||void 0,r.font.underline=!!(null==o?void 0:o.underline)||void 0,r.font.bold=!!(null==o?void 0:o.bold)||void 0,r.font.italic=!!(null==o?void 0:o.italic)||void 0,r}function Jm(e,t){const{id:o}=tf(t.font,e.fonts),{id:i}=tf(t.fill,e.fills),{id:n}=tf(t.border,e.borders),r=function(e,t){if(!e)return 0;let o=Am[e.format];if(!o){const{id:i}=tf(e,t);o=i+am}return o}(t.numFmt,e.numFmts),s={fontId:o,fillId:i,borderId:n,numFmtId:r,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal}},{id:a}=tf(s,e.styles);return a}function ef(e,t,o){let i,n=e.find((e=>e.path===t));return n?(i=`rId${(n.rels.length+1).toString()}`,n.rels.push({...o,id:i})):(i="rId1",e.push({path:t,rels:[{...o,id:i}]})),i}function tf(e,t){for(let[o,i]of Object.entries(t))if(JSON.stringify(i)===JSON.stringify(e))return{id:parseInt(o,10),list:t};let o=t.findIndex((t=>JSON.stringify(t)===JSON.stringify(e)));return-1===o&&(t.push(e),o=t.length-1),{id:o,list:t}}const of=[];function nf(e){const t=of.findIndex((t=>t===e));return-1===t?(of.push(e),of.length):t+1}function rf(e){return Math.round(914400*e/96)}function sf(e,t,o){let i,n,r=e;if(({xc:r,sheetName:i}=Nt(e)),i){const e=o.sheets.findIndex((e=>e.name===i));if(e<0)throw new Error("Unable to find a sheet with the name "+i);n=e}else n=Number(t);const s=Ao(r);return void 0===s.right&&(s.right=o.sheets[n].colNumber),void 0===s.bottom&&(s.bottom=o.sheets[n].rowNumber),(s.right-s.left+1)*(s.bottom-s.top+1)}function af(e){return Math.round(96*e/914400)}function lf(e,t){var o;let i=0;for(let n=0;n<e;n++){const e=t.cols.find((e=>n>=e.min&&n<=e.max));(null==e?void 0:e.width)?i+=e.width:(null===(o=t.sheetFormat)||void 0===o?void 0:o.defaultColWidth)?i+=t.sheetFormat.defaultColWidth:i+=im}return i/om}function cf(e,t){var o;let i=0;for(let n=0;n<e;n++){const e=t.rows[n];(null==e?void 0:e.height)?i+=e.height:(null===(o=t.sheetFormat)||void 0===o?void 0:o.defaultRowHeight)?i+=t.sheetFormat.defaultRowHeight:i+=nm}return i/tm}function hf(e){let t=1;return e.figures.map((o=>function(e,t,o){const i=lf(e.anchors[0].col,o)+af(e.anchors[0].colOffset),n=lf(e.anchors[1].col,o)+af(e.anchors[1].colOffset),r=cf(e.anchors[0].row,o)+af(e.anchors[0].rowOffset),s=cf(e.anchors[1].row,o)+af(e.anchors[1].rowOffset),a=n-i,l=s-r,c=df(e.data);return c?{id:t,x:i,y:r,width:a,height:l,tag:"chart",data:df(e.data)}:void 0}(o,(t++).toString(),e))).filter(Qe)}function df(e){var t;const o=null===(t=e.dataSets[0].label)||void 0===t?void 0:t.replace(/\$/g,"");let i=e.dataSets.map((e=>e.range.replace(/\$/g,"")));return"pie"===e.type&&i.reverse(),{dataSets:i,dataSetsHaveTitle:!1,labelRange:o,title:e.title||"",type:e.type,background:Mm({rgb:e.backgroundColor})||"#FFFFFF",verticalAxisPosition:e.verticalAxisPosition,legendPosition:e.legendPosition,stacked:e.stacked||!1,aggregated:!1,labelsAsText:!1}}const uf=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),gf=new RegExp(/SUBTOTAL\(([0-9]*),/g),pf=new RegExp(Et.source,"ig");function mf(e,t){const o=function(e){const t={};for(let o of e.rows)for(let e of o.cells)e.formula&&void 0!==e.formula.sharedIndex&&e.formula.content&&(t[e.formula.sharedIndex]={refCellXc:e.xc,formula:e.formula.content});return t}(e);for(let i of e.rows.map((e=>e.cells)).flat())(null==i?void 0:i.formula)&&(i.formula.content=void 0===i.formula.sharedIndex||i.formula.content?"="+i.formula.content:"="+vf(i.xc,o[i.formula.sharedIndex]),i.formula.content=ff(i.formula.content,t))}function ff(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(gf,((e,t)=>{const o=Rm[t];return o?o+"(":e}))).replace(uf,((e,o,i,n)=>{var r;o=Number(o)-1,n=n.replace(/\$/g,"");const s=t.externalBooks[o].sheetNames.findIndex((e=>e===i));if(-1===s)return e;const a=null===(r=t.externalBooks[o].datasets.find((e=>e.sheetId===s)))||void 0===r?void 0:r.data;if(!a)return e;const l=a&&a[n];return(Number(l)?l:`"${l}"`)||e}))}function vf(e,t){const o=Dt(t.refCellXc);let i,n=t.formula.slice();do{if(i=pf.exec(n),i){const t=Dt(i[0].replace("$","")),r=Dt(e),s={colFixed:i[0].startsWith("$"),rowFixed:i[0].includes("$",1)},a={col:r.col-o.col,row:r.row-o.row},l={col:s.colFixed?t.col:t.col+a.col,row:s.rowFixed?t.row:t.row+a.row};n=n.slice(0,i.index)+kt(l.col,l.row,s)+n.slice(i.index+i[0].length)}}while(i);return n}function bf(e,t){return e.sheets.map((o=>{mf(o,e);const i=function(e){const t=[0,0];for(let o of e.rows)t[0]=Math.max(t[0],...o.cells.map((e=>Dt(e.xc).col))),t[1]=Math.max(t[1],o.index);return t[0]=Math.max(t[0],rm),t[1]=Math.max(t[1],sm),t}(o),n=o.sheetViews[0];return{id:o.sheetName,areGridLinesVisible:!n||n.showGridLines,name:o.sheetName,colNumber:i[0],rowNumber:i[1],cells:Ef(o,e,i,t),merges:o.merges,cols:Cf(o,i[0]),rows:Sf(o,i[1]),conditionalFormats:Hm(o.cfs,e.dxfs,t),figures:hf(o),isVisible:o.isVisible,panes:n?{xSplit:n.pane.xSplit,ySplit:n.pane.ySplit}:{xSplit:0,ySplit:0},filterTables:[]}}))}function Cf(e,t){var o;const i={};for(let r=1;r<t+1;r++){const t=e.cols.find((e=>e.min<=r&&r<=e.max));let s;s=t&&t.width?t.width:(null===(o=e.sheetFormat)||void 0===o?void 0:o.defaultColWidth)?e.sheetFormat.defaultColWidth:im,i[r-1]={size:(n=s,n?Math.round(n/om*100)/100:n),isHidden:null==t?void 0:t.hidden}}var n;return i}function Sf(e,t){var o;const i={};for(let r=1;r<t+1;r++){const t=e.rows.find((e=>e.index===r));let s;s=t&&t.height?t.height:(null===(o=e.sheetFormat)||void 0===o?void 0:o.defaultRowHeight)?e.sheetFormat.defaultRowHeight:nm,i[r-1]={size:(n=s,n?Math.round(n/tm*100)/100:n),isHidden:null==t?void 0:t.hidden}}var n;return i}function Ef(e,t,o,i){const n={},r=t.sharedStrings.map((e=>e.replace(/\n/g,"")));const s=e.hyperlinks.reduce(((e,t)=>(e[t.xc]=t,e)),{});for(let o of e.rows)for(let e of o.cells)n[e.xc]={content:wf(e,s,r,i),style:e.styleIndex?e.styleIndex+1:void 0,border:e.styleIndex?t.styles[e.styleIndex].borderId+1:void 0,format:e.styleIndex?t.styles[e.styleIndex].numFmtId+1:void 0};for(let i of e.rows.filter((e=>e.styleIndex)))for(let e=1;e<=o[0];e++){const o=kt(e-1,i.index-1);let r=n[o];r||(r={},n[o]=r),r.style=r.style?r.style:i.styleIndex+1,r.border=r.border?r.border:t.styles[i.styleIndex].borderId+1,r.format=r.format?r.format:t.styles[i.styleIndex].numFmtId+1}for(let i of e.cols.filter((e=>e.styleIndex)))for(let e=i.min;e<=Math.min(i.max,o[0]);e++)for(let r=1;r<=o[1];r++){const o=kt(e-1,r-1);let s=n[o];s||(s={},n[o]=s),s.style=s.style?s.style:i.styleIndex+1,s.border=s.border?s.border:t.styles[i.styleIndex].borderId+1,s.format=s.format?s.format:t.styles[i.styleIndex].numFmtId+1}return n}function wf(e,t,o,i){let n;switch(e.type){case"sharedString":n=o[parseInt(e.value,10)];break;case"boolean":n=Number(e.value)?"TRUE":"FALSE";break;case"date":case"error":case"inlineStr":case"number":case"str":n=e.value}return n&&t[e.xc]&&(n=function(e,t,o){const i=e.display||t;e.relTarget||e.location||o.generateNotSupportedWarning(dm.BadlyFormattedHyperlink);const n=e.relTarget?e.relTarget:Ye(Nt(e.location).sheetName);return qe(i,n)}(t[e.xc],n,i)),e.formula&&(n=e.formula.content),n}const yf={fillColor:"#000000",textColor:"#ffffff",bold:!0},xf={bold:!0},If=["thin","#000000FF"];function Rf(e,t){for(const o of t.sheets)for(const t of o.tables){const i=e.sheets.find((e=>e.name===o.sheetName));i&&t.autoFilter&&(i.filterTables||(i.filterTables=[]),i.filterTables.push({range:t.ref}))}!function(e,t){var o,i,n,r;const s=Fm(e.styles),a=Fm(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=Oo(t.ref);for(let e=0;e<t.headerRowCount;e++)Tf(yf,{...h,bottom:h.top+e},c.cells,s);for(let e=0;e<t.totalsRowCount;e++)Tf(xf,{...h,top:h.bottom-e},c.cells,s);(null===(o=t.style)||void 0===o?void 0:o.showFirstColumn)&&Tf(xf,{...h,right:h.left},c.cells,s),(null===(i=t.style)||void 0===i?void 0:i.showLastColumn)&&Tf(xf,{...h,left:h.right},c.cells,s);for(let e=h.left;e<=h.right;e++)for(let o=h.top;o<=h.bottom;o++){const i=kt(e,o),s=c.cells[i],l={left:e===h.left||(null===(n=t.style)||void 0===n?void 0:n.showColumnStripes)?If:void 0,right:e===h.right?If:void 0,top:o===h.top||(null===(r=t.style)||void 0===r?void 0:r.showRowStripes)||o>h.bottom-t.totalsRowCount?If:void 0,bottom:o===h.bottom?If:void 0},d=(null==s?void 0:s.border)?{...a[s.border],...l}:l;let u=a.findIndex((e=>rt(e,d)));-1===u&&(u=a.length,a.push(d)),s?s.border=u:c.cells[i]={border:u}}}e.styles=_m(s),e.borders=_m(a)}(e,t),function(e,t){for(let o of e){const e=t.find((e=>e.sheetName===o.name)).tables;for(let t of e){const e=t.name+"[";for(let i of qo(Oo(t.ref))){const n=kt(i.col,i.row),r=o.cells[n];if(r&&r.content&&r.content.startsWith("=")){let o;for(;-1!==(o=r.content.indexOf(e));){let i=r.content.slice(o+e.length),s=i.indexOf("]");i.startsWith("[")&&(s=i.indexOf("]",s+1),s=i.indexOf("]",s+1)),i=i.slice(0,s);const a=Af(i,t,n);r.content=r.content.slice(0,o)+a+r.content.slice(e.length+o+s+1)}}}}}}(e.sheets,t.sheets)}function Tf(e,t,o,i){for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){const t=kt(n,r),s=o[t],a=(null==s?void 0:s.style)?{...i[s.style],...e}:e;let l=i.findIndex((e=>rt(e,a)));-1===l&&(l=i.length,i.push(a)),s?s.style=l:o[t]={style:l}}}function Af(e,t,o){const i=e.split(","),n=Oo(t.ref),r={...n};let s=!0;if(1===i.length){const e=t.cols.findIndex((e=>e.name===i[0]));r.left=r.right=e+n.left,t.headerRowCount&&(r.top+=t.headerRowCount),t.totalsRowCount&&(r.bottom-=1)}else{switch(i[0].slice(1,i[0].length-1)){case"#All":r.top=t.headerRowCount?n.top+t.headerRowCount:n.top,r.bottom=n.bottom;break;case"#Data":r.top=t.headerRowCount?n.top+t.headerRowCount:n.top,r.bottom=t.totalsRowCount?n.bottom+1:n.bottom;break;case"#This Row":r.top=r.bottom=Dt(o).row;break;case"#Headers":r.top=r.bottom=n.top,t.headerRowCount||(s=!1);break;case"#Totals":r.top=r.bottom=n.bottom,t.totalsRowCount||(s=!1)}const e=i[1].slice(1,i[1].length-1),a=t.cols.findIndex((t=>t.name===e));r.left=r.right=a+n.left}return s?r.top!==r.bottom?No(r):kt(r.left,r.top):X}function Of(e,t,o){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:o}}function Mf(e){return String(e).replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\'/g,"&apos;")}function Nf(e){return new Gp(e.map((([e,t])=>`${e}="${Mf(t)}"`)).join(" "))}function _f(e,t="text/xml"){const o=(new DOMParser).parseFromString(e.toString(),t),i=o.querySelector("parsererror");if(i){const t=i.innerHTML,o=parseInt(t.split(":")[0],10),n=e.toString().trim().split("\n"),r=n.slice(Math.max(o-3,0),Math.min(o+2,n.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${r}`)}return o}function Ff(e,t){return kf`
1413
+ />`,Hp.defaultProps={topOffset:0},Hp.props={topOffset:{type:Number,optional:!0}};const Wp={ROW:Dr,COL:Fr,CELL:_r};class Gp extends t.Component{constructor(){super(...arguments),this.HEADER_HEIGHT=O,this.HEADER_WIDTH=M,this.keyDownMapping={ENTER:()=>{this.env.model.getters.getActiveCell().type===fi.empty?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()},TAB:()=>this.env.model.selection.moveAnchorCell("right",1),"SHIFT+TAB":()=>this.env.model.selection.moveAnchorCell("left",1),F2:()=>{this.env.model.getters.getActiveCell().type===fi.empty?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()},DELETE:()=>{this.env.model.dispatch("DELETE_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},BACKSPACE:()=>{this.env.model.dispatch("DELETE_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},ESCAPE:()=>{this.env.model.getters.hasOpenedPopover()?this.closeOpenedPopover():this.menuState.isOpen?this.closeMenu():this.env.model.dispatch("CLEAN_CLIPBOARD_HIGHLIGHT")},"CTRL+A":()=>this.env.model.selection.loopSelection(),"CTRL+Z":()=>this.env.model.dispatch("REQUEST_UNDO"),"CTRL+Y":()=>this.env.model.dispatch("REQUEST_REDO"),"CTRL+B":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"CTRL+I":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"CTRL+U":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"ALT+=":()=>{var e;const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSelectedZone(),{anchor:i}=this.env.model.getters.getSelection(),n=this.env.model.getters.getAutomaticSums(t,o,i.cell);if(this.env.model.getters.isSingleCellOrMerge(t,o)||this.env.model.getters.isEmpty(t,o)&&n.length<=1){const o=(null===(e=n[0])||void 0===e?void 0:e.zone)?this.env.model.getters.zoneToXC(t,n[0].zone):"",i=`=SUM(${o})`;this.props.onGridComposerCellFocused(i,{start:5,end:5+o.length})}else this.env.model.dispatch("SUM_SELECTION")},"CTRL+HOME":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:o}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,o)},"CTRL+END":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,"COL",this.env.model.getters.getNumberCols(e)-1,0),o=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,o)},"SHIFT+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},o=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:o,zone:t})},"CTRL+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},o=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:o,zone:t})},"CTRL+SHIFT+ ":()=>{this.env.model.selection.selectAll()},"SHIFT+PAGEDOWN":()=>{this.env.model.dispatch("ACTIVATE_NEXT_SHEET")},"SHIFT+PAGEUP":()=>{this.env.model.dispatch("ACTIVATE_PREVIOUS_SHEET")},PAGEDOWN:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PAGEUP:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP"),"CTRL+K":()=>Tr(this.env)}}setup(){this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.hiddenInput=t.useRef("hiddenInput"),this.canvasPosition=Fn(this.gridRef),this.hoveredCell=t.useState({col:void 0,row:void 0}),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),t.useExternalListener(document.body,"cut",this.copy.bind(this,!0)),t.useExternalListener(document.body,"copy",this.copy.bind(this,!1)),t.useExternalListener(document.body,"paste",this.paste),t.onMounted((()=>this.focus())),this.props.exposeFocus((()=>this.focus())),kp("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimensionWithHeaders())),t.useEffect((()=>this.focus()),(()=>[this.env.model.getters.getActiveSheetId()])),this.onMouseWheel=$p(((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.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.focus()}focus(){var e;this.env.model.getters.getSelectedFigureId()||"inactive"!==this.env.model.getters.getEditionMode()||null===(e=this.hiddenInput.el)||void 0===e||e.focus()}get gridEl(){if(!this.gridRef.el)throw new Error("Grid el is not defined.");return this.gridRef.el}getAutofillPosition(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{left:t.x+t.width-4,top:t.y+t.height-4}}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:o,scrollY:i}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o+e,offsetY:i+t})}getClientPositionKey(e){var t,o,i;return`${e.id}-${null===(t=e.position)||void 0===t?void 0:t.sheetId}-${null===(o=e.position)||void 0===o?void 0:o.col}-${null===(i=e.position)||void 0===i?void 0:i.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,{ctrlKey:o,shiftKey:i}){o&&this.env.model.dispatch("PREPARE_SELECTION_INPUT_EXPANSION"),this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),"editing"===this.env.model.getters.getEditionMode()&&this.env.model.dispatch("STOP_EDITION"),i?this.env.model.selection.setAnchorCorner(e,t):o?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t);let n=e,r=t;$r(this.env,((e,t)=>{(e!==n&&-1!=e||t!==r&&-1!=t)&&(n=-1===e?n:e,r=-1===t?r:t,this.env.model.selection.setAnchorCorner(n,r))}),(()=>{this.env.model.dispatch("STOP_SELECTION_INPUT"),this.env.model.getters.isPaintingFormat()&&this.env.model.dispatch("PASTE",{target:this.env.model.getters.getSelectedZones()})}))}onCellDoubleClicked(e,t){const o=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:o,col:e,row:t}));this.env.model.getters.getEvaluatedCell({sheetId:o,col:e,row:t}).type===fi.empty?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()}closeOpenedPopover(){this.env.model.dispatch("CLOSE_CELL_POPOVER")}processArrows(e){e.preventDefault(),e.stopPropagation(),this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),Yu(e,this.env.model.selection),this.env.model.getters.isPaintingFormat()&&this.env.model.dispatch("PASTE",{target:this.env.model.getters.getSelectedZones()})}onKeydown(e){if(e.key.startsWith("Arrow"))return void this.processArrows(e);let t="";e.ctrlKey&&(t+="CTRL+"),e.metaKey&&(t+="CTRL+"),e.altKey&&(t+="ALT+"),e.shiftKey&&(t+="SHIFT+"),t+=e.key.toUpperCase();let o=this.keyDownMapping[t];return o?(e.preventDefault(),e.stopPropagation(),void o()):void 0}onInput(e){(e.isComposing||"insertFromPaste"!==e.inputType)&&e.data&&(e.preventDefault(),e.stopPropagation(),this.props.onGridComposerCellFocused(e.data))}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:o,top:i}=t;let n="CELL";this.env.model.dispatch("STOP_EDITION"),this.env.model.getters.getActiveCols().has(o)?n="COL":this.env.model.getters.getActiveRows().has(i)&&(n="ROW");const{x:r,y:s,width:a,height:l}=this.env.model.getters.getVisibleRect(t);this.toggleContextMenu(n,r+a,s+l)}onCellRightClicked(e,t,{x:o,y:i}){const n=this.env.model.getters.getSelectedZones();let r="CELL";zo(e,t,n[n.length-1])?this.env.model.getters.getActiveCols().has(e)?r="COL":this.env.model.getters.getActiveRows().has(t)&&(r="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(r,o,i)}toggleContextMenu(e,t,o){this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:o},this.menuState.menuItems=Wp[e].getAll()}copy(e,t){if(!this.gridEl.contains(document.activeElement))return;const o=t.clipboardData;if(!o)return void this.displayWarningCopyPasteNotSupported();if("inactive"!==this.env.model.getters.getEditionMode())return;e?Gn(this.env):this.env.model.dispatch("COPY");const i=this.env.model.getters.getClipboardContent();for(const e in i)o.setData(e,i[e]);t.preventDefault()}paste(e){if(!this.gridEl.contains(document.activeElement))return;const t=e.clipboardData;if(t){if(t.types.indexOf(vi.PlainText)>-1){const e=t.getData(vi.PlainText),o=this.env.model.getters.getSelectedZones();this.env.model.getters.getClipboardTextContent()===e?jn(this.env,o):Xn(this.env,o,e)}}else this.displayWarningCopyPasteNotSupported()}displayWarningCopyPasteNotSupported(){this.env.raiseError(r("Copy/Paste is not supported in this browser."))}closeMenu(){this.menuState.isOpen=!1,this.focus()}}Gp.template="o-spreadsheet-Grid",Gp.components={GridComposer:lg,GridOverlay:Op,GridPopover:Mp,HeadersOverlay:Dp,Menu:Hn,Autofill:Pr,ClientTag:Ur,Highlight:Up,Popover:Un,VerticalScrollBar:Hp,HorizontalScrollBar:Bp,FilterIconsOverlay:ug},Gp.props={sidePanelIsOpen:Boolean,exposeFocus:Function,focusComposer:String,onComposerContentFocused:Function,onGridComposerCellFocused:Function};class qp{constructor(e){this.xmlString=e}toString(){return this.xmlString}}const Zp=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart"],jp="000000",Xp={arrow:"3Arrows",smiley:"3Symbols",dot:"3TrafficLights1"},Yp={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"},Kp="http://schemas.openxmlformats.org/drawingml/2006/main",Qp="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"},em={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"},tm="http://schemas.openxmlformats.org/officeDocument/2006/relationships",om=.75,im=.1317,nm=8.43,rm=12.75,sm=30,am=100,lm=164,cm={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}]},hm=["ACOT","ACOTH","AGGREGATE","ARABIC","BASE","BETA.DIST","BETA.INV","BINOM.DIST","BINOM.DIST.RANGE","BINOM.INV","BITAND","BITLSHIFT","BITOR","BITRSHIFT","BITXOR","CEILING.MATH","CEILING.PRECISE","CHISQ.DIST","CHISQ.DIST.RT","CHISQ.INV","CHISQ.INV.RT","CHISQ.TEST","COMBINA","CONCAT","CONFIDENCE.NORM","CONFIDENCE.T","COT","COTH","COVARIANCE.P","COVARIANCE.S","CSC","CSCH","DAYS","DECIMAL","ERF.PRECISE","ERFC.PRECISE","EXPON.DIST","F.DIST","F.DIST.RT","F.INV","F.INV.RT","F.TEST","FILTERXML","FLOOR.MATH","FLOOR.PRECISE","FORECAST.ETS","FORECAST.ETS.CONFINT","FORECAST.ETS.SEASONALITY","FORECAST.ETS.STAT","FORECAST.LINEAR","FORMULATEXT","GAMMA","GAMMA.DIST","GAMMA.INV","GAMMALN.PRECISE","GAUSS","HYPGEOM.DIST","IFNA","IFS","IMCOSH","IMCOT","IMCSC","IMCSCH","IMSEC","IMSECH","IMSINH","IMTAN","ISFORMULA","ISOWEEKNUM","LOGNORM.DIST","LOGNORM.INV","MAXIFS","MINIFS","MODE.MULT","MODE.SNGL","MUNIT","NEGBINOM.DIST","NORM.DIST","NORM.INV","NORM.S.DIST","NORM.S.INV","NUMBERVALUE","PDURATION","PERCENTILE.EXC","PERCENTILE.INC","PERCENTRANK.EXC","PERCENTRANK.INC","PERMUTATIONA","PHI","POISSON.DIST","QUARTILE.EXC","QUARTILE.INC","QUERYSTRING","RANK.AVG","RANK.EQ","RRI","SEC","SECH","SHEET","SHEETS","SKEW.P","STDEV.P","STDEV.S","SWITCH","T.DIST","T.DIST.2T","T.DIST.RT","T.INV","T.INV.2T","T.TEST","TEXTJOIN","UNICHAR","UNICODE","VAR.P","VAR.S","WEBSERVICE","WEIBULL.DIST","XOR","Z.TEST"],dm="[Content_Types].xml";var um;!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"}(um||(um={}));class gm{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,o){let i=`${e} ${t?'"'+t+'" is':"are"} not yet supported. `;o&&(i+=`Only ${o.join(", ")} are currently supported.`),this._conversionWarnings.has(i)||this._conversionWarnings.add(i)}}const pm=["thin"],mm=["general","left","center","right"],fm=["Arial"],vm=["solid"],bm=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWith","containsBlanks","notContainsBlanks"],Cm={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},Sm={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"},Em={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"};const wm={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},ym={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},xm={NoIcons:void 0,"3Arrows":"arrows","3ArrowsGray":"arrows","3Symbols":"smiley","3Symbols2":"smiley","3Signs":"dots","3Flags":"dots","3TrafficLights1":"dots","3TrafficLights2":"dots","4Arrows":"arrows","4ArrowsGray":"arrows","4RedToBlack":"dots","4Rating":"smiley","4TrafficLights":"dots","5Arrows":"arrows","5ArrowsGray":"arrows","5Rating":"smiley","5Quarters":"dots","3Stars":"smiley","3Triangles":"arrows","5Boxes":"dots"},Im={b:"bottom",t:"top",l:"left",r:"right",tr:"right"},Rm={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},Tm={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"},Am={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},Om={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},Mm={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 Nm(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=jp;else{if(!e.indexed)return;t=Mm[e.indexed]}var o;return t=6===(o=t).length?"#"+o+"FF":"#"+o.slice(2)+o.slice(0,2),e.tint&&(t=function(e,t){const o=Ct(e),i=Et(o);t<0&&(i.l=i.l*(1+t));t>0&&(i.l=i.l*(1-t)+(100-100*(1-t)));return bt(St(i))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function _m(e,t){const o=e.split("/"),i=t.split("/");let n="",r=0;for(let e=0;e<o.length-1;e++)o[e]===i[e]?r++:n+="../";return n+=i.slice(r).join("/"),n}function Fm(e,t=0){const o={};for(let i=0;i<e.length;i++)e[i]&&(o[i+t]=e[i]);return o}function Dm(e){const t=[];for(let o of Object.keys(e).map(Number))t[o]=e[o];return t}function km(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,((e,t)=>String.fromCharCode(parseInt(t,16))))}const $m=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function Pm(e,t,o){var i,n,r;if(0===e)return;let s=Am[e]||(null===(i=t.find((t=>t.id===e)))||void 0===i?void 0:i.format);if(s)try{let e=s.replace(/(.*?);.*/,"$1");e=e.replace(/\[(.*)-[A-Z0-9]{3}\]/g,"[$1]"),e=e.replace(/\[\$\]/g,"");const t=(null===(n=e.match(/"/g))||void 0===n?void 0:n.length)||0;if(t/2+((null===(r=e.match(/\[/g))||void 0===r?void 0:r.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($m)}(e)&&(e=function(e){return e=e.toLowerCase(),e=e.replace(/mmmmm/g,"mmm"),e=e.replace(/am\/pm|a\/m/g,"a"),e=e.replace(/hhhh/g,"hh"),e=e.replace(/\bh\b/g,"hh"),e}(e)),function(e){try{return ro(0,e),!0}catch(e){return!1}}(e))return e}catch(e){}o.generateNotSupportedWarning(um.NumFmtIdNotSupported,s||`nmFmtId ${e}`)}function Lm(e,t){const o=e.borders.map((e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(um.DiagonalBorderNotSupported)}(e,t);const o={top:Um(e.top,t),bottom:Um(e.bottom,t),left:Um(e.left,t),right:Um(e.right,t)};return Object.keys(o).forEach((e=>void 0===o[e]&&delete o[e])),o}));return Fm(o,1)}function Um(e,t){if(!e)return;!function(e,t){pm.includes(e.style)||t.generateNotSupportedWarning(um.BorderStyleNotSupported,e.style,pm)}(e,t);const o=Sm[e.style];return o?[o,Nm(e.color)]:void 0}function Vm(e,t){return Fm(e.styles.map((o=>zm({fontStyle:e.fonts[o.fontId],fillStyle:e.fills[o.fillId],alignment:o.alignment},t))),1)}function zm(e,t){var o,i,n,r,s,a,l,c,h,d,u,g;return function(e,t,o){e&&e.name&&!fm.includes(e.name)&&o.generateNotSupportedWarning(um.FontNotSupported,e.name,fm);t&&t.patternType&&!vm.includes(t.patternType)&&o.generateNotSupportedWarning(um.FillStyleNotSupported,t.patternType,vm)}(null==e?void 0:e.fontStyle,null==e?void 0:e.fillStyle,t),function(e,t){e&&!mm.includes(e)&&t.generateNotSupportedWarning(um.HorizontalAlignmentNotSupported,e,mm)}(null===(o=null==e?void 0:e.alignment)||void 0===o?void 0:o.horizontal,t),function(e,t){e&&t.generateNotSupportedWarning(um.VerticalAlignmentNotSupported)}(null===(i=null==e?void 0:e.alignment)||void 0===i?void 0:i.vertical,t),{bold:null===(n=e.fontStyle)||void 0===n?void 0:n.bold,italic:null===(r=e.fontStyle)||void 0===r?void 0:r.italic,strikethrough:null===(s=e.fontStyle)||void 0===s?void 0:s.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)?Em[e.alignment.horizontal]:void 0,fillColor:"solid"===(null===(c=e.fillStyle)||void 0===c?void 0:c.patternType)?Nm(null===(h=e.fillStyle)||void 0===h?void 0:h.fgColor):Nm(null===(d=e.fillStyle)||void 0===d?void 0:d.bgColor),textColor:Nm(null===(u=e.fontStyle)||void 0===u?void 0:u.color),fontSize:(null===(g=e.fontStyle)||void 0===g?void 0:g.size)?Hm(e.fontStyle.size):void 0}}function Bm(e,t){const o=[];for(let i of e.styles){const n=Pm(i.numFmtId,e.numFmts,t);n&&(o[i.numFmtId]=n)}return Fm(o,1)}function Hm(e){return Object.keys(ce).map(Number).reduce(((t,o)=>Math.abs(o-e)<Math.abs(t-e)?o:t))}function Wm(e,t,o){const i=[];let n=1;for(let s of e){if(0===s.cfRules.length)continue;jm(s,t,o);const e=s.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=Gm(n++,s);t&&i.push(t);continue;case"iconSet":const c=qm(n++,s,o);c&&i.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;a=wm[e.type],l.push(e.text);break;case"containsBlanks":case"notContainsBlanks":a=wm[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;a=(r=e.operator).slice(0,1).toUpperCase()+r.slice(1),l.push(e.formula[0]),2===e.formula.length&&l.push(e.formula[1])}a&&void 0!==e.dxfId&&i.push({id:(n++).toString(),ranges:s.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:a,values:l,style:zm({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},o)}})}}var r;return i}function Gm(e,t){const o=t.cfRules[0].colorScale;if(!o||o.cfvos.length!==o.colors.length||o.cfvos.length<2||o.cfvos.length>3)return;const i=[];for(let e=0;e<o.cfvos.length;e++)i.push({color:(n=Nm(o.colors[e])||"#FFFFFF",9===n.length&&(n=n.slice(0,7)),parseInt(n.replace("#",""),16)),type:ym[o.cfvos[e].type],value:o.cfvos[e].value});var n;const r=i[0],s=2===i.length?i[1]:i[2],a=3===i.length?i[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"ColorScaleRule",minimum:r,midpoint:a,maximum:s}}}function qm(e,t,o){const i=t.cfRules[0].iconSet;if(!i)return;let n=i.cfvos,r=i.cfIcons;if(n.length<3||r&&r.length<3)return;n.length>3&&(n=[n[0],n[Math.floor(n.length/2)],n[n.length-1]]),r&&r.length>3&&(r=[r[0],r[Math.floor(r.length/2)],r[r.length-1]]);const s=[];for(let e=1;e<=2;e++){const t=ym[n[e].type];if("value"===t)return;s.push({value:n[e].value||"",operator:n[e].gte?"ge":"gt",type:t})}let a={lower:r?Zm(r[0].iconSet,r[0].iconId):Zm(i.iconSet,0),middle:r?Zm(r[1].iconSet,r[1].iconId):Zm(i.iconSet,1),upper:r?Zm(r[2].iconSet,r[2].iconId):Zm(i.iconSet,2)};i.reverse&&(a={upper:a.lower,middle:a.middle,lower:a.upper});for(let e of Object.keys(a))if(!a[e])switch(o.generateNotSupportedWarning(um.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=Cp.dots.good;break;case"middle":a[e]=Cp.dots.neutral;break;case"lower":a[e]=Cp.dots.bad}return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"IconSetRule",icons:a,upperInflectionPoint:s[1],lowerInflectionPoint:s[0]}}}function Zm(e,t){const o=xm[e];return o?0===t?Cp[o].bad:1===t?Cp[o].neutral:Cp[o].good:""}function jm(e,t,o){if(e.cfRules.length>1&&o.generateNotSupportedWarning(um.MultipleRulesCfNotSupported),bm.includes(e.cfRules[0].type)||o.generateNotSupportedWarning(um.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const i=t[e.cfRules[0].dxfId];i.border&&o.generateNotSupportedWarning(um.CfFormatBorderNotSupported),i.alignment&&o.generateNotSupportedWarning(um.CfFormatAlignmentNotSupported),i.numFmt&&o.generateNotSupportedWarning(um.CfFormatNumFmtNotSupported)}}function Xm(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function Ym(e){return Math.round(om*e*window.devicePixelRatio*100)/100}function Km(e){return Math.round(im*e*100)/100}function Qm(e){if(e)return{style:e[0],color:{rgb:e[1]}}}function Jm(e,t){let o={};e.style&&(o=t.styles[e.style]);const i=function(e,t){if(e.format)return t.formats[e.format];if(e.isFormula){const t=tu(e.content||""),o=Kd.content;if(!t.filter((e=>"FUNCTION"===e.type)).every((e=>o[e.value.toUpperCase()].isExported)))return e.computedFormat}return}(e,t),n={};if(e.border){const o=t.borders[e.border];n.left=Qm(o.left),n.right=Qm(o.right),n.bottom=Qm(o.bottom),n.top=Qm(o.top)}const r={font:{size:(null==o?void 0:o.fontSize)||W,color:{rgb:(null==o?void 0:o.textColor)?o.textColor:"000000"},family:2,name:"Arial"},fill:(null==o?void 0:o.fillColor)?{fgColor:{rgb:o.fillColor}}:{reservedAttribute:"none"},numFmt:i?{format:i,id:0}:void 0,border:n||{},alignment:{vertical:"center",horizontal:o.align}};return r.font.strike=!!(null==o?void 0:o.strikethrough)||void 0,r.font.underline=!!(null==o?void 0:o.underline)||void 0,r.font.bold=!!(null==o?void 0:o.bold)||void 0,r.font.italic=!!(null==o?void 0:o.italic)||void 0,r}function ef(e,t){const{id:o}=of(t.font,e.fonts),{id:i}=of(t.fill,e.fills),{id:n}=of(t.border,e.borders),r=function(e,t){if(!e)return 0;let o=Om[e.format];if(!o){const{id:i}=of(e,t);o=i+lm}return o}(t.numFmt,e.numFmts),s={fontId:o,fillId:i,borderId:n,numFmtId:r,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal}},{id:a}=of(s,e.styles);return a}function tf(e,t,o){let i,n=e.find((e=>e.path===t));return n?(i=`rId${(n.rels.length+1).toString()}`,n.rels.push({...o,id:i})):(i="rId1",e.push({path:t,rels:[{...o,id:i}]})),i}function of(e,t){for(let[o,i]of Object.entries(t))if(JSON.stringify(i)===JSON.stringify(e))return{id:parseInt(o,10),list:t};let o=t.findIndex((t=>JSON.stringify(t)===JSON.stringify(e)));return-1===o&&(t.push(e),o=t.length-1),{id:o,list:t}}const nf=[];function rf(e){const t=nf.findIndex((t=>t===e));return-1===t?(nf.push(e),nf.length):t+1}function sf(e){return Math.round(914400*e/96)}function af(e,t,o){let i,n,r=e;if(({xc:r,sheetName:i}=_t(e)),i){const e=o.sheets.findIndex((e=>e.name===i));if(e<0)throw new Error("Unable to find a sheet with the name "+i);n=e}else n=Number(t);const s=Oo(r);return void 0===s.right&&(s.right=o.sheets[n].colNumber),void 0===s.bottom&&(s.bottom=o.sheets[n].rowNumber),(s.right-s.left+1)*(s.bottom-s.top+1)}function lf(e){return Math.round(96*e/914400)}function cf(e,t){var o;let i=0;for(let n=0;n<e;n++){const e=t.cols.find((e=>n>=e.min&&n<=e.max));(null==e?void 0:e.width)?i+=e.width:(null===(o=t.sheetFormat)||void 0===o?void 0:o.defaultColWidth)?i+=t.sheetFormat.defaultColWidth:i+=nm}return i/im}function hf(e,t){var o;let i=0;for(let n=0;n<e;n++){const e=t.rows[n];(null==e?void 0:e.height)?i+=e.height:(null===(o=t.sheetFormat)||void 0===o?void 0:o.defaultRowHeight)?i+=t.sheetFormat.defaultRowHeight:i+=rm}return i/om}function df(e){let t=1;return e.figures.map((o=>function(e,t,o){const i=cf(e.anchors[0].col,o)+lf(e.anchors[0].colOffset),n=cf(e.anchors[1].col,o)+lf(e.anchors[1].colOffset),r=hf(e.anchors[0].row,o)+lf(e.anchors[0].rowOffset),s=hf(e.anchors[1].row,o)+lf(e.anchors[1].rowOffset),a=n-i,l=s-r,c=uf(e.data);return c?{id:t,x:i,y:r,width:a,height:l,tag:"chart",data:uf(e.data)}:void 0}(o,(t++).toString(),e))).filter(Je)}function uf(e){var t;const o=null===(t=e.dataSets[0].label)||void 0===t?void 0:t.replace(/\$/g,"");let i=e.dataSets.map((e=>e.range.replace(/\$/g,"")));return"pie"===e.type&&i.reverse(),{dataSets:i,dataSetsHaveTitle:!1,labelRange:o,title:e.title||"",type:e.type,background:Nm({rgb:e.backgroundColor})||"#FFFFFF",verticalAxisPosition:e.verticalAxisPosition,legendPosition:e.legendPosition,stacked:e.stacked||!1,aggregated:!1,labelsAsText:!1}}const gf=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),pf=new RegExp(/SUBTOTAL\(([0-9]*),/g),mf=new RegExp(wt.source,"ig");function ff(e,t){const o=function(e){const t={};for(let o of e.rows)for(let e of o.cells)e.formula&&void 0!==e.formula.sharedIndex&&e.formula.content&&(t[e.formula.sharedIndex]={refCellXc:e.xc,formula:e.formula.content});return t}(e);for(let i of e.rows.map((e=>e.cells)).flat())(null==i?void 0:i.formula)&&(i.formula.content=void 0===i.formula.sharedIndex||i.formula.content?"="+i.formula.content:"="+bf(i.xc,o[i.formula.sharedIndex]),i.formula.content=vf(i.formula.content,t))}function vf(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(pf,((e,t)=>{const o=Tm[t];return o?o+"(":e}))).replace(gf,((e,o,i,n)=>{var r;o=Number(o)-1,n=n.replace(/\$/g,"");const s=t.externalBooks[o].sheetNames.findIndex((e=>e===i));if(-1===s)return e;const a=null===(r=t.externalBooks[o].datasets.find((e=>e.sheetId===s)))||void 0===r?void 0:r.data;if(!a)return e;const l=a&&a[n];return(Number(l)?l:`"${l}"`)||e}))}function bf(e,t){const o=kt(t.refCellXc);let i,n=t.formula.slice();do{if(i=mf.exec(n),i){const t=kt(i[0].replace("$","")),r=kt(e),s={colFixed:i[0].startsWith("$"),rowFixed:i[0].includes("$",1)},a={col:r.col-o.col,row:r.row-o.row},l={col:s.colFixed?t.col:t.col+a.col,row:s.rowFixed?t.row:t.row+a.row};n=n.slice(0,i.index)+$t(l.col,l.row,s)+n.slice(i.index+i[0].length)}}while(i);return n}function Cf(e,t){return e.sheets.map((o=>{ff(o,e);const i=function(e){const t=[0,0];for(let o of e.rows)t[0]=Math.max(t[0],...o.cells.map((e=>kt(e.xc).col))),t[1]=Math.max(t[1],o.index);return t[0]=Math.max(t[0],sm),t[1]=Math.max(t[1],am),t}(o),n=o.sheetViews[0];return{id:o.sheetName,areGridLinesVisible:!n||n.showGridLines,name:o.sheetName,colNumber:i[0],rowNumber:i[1],cells:wf(o,e,i,t),merges:o.merges,cols:Sf(o,i[0]),rows:Ef(o,i[1]),conditionalFormats:Wm(o.cfs,e.dxfs,t),figures:df(o),isVisible:o.isVisible,panes:n?{xSplit:n.pane.xSplit,ySplit:n.pane.ySplit}:{xSplit:0,ySplit:0},filterTables:[]}}))}function Sf(e,t){var o;const i={};for(let r=1;r<t+1;r++){const t=e.cols.find((e=>e.min<=r&&r<=e.max));let s;s=t&&t.width?t.width:(null===(o=e.sheetFormat)||void 0===o?void 0:o.defaultColWidth)?e.sheetFormat.defaultColWidth:nm,i[r-1]={size:(n=s,n?Math.round(n/im*100)/100:n),isHidden:null==t?void 0:t.hidden}}var n;return i}function Ef(e,t){var o;const i={};for(let r=1;r<t+1;r++){const t=e.rows.find((e=>e.index===r));let s;s=t&&t.height?t.height:(null===(o=e.sheetFormat)||void 0===o?void 0:o.defaultRowHeight)?e.sheetFormat.defaultRowHeight:rm,i[r-1]={size:(n=s,n?Math.round(n/om*100)/100:n),isHidden:null==t?void 0:t.hidden}}var n;return i}function wf(e,t,o,i){const n={},r=t.sharedStrings.map((e=>e.replace(/\n/g,"")));const s=e.hyperlinks.reduce(((e,t)=>(e[t.xc]=t,e)),{});for(let o of e.rows)for(let e of o.cells)n[e.xc]={content:yf(e,s,r,i),style:e.styleIndex?e.styleIndex+1:void 0,border:e.styleIndex?t.styles[e.styleIndex].borderId+1:void 0,format:e.styleIndex?t.styles[e.styleIndex].numFmtId+1:void 0};for(let i of e.rows.filter((e=>e.styleIndex)))for(let e=1;e<=o[0];e++){const o=$t(e-1,i.index-1);let r=n[o];r||(r={},n[o]=r),r.style=r.style?r.style:i.styleIndex+1,r.border=r.border?r.border:t.styles[i.styleIndex].borderId+1,r.format=r.format?r.format:t.styles[i.styleIndex].numFmtId+1}for(let i of e.cols.filter((e=>e.styleIndex)))for(let e=i.min;e<=Math.min(i.max,o[0]);e++)for(let r=1;r<=o[1];r++){const o=$t(e-1,r-1);let s=n[o];s||(s={},n[o]=s),s.style=s.style?s.style:i.styleIndex+1,s.border=s.border?s.border:t.styles[i.styleIndex].borderId+1,s.format=s.format?s.format:t.styles[i.styleIndex].numFmtId+1}return n}function yf(e,t,o,i){let n;switch(e.type){case"sharedString":n=o[parseInt(e.value,10)];break;case"boolean":n=Number(e.value)?"TRUE":"FALSE";break;case"date":case"error":case"inlineStr":case"number":case"str":n=e.value}return n&&t[e.xc]&&(n=function(e,t,o){const i=e.display||t;e.relTarget||e.location||o.generateNotSupportedWarning(um.BadlyFormattedHyperlink);const n=e.relTarget?e.relTarget:Ke(_t(e.location).sheetName);return Ze(i,n)}(t[e.xc],n,i)),e.formula&&(n=e.formula.content),n}const xf={fillColor:"#000000",textColor:"#ffffff",bold:!0},If={bold:!0},Rf=["thin","#000000FF"];function Tf(e,t){for(const o of t.sheets)for(const t of o.tables){const i=e.sheets.find((e=>e.name===o.sheetName));i&&t.autoFilter&&(i.filterTables||(i.filterTables=[]),i.filterTables.push({range:t.ref}))}!function(e,t){var o,i,n,r;const s=Dm(e.styles),a=Dm(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=Mo(t.ref);for(let e=0;e<t.headerRowCount;e++)Af(xf,{...h,bottom:h.top+e},c.cells,s);for(let e=0;e<t.totalsRowCount;e++)Af(If,{...h,top:h.bottom-e},c.cells,s);(null===(o=t.style)||void 0===o?void 0:o.showFirstColumn)&&Af(If,{...h,right:h.left},c.cells,s),(null===(i=t.style)||void 0===i?void 0:i.showLastColumn)&&Af(If,{...h,left:h.right},c.cells,s);for(let e=h.left;e<=h.right;e++)for(let o=h.top;o<=h.bottom;o++){const i=$t(e,o),s=c.cells[i],l={left:e===h.left||(null===(n=t.style)||void 0===n?void 0:n.showColumnStripes)?Rf:void 0,right:e===h.right?Rf:void 0,top:o===h.top||(null===(r=t.style)||void 0===r?void 0:r.showRowStripes)||o>h.bottom-t.totalsRowCount?Rf:void 0,bottom:o===h.bottom?Rf:void 0},d=(null==s?void 0:s.border)?{...a[s.border],...l}:l;let u=a.findIndex((e=>st(e,d)));-1===u&&(u=a.length,a.push(d)),s?s.border=u:c.cells[i]={border:u}}}e.styles=Fm(s),e.borders=Fm(a)}(e,t),function(e,t){for(let o of e){const e=t.find((e=>e.sheetName===o.name)).tables;for(let t of e){const e=t.name+"[";for(let i of Zo(Mo(t.ref))){const n=$t(i.col,i.row),r=o.cells[n];if(r&&r.content&&r.content.startsWith("=")){let o;for(;-1!==(o=r.content.indexOf(e));){let i=r.content.slice(o+e.length),s=i.indexOf("]");i.startsWith("[")&&(s=i.indexOf("]",s+1),s=i.indexOf("]",s+1)),i=i.slice(0,s);const a=Of(i,t,n);r.content=r.content.slice(0,o)+a+r.content.slice(e.length+o+s+1)}}}}}}(e.sheets,t.sheets)}function Af(e,t,o,i){for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){const t=$t(n,r),s=o[t],a=(null==s?void 0:s.style)?{...i[s.style],...e}:e;let l=i.findIndex((e=>st(e,a)));-1===l&&(l=i.length,i.push(a)),s?s.style=l:o[t]={style:l}}}function Of(e,t,o){const i=e.split(","),n=Mo(t.ref),r={...n};let s=!0;if(1===i.length){const e=t.cols.findIndex((e=>e.name===i[0]));r.left=r.right=e+n.left,t.headerRowCount&&(r.top+=t.headerRowCount),t.totalsRowCount&&(r.bottom-=1)}else{switch(i[0].slice(1,i[0].length-1)){case"#All":r.top=t.headerRowCount?n.top+t.headerRowCount:n.top,r.bottom=n.bottom;break;case"#Data":r.top=t.headerRowCount?n.top+t.headerRowCount:n.top,r.bottom=t.totalsRowCount?n.bottom+1:n.bottom;break;case"#This Row":r.top=r.bottom=kt(o).row;break;case"#Headers":r.top=r.bottom=n.top,t.headerRowCount||(s=!1);break;case"#Totals":r.top=r.bottom=n.bottom,t.totalsRowCount||(s=!1)}const e=i[1].slice(1,i[1].length-1),a=t.cols.findIndex((t=>t.name===e));r.left=r.right=a+n.left}return s?r.top!==r.bottom?_o(r):$t(r.left,r.top):X}function Mf(e,t,o){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:o}}function Nf(e){return String(e).replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\'/g,"&apos;")}function _f(e){return new qp(e.map((([e,t])=>`${e}="${Nf(t)}"`)).join(" "))}function Ff(e,t="text/xml"){const o=(new DOMParser).parseFromString(e.toString(),t),i=o.querySelector("parsererror");if(i){const t=i.innerHTML,o=parseInt(t.split(":")[0],10),n=e.toString().trim().split("\n"),r=n.slice(Math.max(o-3,0),Math.min(o+2,n.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${r}`)}return o}function Df(e,t){return $f`
1414
1414
  <Override ContentType="${t}" PartName="${e}" />
1415
- `}function Df(e){return new Gp(e.join("\n"))}function kf(e,...t){let o=[e[0]];for(let i=0;i<t.length;i++){const n=t[i]instanceof Gp?t[i]:Mf(t[i]);o.push(n+e[i+1])}return new Gp(tt(o))}function $f(e){return e.replace(/[a-z0-9]+:(?=[a-z0-9]+)/gi,"")}function Pf(e){return e.replace(/([a-z0-9]+):(?=[a-z0-9]+)/gi,"$1\\:")}class Lf{constructor(e){this.value=e}asString(){return Dm(String(this.value))}asBool(){return Boolean(Number(this.value))}asNum(){return Number(this.value)}}class Uf{constructor(e,t,o){this.currentFile=void 0,this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=o,this.areNamespaceIgnored=null!==(new DOMParser).parseFromString("<t:test xmlns:t='a'/>","text/xml").querySelector("test"),this.relationships={},e.rels&&this.extractRelationships(e.rels).map((e=>{this.relationships[e.id]=e}))}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:"Relationship"},(e=>({id:this.extractAttr(e,"Id",{required:!0}).asString(),target:this.extractAttr(e,"Target",{required:!0}).asString(),type:this.extractAttr(e,"Type",{required:!0}).asString()})))}getListOfFiles(){return Object.values(this.xlsxFileStructure).flat().filter(Qe)}mapOnElements(e,t){var o;const i=[],n=this.currentFile;let r;if(e.children){const t=null===(o=this.querySelector(e.parent,e.query))||void 0===o?void 0:o.children;r=t||[]}else r=this.querySelectorAll(e.parent,e.query);if(r)for(let e of r)try{i.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=n,i}catchErrorOnElement(e,t){const o=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([o,e.message].join("\n"))}extractAttr(e,t,o){const i=e.attributes[t];i||this.handleMissingValue(e,`attribute "${t}"`,o);const n=(null==i?void 0:i.value)?i.value:null==o?void 0:o.default;return void 0===n?void 0:new Lf(n)}extractTextContent(e,t){var o;if(void 0!==(null==t?void 0:t.default)&&"string"!=typeof t.default)throw new Error("extractTextContent default value should be a string");const i="preserve"===(null===(o=null==e?void 0:e.attributes["xml:space"])||void 0===o?void 0:o.value);let n=null==e?void 0:e.textContent;return e&&null!==n||this.handleMissingValue(e,"text content",t),n&&(n=i?n:n.trim()),n?Dm(n):null==t?void 0:t.default}extractChildAttr(e,t,o,i){var n;let r;r="number"==typeof t?e.children[t]:this.querySelector(e,t),r||this.handleMissingValue(e,"number"==typeof t?`child at index ${t}`:`child <${t}>`,i);const s=r?null===(n=this.extractAttr(r,o,i))||void 0===n?void 0:n.asString():null==i?void 0:i.default;return void 0!==s?new Lf(s):void 0}extractChildTextContent(e,t,o){if(void 0!==(null==o?void 0:o.default)&&"string"!=typeof o.default)throw new Error("extractTextContent default value should be a string");let i=this.querySelector(e,t);return i||this.handleMissingValue(e,`child <${t}>`,o),i?this.extractTextContent(i,o):null==o?void 0:o.default}handleMissingValue(e,t,o){if(null==o?void 0:o.required){if(!(null==o?void 0:o.default))throw new Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`);this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${o.default}`)}}extractColor(e,t,o){var i,n,r,s,a;if(!e)return o?{rgb:o}:void 0;const l=null===(i=this.extractAttr(e,"theme"))||void 0===i?void 0:i.asString();let c;if(void 0!==l){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");c=this.getThemeColor(l,t.clrScheme)}else c=null===(n=this.extractAttr(e,"rgb"))||void 0===n?void 0:n.asString();return{rgb:c,auto:null===(r=this.extractAttr(e,"auto"))||void 0===r?void 0:r.asBool(),indexed:null===(s=this.extractAttr(e,"indexed"))||void 0===s?void 0:s.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 o=this.getListOfFiles().find((e=>e.file.fileName.endsWith(t)));if(!o||!o.file)throw new Error("Cannot find target file");return o}querySelector(e,t){return t=this.areNamespaceIgnored?$f(t):Pf(t),e.querySelector(t)}querySelectorAll(e,t){return t=this.areNamespaceIgnored?$f(t):Pf(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 Vf extends Uf{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:Zp}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:Zp}).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 zf extends Uf{constructor(e,t,o,i){super(e,t,o),this.theme=i}extractConditionalFormattings(){const e=this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > conditionalFormatting"},(e=>{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 o,i,n,r,s,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===(o=this.extractAttr(e,"dxfId"))||void 0===o?void 0:o.asNum(),stopIfTrue:null===(i=this.extractAttr(e,"stopIfTrue"))||void 0===i?void 0:i.asBool(),aboveAverage:null===(n=this.extractAttr(e,"aboveAverage"))||void 0===n?void 0:n.asBool(),percent:null===(r=this.extractAttr(e,"percent"))||void 0===r?void 0:r.asBool(),bottom:null===(s=this.extractAttr(e,"bottom"))||void 0===s?void 0:s.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 o=this.querySelector(e,"colorScale");if(o)return{colors:this.mapOnElements({parent:o,query:"color"},(e=>this.extractColor(e,t,"ffffff"))),cfvos:this.extractCFVos(o)}}extractCfIconSet(e){var t,o;const i=this.querySelector(e,"iconSet, x14:iconSet");if(i)return{iconSet:this.extractAttr(i,"iconSet",{default:"3TrafficLights1"}).asString(),showValue:this.extractAttr(i,"showValue",{default:!0}).asBool(),percent:this.extractAttr(i,"percent",{default:!0}).asBool(),reverse:null===(t=this.extractAttr(i,"reverse"))||void 0===t?void 0:t.asBool(),custom:null===(o=this.extractAttr(i,"custom"))||void 0===o?void 0:o.asBool(),cfvos:this.extractCFVos(i),cfIcons:this.extractCfIcons(i)}}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,o;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===(o=this.extractAttr(e,"val"))||void 0===o?void 0:o.asString():this.extractChildTextContent(e,"f, xm:f")}}))}}class Bf extends Uf{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},(e=>{const t=this.getChartType(e);if(!Im[t])throw new Error(`Unsupported chart type ${t}`);const o=this.mapOnElements({parent:e,query:"c:title a:t"},(e=>e.textContent||"")).join(""),i=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString();return{title:o,type:Im[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:xm[this.extractChildAttr(e,"c:legendPos","val",{default:"b"}).asString()],stacked:"stacked"===i,fontColor:"000000"}}))[0]}extractChartDatasets(e){return this.mapOnElements({parent:e,query:"c:ser"},(e=>({label:this.extractChildTextContent(e,"c: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=$f(e.tagName);if(qp.some((e=>e===t)))return t}throw new Error("Unknown chart type")}}class Hf extends Uf{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},(e=>{if("twoCellAnchor"!==$f(e.tagName))throw new Error("Only twoCellAnchor are supported for xlsx drawings.");const t=this.querySelector(e,"c:chart");if(!t)throw new Error("Only chart figures are currently supported.");return{anchors:[this.extractFigureAnchor("xdr:from",e),this.extractFigureAnchor("xdr:to",e)],data:this.extractChart(t)}}))}extractFigureAnchor(e,t){const o=this.querySelector(t,e);if(!o)throw new Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(o,"xdr:col",{required:!0})),colOffset:Number(this.extractChildTextContent(o,"xdr:colOff",{required:!0})),row:Number(this.extractChildTextContent(o,"xdr:row",{required:!0})),rowOffset:Number(this.extractChildTextContent(o,"xdr:rowOff",{required:!0}))}}extractChart(e){const t=this.extractAttr(e,"r:id",{required:!0}).asString(),o=this.getTargetXmlFile(this.relationships[t]),i=new Bf(o,this.xlsxFileStructure,this.warningManager).extractChart();if(!i)throw new Error("Unable to extract chart definition");return i}}class Wf extends Uf{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 Gf extends Uf{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,o,i,n,r;return{name:null===(t=this.extractAttr(e,"name"))||void 0===t?void 0:t.asString(),showFirstColumn:null===(o=this.extractAttr(e,"showFirstColumn"))||void 0===o?void 0:o.asBool(),showLastColumn:null===(i=this.extractAttr(e,"showLastColumn"))||void 0===i?void 0:i.asBool(),showRowStripes:null===(n=this.extractAttr(e,"showRowStripes"))||void 0===n?void 0:n.asBool(),showColumnStripes:null===(r=this.extractAttr(e,"showColumnStripes"))||void 0===r?void 0:r.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 qf extends Uf{constructor(e,t,o,i){super(e,t,o),this.theme=i}getSheet(){return this.mapOnElements({query:"worksheet",parent:this.rootFile.file.xml},(e=>{const t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:[...this.extractTables(e),...this.extractPivotTables()],isVisible:"visible"===t.state}}))[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:"sheetView"},(e=>{const t=this.querySelector(e,"pane");return{tabSelected:this.extractAttr(e,"tabSelected",{default:!1}).asBool(),showFormulas:this.extractAttr(e,"showFormulas",{default:!1}).asBool(),showGridLines:this.extractAttr(e,"showGridLines",{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,"showRowColHeaders",{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,"xSplit",{default:0}).asNum():0,ySplit:t?this.extractAttr(t,"ySplit",{default:0}).asNum():0}}}))}extractSheetName(){const e=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,o=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:"sheet"},(e=>({relationshipId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetId:this.extractAttr(e,"sheetId",{required:!0}).asString(),sheetName:this.extractAttr(e,"name",{required:!0}).asString(),state:this.extractAttr(e,"state",{default:"visible"}).asString()}))).find((e=>e.relationshipId===t));if(!o)throw new Error("Cannot find corresponding workbook sheet");return o}extractConditionalFormats(){return new zf(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractFigures(e){return this.mapOnElements({parent:e,query:"drawing"},(e=>{var t;const o=null===(t=this.extractAttr(e,"r:id",{required:!0}))||void 0===t?void 0:t.asString(),i=this.getTargetXmlFile(this.relationships[o]);return new Hf(i,this.xlsxFileStructure,this.warningManager).extractFigures()}))[0]||[]}extractTables(e){return this.mapOnElements({query:"tablePart",parent:e},(e=>{var t;const o=null===(t=this.extractAttr(e,"r:id",{required:!0}))||void 0===t?void 0:t.asString(),i=this.getTargetXmlFile(this.relationships[o]);return new Gf(i,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 Wf(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:im.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:nm.toString()}).asNum()}}extractCols(e){return this.mapOnElements({parent:e,query:"cols col"},(e=>{var t,o,i,n,r,s,a;return{width:null===(t=this.extractAttr(e,"width"))||void 0===t?void 0:t.asNum(),customWidth:null===(o=this.extractAttr(e,"customWidth"))||void 0===o?void 0:o.asBool(),bestFit:null===(i=this.extractAttr(e,"bestFit"))||void 0===i?void 0:i.asBool(),hidden:null===(n=this.extractAttr(e,"hidden"))||void 0===n?void 0:n.asBool(),min:null===(r=this.extractAttr(e,"min",{required:!0}))||void 0===r?void 0:r.asNum(),max:null===(s=this.extractAttr(e,"max",{required:!0}))||void 0===s?void 0:s.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,o,i,n,r;return{index:null===(t=this.extractAttr(e,"r",{required:!0}))||void 0===t?void 0:t.asNum(),cells:this.extractCells(e),height:null===(o=this.extractAttr(e,"ht"))||void 0===o?void 0:o.asNum(),customHeight:null===(i=this.extractAttr(e,"customHeight"))||void 0===i?void 0:i.asBool(),hidden:null===(n=this.extractAttr(e,"hidden"))||void 0===n?void 0:n.asBool(),styleIndex:null===(r=this.extractAttr(e,"s"))||void 0===r?void 0:r.asNum()}}))}extractCells(e){return this.mapOnElements({parent:e,query:"c"},(e=>{var t,o,i;return{xc:null===(t=this.extractAttr(e,"r",{required:!0}))||void 0===t?void 0:t.asString(),styleIndex:null===(o=this.extractAttr(e,"s"))||void 0===o?void 0:o.asNum(),type:bm[null===(i=this.extractAttr(e,"t",{default:"n"}))||void 0===i?void 0:i.asString()],value:this.extractChildTextContent(e,"v"),formula:this.extractCellFormula(e)}}))}extractCellFormula(e){var t,o;const i=this.querySelector(e,"f");if(i)return{content:this.extractTextContent(i),sharedIndex:null===(t=this.extractAttr(i,"si"))||void 0===t?void 0:t.asNum(),ref:null===(o=this.extractAttr(i,"ref"))||void 0===o?void 0:o.asString()}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:"hyperlink"},(e=>{var t,o,i,n;const r=null===(t=this.extractAttr(e,"r:id"))||void 0===t?void 0:t.asString();return{xc:null===(o=this.extractAttr(e,"ref",{required:!0}))||void 0===o?void 0:o.asString(),location:null===(i=this.extractAttr(e,"location"))||void 0===i?void 0:i.asString(),display:null===(n=this.extractAttr(e,"display"))||void 0===n?void 0:n.asString(),relTarget:r?this.relationships[r].target:void 0}}))}extractSharedFormulas(e){const t=this.querySelectorAll(e,"f[si][ref]"),o={};for(let e of t){const t=this.extractAttr(e,"si",{required:!0}).asNum(),i=this.extractTextContent(e,{required:!0});o[t]=i}const i=[];for(let e=0;e<Object.keys(o).length;e++)o[e]?i.push(o[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),i.push(""));return i}}class Zf extends Uf{constructor(e,t,o){super(e.styles,e,t),this.theme=o}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"numFmt"},(e=>this.extractNumFormats(e)))}extractNumFormats(e){return{id:this.extractAttr(e,"numFmtId",{required:!0}).asNum(),format:this.extractAttr(e,"formatCode",{required:!0,default:""}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"font"},(e=>this.extractFont(e)))}extractFont(e){var t,o,i,n;const r=this.extractChildAttr(e,"name","val",{default:"Arial"}).asString(),s=this.extractChildAttr(e,"sz","val",{default:W.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===(o=h.attributes.val)||void 0===o?void 0:o.value),u=this.querySelector(e,"strike")||void 0,g=u&&"0"!==(null===(i=u.attributes.val)||void 0===i?void 0:i.value),p=this.querySelector(e,"u")||void 0;return{name:r,size:s,color:a,italic:c,bold:d,underline:p&&"none"!==(null===(n=p.attributes.val)||void 0===n?void 0:n.value),strike:g}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"fill"},(e=>this.extractFill(e)))}extractFill(e){var t;const o=e.children[0];return"patternFill"===o.tagName?{patternType:null===(t=o.attributes.patternType)||void 0===t?void 0:t.value,bgColor:this.extractColor(this.querySelector(o,"bgColor"),this.theme),fgColor:this.extractColor(this.querySelector(o,"fgColor"),this.theme)}:{patternType:"solid",fgColor:this.extractColor(this.querySelectorAll(o,"color")[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"border"},(e=>this.extractBorder(e)))}extractBorder(e){var t,o;const i={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 i.diagonal&&(i.diagonalUp=null===(t=this.extractAttr(e,"diagonalUp"))||void 0===t?void 0:t.asBool(),i.diagonalDown=null===(o=this.extractAttr(e,"diagonalDown"))||void 0===o?void 0:o.asBool()),i}extractSingleBorder(e,t,o){const i=this.querySelector(e,t);if(i&&i.attributes.style)return{style:this.extractAttr(i,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(i.children[0],o,"000000")}}extractAlignment(e){var t,o,i,n,r,s,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===(o=this.extractAttr(e,"wrapText"))||void 0===o?void 0:o.asBool(),indent:null===(i=this.extractAttr(e,"indent"))||void 0===i?void 0:i.asNum(),relativeIndent:null===(n=this.extractAttr(e,"relativeIndent"))||void 0===n?void 0:n.asNum(),justifyLastLine:null===(r=this.extractAttr(e,"justifyLastLine"))||void 0===r?void 0:r.asBool(),shrinkToFit:null===(s=this.extractAttr(e,"shrinkToFit"))||void 0===s?void 0:s.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"),o=this.querySelector(e,"fill"),i=this.querySelector(e,"border"),n=this.querySelector(e,"numFmt"),r=this.querySelector(e,"alignment");return{font:t?this.extractFont(t):void 0,fill:o?this.extractFill(o):void 0,numFmt:n?this.extractNumFormats(n):void 0,alignment:r?this.extractAlignment(r):void 0,border:i?this.extractBorder(i):void 0}}))}getStyles(){return this.mapOnElements({query:"cellXfs xf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"alignment");return{fontId:this.extractAttr(e,"fontId",{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,"fillId",{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,"borderId",{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,"numFmtId",{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}}))}}class jf extends Uf{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"externalBook"},(e=>({rId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:"sheetName"},(e=>this.extractAttr(e,"val",{required:!0}).asString())),datasets:this.extractExternalSheetData(e)})))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:"sheetData"},(e=>{const t=this.mapOnElements({parent:e,query:"cell"},(e=>({xc:this.extractAttr(e,"r",{required:!0}).asString(),value:this.extractChildTextContent(e,"v",{required:!0})}))),o={};for(let e of t)o[e.xc]=e.value;return{sheetId:this.extractAttr(e,"sheetId",{required:!0}).asNum(),data:o}}))}}function Xf(e,t){const o=function(e,t){const o=t[hm],i=o.querySelectorAll(`Override[ContentType="${e}"]`),n=[];for(let e of i){const t=null==e?void 0:e.attributes.PartName.value;n.push(t.substring(1))}return n}(e,t);return function(e,t){const o=[];for(let i of e){const e=Yf(i,t);o.push({file:{fileName:i,xml:t[i]},rels:e?{fileName:e,xml:t[e]}:void 0})}return o}(o,t)}function Yf(e,t){if(e===hm)return"_rels/.rels";let o="";const i=e.split("/");for(let e=0;e<i.length-1;e++)o+=i[e]+"/";return o+="_rels/",o+=i[i.length-1]+".rels",t[o]||(o=void 0),o}class Kf{constructor(e){this.warningManager=new um,this.xmls={};for(let t of Object.keys(e))(t.endsWith(".xml")||t.endsWith(".rels"))&&(this.xmls[t]=_f(new Gp(e[t])))}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new Vf(e.theme,e,this.warningManager).getTheme():void 0,o=e.sharedStrings?new Vf(e.sharedStrings,e,this.warningManager).getSharedStrings():[],i=e.sheets.sort(((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0}))).map((o=>new qf(o,e,this.warningManager,t).getSheet())),n=e.externalLinks.map((t=>new jf(t,e,this.warningManager).getExternalBook())),r=new Zf(e,this.warningManager,t);return{fonts:r.getFonts(),fills:r.getFills(),borders:r.getBorders(),dxfs:r.getDxfs(),numFmts:r.getNumFormats(),styles:r.getStyles(),sheets:i,sharedStrings:o,externalBooks:n}}buildXlsxFileStructure(){const e={sheets:Xf(Qp.sheet,this.xmls),workbook:Xf(Qp.workbook,this.xmls)[0],styles:Xf(Qp.styles,this.xmls)[0],sharedStrings:Xf(Qp.sharedStrings,this.xmls)[0],theme:Xf(Qp.themes,this.xmls)[0],charts:Xf(Qp.chart,this.xmls),figures:Xf(Qp.drawing,this.xmls),tables:Xf(Qp.table,this.xmls),pivots:Xf(Qp.pivot,this.xmls),externalLinks:Xf(Qp.externalLink,this.xmls)};if(!e.workbook.rels)throw Error(r("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:12,sheets:bf(e,this.warningManager),styles:Um(e,this.warningManager),formats:zm(e,this.warningManager),borders:Pm(e,this.warningManager),entities:{},revisionId:Y};return Rf(t,e),Object.keys(e.styles).map((t=>{e.styles[t]=st(e.styles[t])})),t}}function Qf(e){const t=Fu(e);let o=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&Et.test(e.value)){const t=e.value.trim();return o.includes(t)||o.push(t),`${re}${o.indexOf(t)}${re}`}return e.value}))),dependencies:o}}const Jf=12,ev="Sheet1";function tv(e,t){if(!e)return sv();if(e["[Content_Types].xml"]){const o=new Kf(e);if(e=o.convertXlsx(),t)for(let e of o.warningManager.warnings.sort())console.warn(e)}return"version"in(e=Me(e))&&e.version<Jf&&(e=function(e){for(let t=ov.findIndex((t=>t.from===e.version));t<ov.length;t++)e=ov[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,o=new To;for(const i of e.sheets||[])for(const e of i.figures||[])t.has(e.id)&&(e.id+=o.uuidv4()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){e=Object.assign(sv(),e,{version:Jf}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(rv(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(rv(ev,"Sheet1"));return e}(e),e}(e),e}const ov=[{description:"add the `activeSheet` field on data",from:1,to:2,applyMigration:e=>(e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e)},{description:"add an id field in each sheet",from:2,to:3,applyMigration(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}},{description:"activeSheet is now an id, not the name of a sheet",from:3,to:4,applyMigration(e){if(e.sheets&&e.activeSheet){const t=e.sheets.find((t=>t.name===e.activeSheet));e.activeSheet=t.id}return e}},{description:"add figures object in each sheets",from:4,to:5,applyMigration(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}},{description:"normalize the content of the cell if it is a formula to avoid parsing all the formula that vary only by the cells they use",from:5,to:6,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const o=t.cells[e];o.content&&o.content.startsWith("=")&&(o.formula=Qf(o.content))}return e}},{description:"transform chart data structure",from:6,to:7,applyMigration(e){for(let t of e.sheets||[])for(let e in t.figures||[]){const{dataSets:o,...i}=t.figures[e].data,n=[];for(let e of o)if(e.labelCell){const t=Oo(e.dataRange),o=e.labelCell+":"+kt(t.right,t.bottom);n.push(o)}else n.push(e.dataRange);i.dataSetsHaveTitle=Boolean(o[0].labelCell),i.dataSets=n,t.figures[e].data=i}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){var t;const o=[],i=new RegExp(ne,"g");for(let n of e.sheets||[]){if(!n.name)continue;const e=n.name,r=e.replace(i,"_");let s=1,a=r;for(;o.includes(a);)a=`${r}${s}`,s++;n.name=a,o.push(a);const l=t=>{if(void 0===t)return t;let o=t.replace(e,a),i=t;for(;i!==o;)i=o,o=i.replace(e,a);return i};for(let e in n.cells){const t=n.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(l))}for(let e of n.figures||[])if("chart"===e.type){const t=e.data.dataSets.map(l),o=l(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:o}}for(let e of n.conditionalFormats||[]){e.ranges=e.ranges.map(l);for(const o of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===(null===(t=e.rule[o])||void 0===t?void 0:t.type)&&(e.rule[o].value=l(e.rule[o].value))}}return e}},{description:"transform chart data structure with design attributes",from:8,to:9,applyMigration(e){for(const t of e.sheets||[])for(const e of t.figures||[])e.data.background=w,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stacked=!1;return e}},{description:"de-normalize formula to reduce exported json size (~30%)",from:9,to:10,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const o=t.cells[e];if(o.formula){let{text:e,dependencies:t}=o.formula;for(let[o,i]of Object.entries(t)){const t=`\\${re}${o}\\${re}`;e=e.replace(new RegExp(t,"g"),i)}o.content=e,delete o.formula}}return e}},{description:"normalize the formats of the cells",from:10,to:11,applyMigration(e){const t={};for(let o of e.sheets||[])for(let e in o.cells||[]){const i=o.cells[e];i.format&&(i.format=et(i.format,t))}return e.formats=t,e}},{description:"Add isVisible to sheets",from:11,to:12,applyMigration(e){for(let t of e.sheets||[])t.isVisible=!0;return e}}];function iv(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const o=[],i=[],n=e=>{if("CREATE_SHEET"===e.type)o.push(e.sheetId);else if("sheetId"in e&&!o.includes(e.sheetId))return{...e,sheetId:ev};return e};for(const e of t)"REMOTE_REVISION"===e.type?i.push({...e,commands:e.commands.map(n)}):i.push(e);return i}(e,t),t=nv(t,"SORT_CELLS"),t=function(e,t){var o;const i=[],n={};for(const t of e.sheets||[])null===(o=t.figures)||void 0===o||o.forEach((e=>{"chart"===e.tag&&(n[e.id]=e.data)}));for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const o of e.commands){let e=o;switch(o.type){case"CREATE_CHART":n[o.id]=o.definition;break;case"UPDATE_CHART":if(!n[o.id]){console.log(`Fix chart definition: chart with id ${o.id} not found.`);continue}const t={...n[o.id],...o.definition};e={...o,definition:t},n[o.id]=t}t.push(e)}i.push({...e,commands:t})}else i.push(e);return i}(e,t=nv(t,"SET_DECIMAL")),t}function nv(e,t){const o=[];for(const i of e)"REMOTE_REVISION"===i.type?o.push({...i,commands:i.commands.filter((e=>e.type!==t))}):o.push(i);return o}function rv(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:Jf,sheets:[rv(ev,e)],entities:{},styles:{},formats:{},borders:{},revisionId:Y,uniqueFigureIds:!0}}function av(e,t){return{...rv(e,t),charts:[]}}class lv extends Wu{constructor({getters:e,stateObserver:t,range:o,dispatch:i,uuidGenerator:n}){super(t,i),this.range=o,o.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=n}import(e){}export(e){}adaptRanges(e,t){}garbageCollectExternalResources(){}}class cv extends lv{constructor(){super(...arguments),this.borders={}}handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":const t=this.borders[e.sheetId];if(t){const o=t.slice().map((e=>null==e?void 0:e.slice().map((e=>({...e})))));this.history.update("borders",e.sheetIdTo,o)}break;case"DELETE_SHEET":const o={...this.borders};delete o[e.sheetId],this.history.update("borders",o);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_FORMATTING":if(e.border){const t=e.target.map((t=>this.getters.expandZone(e.sheetId,t)));this.setBorders(e.sheetId,t,e.border)}break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target);break;case"REMOVE_COLUMNS_ROWS":for(let t of e.elements)"COL"===e.dimension?this.shiftBordersHorizontally(e.sheetId,t+1,-1):this.shiftBordersVertically(e.sheetId,t+1,-1);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumns(e):this.handleAddRows(e)}}handleAddColumns(e){let t,o;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),t=e.base-1,o=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),t=e.base,o=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,o)}handleAddRows(e){let t,o;"before"===e.position?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity,{moveFirstTopBorder:!0}),t=e.base-1,o=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity,{moveFirstTopBorder:!1}),t=e.base,o=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,o)}getCellBorder({sheetId:e,col:t,row:o}){var i,n,r,s,a,l,c,h,d,u,g,p;const m={top:null===(r=null===(n=null===(i=this.borders[e])||void 0===i?void 0:i[t])||void 0===n?void 0:n[o])||void 0===r?void 0:r.horizontal,bottom:null===(l=null===(a=null===(s=this.borders[e])||void 0===s?void 0:s[t])||void 0===a?void 0:a[o+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[o])||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[o])||void 0===p?void 0:p.vertical};return m.bottom||m.left||m.right||m.top?m:null}ensureColumnBorderContinuity(e,t,o){const i=Le(t+1,o);for(let n=0;n<this.getters.getNumberRows(e);n++){const r=this.getCellBorder({sheetId:e,col:t,row:n}),s=this.getCellBorder({sheetId:e,col:o,row:n});if(r&&s){const t=this.getCommonSides(r,s);for(let o of i)this.addBorder(e,o,n,t)}}}ensureRowBorderContinuity(e,t,o){const i=Le(t+1,o);for(let n=0;n<this.getters.getNumberCols(e);n++){const r=this.getCellBorder({sheetId:e,col:n,row:t}),s=this.getCellBorder({sheetId:e,col:n,row:o});if(r&&s){const t=this.getCommonSides(r,s);for(let o of i)this.addBorder(e,n,o,t)}}}getCommonSides(e,t){const o={};for(let i of["top","bottom","left","right"])e[i]&&e[i]===t[i]&&(o[i]=e[i]);return o}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsRange(e){return this.borders[e]?Le(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,o,{moveFirstLeftBorder:i}={}){this.borders[e]&&(o<0&&this.moveBordersOfColumn(e,t,o,"vertical",{destructive:!1}),this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>o<0?e-t:t-e)).forEach((n=>{(n===t&&i||n!==t)&&this.moveBordersOfColumn(e,n,o,"vertical"),this.moveBordersOfColumn(e,n,o,"horizontal")})))}shiftBordersVertically(e,t,o,{moveFirstTopBorder:i}={}){this.borders[e]&&(o<0&&this.moveBordersOfRow(e,t,o,"horizontal",{destructive:!1}),this.getRowsRange(e).filter((e=>e>=t)).sort(((e,t)=>o<0?e-t:t-e)).forEach((n=>{(n===t&&i||n!==t)&&this.moveBordersOfRow(e,n,o,"horizontal"),this.moveBordersOfRow(e,n,o,"vertical")})))}moveBordersOfRow(e,t,o,i,{destructive:n}={destructive:!0}){const r=this.borders[e];r&&this.getColumnsWithBorders(e).forEach((s=>{var a,l,c,h;const d=null===(l=null===(a=r[s])||void 0===a?void 0:a[t+o])||void 0===l?void 0:l[i],u=null===(h=null===(c=r[s])||void 0===c?void 0:c[t])||void 0===h?void 0:h[i];this.history.update("borders",e,s,t+o,i,n?u:u||d),this.history.update("borders",e,s,t,i,void 0)}))}moveBordersOfColumn(e,t,o,i,{destructive:n}={destructive:!0}){const r=this.borders[e];r&&this.getRowsRange(e).forEach((s=>{var a,l,c,h;const d=null===(l=null===(a=r[t+o])||void 0===a?void 0:a[s])||void 0===l?void 0:l[i],u=null===(h=null===(c=r[t])||void 0===c?void 0:c[s])||void 0===h?void 0:h[i];this.history.update("borders",e,t+o,s,i,n?u:u||d),this.history.update("borders",e,t,s,i,void 0)}))}setBorder(e,t,o,i,n=!0){var r,s,a,l,c,h,d,u,g,p,m,f,v,b,C,S;!n&&(null===(l=null===(a=null===(s=null===(r=this.borders)||void 0===r?void 0:r[e])||void 0===s?void 0:s[t])||void 0===a?void 0:a[o])||void 0===l?void 0:l.vertical)||this.history.update("borders",e,t,o,"vertical",null==i?void 0:i.left),!n&&(null===(u=null===(d=null===(h=null===(c=this.borders)||void 0===c?void 0:c[e])||void 0===h?void 0:h[t])||void 0===d?void 0:d[o])||void 0===u?void 0:u.horizontal)||this.history.update("borders",e,t,o,"horizontal",null==i?void 0:i.top),!n&&(null===(f=null===(m=null===(p=null===(g=this.borders)||void 0===g?void 0:g[e])||void 0===p?void 0:p[t+1])||void 0===m?void 0:m[o])||void 0===f?void 0:f.vertical)||this.history.update("borders",e,t+1,o,"vertical",null==i?void 0:i.right),!n&&(null===(S=null===(C=null===(b=null===(v=this.borders)||void 0===v?void 0:v[e])||void 0===b?void 0:b[t])||void 0===C?void 0:C[o+1])||void 0===S?void 0:S.horizontal)||this.history.update("borders",e,t,o+1,"horizontal",null==i?void 0:i.bottom)}clearBorders(e,t){for(let o of t){for(let t=o.top;t<=o.bottom;t++){this.history.update("borders",e,o.right+1,t,"vertical",void 0);for(let i=o.left;i<=o.right;i++)this.history.update("borders",e,i,t,void 0)}for(let t=o.left;t<=o.right;t++)this.history.update("borders",e,t,o.bottom+1,"horizontal",void 0)}}addBorder(e,t,o,i){this.setBorder(e,t,o,{...this.getCellBorder({sheetId:e,col:t,row:o}),...i})}setBorders(e,t,o){if("clear"===o)return this.clearBorders(e,t);for(let i of t){if("h"===o||"hv"===o||"all"===o)for(let t=i.top+1;t<=i.bottom;t++)for(let o=i.left;o<=i.right;o++)this.addBorder(e,o,t,{top:q});if("v"===o||"hv"===o||"all"===o)for(let t=i.top;t<=i.bottom;t++)for(let o=i.left+1;o<=i.right;o++)this.addBorder(e,o,t,{left:q});if("left"===o||"all"===o||"external"===o)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:q});if("right"===o||"all"===o||"external"===o)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right+1,t,{left:q});if("top"===o||"all"===o||"external"===o)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:q});if("bottom"===o||"all"===o||"external"===o)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom+1,{top:q})}}addBordersToMerge(e,t){const{left:o,right:i,top:n,bottom:r}=t,s=this.getCellBorder({sheetId:e,col:o,row:n}),a=this.getCellBorder({sheetId:e,col:i,row:r});this.clearBorders(e,[t]),(null==s?void 0:s.top)&&this.setBorders(e,[{...t,bottom:n}],"top"),(null==s?void 0:s.left)&&this.setBorders(e,[{...t,right:o}],"left"),((null==a?void 0:a.bottom)||(null==s?void 0:s.bottom))&&this.setBorders(e,[{...t,top:r}],"bottom"),((null==a?void 0:a.right)||(null==s?void 0:s.right))&&this.setBorders(e,[{...t,left:i}],"right")}import(e){if(e.borders)for(let t of e.sheets)for(let[o,i]of Object.entries(t.cells))if(null==i?void 0:i.border){const n=e.borders[i.border],{col:r,row:s}=Dt(o);this.setBorder(t.id,r,s,n,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Oo(e))}export(e){let t=0;const o={};function i(e){for(let[t,i]of Object.entries(o))if(Te(i)===Te(e))return parseInt(t,10);return o[++t]=e,t}for(let t of e.sheets)for(let e=0;e<t.colNumber;e++)for(let o=0;o<t.rowNumber;o++){const n=this.getCellBorder({sheetId:t.id,col:e,row:o});if(n){const r=kt(e,o),s=t.cells[r],a=i(n);s?s.border=a:t.cells[r]={border:a}}}e.borders=o}exportForExcel(e){this.export(e)}}cv.getters=["getCellBorder"];const hv=new RegExp(String.fromCharCode(160),"g");class dv extends lv{constructor(){super(...arguments),this.nextId=1,this.cells={}}adaptRanges(e,t){for(const o of Object.keys(this.cells))for(const i of Object.values(this.cells[o]||{}))if(i.isFormula)for(const n of i.dependencies)if(!t||n.sheetId===t){const t=e(n);"NONE"!==t.changeType&&this.history.update("cells",o,i.id,"dependencies",i.dependencies.indexOf(n),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":case"CLEAR_CELL":return this.checkCellOutOfSheet(e.sheetId,e.col,e.row);default:return 0}}handle(e){switch(e.type){case"SET_FORMATTING":"style"in e&&this.setStyle(e.sheetId,e.target,e.style),"format"in e&&void 0!==e.format&&this.setFormatter(e.sheetId,e.target,e.format);break;case"CLEAR_FORMATTING":this.clearFormatting(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case"UPDATE_CELL":this.updateCell(e.sheetId,e.col,e.row,e);break;case"CLEAR_CELL":this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col,row:e.row,content:"",style:null,format:""})}}setFormatter(e,t,o){for(let i of t)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,format:o})}clearFormatting(e,t){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,style:null,format:""})}handleAddColumnsRows(e,t){let o,i;"before"===e.position?(o=Le(e.base,e.base+e.quantity),i=e.base+e.quantity):(o=Le(e.base+1,e.base+e.quantity+1),i=e.base),t(e.sheetId,i,o)}import(e){for(let t of e.sheets)for(let o in t.cells){const i=t.cells[o],{col:n,row:r}=Dt(o);if((null==i?void 0:i.content)||(null==i?void 0:i.format)||(null==i?void 0:i.style)){const o=this.importCell(t.id,i,e.styles,e.formats);this.history.update("cells",t.id,o.id,o),this.dispatch("UPDATE_CELL_POSITION",{cellId:o.id,col:n,row:r,sheetId:t.id})}}}export(e){const t={},o={};for(let i of e.sheets){const e={},n=Object.keys(this.cells[i.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const i of n){const n=this.getters.getCell(i);e[kt(i.col,i.row)]={style:n.style?et(n.style,t):void 0,format:n.format?et(n.format,o):void 0,content:n.content||void 0}}i.cells=e}e.styles=t,e.formats=o}importCell(e,t,o,i){const n=t.style&&o[t.style]||void 0,r=t.format&&i[t.format]||void 0,s=this.getNextUid();return this.createCell(s,(null==t?void 0:t.content)||"",r,n,e)}exportForExcel(e){this.export(e)}getCells(e){return this.cells[e]||{}}getCellById(e){for(const t in this.cells){const o=this.cells[t][e];if(o)return o}}buildFormulaContent(e,t,o){const i=o||[...t.dependencies];return tt(t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=i.shift();return this.getters.getRangeString(t,e)}return t.value})))}getFormulaCellContent(e,t){return this.buildFormulaContent(e,t)}getCellStyle(e){var t;return(null===(t=this.getters.getCell(e))||void 0===t?void 0:t.style)||{}}zoneToXC(e,t,o=[{colFixed:!1,rowFixed:!1}]){const i=kt((t=this.getters.expandZone(e,t)).left,t.top,o[0]),n=kt(t.right,t.bottom,o.length>1?o[1]:o[0]),r=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),s=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=r.col===s.col&&r.row===s.row;return i==n||a?i:i+":"+n}setStyle(e,t,o){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++){const i=this.getters.getCell({sheetId:e,col:t,row:n});this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,style:o?{...null==i?void 0:i.style,...o}:void 0})}}copyColumnStyle(e,t,o){for(let i=0;i<this.getters.getNumberRows(e);i++){const n=this.getFormat(e,t,i);if(n.style||n.format)for(let t of o)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,...n})}}copyRowStyle(e,t,o){for(let i=0;i<this.getters.getNumberCols(e);i++){const n=this.getFormat(e,i,t);if(n.style||n.format)for(let t of o)this.dispatch("UPDATE_CELL",{sheetId:e,col:i,row:t,...n})}}getFormat(e,t,o){const i={},n=this.getters.getMainCellPosition({sheetId:e,col:t,row:o}),r=this.getters.getCell(n);return r&&(r.style&&(i.style=r.style),r.format&&(i.format=r.format)),i}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,o,i){var n;const r=this.getters.getCell({sheetId:e,col:t,row:o}),s="content"in i||"formula"in i,a=s?(null===(n=i.content)||void 0===n?void 0:n.replace(hv,""))||"":(null==r?void 0:r.content)||"";let l;l=void 0!==i.style?i.style||void 0:r?r.style:void 0;let c=("format"in i?i.format:r&&r.format)||fo(a);if((s&&!a&&!i.formula||!s&&(!r||""===r.content))&&!l&&!c)return void(r&&(this.history.update("cells",e,r.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:o,sheetId:e})));const h=(null==r?void 0:r.id)||this.getNextUid(),d=this.createCell(h,a,c,l,e);this.history.update("cells",e,d.id,d),this.dispatch("UPDATE_CELL_POSITION",{cellId:d.id,col:t,row:o,sheetId:e})}createCell(e,t,o,i,n){if(!t.startsWith("="))return this.createLiteralCell(e,t,o,i);try{return this.createFormulaCell(e,t,o,i,n)}catch(n){return this.createErrorFormula(e,t,o,i,n)}}createLiteralCell(e,t,o,i){return{id:e,content:t,style:i,format:o,isFormula:!1}}createFormulaCell(e,t,o,i,n){const r=Uu(t);return r.dependencies.length?this.createFormulaCellWithDependencies(e,r,o,i,n):{id:e,content:t,style:i,format:o,isFormula:!0,compiledFormula:r,dependencies:[]}}createFormulaCellWithDependencies(e,t,o,i,n){const r=t.dependencies.map((e=>this.getters.getRangeFromSheetXC(n,e))),s=this.buildFormulaContent.bind(this);return{id:e,get content(){return s(n,{dependencies:this.dependencies,compiledFormula:this.compiledFormula})},style:i,format:o,isFormula:!0,compiledFormula:t,dependencies:r}}createErrorFormula(e,t,o,i,n){return{id:e,content:t,style:i,format:o,isFormula:!0,compiledFormula:{dependencies:[],tokens:eu(t),execute:function(){throw n}},dependencies:[]}}checkCellOutOfSheet(e,t,o){if(!this.getters.tryGetSheet(e))return 27;return Vo(t,o,this.getters.getSheetZone(e))?0:18}}dv.getters=["zoneToXC","getCells","getFormulaCellContent","getCellStyle","buildFormulaContent","getCellById"];class uv extends lv{constructor(){super(...arguments),this.charts={},this.createChart=function(e){const t=In.getAll();return function(o,i,n){const r=t.find((e=>e.match(i.type)));if(!r)throw new Error(`No builder for this chart: ${i.type}`);return r.createChart(i,n,e)}}(this.getters),this.validateChartDefinition=e=>function(e,t){const o=In.getAll().find((e=>e.match(t.type)));if(!o)throw new Error("Unknown chart type.");return o.validateChartDefinition(e,t)}(this,e.definition)}adaptRanges(e){for(const[t,o]of Object.entries(this.charts))this.history.update("charts",t,null==o?void 0:o.updateRanges(e))}allowDispatch(e){switch(e.type){case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists));default:return 0}}handle(e){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 o=this.getters.getFigures(e.sheetId);for(const i of o)if("chart"===i.tag){const o=i.id.split(Q).pop(),n=`${e.sheetIdTo}${Q}${o}`,r=null===(t=this.charts[i.id])||void 0===t?void 0:t.copyForSheetId(e.sheetIdTo);r&&this.dispatch("CREATE_CHART",{id:n,position:{x:i.x,y:i.y},size:{width:i.width,height:i.height},definition:r.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 o=null===(t=this.charts[e])||void 0===t?void 0:t.type;if(!o)throw new Error("Chart not defined.");return o}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 o=null===(t=this.charts[e])||void 0===t?void 0:t.getDefinition();if(!o)throw new Error(`There is no chart with the given figureId: ${e}`);return o}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 o of e.sheets){const e=this.getters.getFigures(o.id),i=[];for(let o of e){const e=o;if(e&&"chart"===e.tag){const o=null===(t=this.charts[e.id])||void 0===t?void 0:t.getDefinition();o&&(e.data=o,i.push(e))}else i.push(e)}o.figures=i}}exportForExcel(e){var t;for(let o of e.sheets){const e=this.getters.getFigures(o.id),i=[];for(let o of e)if(o&&"chart"===o.tag){const e=null===(t=this.charts[o.id])||void 0===t?void 0:t.getDefinitionForExcel();e&&i.push({...o,data:e})}o.charts=i}}addFigure(e,t,o={x:0,y:0},i={width:536,height:335}){if(this.getters.getFigure(t,e))return;const n={id:e,x:o.x,y:o.y,width:i.width,height:i.height,tag:"chart"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:n})}addChart(e,t){const o=this.getters.getFigureSheetId(e);o&&this.history.update("charts",e,this.createChart(e,t,o))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.id)?84:0}checkChartExists(e){return this.getters.getFigureSheetId(e.id)?0:85}}function gv(e){return""===e?NaN:Number(e)}uv.getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];class pv extends lv{constructor(){super(...arguments),this.cfRules={}}loopThroughRangesOfSheet(e,t){for(const o of this.cfRules[e])for(const i of o.ranges){const n=t(i);switch(n.changeType){case"REMOVE":let t=o.ranges.slice();t.splice(o.ranges.indexOf(i),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"ranges",t):this.removeConditionalFormatting(o.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"ranges",o.ranges.indexOf(i),n.range)}}}adaptRanges(e,t){if(t)this.loopThroughRangesOfSheet(t,e);else for(const t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,e)}allowDispatch(e){switch(e.type){case"ADD_CONDITIONAL_FORMAT":return this.checkValidations(e,this.checkCFRule,this.checkEmptyRange);case"MOVE_CONDITIONAL_FORMAT":return this.checkValidReordering(e.cfId,e.direction,e.sheetId)}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const o={...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))};this.addConditionalFormatting(o,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId);break;case"MOVE_CONDITIONAL_FORMAT":this.reorderConditionalFormatting(e.cfId,e.direction,e.sheetId)}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map((e=>this.mapToConditionalFormatInternal(t.id,e)))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map((e=>this.mapToConditionalFormat(t.id,e))))}exportForExcel(e){this.export(e)}getConditionalFormats(e){var t;return(null===(t=this.cfRules[e])||void 0===t?void 0:t.map((t=>this.mapToConditionalFormat(e,t))))||[]}getRulesSelection(e,t){const o=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{o.add(e)}))})),Array.from(o)}getRulesByZone(e,t){const o=new Set;for(let i=t.top;i<=t.bottom;i++)for(let n=t.left;n<=t.right;n++){this.getRulesByCell(e,n,i).forEach((e=>{o.add(e.id)}))}return o}getRulesByCell(e,t,o){const i=[];for(let n of this.cfRules[e])for(let e of n.ranges)Vo(t,o,e.zone)&&i.push(n);return new Set(i.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e)))}}mapToConditionalFormatInternal(e,t){const o={...t,ranges:t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)))};return o}addConditionalFormatting(e,t){const o=this.cfRules[t].slice(),i=o.findIndex((t=>t.id===e.id)),n=this.mapToConditionalFormatInternal(t,e);i>-1?o.splice(i,1,n):o.push(n),this.history.update("cfRules",t,o)}checkValidReordering(e,t,o){if(!this.cfRules[o])return 27;const i=this.cfRules[o].findIndex((t=>t.id===e));if(-1===i)return 71;const n="up"===t?i-1:i+1;return n<0||n>=this.cfRules[o].length?71:0}checkEmptyRange(e){return e.ranges.length?0:24}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber(2,["Between","NotBetween"]),this.checkOperatorArgsNumber(1,["BeginsWith","ContainsText","EndsWith","GreaterThan","GreaterThanOrEqual","LessThan","LessThanOrEqual","NotContains"]),this.checkOperatorArgsNumber(0,["IsEmpty","IsNotEmpty"]));case"ColorScaleRule":return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case"IconSetRule":return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)))}return 0}checkOperatorArgsNumber(e,t){if(e>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");return o=>{if(t.includes(o.operator)){const t=[],i=e=>void 0===e||""===e;return e>=1&&i(o.values[0])&&t.push(51),e>=2&&i(o.values[1])&&t.push(52),t.length?t:0}return 0}}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return 53;case"max":return 55;case"mid":return 54;case"upperInflectionPoint":return 56;case"lowerInflectionPoint":return 57}return 0}checkFormulaCompilation(e,t){if("formula"!==e.type)return 0;try{Uu(e.value||"")}catch(e){switch(t){case"min":return 58;case"max":return 60;case"mid":return 59;case"upperInflectionPoint":return 61;case"lowerInflectionPoint":return 62}}return 0}checkThresholds(e){return this.batchValidations((t=>e(t.minimum,"min")),(t=>e(t.maximum,"max")),(t=>t.midpoint?e(t.midpoint,"mid"):0))}checkInflectionPoints(e){return this.batchValidations((t=>e(t.lowerInflectionPoint,"lowerInflectionPoint")),(t=>e(t.upperInflectionPoint,"upperInflectionPoint")))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,o=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(o)?48:0}checkMinBiggerThanMax(e){const t=e.minimum.value,o=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&gv(t)>=gv(o)?47:0}checkMidBiggerThanMax(e){var t;const o=null===(t=e.midpoint)||void 0===t?void 0:t.value,i=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&gv(o)>=gv(i)?49:0}checkMinBiggerThanMid(e){var t;const o=e.minimum.value,i=null===(t=e.midpoint)||void 0===t?void 0:t.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&gv(o)>=gv(i)?50:0}removeConditionalFormatting(e,t){const o=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==o){const e=this.cfRules[t].slice();e.splice(o,1),this.history.update("cfRules",t,e)}}reorderConditionalFormatting(e,t,o){const i=this.cfRules[o].findIndex((t=>t.id===e)),n="up"===t?i-1:i+1;if(!(n<0||n>=this.cfRules[o].length)&&-1!==i&&-1!==n){const e=[...this.cfRules[o]],t=e[i];e[i]=e[n],e[n]=t,this.history.update("cfRules",o,e)}}}pv.getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];class mv extends lv{constructor(){super(...arguments),this.figures={}}allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkFigureDuplicate(e.figure.id);case"UPDATE_FIGURE":case"DELETE_FIGURE":return this.checkFigureExists(e.sheetId,e.id);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":this.addFigure(e.figure,e.sheetId);break;case"UPDATE_FIGURE":const{type:t,sheetId:o,...i}=e,n=i;this.updateFigure(o,n);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId)}}updateFigure(e,t){if("id"in t)for(const[o,i]of Object.entries(t))switch(o){case"x":case"y":void 0!==i&&this.history.update("figures",e,t.id,o,Math.max(i,0));break;case"width":case"height":void 0!==i&&this.history.update("figures",e,t.id,o,i)}}addFigure(e,t){this.history.update("figures",t,e.id,e)}deleteSheet(e){this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){var o;return void 0===(null===(o=this.figures[e])||void 0===o?void 0:o[t])?70:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>null==t?void 0:t[e]))?82:0}getFigures(e){return Object.values(this.figures[e]||{}).filter(Qe)}getFigure(e,t){var o;return null===(o=this.figures[e])||void 0===o?void 0:o[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>{var o;return void 0!==(null===(o=this.figures[t])||void 0===o?void 0:o[e])}))}import(e){for(let t of e.sheets){const e={};t.figures.forEach((t=>{e[t.id]=t})),this.figures[t.id]=e}}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const o=void 0;t.figures.push({...e,data:o})}}exportForExcel(e){this.export(e)}}mv.getters=["getFigures","getFigure","getFigureSheetId"];class fv{constructor(e){this.filters=[],this.zone=e;const t=new To;this.id=t.uuidv4();for(const o of Le(e.left,e.right+1)){const e={...this.zone,left:o,right:o};this.filters.push(new vv(t.uuidv4(),e))}}get contentZone(){if(this.zone.bottom!==this.zone.top)return{...this.zone,top:this.zone.top+1}}getFilterId(e){var t;return null===(t=this.filters.find((t=>t.col===e)))||void 0===t?void 0:t.id}clone(){return new fv(this.zone)}}class vv{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 bv extends lv{constructor(){super(...arguments),this.tables={}}allowDispatch(e){switch(e.type){case"CREATE_FILTER_TABLE":if(!Jo(...e.target))return 81;const t=$o(...e.target),o=()=>this.getFilterTables(e.sheetId).some((e=>Uo(e.zone,t)))?78:0,i=()=>{const o=this.getters.getMergesInZone(e.sheetId,t);for(let e of o)if(Uo(t,e))return 80;return 0};return this.checkValidations(e,o,i);case"ADD_MERGE":for(let t of e.target)for(let o of this.getFilterTables(e.sheetId))if(Uo(o.zone,t))return 80}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break;case"DUPLICATE_SHEET":this.history.update("tables",e.sheetIdTo,Me(this.tables[e.sheetId]));break;case"ADD_COLUMNS_ROWS":this.onAddColumnsRows(e);break;case"REMOVE_COLUMNS_ROWS":this.onDeleteColumnsRows(e);break;case"CREATE_FILTER_TABLE":{const t=$o(...e.target),o=this.createFilterTable(t);this.history.update("tables",e.sheetId,o.id,o);break}case"REMOVE_FILTER_TABLE":{const t={};for(const o of this.getFilterTables(e.sheetId))e.target.every((e=>!Po(e,o.zone)))&&(t[o.id]=o);this.history.update("tables",e.sheetId,t);break}case"UPDATE_CELL":{const t=e.sheetId;for(let o of this.getFilterTables(t))this.canUpdateCellCmdExtendTable(e,o)&&this.extendTableDown(t,o);break}}}getFilters(e){return this.getFilterTables(e).map((e=>e.filters)).flat()}getFilterTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(Qe):[]}getFilter(e){var t;return null===(t=this.getFilterTable(e))||void 0===t?void 0:t.filters.find((t=>t.col===e.col))}getFilterId(e){var t;return null===(t=this.getFilter(e))||void 0===t?void 0:t.id}getFilterTable({sheetId:e,col:t,row:o}){return this.getFilterTables(e).find((e=>Vo(t,o,e.zone)))}getFilterTablesInZone(e,t){return this.getFilterTables(e).filter((e=>zo(e.zone,t)))}doesZonesContainFilter(e,t){for(const o of t)for(const t of this.getFilterTables(e))if(Po(o,t.zone))return!0;return!1}onAddColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const o=_o(t.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),i=[];for(const o of t.filters){const t=_o(o.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);i.push(new vv(o.id,t))}if(i.length<Wo(o).width){for(let e=o.left;e<=o.right;e++)i.find((t=>t.col===e))||i.push(new vv(this.uuidGenerator.uuidv4(),{...o,left:e,right:e}));i.sort(((e,t)=>e.col-t.col))}this.history.update("tables",e.sheetId,t.id,"zone",o),this.history.update("tables",e.sheetId,t.id,"filters",i)}}onDeleteColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const o=ko(t.zone,"COL"===e.dimension?"left":"top",e.elements);if(o){if(No(o)!==No(t.zone)){const i=[];for(const o of t.filters){const t=ko(o.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.elements);t&&i.push(new vv(o.id,t))}this.history.update("tables",e.sheetId,t.id,"zone",o),this.history.update("tables",e.sheetId,t.id,"filters",i)}}else{const o={...this.tables[e.sheetId]};delete o[t.id],this.history.update("tables",e.sheetId,o)}}}createFilterTable(e){return new fv(e)}extendTableDown(e,t){const o={...t.zone,bottom:t.zone.bottom+1};this.history.update("tables",e,t.id,"zone",o);for(let o=0;o<t.filters.length;o++){const i=t.filters[o],n={...i.zoneWithHeaders,bottom:i.zoneWithHeaders.bottom+1};this.history.update("tables",e,t.id,"filters",o,"zoneWithHeaders",n)}}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:o,row:i},n){var r;if(!e)return;const s=n.zone;if(!(s.bottom+1===i&&o>=s.left&&o<=s.right))return!1;for(const e of Le(s.left,s.right+1)){const o={sheetId:t,col:e,row:i};if(null===(r=this.getters.getCell(o))||void 0===r?void 0:r.content)return!1;if(this.getters.getFilter(o))return!1;if(this.getters.isInMerge(o))return!1}return!0}import(e){for(const t of e.sheets)for(const e of t.filterTables||[]){const o=this.createFilterTable(Oo(e.range));this.history.update("tables",t.id,o.id,o)}}export(e){for(const t of e.sheets)for(const e of this.getFilterTables(t.id))t.filterTables.push({range:No(e.zone)})}exportForExcel(e){this.export(e)}}bv.getters=["doesZonesContainFilter","getFilter","getFilters","getFilterTable","getFilterTables","getFilterTablesInZone","getFilterId"];class Cv extends lv{constructor(){super(...arguments),this.sizes={}}handle(e){var t,o,i;switch(e.type){case"CREATE_SHEET":{const t=this.computeSheetSizes(e.sheetId),o={COL:t.COL.map((e=>({manualSize:void 0,computedSize:ot(e)}))),ROW:t.ROW.map((e=>({manualSize:void 0,computedSize:ot(e)})))};this.history.update("sizes",e.sheetId,o);break}case"DUPLICATE_SHEET":for(const t of this.sizes[e.sheetId].ROW)t.computedSize();for(const t of this.sizes[e.sheetId].COL)t.computedSize();this.history.update("sizes",e.sheetIdTo,Me(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 o of[...e.elements].sort(((e,t)=>t-e)))t.splice(o,1);const o=Math.min(...e.elements);t=t.map(((t,i)=>"ROW"===e.dimension&&i>=o?{manualSize:t.manualSize,computedSize:ot((()=>this.getRowTallestCellSize(e.sheetId,i)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];const o=nt(e.position,e.base),i=t[e.base];t.splice(o,0,...Array(e.quantity).fill(i)),t=t.map(((t,o)=>"ROW"===e.dimension&&o>e.base+e.quantity?{manualSize:t.manualSize,computedSize:ot((()=>this.getRowTallestCellSize(e.sheetId,o)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"RESIZE_COLUMNS_ROWS":for(let t of e.elements)if("ROW"===e.dimension){const o=this.getRowTallestCellSize(e.sheetId,t);this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:ot(o)})}else this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:ot(e.size||N)});break;case"UPDATE_CELL":if(!(null===(i=null===(o=null===(t=this.sizes[e.sheetId])||void 0===t?void 0:t.ROW)||void 0===o?void 0:o[e.row])||void 0===i?void 0:i.manualSize)){const{sheetId:t,row:o}=e;this.history.update("sizes",t,"ROW",o,"computedSize",ot((()=>this.getRowTallestCellSize(t,o))))}break;case"ADD_MERGE":case"REMOVE_MERGE":for(let t of e.target)for(let o of Le(t.top,t.bottom+1)){const t=this.getRowTallestCellSize(e.sheetId,o);t!==this.getRowSize(e.sheetId,o)&&this.history.update("sizes",e.sheetId,"ROW",o,"computedSize",ot(t))}}}getColSize(e,t){return this.getHeaderSize(e,"COL",t)}getRowSize(e,t){return this.getHeaderSize(e,"ROW",t)}getHeaderSize(e,t,o){var i,n,r,s;return Math.round((null===(n=null===(i=this.sizes[e])||void 0===i?void 0:i[t][o])||void 0===n?void 0:n.manualSize)||(null===(s=null===(r=this.sizes[e])||void 0===r?void 0:r[t][o])||void 0===s?void 0:s.computedSize())||this.getDefaultHeaderSize(t))}computeSheetSizes(e){var t,o;const i={COL:[],ROW:[]};for(let t of Le(0,this.getters.getNumberCols(e)))i.COL.push(this.getHeaderSize(e,"COL",t));for(let n of Le(0,this.getters.getNumberRows(e))){let r=null===(o=null===(t=this.sizes[e])||void 0===t?void 0:t.ROW)||void 0===o?void 0:o[n].manualSize;if(!r){r=this.getRowTallestCellSize(e,n)}i.ROW.push(r)}return i}getDefaultHeaderSize(e){return"COL"===e?N:_}getCellHeight(e){const t=this.getters.getMerge(e);if(t&&t.bottom!==t.top)return _;const o=this.getters.getCell(e);return De(Pe(null==o?void 0:o.style))+2*L}getRowTallestCellSize(e,t){const o=this.getters.getRowCells(e,t);let i=0;for(let e=0;e<o.length;e++){const t=this.getters.getCellById(o[e]);if(!t)continue;const n=this.getters.getCellPosition(t.id),r=this.getCellHeight(n);r>i&&r>_&&(i=r)}return i<=_?_:i}import(e){for(let t of e.sheets){const e={COL:[],ROW:[]};for(let[o,i]of Object.entries(t.rows))i.size&&(e.ROW[o]=i.size);for(let[o,i]of Object.entries(t.cols))i.size&&(e.COL[o]=i.size);const o=this.computeSheetSizes(t.id);this.sizes[t.id]={COL:o.COL.map(((t,o)=>({manualSize:e.COL[o],computedSize:ot(t)}))),ROW:o.ROW.map(((t,o)=>({manualSize:e.ROW[o],computedSize:ot(t)})))}}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){var o,i;for(let n of e.sheets){void 0===n.rows&&(n.rows={});for(let e of Le(0,this.getters.getNumberRows(n.id)))(t||(null===(o=this.sizes[n.id].ROW[e])||void 0===o?void 0:o.manualSize))&&(n.rows[e]={...n.rows[e],size:this.getRowSize(n.id,e)});void 0===n.cols&&(n.cols={});for(let e of Le(0,this.getters.getNumberCols(n.id)))(t||(null===(i=this.sizes[n.id].COL[e])||void 0===i?void 0:i.manualSize))&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}}Cv.getters=["getRowSize","getColSize"];class Sv extends lv{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),o="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=o?66:Math.min(...e.elements)<0||Math.max(...e.elements)>o?86:0}case"REMOVE_COLUMNS_ROWS":return this.getters.tryGetSheet(e.sheetId)?this.canRemoveHeaders(e.sheetId,e.dimension,e.elements)?0:8: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,Me(this.hiddenHeaders[e.sheetId]));break;case"DELETE_SHEET":this.history.update("hiddenHeaders",e.sheetId,void 0);break;case"REMOVE_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let o of[...e.elements].sort(((e,t)=>t-e)))t.splice(o,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]],o=nt(e.position,e.base);t.splice(o,0,...Array(e.quantity).fill(!1)),this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"HIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!0);break;case"UNHIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!1)}}canRemoveHeaders(e,t,o){const i=this.getAllVisibleHeaders(e,t);return n=o,!i.every((e=>n.includes(e)));var n}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]}getHiddenColsGroups(e){const t=[[]],o=this.hiddenHeaders[e].COL;for(let e=0;e<o.length;e++){o[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getHiddenRowsGroups(e){const t=[[]],o=this.hiddenHeaders[e].ROW;for(let e=0;e<o.length;e++){o[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getAllVisibleHeaders(e,t){return Le(0,this.hiddenHeaders[e][t].length).filter((o=>!this.hiddenHeaders[e][t][o]))}import(e){var t,o;for(let i of e.sheets){this.hiddenHeaders[i.id]={COL:[],ROW:[]};for(let e=0;e<i.rowNumber;e++)this.hiddenHeaders[i.id].ROW[e]=Boolean(null===(t=i.rows[e])||void 0===t?void 0:t.isHidden);for(let e=0;e<i.colNumber;e++)this.hiddenHeaders[i.id].COL[e]=Boolean(null===(o=i.cols[e])||void 0===o?void 0:o.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let o of e.sheets){void 0===o.rows&&(o.rows={});for(let e=0;e<this.getters.getNumberRows(o.id);e++)(t||this.hiddenHeaders[o.id].ROW[e])&&(void 0===o.rows[e]&&(o.rows[e]={}),o.rows[e].isHidden=this.hiddenHeaders[o.id].ROW[e]);void 0===o.cols&&(o.cols={});for(let e=0;e<this.getters.getNumberCols(o.id);e++)(t||this.hiddenHeaders[o.id].COL[e])&&(void 0===o.cols[e]&&(o.cols[e]={}),o.cols[e].isHidden=this.hiddenHeaders[o.id].COL[e])}}}Sv.getters=["canRemoveHeaders","getHiddenColsGroups","getHiddenRowsGroups","isRowHiddenByUser","isColHiddenByUser"];class Ev extends lv{constructor(e){super(e),this.images={},this.syncedImages=new Set,this.fileStore=e.external.fileStore}allowDispatch(e){return"CREATE_IMAGE"===e.type&&this.getters.getFigure(e.sheetId,e.figureId)?28:0}handle(e){switch(e.type){case"CREATE_IMAGE":this.addFigure(e.figureId,e.sheetId,e.position,e.size),this.history.update("images",e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const o of t)if("image"===o.tag){const t=o.id.split(Q).pop(),i=`${e.sheetIdTo}${Q}${t}`,n=this.getImage(o.id);if(n){const t={width:o.width,height:o.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:i,position:{x:o.x,y:o.y},size:t,definition:Me(n)})}}break}case"DELETE_FIGURE":this.history.update("images",e.sheetId,e.id,void 0);break;case"DELETE_SHEET":this.history.update("images",e.sheetId,void 0)}}garbageCollectExternalResources(){var e;const t=new Set(this.getAllImages().map((e=>e.path)));for(const o of this.syncedImages)t.has(o)||null===(e=this.fileStore)||void 0===e||e.delete(o)}getImage(e){for(const t of Object.values(this.images))if(t&&t[e])return t[e];throw new Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,o,i){const n={id:e,x:o.x,y:o.y,width:i.width,height:i.height,tag:"image"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:n})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter((e=>"image"===e.tag));for(const o of e)this.history.update("images",t.id,o.id,o.data),this.syncedImages.add(o.data.path)}}export(e){var t;for(const o of e.sheets){const e=o.figures.filter((e=>"image"===e.tag));for(const i of e)i.data=null===(t=this.images[o.id])||void 0===t?void 0:t[i.id]}}getAllImages(){const e=[];for(const t in this.images)e.push(...Object.values(this.images[t]||{}).filter(Qe));return e}}Ev.getters=["getImage","getImagePath","getImageSize"];class wv extends lv{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 o of Object.values(t).filter(Qe))this.addMerge(e.sheetIdTo,o.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(e.sheetId,t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){const o=t?[t]:Object.keys(this.merges);for(const t of o)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(Qe)}getMerge({sheetId:e,col:t,row:o}){var i;const n=this.mergeCellMap[e],r=n?t in n&&(null===(i=n[t])||void 0===i?void 0:i[o]):void 0;return r?this.getMergeById(e,r):void 0}getMergesInZone(e,t){var o;const i=this.mergeCellMap[e];if(!i)return[];const n=new Set;for(const{col:e,row:r}of qo(t)){const t=null===(o=i[e])||void 0===o?void 0:o[r];t&&n.add(t)}return Array.from(n).map((t=>this.getMergeById(e,t))).filter(Qe)}doesIntersectMerge(e,t){return qo(t).some((({col:t,row:o})=>void 0!==this.getMerge({sheetId:e,col:t,row:o})))}doesColumnsHaveCommonMerges(e,t,o){const i=this.getters.getSheet(e);for(let n=0;n<this.getters.getNumberRows(e);n++)if(this.isInSameMerge(i.id,t,n,o,n))return!0;return!1}doesRowsHaveCommonMerges(e,t,o){const i=this.getters.getSheet(e);for(let n=0;n<=this.getters.getNumberCols(e);n++)if(this.isInSameMerge(i.id,n,t,n,o))return!0;return!1}expandZone(e,t){let{left:o,right:i,top:n,bottom:r}=t,s={left:o,right:i,top:n,bottom:r};for(let t in this.merges[e]){const o=this.getMergeById(e,parseInt(t));o&&Uo(o,s)&&(s=$o(o,s))}return Lo(s,t)?s:this.expandZone(e,s)}isInSameMerge(e,t,o,i,n){const r=this.getMerge({sheetId:e,col:t,row:o}),s=this.getMerge({sheetId:e,col:i,row:n});return!(!r||!s)&&Lo(r,s)}isInMerge({sheetId:e,col:t,row:o}){var i;const n=this.mergeCellMap[e];return!!n&&(t in n&&Boolean(null===(i=n[t])||void 0===i?void 0:i[o]))}getMainCellPosition(e){if(!this.isInMerge(e))return e;const t=this.getMerge(e).topLeft;return{sheetId:e.sheetId,col:t.col,row:t.row}}getBottomLeftCell(e){if(!this.isInMerge(e))return e;const{bottom:t,left:o}=this.getMerge(e);return{sheetId:e.sheetId,col:o,row:t}}isMergeHidden(e,t){const o=this.getters.getHiddenColsGroups(e),i=this.getters.getHiddenRowsGroups(e);for(let e of o)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of i)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const o=this.getMerge({sheetId:e,col:t.left,row:t.top});if(o)return Lo(t,o);const{width:i,height:n}=Wo(t);return 1===i&&1===n}isMergeDestructive(e,t){let{left:o,right:i,top:n,bottom:r}=t;i=Fe(i,0,this.getters.getNumberCols(e)-1),r=Fe(r,0,this.getters.getNumberRows(e)-1);for(let t=n;t<=r;t++)for(let r=o;r<=i;r++)if(r!==o||t!==n){const o=this.getters.getCell({sheetId:e,col:r,row:t});if(o&&""!==o.content)return!0}return!1}getMergeById(e,t){var o;const i=null===(o=this.merges[e])||void 0===o?void 0:o[t];return void 0!==i?xv(t,i):void 0}checkDestructiveMerge({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;return t.some((t=>this.isMergeDestructive(e,t)))?3:0}checkOverlap({target:e}){for(const t of e)for(const o of e)if(t!==o&&Uo(t,o))return 65;return 0}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;const{xSplit:o,ySplit:i}=this.getters.getPaneDivisions(e);for(const e of t)if(e.left<o&&e.right>=o||e.top<i&&e.bottom>=i)return 75;return 0}checkMergedContentUpdate(e){const{col:t,row:o,content:i}=e;if(void 0===i)return 0;const{col:n,row:r}=this.getMainCellPosition(e);return n===t&&r===o?0:4}checkMergeExists(e){const{sheetId:t,target:o}=e;for(const e of o){const{left:o,top:i}=e,n=this.getMerge({sheetId:t,col:o,row:i});if(void 0===n||!Lo(e,n))return 5}return 0}addMerge(e,t){let{left:o,right:i,top:n,bottom:r}=t;i=Fe(i,0,this.getters.getNumberCols(e)-1),r=Fe(r,0,this.getters.getNumberRows(e)-1);if(kt(o,n)===kt(i,r))return;const s=this.getters.getCell({sheetId:e,col:o,row:n});let a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,No({left:o,top:n,right:i,bottom:r})));let l=new Set;for(let t=n;t<=r;t++)for(let r=o;r<=i;r++){r===o&&t===n||this.dispatch("UPDATE_CELL",{sheetId:e,col:r,row:t,style:s?s.style:null,content:""});const i=this.getMerge({sheetId:e,col:r,row:t});i&&l.add(i.id),this.history.update("mergeCellMap",e,r,t,a)}for(let t of l){const{top:o,bottom:i,left:n,right:r}=this.getMergeById(e,t);for(let t=o;t<=i;t++)for(let o=n;o<=r;o++){const i={sheetId:e,col:o,row:t},n=this.getMerge(i);n&&n.id===a||(this.history.update("mergeCellMap",e,o,t,void 0),this.dispatch("CLEAR_CELL",i))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:o,top:i,bottom:n,right:r}=t,s=this.getMerge({sheetId:e,col:o,row:i});if(void 0!==s&&Lo(t,s)){this.history.update("merges",e,s.id,void 0);for(let t=i;t<=n;t++)for(let i=o;i<=r;i++)this.history.update("mergeCellMap",e,i,t,void 0)}}applyRangeChangeOnSheet(e,t){const o=Object.entries(this.merges[e]||{});for(const[i,n]of o)if(n){const o=n.zone,r=t(n);switch(r.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,o);break;default:const{width:t,height:n}=Wo(r.range.zone);1===t&&1===n?this.removeMerge(e,o):this.history.update("merges",e,parseInt(i,10),r.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:o,row:i}of qo(t))this.history.update("mergeCellMap",e,o,i,t.id)}import(e){const t=e.sheets||[];for(let e of t)this.history.update("merges",e.id,{}),this.history.update("mergeCellMap",e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let o of t)this.addMerge(e,Oo(o))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...yv(e))}}exportForExcel(e){this.export(e)}}function yv(e){return Object.entries(e).map((([e,t])=>t?xv(parseInt(e,10),t):void 0)).filter(Qe).map((e=>kt(e.left,e.top)+":"+kt(e.right,e.bottom)))}function xv(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}wv.getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge"];class Iv{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",o="COL"===e.dimension?"right":"bottom",i="COL"===e.dimension?"columns":"rows";const n=[...e.elements];n.sort(((e,t)=>t-e));const r=Ue(n);this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};let s=n,a="NONE";for(let e of r){const r=Math.min(...e),l=Math.max(...e);if(n.zone[t]<=r&&r<=n.zone[o]){const e=Math.min(n.zone[o],l)-r+1;a="RESIZE",s=this.createAdaptedRange(s,i,a,-e)}else if(n.zone[t]>=r&&n.zone[o]<=l)a="REMOVE",s=n.clone({...this.getInvalidRange()});else if(n.zone[t]<=l&&n.zone[o]>=l){const e=l-n.zone[t]+1;a="RESIZE",s=this.createAdaptedRange(s,i,a,-e),s=this.createAdaptedRange(s,i,"MOVE",-(n.zone[t]-r))}else r<n.zone[t]&&(a="MOVE",s=this.createAdaptedRange(s,i,a,-(l-r+1)))}return"NONE"!==a?{changeType:a,range:s}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",o="COL"===e.dimension?"right":"bottom",i="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(n.zone[t]<=e.base&&e.base<n.zone[o])return{changeType:"RESIZE",range:this.createAdaptedRange(n,i,"RESIZE",e.quantity)};if(e.base<n.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(n,i,"MOVE",e.quantity)}}else{if(n.zone[t]<e.base&&e.base<=n.zone[o])return{changeType:"RESIZE",range:this.createAdaptedRange(n,i,"RESIZE",e.quantity)};if(e.base<=n.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(n,i,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId!==e.sheetId)return{changeType:"NONE"};const o=this.getters.getSheetName(e.sheetId);return{changeType:"REMOVE",range:t=t.clone({...this.getInvalidRange(),invalidSheetName:o})}}),e.sheetId);break;case"RENAME_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.name&&t.invalidSheetName===e.name){const o=void 0,i=e.sheetId;return{changeType:"CHANGE",range:t.clone({sheetId:i,invalidSheetName:o})}}return{changeType:"NONE"}}));break;case"MOVE_RANGES":{const t=e.target[0];this.executeOnAllRanges((o=>{if(o.sheetId!==e.sheetId||!zo(o.zone,t))return{changeType:"NONE"};const i=e.targetSheetId,n=e.col-t.left,r=e.row-t.top,s=this.createAdaptedRange(o,"both","MOVE",[n,r]),a=e.sheetId!==i||s.prefixSheet;return{changeType:"MOVE",range:s.clone({sheetId:i,prefixSheet:a})}}));break}}}finalize(){}verifyRangeRemoved(e){return t=>{const o=e(t);return"NONE"===o.changeType||Mo(o.range.zone)?o:{range:o.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,o,i){const n=Zo(e.unboundedZone,t,o,i);return e.clone({zone:n})}executeOnAllRanges(e,t){const o=this.verifyRangeRemoved(e);for(const e of this.providers)e(o,t)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,o,i){const n=e.map((e=>yo.fromRange(e,this.getters)));return n.map((e=>{if(!Mo(e.zone))return e;const n=e.prefixSheet?e.sheetId:i,r={...e.unboundedZone,left:e.isFullRow&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:e.isFullRow?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.isFullCol&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:o),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:o)};return e.clone({sheetId:n,zone:r}).orderZone()}))}getRangeFromSheetXC(e,t){if(!Rt.test(t))return new yo({sheetId:"",zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let o,i=t,n=!1;t.includes("!")&&(({xc:i,sheetName:o}=Nt(t)),o&&(n=!0));const r=Ao(i),s=yo.getRangeParts(i,r),a=o&&!this.getters.getSheetIdByName(o)?o:void 0,l=this.getters.getSheetIdByName(o)||e;return new yo({prefixSheet:n,zone:r,sheetId:l,invalidSheetName:a,parts:s},this.getters.getSheetSize).orderZone()}getSelectionRangeString(e,t){const o=yo.fromRange(e,this.getters),i=this.getters.expandZone(o.sheetId,o.zone),n=o.clone({zone:{...i,bottom:o.isFullCol?void 0:i.bottom,right:o.isFullRow?void 0:i.right}});return this.getRangeString(n,t)}getRangeString(e,t){if(!e)return X;if(e.invalidXc)return e.invalidXc;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 o=yo.fromRange(e,this.getters);let i=o.sheetId!==t||o.invalidSheetName||o.prefixSheet,n="";if(i&&(n=o.invalidSheetName?o.invalidSheetName:_e(this.getters.getSheetName(o.sheetId))),i&&!n)return X;let r=this.getRangePartString(o,0);return o.parts&&2===o.parts.length&&(o.zone.top!==o.zone.bottom||o.zone.left!==o.zone.right||o.parts[0].rowFixed||o.parts[0].colFixed||o.parts[1].rowFixed||o.parts[1].colFixed)&&(r+=":",r+=this.getRangePartString(o,1)),`${i?n+"!":""}${r}`}getRangeDataFromXc(e,t){return this.getters.getRangeFromSheetXC(e,t).rangeData}getRangeDataFromZone(e,t){return{_sheetId:e,_zone:t}}getRangeFromRangeData(e){const t={prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]};return new yo(t,this.getters.getSheetSize)}getRangePartString(e,t){const o=e.parts&&e.parts[t].colFixed?"$":"",i=_t(0===t?e.zone.left:e.zone.right),n=e.parts&&e.parts[t].rowFixed?"$":"",r=String(0===t?e.zone.top+1:e.zone.bottom+1);let s="";return s=e.isFullCol?0===t&&e.unboundedZone.hasHeader?o+i+n+r:o+i:e.isFullRow?0===t&&e.unboundedZone.hasHeader?o+i+n+r:n+r:o+i+n+r,s}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:X}}}Iv.getters=["getRangeString","getSelectionRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData"];class Rv extends lv{constructor(){super(...arguments),this.sheetIdsMapName={},this.orderedSheetIds=[],this.sheets={},this.cellPosition={}}allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZones)(e);if(0!==t)return t;switch(e.type){case"HIDE_SHEET":return 1===this.getVisibleSheetIds().length?9:0;case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"MOVE_SHEET":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.orderedSheetIds.length>1?0:9;case"ADD_COLUMNS_ROWS":const o="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return e.base<0||e.base>o?86:e.quantity<=0?87:0;case"REMOVE_COLUMNS_ROWS":{const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return Math.min(...e.elements)<0||Math.max(...e.elements)>t?86: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,o;for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let i of e.sheets){const e=i.name||n("Sheet")+(Object.keys(this.sheets).length+1),{colNumber:r,rowNumber:s}=this.getImportedSheetSize(i),a={id:i.id,name:e,numberOfCols:r,rows:Ro(s),areGridLinesVisible:void 0===i.areGridLinesVisible||i.areGridLinesVisible,isVisible:i.isVisible,panes:{xSplit:(null===(t=i.panes)||void 0===t?void 0:t.xSplit)||0,ySplit:(null===(o=i.panes)||void 0===o?void 0:o.ySplit)||0}};this.orderedSheetIds.push(a.id),this.sheets[a.id]=a}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(Qe).map((e=>{const t=this.sheets[e],o={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},conditionalFormats:[],figures:[],filterTables:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible};return(t.panes.xSplit||t.panes.ySplit)&&(o.panes=t.panes),o}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){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(e.toUpperCase()===t.toUpperCase())return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}getEvaluationSheets(){return this.sheets}doesHeaderExist(e,t,o){return"COL"===t?o>=0&&o<this.getNumberCols(e):o>=0&&o<this.getNumberRows(e)}getRow(e,t){const o=this.getSheet(e).rows[t];if(!o)throw new Error(`Row ${o} not found.`);return o}getCell({sheetId:e,col:t,row:o}){var i;const n=this.tryGetSheet(e),r=null===(i=null==n?void 0:n.rows[o])||void 0===i?void 0:i.cells[t];if(void 0!==r)return this.getters.getCellById(r)}getColsZone(e,t,o){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:o}}getRowCells(e,t){var o;return Object.values(null===(o=this.getSheet(e).rows[t])||void 0===o?void 0:o.cells).filter(Qe)}getRowsZone(e,t,o){return{top:t,bottom:o,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){let t=1;const o=this.orderedSheetIds.map(this.getSheetName.bind(this));let i=`${e}${t}`;for(;o.includes(i);)i=`${e}${t}`,t++;return i}getSheetSize(e){return{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,o){const i={...this.getPaneDivisions(e)};"COL"===o?i.xSplit=t:"ROW"===o&&(i.ySplit=t),this.history.update("sheets",e,"panes",i)}isEmpty(e,t){return qo(t).map((({col:t,row:o})=>this.getCell({sheetId:e,col:t,row:o}))).every((e=>!e||""===e.content))}updateCellPosition(e){const{sheetId:t,cellId:o,col:i,row:n}=e;o?this.setNewPosition(o,t,i,n):this.clearPosition(t,i,n)}setNewPosition(e,t,o,i){const n=this.cellPosition[e];n&&this.clearPosition(t,n.col,n.row),this.history.update("cellPosition",e,{row:i,col:o,sheetId:t}),this.history.update("sheets",t,"rows",i,"cells",o,e)}clearPosition(e,t,o){var i;const n=null===(i=this.sheets[e])||void 0===i?void 0:i.rows[o].cells[t];n&&(this.history.update("cellPosition",n,void 0),this.history.update("sheets",e,"rows",o,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}clearZones(e,t){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++){this.sheets[e].rows[i].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:i})}}createSheet(e,t,o,i,n){const r={id:e,name:t,numberOfCols:o,rows:Ro(i),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},s=this.orderedSheetIds.slice();s.splice(n,0,r.id);const a=this.sheets;return this.history.update("orderedSheetIds",s),this.history.update("sheets",Object.assign({},a,{[r.id]:r})),r}moveSheet(e,t){const o=this.orderedSheetIds.slice(),i=o.findIndex((t=>t===e)),n=o.splice(i,1);let r="left"===t?this.findIndexOfPreviousVisibleSheet(i-1,o):this.findIndexOfNextVisibleSheet(i+1,o);void 0===r&&(r=o.length),o.splice(r,0,n[0]),this.history.update("orderedSheetIds",o)}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:o}=this,i=e.name&&e.name.trim().toLowerCase();return t.find((e=>{var t;return(null===(t=o[e])||void 0===t?void 0:t.name.toLowerCase())===i}))?11:ne.test(i)?13:0}checkSheetPosition(e){const{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?15:0}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?0:74}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?0:74}checkRowFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let o of t)if(o.top<e.quantity&&e.quantity<=o.bottom)return 65;return 0}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let o of t)if(o.left<e.quantity&&e.quantity<=o.right)return 65;return 0}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):10}renameSheet(e,t){const o=e.name;this.history.update("sheets",e.id,"name",t.trim());const i=Object.assign({},this.sheetIdsMapName);i[t]=e.id,delete i[o],this.history.update("sheetIdsMapName",i)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t){const o=this.getSheet(e),i=this.getDuplicateSheetName(o.name),n=Me(o);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 r=this.orderedSheetIds.slice(),s=r.indexOf(e);r.splice(s+1,0,n.id),this.history.update("orderedSheetIds",r),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:o}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:n.id,col:e,row:o,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIdsMapName);a[n.name]=n.id,this.history.update("sheetIdsMapName",a)}getDuplicateSheetName(e){let t=1;const o=this.orderedSheetIds.map(this.getSheetName.bind(this)),i=r("Copy of %s",e);let n=i.toString();for(;o.includes(n);)n=`${i} (${t})`,t++;return n}deleteSheet(e){const t=e.name,o=Object.assign({},this.sheets);delete o[e.id],this.history.update("sheets",o);const i=this.orderedSheetIds.slice(),n=i.indexOf(e.id);i.splice(n,1),this.history.update("orderedSheetIds",i);const r=Object.assign({},this.sheetIdsMapName);delete r[t],this.history.update("sheetIdsMapName",r)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(let o of t)this.moveCellOnColumnsDeletion(e,o);const o=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",o-t.length);const i=t.filter((t=>t<e.panes.xSplit)).length;i&&this.setPaneDivisions(e.id,e.panes.xSplit-i,"COL")}removeRows(e,t){t.sort(((e,t)=>t-e));for(let o of Ue(t))this.moveCellOnRowsDeletion(e,o[o.length-1],o[0]),o.map((t=>this.updateRowsStructureOnDeletion(t,e)));const o=t.filter((t=>t<e.panes.ySplit)).length;o&&this.setPaneDivisions(e.id,e.panes.ySplit-o,"ROW")}addColumns(e,t,o,i){const n="before"===o?t:t+1;this.moveCellsOnAddition(e,n,i,"columns");const r=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",r+i),n<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+i,"COL")}addRows(e,t,o,i){const n="before"===o?t:t+1;this.addEmptyRows(e,i),this.moveCellsOnAddition(e,n,i,"rows"),this.updateRowsStructureOnAddition(e,t,i),n<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+i,"ROW")}moveCellOnColumnsDeletion(e,t){for(let o=0;o<e.rows.length;o++){const i=e.rows[o];for(let n in i.cells){const r=Number(n),s=i.cells[n];s&&(r===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:r,row:o}),r>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:s,col:r-1,row:o}))}}}moveCellsOnAddition(e,t,o,i){const n=[];for(let r=0;r<e.rows.length;r++){const s=e.rows[r];if("rows"!==i||r>=t)for(let a in s.cells){const l=Number(a),c=s.cells[a];c&&("rows"===i||l>=t)&&n.push({type:"UPDATE_CELL_POSITION",sheetId:e.id,cellId:c,col:l+("columns"===i?o:0),row:r+("rows"===i?o:0)})}}for(let e of n.reverse())this.dispatch(e.type,e)}moveCellOnRowsDeletion(e,t,o){const i=o-t+1;for(let n=0;n<e.rows.length;n++){const r=e.rows[n];if(n>=t&&n<=o)for(let t in r.cells){const o=Number(t);r.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:o,row:n})}if(n>o)for(let t in r.cells){const o=Number(t),s=r.cells[t];s&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:s,col:o,row:n-i})}}}updateRowsStructureOnDeletion(e,t){const o=[],i=t.rows.map((e=>e.cells));for(let n in t.rows)Number(n)!==e&&o.push({cells:i.shift()});this.history.update("sheets",t.id,"rows",o)}updateRowsStructureOnAddition(e,t,o){const i=[],n=e.rows.map((e=>e.cells));e.rows.forEach((()=>i.push({cells:n.shift()}))),this.history.update("sheets",e.id,"rows",i)}addEmptyRows(e,t){const o=e.rows.slice();for(let e=0;e<t;e++)o.push({cells:{}});this.history.update("sheets",e.id,"rows",o)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(Dt);let o=e.rowNumber,i=e.colNumber;for(let{col:e,row:n}of t)o=Math.max(o,n+1),i=Math.max(i,e+1);return{rowNumber:o,colNumber:i}}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?27:"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?12:0}checkZones(e){const t=[];if("zone"in e&&t.push(e.zone),"target"in e&&Array.isArray(e.target)&&t.push(...e.target),"ranges"in e&&Array.isArray(e.ranges)&&t.push(...e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone))),!t.every(Mo))return 25;if(t.length&&"sheetId"in e){const o=this.getSheetZone(e.sheetId);return t.every((e=>zo(e,o)))?0:18}return 0}}Rv.getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheetIds","getVisibleSheetIds","isSheetVisible","getEvaluationSheets","doesHeaderExist","getCell","getCellPosition","getColsZone","getRowCells","getRowsZone","getNumberCols","getNumberRows","getNumberHeaders","getGridLinesVisibility","getNextSheetName","isEmpty","getSheetSize","getSheetZone","getPaneDivisions"];class Tv extends Gu{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 o=Object.values(this.getters.getCells(t));e=e.concat(this.getColorsFromCells(o),this.getFormattingColors(t),this.getChartColors(t))}return function(e){const t=[{leadColor:mt(255,0,0),colors:[]},{leadColor:mt(255,128,0),colors:[]},{leadColor:mt(128,128,0),colors:[]},{leadColor:mt(128,255,0),colors:[]},{leadColor:mt(0,255,0),colors:[]},{leadColor:mt(0,255,128),colors:[]},{leadColor:mt(0,255,255),colors:[]},{leadColor:mt(0,127,255),colors:[]},{leadColor:mt(0,0,255),colors:[]},{leadColor:mt(127,0,255),colors:[]},{leadColor:mt(128,0,128),colors:[]},{leadColor:mt(255,0,128),colors:[]}];for(const o of e.map(bt)){let e=500,i=0;t.forEach(((t,n)=>{const r=(s=o,a=t.leadColor,Math.sqrt(Math.pow(s.r-a.r,2)+Math.pow(s.g-a.g,2)+Math.pow(s.b-a.b,2)));var s,a;e>r&&(e=r,i=n)})),t[i].colors.push(o)}return t.map((e=>e.colors.sort(((e,t)=>St(e).s-St(t).s)))).flat().map(vt)}([...new Set([...new Set([...e,...this.customColors])].filter(gt).map(ut))]).filter((e=>!A.includes(e)))}getColorsFromCells(e){var t,o;const i=new Set;for(const n of e)(null===(t=n.style)||void 0===t?void 0:t.textColor)&&i.add(n.style.textColor),(null===(o=n.style)||void 0===o?void 0:o.fillColor)&&i.add(n.style.fillColor);return[...i]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),o=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(o.push(t.style.textColor),o.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(o.push(dt(t.minimum.color)),o.push(t.midpoint?dt(t.midpoint.color):void 0),o.push(dt(t.maximum.color)))}return o.filter(Qe)}getChartColors(e){const t=this.getters.getChartIds(e).map((e=>this.getters.getChart(e)));let o=new Set;for(let e of t){if(void 0===e)continue;const t=e.getDefinition().background;switch(void 0!==t&&o.add(t),e.type){case"gauge":const t=e.sectionRule.colors;o.add(t.lowerColor),o.add(t.middleColor),o.add(t.upperColor);break;case"scorecard":const i=e;o.add(i.baselineColorDown),o.add(i.baselineColorUp)}}return[...o]}tryToAddColor(e){const t=ut(e);e&&!A.includes(t)&&this.customColors.add(t)}}Tv.getters=["getCustomColors"];const Av=Yd.mapping;class Ov extends Gu{constructor(e){super(e),this.isUpToDate=!1,this.evaluatedCells={},this.evalContext=e.custom,this.lazyEvaluation=e.lazyEvaluation}handle(e){switch(vi.has(e.type)&&(this.isUpToDate=!1),e.type){case"UPDATE_CELL":("content"in e||"format"in e)&&(this.isUpToDate=!1);break;case"EVALUATE_CELLS":this.evaluate()}}finalize(){this.isUpToDate||(this.evaluate(),this.isUpToDate=!0)}evaluateFormula(e,t=this.getters.getActiveSheetId()){const o=Uu(e),i=this.getCompilationParameters((e=>this.getEvaluatedCell(this.getters.getCellPosition(e.id)))),n=[];for(let e of o.dependencies)n.push(this.getters.getRangeFromSheetXC(t,e));return o.execute(n,...i).value}getRangeFormattedValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.formattedValue))}getRangeValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.value))}getEvaluatedCell({sheetId:e,col:t,row:o}){var i,n,r;return void 0===this.getters.getCell({sheetId:e,col:t,row:o})?wg(""):(null===(r=null===(n=null===(i=this.evaluatedCells[e])||void 0===i?void 0:i[t])||void 0===n?void 0:n[o])||void 0===r?void 0:r.call(n))||wg("")}getEvaluatedCells(e){const t=this.getters.getCells(e)||{},o={};for(let e of Object.keys(t)){const t=this.getters.getCellPosition(e);o[e]=this.getEvaluatedCell(t)}return o}getColEvaluatedCells(e,t){var o;return Object.values((null===(o=this.evaluatedCells[e])||void 0===o?void 0:o[t])||[]).filter(Qe).map((e=>e()))}getEvaluatedCellsInZone(e,t){return qo(t).map((({col:t,row:o})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:o})))}setEvaluatedCell(e,t){const{col:o,row:i,sheetId:n}=this.getters.getCellPosition(e);this.evaluatedCells[n]||(this.evaluatedCells[n]={}),this.evaluatedCells[n][o]||(this.evaluatedCells[n][o]={}),this.evaluatedCells[n][o][i]=t,this.lazyEvaluation||this.evaluatedCells[n][o][i]()}*getAllCells(){for(const e of this.getters.getSheetIds()){const t=this.getters.getCells(e);for(const e in t)yield t[e]}}evaluate(){this.evaluatedCells={};const e=new Set,t=e=>{var t,n;const r=e.id,{col:s,row:a,sheetId:l}=this.getters.getCellPosition(r),c=null===(n=null===(t=this.evaluatedCells[l])||void 0===t?void 0:t[s])||void 0===n?void 0:n[a];return c||ot((()=>{try{switch(e.isFormula){case!0:return i(e);case!1:return Sg(e.content,e.format)}}catch(t){return o(t,e)}}))},o=(e,t)=>{e instanceof Error||(e=new Error(e));const o=(null==e?void 0:e.errorType)||a.GenericError,i=n[2].__lastFnCalled||"",r=new c(o,e.message.replace("[[FUNCTION_NAME]]",i),void 0!==e.logLevel?e.logLevel:l.error);return Rg(t.content,r)},i=t=>{const o=t.id;if(e.has(o))throw new d;n[2].__originCellXC=()=>{const e=n[2].getters.getCellPosition(o);return kt(e.col,e.row)},e.add(o);const i=t.compiledFormula.execute(t.dependencies,...n);if(e.delete(o),Array.isArray(i.value))throw new Error(r("This formula depends on invalid values"));return wg(i.value,t.format||i.format)},n=this.getCompilationParameters((e=>t(e)()));for(const e of this.getAllCells())this.setEvaluatedCell(e.id,t(e))}getCompilationParameters(e){const t=Object.assign(Object.create(Av),this.evalContext,{getters:this.getters}),o=this.getters;const i=t=>{const o=e(t);if(o.type===mi.error)throw o.error;return o};return[function(e,t,n,s){if(t)return{value:No(e.zone)};if(!Mo(e.zone))throw new u;if(e.zone.bottom!==e.zone.top||e.zone.left!==e.zone.right)throw new Error(s?r("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",n.toString(),s.toString()):r("Function %s expects its parameters to be single values or single cell references, not ranges.",n.toString()));if(e.invalidSheetName)throw new Error(r("Invalid sheet name: %s",e.invalidSheetName));return function(e){let t;if(!o.tryGetSheet(e.sheetId))throw new Error(r("Invalid sheet name"));return t=o.getCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}),t&&""!==t.content?i(t):{value:null,format:null==t?void 0:t.format}}(e)},function(e){const n=e.sheetId;if(!Mo(e.zone))throw new u;const r=o.getSheetZone(n),s=[],a=Po(e.zone,r);if(!a)return s.push([]),s;for(let o=a.left;o<=a.right;o++){const n=[];for(let r=a.top;r<=a.bottom;r++){const s=t.getters.getCell({sheetId:e.sheetId,col:o,row:r});n.push(s?i(s):void 0)}s.push(n)}return s},t]}exportForExcel(e){for(let t of e.sheets)for(const e in t.cells){const o={sheetId:t.id,...Dt(e)},i=this.getters.getCell(o);if(i){const n=t.cells[e],r=this.getEvaluatedCell(o);n.value=r.value,n.isFormula=i.isFormula&&!this.isBadExpression(i.content),i.format!==r.format&&(n.computedFormat=r.format)}}}isBadExpression(e){try{return Uu(e),!1}catch(e){return!0}}}Ov.getters=["evaluateFormula","getRangeFormattedValues","getRangeValues","getEvaluatedCell","getEvaluatedCells","getColEvaluatedCells","getEvaluatedCellsInZone"];class Mv extends Gu{constructor(){super(...arguments),this.charts={},this.createRuntimeChart=function(e){const t=In.getAll();return function(o){const i=t.find((e=>e.match(o.type)));if(!i)throw new Error("No runtime builder for this chart.");return i.getChartRuntime(o,e)}}(this.getters)}handle(e){if(vi.has(e.type)||bi.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]}getBackgroundOfSingleCellChart(e,t){if(e)return e;if(!t)return w;const o=t.zone.left,i=t.zone.top,n=t.sheetId;return this.getters.getCellComputedStyle({sheetId:n,col:o,row:i}).fillColor||w}}Mv.getters=["getChartRuntime","getBackgroundOfSingleCellChart"];class Nv extends Gu{constructor(){super(...arguments),this.isStale=!0,this.computedStyles={},this.computedIcons={},this.rulePredicate={CellIsRule:(e,t)=>{if(e.type===mi.error)return!1;const o=t.values.map(Eg);switch(t.operator){case"IsEmpty":return""===e.value.toString().trim();case"IsNotEmpty":return""!==e.value.toString().trim();case"BeginsWith":return""!==o[0]&&e.value.toString().startsWith(o[0].toString());case"EndsWith":return""!==o[0]&&e.value.toString().endsWith(o[0].toString());case"Between":return e.value>=o[0]&&e.value<=o[1];case"NotBetween":return!(e.value>=o[0]&&e.value<=o[1]);case"ContainsText":return e.value.toString().indexOf(o[0].toString())>-1;case"NotContains":return!e.value||-1==e.value.toString().indexOf(o[0].toString());case"GreaterThan":return e.value>o[0];case"GreaterThanOrEqual":return e.value>=o[0];case"LessThan":return e.value<o[0];case"LessThanOrEqual":return e.value<=o[0];case"NotEqual":return""!==o[0]&&e.value!==o[0];case"Equal":return""===o[0]||e.value===o[0];default:console.warn(r("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}}}handle(e){switch((bi.has(e.type)||"UPDATE_CELL"===e.type&&"content"in e)&&(this.isStale=!0),e.type){case"ACTIVATE_SHEET":const t=e.sheetIdTo;this.computedStyles[t]=this.computedStyles[t]||{},this.computedIcons[t]=this.computedIcons[t]||{},this.isStale=!0;break;case"AUTOFILL_CELL":const o=this.getters.getActiveSheetId(),i=this.getters.getRulesByCell(o,e.originCol,e.originRow);for(const t of i)this.adaptRules(o,t,[kt(e.col,e.row)],[]);break;case"PASTE_CONDITIONAL_FORMAT":this.pasteCf(e.origin,e.target,e.operation)}}finalize(){this.isStale&&(this.computeStyles(),this.isStale=!1)}getCellComputedStyle(e){var t;const{sheetId:o,col:i,row:n}=e,r=this.getters.getCell(e),s=this.computedStyles[o],a=s&&(null===(t=s[i])||void 0===t?void 0:t[n]),l={...null==r?void 0:r.style,...a};return this.getters.getEvaluatedCell(e).link&&!l.textColor&&(l.textColor=x),this.getters.isFilterHeader(e)&&(l.bold=!0),l}getConditionalIcon({col:e,row:t}){var o;const i=this.getters.getActiveSheetId(),n=this.computedIcons[i];return n&&(null===(o=n[e])||void 0===o?void 0:o[t])}computeStyles(){var e;const t=this.getters.getActiveSheetId();this.computedStyles[t]={},this.computedIcons[t]={};const o=this.computedStyles[t];for(let i of this.getters.getConditionalFormats(t).reverse())try{switch(i.rule.type){case"ColorScaleRule":for(let e of i.ranges)this.applyColorScale(e,i.rule);break;case"IconSetRule":for(let e of i.ranges)this.applyIcon(e,i.rule);break;default:for(let n of i.ranges){const r=this.getters.getRangeFromSheetXC(t,n).zone;for(let n=r.top;n<=r.bottom;n++)for(let s=r.left;s<=r.right;s++){const r=this.rulePredicate[i.rule.type];let a=this.getters.getEvaluatedCell({sheetId:t,col:s,row:n});r&&r(a,i.rule)&&(o[s]||(o[s]=[]),o[s][n]=Object.assign((null===(e=o[s])||void 0===e?void 0:e[n])||{},i.rule.style))}}}}catch(e){}}parsePoint(e,t,o){const i=this.getters.getActiveSheetId(),n=this.getters.getEvaluatedCellsInZone(i,this.getters.getRangeFromSheetXC(i,e).zone).filter((e=>e.type===mi.number)).map((e=>e.value));switch(t.type){case"value":return"max"===o?Math.max(...n):Math.min(...n);case"number":return Number(t.value);case"percentage":const e=Math.min(...n);return e+(Math.max(...n)-e)*Number(t.value)/100;case"percentile":return Xt(n,Number(t.value)/100,!0);case"formula":const i=t.value&&this.getters.evaluateFormula(t.value);return i instanceof Promise?null:i;default:return null}}applyIcon(e,t){const o=this.parsePoint(e,t.lowerInflectionPoint),i=this.parsePoint(e,t.upperInflectionPoint);if(null===o||null===i||o>i)return;const n=this.getters.getActiveSheetId(),r=this.getters.getRangeFromSheetXC(n,e).zone,s=this.computedIcons[n],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=r.top;e<=r.bottom;e++)for(let l=r.left;l<=r.right;l++){const r=this.getters.getEvaluatedCell({sheetId:n,col:l,row:e});if(r.type!==mi.number)continue;const c=this.computeIcon(r.value,i,t.upperInflectionPoint.operator,o,t.lowerInflectionPoint.operator,a);s[l]||(s[l]=[]),s[l][e]=c}}computeIcon(e,t,o,i,n,r){return"ge"===o&&e>=t||"gt"===o&&e>t?r[0]:"ge"===n&&e>=i||"gt"===n&&e>i?r[1]:r[2]}applyColorScale(e,t){var o;const i=this.parsePoint(e,t.minimum,"min"),n=t.midpoint?this.parsePoint(e,t.midpoint):null,r=this.parsePoint(e,t.maximum,"max");if(null===i||null===r||i>=r||n&&(i>=n||n>=r))return;const s=this.getters.getActiveSheetId(),a=this.getters.getRangeFromSheetXC(s,e).zone,l=this.computedStyles[s],c=[];t.midpoint&&n?(c.push({minValue:i,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(i,n,t.minimum.color,t.midpoint.color)}),c.push({minValue:n,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(n,r,t.midpoint.color,t.maximum.color)})):c.push({minValue:i,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(i,r,t.minimum.color,t.maximum.color)});for(let e=a.top;e<=a.bottom;e++)for(let t=a.left;t<=a.right;t++){const a=this.getters.getEvaluatedCell({sheetId:s,col:t,row:e});if(a.type===mi.number){const s=Fe(a.value,i,r);let h;h=2===c.length&&n?s<=n?this.colorCell(s,c[0].minValue,c[0].minColor,c[0].colorDiffUnit):this.colorCell(s,c[1].minValue,c[1].minColor,c[1].colorDiffUnit):this.colorCell(s,c[0].minValue,c[0].minColor,c[0].colorDiffUnit),l[t]||(l[t]=[]),l[t][e]=(null===(o=l[t])||void 0===o?void 0:o[e])||{},l[t][e].fillColor=dt(h)}}}computeColorDiffUnits(e,t,o,i){const n=t-e;return[((o>>16)%256-(i>>16)%256)/n,((o>>8)%256-(i>>8)%256)/n,(o%256-i%256)/n]}colorCell(e,t,o,i){const[n,r,s]=i;return Math.round((o>>16)%256-n*(e-t))<<16|Math.round((o>>8)%256-r*(e-t))<<8|Math.round(o%256-s*(e-t))}adaptRules(e,t,o,i){if(0===o.length&&0===i.length)return;const n=this.getters.getConditionalFormats(e),r=n.findIndex((e=>e.id===t.id));let s=[];r>-1&&(s=n[r].ranges),s=s.concat(o);const a=Bo(s,i);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})}pasteCf(e,t,o){const i=kt(t.col,t.row);for(let n of this.getters.getConditionalFormats(e.sheetId))for(let r of n.ranges)if(Vo(e.col,e.row,this.getters.getRangeFromSheetXC(e.sheetId,r).zone)){const r=n,s=[];"CUT"===o&&s.push(kt(e.col,e.row)),e.sheetId===t.sheetId?this.adaptRules(e.sheetId,r,[i],s):(this.adaptRules(t.sheetId,r,[i],[]),this.adaptRules(e.sheetId,r,[],s))}}}Nv.getters=["getConditionalIcon","getCellComputedStyle"];class _v extends Gu{constructor(){super(...arguments),this.filterValues={},this.hiddenRows=new Set,this.isEvaluationDirty=!1}allowDispatch(e){if("UPDATE_FILTER"===e.type)if(!this.getters.getFilterId(e))return 79;return 0}handle(e){switch(e.type){case"UNDO":case"REDO":case"UPDATE_CELL":case"EVALUATE_CELLS":case"ACTIVATE_SHEET":case"REMOVE_FILTER_TABLE":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":this.updateHiddenRows();break;case"UPDATE_FILTER":this.updateFilter(e),this.updateHiddenRows();break;case"DUPLICATE_SHEET":const t={};for(const o of this.getters.getFilters(e.sheetIdTo)){const i=o.zoneWithHeaders;t[o.id]=this.getFilterValues({sheetId:e.sheetId,col:i.left,row:i.top})}this.filterValues[e.sheetIdTo]=t}}finalize(){this.isEvaluationDirty&&(this.updateHiddenRows(),this.isEvaluationDirty=!1)}isRowFiltered(e,t){return e===this.getters.getActiveSheetId()&&this.hiddenRows.has(t)}getCellBorderWithFilterBorder(e){const{sheetId:t,col:o,row:i}=e;let n;for(let e of this.getters.getFilterTables(t)){const r=e.zone;if(Vo(o,i,r)){const e=this.intersectZoneWithViewport(t,r);n={top:i===e.top?Z:void 0,bottom:i===e.bottom?Z:void 0,left:o===e.left?Z:void 0,right:o===e.right?Z:void 0}}}const r=this.getters.getCellBorder(e),s={...n,...st(r||{})};return Je(s)?null:s}getFilterHeaders(e){const t=[];for(let o of this.getters.getFilterTables(e)){const i=o.zone;if(!i)continue;const n=i.top;for(let o=i.left;o<=i.right;o++)this.getters.isColHidden(e,o)||this.getters.isRowHidden(e,n)||t.push({col:o,row:n})}return t}getFilterValues(e){const t=this.getters.getFilterId(e),o=e.sheetId;return t&&this.filterValues[o]&&this.filterValues[o][t]||[]}isFilterHeader({sheetId:e,col:t,row:o}){return this.getFilterHeaders(e).some((e=>e.col===t&&e.row===o))}isFilterActive(e){var t,o;const i=this.getters.getFilterId(e),n=e.sheetId;return Boolean(i&&(null===(o=null===(t=this.filterValues[n])||void 0===t?void 0:t[i])||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:o,sheetId:i}){const n=this.getters.getFilterId({sheetId:i,col:e,row:t});n&&(this.filterValues[i]||(this.filterValues[i]={}),this.filterValues[i][n]=o)}updateHiddenRows(){var e,t;const o=this.getters.getActiveSheetId(),i=this.getters.getFilters(o).sort(((e,t)=>e.zoneWithHeaders.top-t.zoneWithHeaders.top)),n=new Set;for(let r of i){if(this.getters.isRowHiddenByUser(o,r.zoneWithHeaders.top))continue;if(n.has(r.zoneWithHeaders.top))continue;const i=null===(t=null===(e=this.filterValues[o])||void 0===e?void 0:e[r.id])||void 0===t?void 0:t.map(at);if(i&&r.filteredZone)for(let e=r.filteredZone.top;e<=r.filteredZone.bottom;e++){const t=this.getCellValueAsString(o,r.col,e);i.includes(t)&&n.add(e)}}this.hiddenRows=n}getCellValueAsString(e,t,o){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:o}).formattedValue.toLowerCase()}exportForExcel(e){for(const t of e.sheets)for(const e of t.filterTables){const o=Oo(e.range),i=[],n=[];for(const e of Le(0,Wo(o).width)){const r={sheetId:t.id,col:o.left+e,row:o.top},s=this.getFilterValues(r),a=this.getters.getFilter(r);if(!a)continue;const l=(a.filteredZone?qo(a.filteredZone).map((({col:e,row:o})=>this.getters.getEvaluatedCell({sheetId:t.id,col:e,row:o}))).filter((e=>e.type!==mi.empty)).map((e=>e.formattedValue)):[]).filter((e=>!s.includes(e)));i.push({colId:e,filteredValues:[...new Set(l)]});const c={col:a.col,row:a.zoneWithHeaders.top,sheetId:t.id},h=this.getters.getEvaluatedCell(c).formattedValue,d=this.getUniqueColNameForExcel(e,h,n);n.push(d),t.cells[kt(c.col,c.row)]={...t.cells[kt(c.col,c.row)],content:d,value:d,isFormula:!1}}e.filters=i}}getUniqueColNameForExcel(e,t,o){t||(t=`Column${e}`);let i=t,n=2;for(;o.includes(i);)i=t+String(n),n++;return i}}_v.getters=["getCellBorderWithFilterBorder","getFilterHeaders","getFilterValues","isFilterHeader","isRowFiltered","isFilterActive"];class Fv{constructor(e,t,o,i,n,r){this.getters=e,this.sheetId=t,this.boundaries=o,this.viewportWidth=i.width,this.viewportHeight=i.height,this.offsetScrollbarX=r.x,this.offsetScrollbarY=r.y,this.canScrollVertically=n.canScrollVertically,this.canScrollHorizontally=n.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){const e=this.getters.findLastVisibleColRowIndex(this.sheetId,"COL",{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,"ROW",{first:this.boundaries.top,last:this.boundaries.bottom}),{end:o,size:i}=this.getters.getColDimensions(this.sheetId,e),{end:n,size:r}=this.getters.getRowDimensions(this.sheetId,t),s=this.searchHeaderIndex("COL",o-this.viewportWidth,0),a=this.getters.getColSize(this.sheetId,s),l=this.searchHeaderIndex("ROW",n-this.viewportHeight,0),c=this.getters.getRowSize(this.sheetId,l);let h=o-this.offsetCorrectionX;this.canScrollHorizontally&&(h+=Math.max(N,Math.min(a,this.viewportWidth-i)),h=Math.max(h,this.viewportWidth));let d=n-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(_+5,Math.min(c,this.viewportHeight-r)),d=Math.max(d,this.viewportHeight)),{width:h,height:d}}getColIndex(e,t=!1){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex("COL",e-this.offsetCorrectionX,this.left,t)}getRowIndex(e,t=!1){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex("ROW",e-this.offsetCorrectionY,this.top,t)}adjustPosition(e){const t=this.sheetId;e||(e=this.getters.getSheetPosition(t));const o=this.getters.getMainCellPosition({sheetId:t,...e}),{col:i,row:n}=this.getters.getNextVisibleCellPosition(o);Vo(i,this.boundaries.top,this.boundaries)&&this.adjustPositionX(i),Vo(this.boundaries.left,n,this.boundaries)&&this.adjustPositionY(n)}adjustPositionX(e){const t=this.sheetId,{end:o}=this.getters.getColDimensions(t,e),i=this.getters.getNumberCols(t);if(this.offsetX+this.offsetCorrectionX+this.viewportWidth<o)for(let e=this.left;this.offsetX+this.offsetCorrectionX+this.viewportWidth<o&&!(e>i);e++)this.getters.isColHidden(t,e)||(this.offsetX=this.getters.getColDimensions(t,e).end-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX());else if(this.left>e)for(let o=this.left;o>=e&&!(o<0);o--)this.getters.isColHidden(t,o)||(this.offsetX=this.getters.getColDimensions(t,o).start-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX())}adjustPositionY(e){const t=this.sheetId,{end:o}=this.getters.getRowDimensions(t,e),i=this.getters.getNumberRows(t);if(this.offsetY+this.viewportHeight+this.offsetCorrectionY<o)for(let e=this.top;this.offsetY+this.viewportHeight+this.offsetCorrectionY<o&&!(e>i);e++)this.getters.isRowHidden(t,e)||(this.offsetY=this.getters.getRowDimensions(t,e).end-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY());else if(this.top>e)for(let o=this.top;o>=e&&!(o<0);o--)this.getters.isRowHidden(t,o)||(this.offsetY=this.getters.getRowDimensions(t,o).start-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY())}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getRect(e){const t=Po(e,this.zone);if(t){return{x:this.getters.getColRowOffset("COL",this.zone.left,t.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset("ROW",this.zone.top,t.top)+this.offsetCorrectionY,width:Math.min(this.getters.getColRowOffset("COL",t.left,t.right+1),this.viewportWidth),height:Math.min(this.getters.getColRowOffset("ROW",t.top,t.bottom+1),this.viewportHeight)}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,o=0,i=!1){let n=0;const r=this.sheetId,s=this.getters.getNumberHeaders(r,e);for(let a=o;a<=s-1;a++){const o=i||"COL"!==e?a<this.top&&a>this.bottom:a<this.left&&a>this.right;if(!this.getters.isHeaderHidden(r,e,a)&&!o&&(n+="COL"===e?this.getters.getColSize(r,a):this.getters.getRowSize(r,a),n>t))return a}return-1}get zone(){return{left:this.left,right:this.right,top:this.top,bottom:this.bottom}}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetScrollbarX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetScrollbarY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){const{width:e}=this.getMaxSize();this.viewportWidth+this.offsetScrollbarX>e&&(this.offsetScrollbarX=Math.max(0,e-this.viewportWidth))}this.left=this.getColIndex(this.offsetScrollbarX,!0),this.right=this.getColIndex(this.offsetScrollbarX+this.viewportWidth,!0),-1===this.right&&(this.right=this.boundaries.right),this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){const{height:e}=this.getMaxSize();this.viewportHeight+this.offsetScrollbarY>e&&(this.offsetScrollbarY=Math.max(0,e-this.viewportHeight))}this.top=this.getRowIndex(this.offsetScrollbarY,!0),this.bottom=this.getRowIndex(this.offsetScrollbarY+this.viewportWidth,!0),-1===this.bottom&&(this.bottom=this.boundaries.bottom),this.adjustViewportZoneY()}adjustViewportZoneX(){const e=this.sheetId;this.left=this.searchHeaderIndex("COL",this.offsetScrollbarX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex("COL",this.viewportWidth,this.left)),-1===this.right&&(this.right=this.getters.getNumberCols(e)-1),this.offsetX=this.getters.getColDimensions(e,this.left).start-this.getters.getColDimensions(e,this.boundaries.left).start}adjustViewportZoneY(){const e=this.sheetId;this.top=this.searchHeaderIndex("ROW",this.offsetScrollbarY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex("ROW",this.viewportHeight,this.top)),-1===this.bottom&&(this.bottom=this.getters.getNumberRows(e)-1),this.offsetY=this.getters.getRowDimensions(e,this.top).start-this.getters.getRowDimensions(e,this.boundaries.top).start}}class Dv extends Gu{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":let{col:t,row:o}=jo(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const i=e.previousAnchor.zone,n=e.anchor.zone,{top:r,bottom:s,left:a,right:l}=this.getters.getActiveMainViewport();i.left===n.left&&i.right===n.right&&(t=a>t||t>l?a:t),i.top===n.top&&i.bottom===n.bottom&&(o=r>o||o>s?r:o)}const i=this.getters.getActiveSheetId();t=Math.min(t,this.getters.getNumberCols(i)-1),o=Math.min(o,this.getters.getNumberRows(i)-1),this.refreshViewport(this.getters.getActiveSheetId(),{col:t,row:o})}}handle(e){var t;switch(this.cleanViewports(),e.type){case"START":this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case"UNDO":case"REDO":this.resetSheetViews();break;case"RESIZE_SHEETVIEW":this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case"SET_VIEWPORT_OFFSET":this.setSheetViewOffset(e.offsetX,e.offsetY);break;case"SHIFT_VIEWPORT_DOWN":const{top:o}=this.getActiveMainViewport(),i=this.getters.getActiveSheetId(),n=this.clipOffsetY(this.getters.getRowDimensions(i,o).start+this.sheetViewHeight);this.shiftVertically(n);break;case"SHIFT_VIEWPORT_UP":{const{top:e}=this.getActiveMainViewport(),t=this.getters.getActiveSheetId(),o=this.clipOffsetY(this.getters.getRowDimensions(t,e).end-this.sheetViewHeight);this.shiftVertically(o);break}case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"UPDATE_FILTER":this.resetViewports(e.sheetId);break;case"UPDATE_CELL":("content"in e||"format"in e||void 0!==(null===(t=e.style)||void 0===t?void 0:t.fontSize))&&this.sheetsWithDirtyViewports.add(e.sheetId);break;case"ACTIVATE_SHEET":this.setViewports(),this.refreshViewport(e.sheetIdTo);break;case"UNFREEZE_ROWS":case"UNFREEZE_COLUMNS":case"FREEZE_COLUMNS":case"FREEZE_ROWS":case"UNFREEZE_COLUMNS_ROWS":this.resetViewports(this.getters.getActiveSheetId());break;case"DELETE_SHEET":this.sheetsWithDirtyViewports.delete(e.sheetId);break;case"START_EDITION":const{col:r,row:s}=this.getters.getActivePosition();this.refreshViewport(this.getters.getActiveSheetId(),{col:r,row:s})}}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 o of t)(null===(e=this.viewports[o])||void 0===e?void 0:e.bottomRight)||this.resetViewports(o)}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=>Le(e.left,e.right+1))).flat())].filter((t=>!this.getters.isHeaderHidden(e,"COL",t)))}getSheetViewVisibleRows(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>Le(e.top,e.bottom+1))).flat())].filter((t=>!this.getters.isHeaderHidden(e,"ROW",t)))}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:o,ySplit:i}=this.getters.getPaneDivisions(e);let{width:n,height:r}=t.getMaxSize();return{x:this.getters.getColDimensions(e,o).start,y:this.getters.getRowDimensions(e,i).start,width:n,height:r}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:o}=this.getMainViewportRect(),i=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-i.viewportWidth+1),maxOffsetY:Math.max(0,o-i.viewportHeight+1)}}getColRowOffsetInViewport(e,t,o){const i=this.getters.getActiveSheetId(),n=this.getters.getSheetViewVisibleCols(),r=this.getters.getSheetViewVisibleRows();if(o<t)return-this.getColRowOffsetInViewport(e,o,t);let s=0;const a="COL"===e?n:r;for(let n=t;n<o;n++)a.includes(n)&&(s+="COL"===e?this.getters.getColSize(i,n):this.getters.getRowSize(i,n));return s}isVisibleInViewport({sheetId:e,col:t,row:o}){return this.getSubViewports(e).some((e=>e.isVisible(t,o)))}getEdgeScrollCol(e,t,o){let i=!1,n=0,r=0;const{xSplit:s}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(i=!0,r=Ut(e-a),n=1):e<l&&o>=l&&c>0?(i=!0,r=Ut(l-e),n=-1):s&&t<l&&e>l&&(i=!0,r=Ut(e),n="reset"),{canEdgeScroll:i,direction:n,delay:r}}getEdgeScrollRow(e,t,o){let i=!1,n=0,r=0;const{ySplit:s}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(i=!0,r=Ut(e-a),n=1):e<l&&o>=l&&c>0?(i=!0,r=Ut(l-e),n=-1):s&&t<l&&e>l&&(i=!0,r=Ut(e),n="reset"),{canEdgeScroll:i,direction:n,delay:r}}getVisibleRect(e){const t=this.getters.getActiveSheetId(),o=this.getSubViewports(t).map((t=>t.getRect(e))).filter(Qe);if(0===o.length)return{x:0,y:0,width:0,height:0};const i=Math.min(...o.map((e=>e.x))),n=Math.min(...o.map((e=>e.y))),r=Math.max(...o.map((e=>e.x+e.width)))-i,s=Math.max(...o.map((e=>e.y+e.height)))-n;return{x:i+this.gridOffsetX,y:n+this.gridOffsetY,width:r,height:s}}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,o).start}}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(Qe)}checkPositiveDimension(e){return e.width<0||e.height<0?68:0}checkValuesAreDifferent(e){const{height:t,width:o}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===o&&e.height===t?76:0}checkScrollingDirection({offsetX:e,offsetY:t}){const o=this.getMainInternalViewport(this.getters.getActiveSheetId());return!o.canScrollHorizontally&&e>0||!o.canScrollVertically&&t>0?69:0}getMainViewport(e){const t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){const e=this.getters.getSheetIds();for(let t of Object.keys(this.viewports))e.includes(t)||delete this.viewports[t]}resetSheetViews(){for(let e of Object.keys(this.viewports)){const t=this.getters.getSheetPosition(e);this.resetViewports(e);const o=this.getSubViewports(e);Object.values(o).forEach((e=>{e.adjustPosition(t)}))}}resizeSheetView(e,t,o=0,i=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=o,this.gridOffsetY=i,this.recomputeViewports()}recomputeViewports(){for(let e of Object.keys(this.viewports))this.resetViewports(e)}setSheetViewOffset(e,t){const o=this.getters.getActiveSheetId(),{maxOffsetX:i,maxOffsetY:n}=this.getMaximumSheetOffset();Object.values(this.getSubViewports(o)).forEach((o=>o.setViewportOffset(Fe(e,0,i),Fe(t,0,n))))}clipOffsetY(e){const{height:t}=this.getMainViewportRect(),o=t-this.sheetViewHeight;return e=Math.min(e,o),e=Math.max(e,0)}getViewportOffset(e){var t,o;return{x:(null===(t=this.viewports[e])||void 0===t?void 0:t.bottomRight.offsetScrollbarX)||0,y:(null===(o=this.viewports[e])||void 0===o?void 0:o.bottomRight.offsetScrollbarY)||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e),i=this.getters.getNumberCols(e),n=this.getters.getNumberRows(e),r=this.getters.getColRowOffset("COL",0,t,e),s=this.getters.getColRowOffset("ROW",0,o,e),{xRatio:a,yRatio:l}=this.getFrozenSheetViewRatio(e),c=a<1,h=l<1,d=this.getViewportOffset(e),u={topLeft:o&&t&&new Fv(this.getters,e,{left:0,right:t-1,top:0,bottom:o-1},{width:r,height:s},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:o&&new Fv(this.getters,e,{left:t,right:i-1,top:0,bottom:o-1},{width:this.sheetViewWidth-r,height:s},{canScrollHorizontally:c,canScrollVertically:!1},{x:c?d.x:0,y:0})||void 0,bottomLeft:t&&new Fv(this.getters,e,{left:0,right:t-1,top:o,bottom:n-1},{width:r,height:this.sheetViewHeight-s},{canScrollHorizontally:!1,canScrollVertically:h},{x:0,y:h?d.y:0})||void 0,bottomRight:new Fv(this.getters,e,{left:t,right:i-1,top:o,bottom:n-1},{width:this.sheetViewWidth-r,height:this.sheetViewHeight-s},{canScrollHorizontally:c,canScrollVertically:h},{x:c?d.x:0,y:h?d.y:0})};this.viewports[e]=u}refreshViewport(e,t){Object.values(this.getSubViewports(e)).forEach((e=>{e.adjustViewportZone(),e.adjustPosition(t)}))}shiftVertically(e){const{top:t}=this.getActiveMainViewport(),{scrollX:o}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(o,e);const{anchor:i}=this.getters.getSelection(),n=this.getActiveMainViewport().top-t;this.selection.selectCell(i.cell.col,i.cell.row+n)}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],o=this.getters.getFigures(e),{scrollX:i,scrollY:n}=this.getActiveSheetScrollInfo(),{x:r,y:s}=this.getters.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const e of o)e.x>=r&&(e.x+e.width<=r+i||e.x>=a+i+r)||e.y>=s&&(e.y+e.height<=s+n||e.y>=l+n+s)||t.push(e);return t}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e),i=this.getters.getColDimensions(e,t).start,n=this.getters.getRowDimensions(e,o).start;return{xRatio:i/(this.sheetViewWidth+this.gridOffsetX),yRatio:n/(this.sheetViewHeight+this.gridOffsetY)}}}Dv.getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getActiveSheetDOMScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio"];class kv{constructor(e,t,o){this.index=0,this.cells=e,this.getters=t,this.direction=o}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:o,tooltip:i}=Ag.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:o,tooltip:i,origin:{col:e.data.col,row:e.data.row}}}}class $v extends Gu{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:Fe(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:Fe(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?0:45;case"AUTOFILL_AUTO":const o=this.getters.getSelectedZone();return o.top===o.bottom?0:1}return 0}handle(e){switch(e.type){case"AUTOFILL":this.autofill(!0);break;case"AUTOFILL_SELECT":this.select(e.col,e.row);break;case"AUTOFILL_AUTO":this.autofillAuto();break;case"AUTOFILL_CELL":this.autoFillMerge(e.originCol,e.originRow,e.col,e.row);const t=this.getters.getActiveSheetId();this.dispatch("UPDATE_CELL",{sheetId:t,col:e.col,row:e.row,style:e.style||null,content:e.content||"",format:e.format||""}),this.dispatch("SET_BORDER",{sheetId:t,col:e.col,row:e.row,border:e.border})}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),o=this.autofillZone;switch(this.direction){case"down":for(let i=t.left;i<=t.right;i++){const n=[];for(let e=t.top;e<=t.bottom;e++)n.push(kt(i,e));const r=this.createGenerator(n);for(let t=o.top;t<=o.bottom;t++)this.computeNewCell(r,i,t,e)}break;case"up":for(let i=t.left;i<=t.right;i++){const n=[];for(let e=t.bottom;e>=t.top;e--)n.push(kt(i,e));const r=this.createGenerator(n);for(let t=o.bottom;t>=o.top;t--)this.computeNewCell(r,i,t,e)}break;case"left":for(let i=t.top;i<=t.bottom;i++){const n=[];for(let e=t.right;e>=t.left;e--)n.push(kt(e,i));const r=this.createGenerator(n);for(let t=o.right;t>=o.left;t--)this.computeNewCell(r,t,i,e)}break;case"right":for(let i=t.top;i<=t.bottom;i++){const n=[];for(let e=t.left;e<=t.right;e++)n.push(kt(e,i));const r=this.createGenerator(n);for(let t=o.left;t<=o.right;t++)this.computeNewCell(r,t,i,e)}}e&&(this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0)}select(e,t){const o=this.getters.getSelectedZone();if(Vo(e,t,o))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,o.top-1,o.left,o.right),this.steps=o.top-t;break;case"down":this.saveZone(o.bottom+1,t,o.left,o.right),this.steps=t-o.bottom;break;case"left":this.saveZone(o.top,o.bottom,e,o.left-1),this.steps=o.left-e;break;case"right":this.saveZone(o.top,o.bottom,o.right+1,e),this.steps=e-o.right}this.autofill(!1)}}autofillAuto(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let o=e.left,i=e.bottom;if(o>0){let e=this.getters.getEvaluatedCell({sheetId:t,col:o-1,row:i});for(;e.type!==mi.empty;)i+=1,e=this.getters.getEvaluatedCell({sheetId:t,col:o-1,row:i})}if(i===e.bottom&&(o=e.right,o<=this.getters.getNumberCols(t))){let e=this.getters.getEvaluatedCell({sheetId:t,col:o+1,row:i});for(;e.type!==mi.empty;)i+=1,e=this.getters.getEvaluatedCell({sheetId:t,col:o+1,row:i})}i!==e.bottom&&(this.select(e.left,i-1),this.autofill(!0))}computeNewCell(e,t,o,i){const{cellData:n,tooltip:r,origin:s}=e.next(),{content:a,style:l,border:c,format:h}=n;this.tooltip=r,i&&this.dispatch("AUTOFILL_CELL",{originCol:s.col,originRow:s.row,col:t,row:o,content:a,style:l,border:c,format:h})}getRule(e,t){const o=Og.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((o=>o.condition(e,t)));return o&&o.generateRule(e,t)}createGenerator(e){const t=[],o=[],i=this.getters.getActiveSheetId();for(let t of e){const{col:e,row:n}=Dt(t),r=this.getters.getCell({sheetId:i,col:e,row:n});o.push({col:e,row:n,cell:r,sheetId:i})}const n=o.map((e=>e.cell));for(let e of o){let o={type:"COPY_MODIFIER"};if(e&&e.cell){o=this.getRule(e.cell,n)||o}const i=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:i},rule:o})}return new kv(t,this.getters,this.direction)}saveZone(e,t,o,i){this.autofillZone={top:e,bottom:t,left:o,right:i}}getDirection(e,t){const o=this.getters.getSelectedZone(),i={up:{number:o.top-t,value:"up"},down:{number:t-o.bottom,value:"down"},left:{number:o.left-e,value:"left"},right:{number:e-o.right,value:"right"}};if(1===Object.values(i).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(i).find((e=>e.number>0?1:0)).value;const n=i.up.number>0?"up":"down",r=i.left.number>0?"left":"right";return Math.abs(i[n].number)>=Math.abs(i[r].number)?i[n].value:i[r].value}autoFillMerge(e,t,o,i){const n=this.getters.getActiveSheetId(),r={sheetId:n,col:o,row:i},s={sheetId:n,col:e,row:t};if(this.getters.isInMerge(r)&&!this.getters.isInMerge(s)){const e=this.getters.getMerge(r);e&&this.dispatch("REMOVE_MERGE",{sheetId:n,target:[e]})}const a=this.getters.getMerge(s);(null==a?void 0:a.topLeft.col)===e&&(null==a?void 0:a.topLeft.row)===t&&this.dispatch("ADD_MERGE",{sheetId:n,target:[{top:i,bottom:i+a.bottom-a.top,left:o,right:o+a.right-a.left}]})}drawGrid(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:o}=e,{x:i,y:n,width:r,height:s}=this.getters.getVisibleRect(this.autofillZone);r>0&&s>0&&(t.strokeStyle="black",t.lineWidth=o,t.setLineDash([3]),t.strokeRect(i,n,r,s),t.setLineDash([]))}}$v.layers=[5],$v.getters=["getAutofillTooltip"];class Pv extends Gu{handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:o}=this.getters.getSelection();for(const i of t){const t=this.getAutomaticSums(e,i,o.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,o){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,o):this.sumData(e,t)}sumData(e,t){const o=this.dimensionsToSum(e,t),i=this.sumDimensions(e,t,o).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return o.has("ROW")&&o.has("COL")&&i.push(this.sumTotal(t)),i}sumAdjacentData(e,t,o){const{col:i,row:n}=Vo(o.col,o.row,t)?o:{col:t.left,row:t.top},r=this.findAdjacentData(e,i,n);return r?this.getters.isSingleCellOrMerge(e,t)||Go($o(r,t))?[{position:{col:i,row:n},zone:r}]:this.sumDimensions(e,$o(r,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,o){const i=this.getters.getSheet(e),n=this.getters.getMainCellPosition({sheetId:e,col:t,row:o}),r=this.findSuitableZoneToSum(i,n.col,n.row);if(r)return this.getters.expandZone(e,r)}findSuitableZoneToSum(e,t,o){const i=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:o-1}),n=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:o});if(this.isNumber(n)&&!this.isNumber(i))return this.findHorizontalZone(e,t,o);const r=this.findVerticalZone(e,t,o);if(this.isZoneValid(r))return r;const s=this.findHorizontalZone(e,t,o);return this.isZoneValid(s)?s:void 0}findVerticalZone(e,t,o){const i={top:0,bottom:o-1,left:t,right:t},n=this.reduceZoneStart(e,i,i.bottom);return{...i,top:n}}findHorizontalZone(e,t,o){const i={top:o,bottom:o,left:0,right:t-1},n=this.reduceZoneStart(e,i,i.right);return{...i,left:n}}reduceZoneStart(e,t,o){const i=this.getters.getEvaluatedCellsInZone(e.id,t),n=Le(o,-1,-1),r=n.filter((e=>i[e]&&!i[e].isAutoSummable)),s=Math.max(...r),a=Ue(n.filter((e=>this.isNumber(i[e]))))[0]||[];return Math.max(...a)<s?1/0:Math.min(...a)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){var t;return e.type===mi.number&&!(null===(t=e.format)||void 0===t?void 0:t.match(j))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){const o=new Set;return Go(t)?(o.add(1===Wo(t).width?"COL":"ROW"),o):(this.lastColIsEmpty(e,t)&&o.add("ROW"),this.lastRowIsEmpty(e,t)&&o.add("COL"),0===o.size&&o.add("COL"),o)}sumDimensions(e,t,o){return[...o.has("COL")?this.sumColumns(t,e):[],...o.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:o}=e;return{position:{col:o,row:t},zone:{...e,top:t,right:o-1}}}sumColumns(e,t){const o=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,o.bottom-1)},qo(o).map((t=>({position:t,zone:{...e,right:t.col,left:t.col}})))}sumRows(e,t){const o=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,o.right-1)},qo(o).map((t=>({position:t,zone:{...e,top:t.row,bottom:t.row}})))}dispatchCellUpdates(e,t){for(const o of t){const{col:t,row:i}=o.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,content:`=SUM(${this.getters.zoneToXC(e,o.zone)})`})}}nextEmptyRow(e,t){let o=t.bottom+1;const{left:i,right:n}=t;for(;!this.getters.isEmpty(e,{bottom:o,top:o,left:i,right:n});)o++;return{...t,top:o,bottom:o}}nextEmptyCol(e,t){let o=t.right+1;const{top:i,bottom:n}=t;for(;!this.getters.isEmpty(e,{left:o,right:o,top:i,bottom:n});)o++;return{...t,left:o,right:o}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}Pv.getters=["getAutomaticSums"];class Lv extends Gu{allowDispatch(e){if("OPEN_CELL_POPOVER"===e.type){try{zg.get(e.popoverType)}catch(e){return 72}return 0}return 0}handle(e){switch(e.type){case"ACTIVATE_SHEET":case"CLOSE_CELL_POPOVER":this.persistentPopover=void 0;break;case"OPEN_CELL_POPOVER":this.persistentPopover={col:e.col,row:e.row,sheetId:this.getters.getActiveSheetId(),type:e.popoverType}}}getCellPopover({col:e,row:t}){var o,i;const n=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){const e=this.getters.getMainCellPosition(this.persistentPopover),t=null===(i=(o=zg.get(this.persistentPopover.type)).onOpen)||void 0===i?void 0:i.call(o,e,this.getters);return(null==t?void 0:t.isOpen)?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}if(void 0===e||void 0===t||!this.getters.isVisibleInViewport({sheetId:n,col:e,row:t}))return{isOpen:!1};const r=this.getters.getMainCellPosition({sheetId:n,col:e,row:t}),s=zg.getAll().map((e=>{var t;return null===(t=e.onHover)||void 0===t?void 0:t.call(e,r,this.getters)})).find((e=>null==e?void 0:e.isOpen));return(null==s?void 0:s.isOpen)?{...s,anchorRect:this.computePopoverAnchorRect(r)}:{isOpen:!1}}hasOpenedPopover(){return void 0!==this.persistentPopover}getPersistentPopoverTypeAtPosition({col:e,row:t}){if(this.persistentPopover&&this.persistentPopover.col===e&&this.persistentPopover.row===t)return this.persistentPopover.type}computePopoverAnchorRect({col:e,row:t}){const o=this.getters.getActiveSheetId(),i=this.getters.getMerge({sheetId:o,col:e,row:t});return i?this.getters.getVisibleRect(i):this.getters.getVisibleRect(Yo({col:e,row:t}))}}Lv.getters=["getCellPopover","getPersistentPopoverTypeAtPosition","hasOpenedPopover"];var Uv;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(Uv||(Uv={}));class Vv extends Gu{constructor(){super(...arguments),this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1},this.toSearch=""}handle(e){switch(e.type){case"UPDATE_SEARCH":this.updateSearch(e.toSearch,e.searchOptions);break;case"CLEAR_SEARCH":case"UNDO":case"REDO":case"REMOVE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":this.clearSearch();break;case"SELECT_SEARCH_PREVIOUS_MATCH":this.selectNextCell(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"ACTIVATE_SHEET":case"REFRESH_SEARCH":this.refreshSearch()}}getSearchMatches(){return this.searchMatches}getCurrentSelectedMatchIndex(){return this.selectedMatchIndex}updateSearch(e,t){this.searchOptions=t,e!==this.toSearch&&(this.selectedMatchIndex=null),this.toSearch=e,this.updateRegex(),this.refreshSearch()}refreshSearch(){const e=this.findMatches();this.searchMatches=e,this.selectNextCell(Uv.current)}updateRegex(){let e=Oe(this.toSearch);const t=this.searchOptions.matchCase?"":"i";this.searchOptions.exactMatch&&(e=`^${e}$`),this.currentSearchRegex=RegExp(e,t)}findMatches(){const e=this.getters.getActiveSheetId(),t=this.getters.getCells(e),o=[];if(this.toSearch)for(const i of Object.values(t)){const{col:t,row:n}=this.getters.getCellPosition(i.id);if(i&&this.currentSearchRegex&&this.currentSearchRegex.test(this.getSearchableString({sheetId:e,col:t,row:n}))){const e={col:t,row:n,selected:!1};o.push(e)}}return o.sort(this.sortByRowThenColumn)}sortByRowThenColumn(e,t){return e.row===t.row?e.col-t.col:e.row>t.row?1:-1}selectNextCell(e){const t=this.searchMatches;if(!t.length)return void(this.selectedMatchIndex=null);let o;o=null===this.selectedMatchIndex?0:this.selectedMatchIndex+e,o=(o%t.length+t.length)%t.length,this.selectedMatchIndex=o,this.selection.selectCell(t[o].col,t[o].row);for(let e=0;e<this.searchMatches.length;e++)this.searchMatches[e].selected=e===this.selectedMatchIndex}clearSearch(){this.toSearch="",this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1}}replace(e){if(null===this.selectedMatchIndex||!this.currentSearchRegex)return;const t=this.searchMatches[this.selectedMatchIndex],o=this.getters.getActiveSheetId(),i=this.getters.getCell({sheetId:o,...t});if((null==i?void 0:i.isFormula)&&!this.searchOptions.searchFormulas)this.selectNextCell(Uv.next);else{const i=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),n=this.getSearchableString({sheetId:o,col:t.col,row:t.row}).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)}}replaceAll(e){const t=this.searchMatches.length;for(let o=0;o<t;o++)this.replace(e)}getSearchableString(e){const t=this.getters.getCell(e);return this.searchOptions.searchFormulas&&(null==t?void 0:t.isFormula)?t.content:this.getters.getEvaluatedCell(e).formattedValue}drawGrid(e){const{ctx:t}=e,o=this.getters.getActiveSheetId();for(const e of this.searchMatches){const i=this.getters.getMerge({sheetId:o,col:e.col,row:e.row}),n=i?i.left:e.col,r=i?i.right:e.col,s=i?i.top:e.row,a=i?i.bottom:e.row,{x:l,y:c,width:h,height:d}=this.getters.getVisibleRect({top:s,left:n,right:r,bottom:a});h>0&&d>0&&(t.fillStyle="#8B008B33",t.fillRect(l,c,h,d),e.selected&&(t.strokeStyle="#8B008B",t.strokeRect(l,c,h,d)))}}}Vv.layers=[3],Vv.getters=["getSearchMatches","getCurrentSelectedMatchIndex"];class zv extends Gu{isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,o){return"COL"===t?this.isColHidden(e,o):this.isRowHidden(e,o)}getNextVisibleCellPosition({sheetId:e,col:t,row:o}){return{sheetId:e,col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",o,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,o,i){if(o<=i)for(let n=o;n<=i;n++)if(this.getters.doesHeaderExist(e,t,n)&&!this.isHeaderHidden(e,t,n))return n;if(o>i)for(let n=o;n>=i;n--)if(this.getters.doesHeaderExist(e,t,n)&&!this.isHeaderHidden(e,t,n))return n}findLastVisibleColRowIndex(e,t,{last:o,first:i}){return Le(o,i,-1).find((o=>!this.isHeaderHidden(e,t,o)))||i}findFirstVisibleColRowIndex(e,t){const o=this.getters.getNumberHeaders(e,t);for(let i=0;i<o;i++){if("COL"===t&&!this.isColHidden(e,i))return i;if("ROW"===t&&!this.isRowHidden(e,i))return i}}exportForExcel(e){for(const t of e.sheets)for(const[e,o]of Object.entries(t.rows)){const i=this.isRowHidden(t.id,Number(e));o.isHidden=i}}}zv.getters=["getNextVisibleCellPosition","findVisibleHeader","findLastVisibleColRowIndex","findFirstVisibleColRowIndex","isRowHidden","isColHidden","isHeaderHidden"];class Bv extends Gu{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:o}=Wo(e.zone),i=t*o==1?this.getters.expandZone(e.sheetId,e.zone):e.zone;return{...e,zone:i}}))}drawGrid(e){const{ctx:t,thinLineWidth:o}=e,i=this.getters.getActiveSheetId(),n=3*o;t.lineWidth=n;const r=this.getHighlights();for(let e of r.filter(((e,t)=>r.findIndex((t=>Lo(t.zone,e.zone)&&t.sheetId===i))===t))){const{x:o,y:i,width:r,height:s}=this.getters.getVisibleRect(e.zone);r>0&&s>0&&(t.strokeStyle=e.color,t.strokeRect(o+n/2,i+n/2,r-n,s-n),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(o+n,i+n,r-2*n,s-2*n))}}}Bv.layers=[1],Bv.getters=["getHighlights"];class Hv extends Gu{constructor(){super(...arguments),this.boxes=[]}getColDimensionsInViewport(e,t){const o=Math.min(...this.getters.getSheetViewVisibleCols()),i=this.getters.getColRowOffsetInViewport("COL",o,t),n=this.getters.getColSize(e,t);return{start:i,size:n,end:i+(this.getters.isColHidden(e,t)?0:n)}}getRowDimensionsInViewport(e,t){const o=Math.min(...this.getters.getSheetViewVisibleRows()),i=this.getters.getColRowOffsetInViewport("ROW",o,t),n=this.getters.getRowSize(e,t);return{start:i,size:n,end:i+(this.getters.isRowHidden(e,t)?0:n)}}getHeaderOffset(e,t,o){let i=this.getters.getColRowOffsetInViewport(e,t,o);return this.getters.isDashboard()||(i+="ROW"===e?O:M),i}drawGrid(e,t){switch(t){case 0:this.boxes=this.getGridBoxes(),this.drawBackground(e),this.drawOverflowingCellBackground(e),this.drawCellBackground(e),this.drawBorders(e),this.drawTexts(e),this.drawIcon(e),this.drawFrozenPanes(e);break;case 7:this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e))}}drawBackground(e){const{ctx:t,thinLineWidth:o}=e,{width:i,height:n}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle="#ffffff",t.fillRect(0,0,i+m,n+m);const r=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),s=r?.1*o:0;if(r)for(const e of this.boxes)t.strokeStyle="#E2E3E3",t.lineWidth=o,t.strokeRect(e.x+s,e.y+s,e.width-2*s,e.height-2*s)}drawCellBackground(e){const{ctx:t}=e;for(const e of this.boxes){let o=e.style;o.fillColor&&"#ffffff"!==o.fillColor&&(t.fillStyle=o.fillColor||"#ffffff",t.fillRect(e.x,e.y,e.width,e.height)),e.error&&(t.fillStyle="red",t.beginPath(),t.moveTo(e.x+e.width-5,e.y),t.lineTo(e.x+e.width,e.y),t.lineTo(e.x+e.width,e.y+5),t.fill())}}drawOverflowingCellBackground(e){var t,o;const{ctx:i,thinLineWidth:n}=e;for(const e of this.boxes)if(e.content&&e.isOverflow){const r=e.content.align||"left";let s,a;const l=e.y+n/2,c=e.height-n,h=Math.min((null===(t=e.clipRect)||void 0===t?void 0:t.width)||1/0,e.content.width);"left"===r?(s=e.x+n/2,a=h-2*n):"right"===r?(s=e.x+e.width-n/2,a=2*n-h):(s=((null===(o=e.clipRect)||void 0===o?void 0:o.x)||e.x+e.width/2-e.content.width/2)+n/2,a=h-2*n),i.fillStyle="#ffffff",i.fillRect(s,l,a,c)}}drawBorders(e){const{ctx:t,thinLineWidth:o}=e;for(let e of this.boxes){const t=e.border;if(t){const{x:o,y:n,width:r,height:s}=e;t.left&&i(t.left,o,n,o,n+s),t.top&&i(t.top,o,n,o+r,n),t.right&&i(t.right,o+r,n,o+r,n+s),t.bottom&&i(t.bottom,o,n+s,o+r,n+s)}}function i([e,i],n,r,s,a){t.strokeStyle=i,t.lineWidth=("thin"===e?2:3)*o,t.beginPath(),t.moveTo(n,r),t.lineTo(s,a),t.stroke()}}drawTexts(e){const{ctx:t,thinLineWidth:o}=e;let i;t.textBaseline="top";for(let e of this.boxes)if(e.content){const n=e.style||{},r=e.content.align||"left",s=$e(n);s!==i&&(i=s,t.font=s),t.fillStyle=n.textColor||"#000";let a=e.x;if(a+="left"===r?P+(e.image?e.image.size+$:0):"right"===r?e.width-P-(e.isFilterHeader?20:0):e.width/2,t.textAlign=r,e.clipRect){t.save(),t.beginPath();const{x:o,y:i,width:n,height:r}=e.clipRect;t.rect(o,i,n,r),t.clip()}const l=Pe(n),c=e.content.textLines.length;let h=this.computeTextYCoordinate(e,l,c);for(let i of e.content.textLines){if(t.fillText(i,Math.round(a),Math.round(h)),n.strikethrough||n.underline){const e=ke(t,i,n);let s=a;"right"===r?s-=e:"center"===r&&(s-=e/2),n.strikethrough&&t.fillRect(s,h+l/2,e,2.6*o),n.underline&&t.fillRect(s,h+l+1,e,1.3*o)}h+=P+l}e.clipRect&&t.restore()}}drawIcon(e){const{ctx:t}=e;for(const e of this.boxes)if(e.image){const o=e.image.image;if(e.image.clipIcon){t.save(),t.beginPath();const{x:o,y:i,width:n,height:r}=e.image.clipIcon;t.rect(o,i,n,r),t.clip()}const i=e.image.size,n=this.computeTextYCoordinate(e,i);t.drawImage(o,e.x+$,n,i,i),e.image.clipIcon&&t.restore()}}computeTextYCoordinate(e,t,o=1){const i=e.y+1,n=De(t,o),r=e.height>n+2*P,s=e.verticalAlign||"middle";if(r){if("middle"===s)return i+(e.height-n)/2;if("bottom"===s)return i+e.height-n-P}return i+P}drawHeaders(e){const{ctx:t,thinLineWidth:o}=e,i=this.getters.getSheetViewVisibleCols(),n=i[0],r=i[i.length-1],s=this.getters.getSheetViewVisibleRows(),a=s[0],l=s[s.length-1],{width:c,height:h}=this.getters.getSheetViewDimensionWithHeaders(),d=this.getters.getSelectedZones(),u=function(e){const t=new Set;for(let o of e)for(let e of Le(o.left,o.right+1))t.add(e);return t}(d),g=function(e){const t=new Set;for(let o of e)for(let e of Le(o.top,o.bottom+1))t.add(e);return t}(d),p=this.getters.getActiveSheetId(),m=this.getters.getNumberCols(p),f=this.getters.getNumberRows(p),E=this.getters.getActiveCols(),w=this.getters.getActiveRows();t.font=`400 11px ${G}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=o,t.strokeStyle="#333";for(let e=n;e<=r;e++){const o={left:e,right:e,top:0,bottom:f-1},{x:i,width:n}=this.getters.getVisibleRect(o),r=this.getters.doesZonesContainFilter(p,[o]),s=E.has(e),a=u.has(e);t.fillStyle=s?r?I:C:a?r?T:b:r?R:v,t.fillRect(i,0,n,O)}for(let e=a;e<=l;e++){const o={top:e,bottom:e,left:0,right:m-1},{y:i,height:n}=this.getters.getVisibleRect(o),r=this.getters.doesZonesContainFilter(p,[o]),s=w.has(e),a=g.has(e);t.fillStyle=s?r?I:C:a?r?T:b:r?R:v,t.fillRect(0,i,M,n)}t.beginPath(),t.moveTo(M,0),t.lineTo(M,h),t.moveTo(0,O),t.lineTo(c,O),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(const e of i){const o=this.getters.getColSize(p,e),i=_t(e);t.fillStyle=E.has(e)?"#fff":S;let r=this.getHeaderOffset("COL",n,e);t.fillText(i,r+o/2,13),t.moveTo(r+o,0),t.lineTo(r+o,O)}for(const e of s){const o=this.getters.getRowSize(p,e);t.fillStyle=w.has(e)?"#fff":S;let i=this.getHeaderOffset("ROW",a,e);t.fillText(String(e+1),24,i+o/2),t.moveTo(0,i+o),t.lineTo(M,i+o)}t.stroke()}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:o}=e,{x:i,y:n}=this.getters.getMainViewportCoordinates(),r=this.getters.isDashboard()?0:M,s=this.getters.isDashboard()?0:O;t.lineWidth=6*o,t.strokeStyle="#BCBCBC",t.beginPath(),i&&(t.moveTo(r+i,0),t.lineTo(r+i,s)),n&&(t.moveTo(0,s+n),t.lineTo(r,s+n)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:o}=e,{x:i,y:n}=this.getters.getMainViewportCoordinates(),r=this.getters.getSheetViewVisibleCols(),s=r[0],a=r[r.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:s,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*o,t.strokeStyle="#DADFE8",t.beginPath(),i&&(t.moveTo(d+i,u),t.lineTo(d+i,h.height+u)),n&&(t.moveTo(d,u+n),t.lineTo(h.width+d,u+n)),t.stroke()}findNextEmptyCol(e,t,o){const i=this.getters.getActiveSheetId();let n=e;for(;n<t;){const e={sheetId:i,col:n+1,row:o},t=this.getters.getEvaluatedCell(e),r=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==mi.empty||this.getters.isInMerge(e)||(null==r?void 0:r.left))return n;n++}return n}findPreviousEmptyCol(e,t,o){const i=this.getters.getActiveSheetId();let n=e;for(;n>t;){const e={sheetId:i,col:n-1,row:o},t=this.getters.getEvaluatedCell(e),r=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==mi.empty||this.getters.isInMerge(e)||(null==r?void 0:r.right))return n;n--}return n}computeCellAlignment(e,t){const o=this.getters.getCell(e);if((null==o?void 0:o.isFormula)&&this.getters.shouldShowFormulas())return"left";const{align:i}=this.getters.getCellStyle(e),n=this.getters.getEvaluatedCell(e);return t&&n.type===mi.number?"center"!==i?"left":i:i||n.defaultAlign}createZoneBox(e,t,o){const{left:i,right:n}=o,r=t.left,s=t.top,a={sheetId:e,col:r,row:s},c=this.getters.getEvaluatedCell(a),h=this.getters.shouldShowFormulas(),{x:d,y:u,width:g,height:p}=this.getters.getVisibleRect(t),{verticalAlign:m}=this.getters.getCellStyle(a),f={x:d,y:u,width:g,height:p,border:this.getters.getCellBorderWithFilterBorder(a)||void 0,style:this.getters.getCellComputedStyle(a),verticalAlign:m};if(c.type===mi.empty)return f;const v=this.getters.getConditionalIcon(a),b=Pe(f.style),C=v?$+b:0;v&&(f.image={type:"icon",size:b,clipIcon:{x:f.x,y:f.y,width:Math.min(C,g),height:p},image:vp[v].img}),f.isFilterHeader=this.getters.isFilterHeader(a);const S=f.isFilterHeader?19:0,E=this.getters.getCellText(a,h),w=this.getters.getTextWidth(a)+P,y=this.getters.getCellStyle(a).wrapping||"overflow",x="wrap"===y?this.getters.getCellMultiLineText(a,g-2*P):[E],I=C+w+S,R=this.computeCellAlignment(a,I>g);f.content={textLines:x,width:"overflow"===y?w:g,align:R},c.type===mi.error&&c.error.logLevel>l.silent&&(f.error=c.error.message);const T=I>g||b>p;if(v||f.isFilterHeader)f.clipRect={x:f.x+C,y:f.y,width:Math.max(0,g-C-S),height:p};else if(T&&"overflow"===y){let e,o;switch(this.getters.isInMerge(a)?(e=this.getters.getMerge(a).right,o=r):(e=this.findNextEmptyCol(r,n,s),o=this.findPreviousEmptyCol(r,i,s),f.isOverflow=!0),R){case"left":{const o=Yo({col:e,row:s}),{x:i,y:n,width:r,height:a}=this.getters.getVisibleRect($o(t,o));(r<I||b>a)&&(f.clipRect={x:i,y:n,width:r,height:a});break}case"right":{const e=Yo({col:o,row:s}),{x:i,y:n,width:r,height:a}=this.getters.getVisibleRect($o(t,e));(r<I||b>a)&&(f.clipRect={x:i,y:n,width:r,height:a});break}case"center":{const i={...t,left:o,right:e},{x:n,y:r,height:s,width:a}=this.getters.getVisibleRect(i),l=I/2,c=f.x+f.width/2;if(n+a<c+l||n>c-l||b>s){const e=n>c-l?n:c-l,t=n+a-e;f.clipRect={x:e,y:r,width:t,height:s}}break}}}else"clip"!==y&&"wrap"!==y||(f.clipRect={x:f.x,y:f.y,width:g,height:p});return f}getGridBoxes(){const e=[],t=this.getters.getSheetViewVisibleCols(),o=t[0],i=t[t.length-1],n=this.getters.getSheetViewVisibleRows(),r={left:o,right:i,top:n[0],bottom:n[n.length-1]},s=this.getters.getActiveSheetId();for(const o of n)for(const i of t){const t={sheetId:s,col:i,row:o};this.getters.isInMerge(t)||e.push(this.createZoneBox(s,Yo(t),r))}for(const t of this.getters.getMerges(s))if(!this.getters.isMergeHidden(s,t)&&Uo(t,r)){const o=this.createZoneBox(s,t,r),i=this.getters.getCellBorder({sheetId:s,col:t.right,row:t.bottom});o.border={...o.border,bottom:i?i.bottom:void 0,right:i?i.right:void 0},o.isMerge=!0,e.push(o)}return e}}Hv.layers=[0,7],Hv.getters=["getColDimensionsInViewport","getRowDimensionsInViewport"];class Wv extends Gu{constructor(e,t,o){if(o&&t.length>1)throw new Error("Input with a single range cannot be instantiated with several range references.");super(e),this.inputHasSingleRange=o,this.ranges=[],this.focusedRangeIndex=null,this.willAddNewRange=!1,this.insertNewRange(0,t),this.activeSheet=this.getters.getActiveSheetId(),0===this.ranges.length&&(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}allowDispatch(e){switch(e.type){case"ADD_EMPTY_RANGE":if(this.inputHasSingleRange&&1===this.ranges.length)return 30;break;case"CHANGE_RANGE":if(this.inputHasSingleRange&&e.value.split(",").length>1)return 30}return 0}handleEvent(e){const t=No(e.anchor.zone),o=this.activeSheet,i=this.getters.getActiveSheetId(),n=this.getters.getSheetName(i);this.add([i===o?t:`${_e(n)}!${t}`])}handle(e){switch(e.type){case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"FOCUS_RANGE":this.focus(this.getIndex(e.rangeId));break;case"CHANGE_RANGE":{const t=this.getIndex(e.rangeId);if(null!==t&&this.focusedRangeIndex!==t&&this.focus(t),null!==t){const o=e.value.split(",").map((e=>e.trim()));this.setRange(t,o)}break}case"ADD_EMPTY_RANGE":this.insertNewRange(this.ranges.length,[""]),this.focusLast();break;case"REMOVE_RANGE":const t=this.getIndex(e.rangeId);null!==t&&this.removeRange(t);break;case"STOP_SELECTION_INPUT":this.willAddNewRange=!1;break;case"PREPARE_SELECTION_INPUT_EXPANSION":{const e=this.focusedRangeIndex;null===e||this.inputHasSingleRange||(this.willAddNewRange=""!==this.ranges[e].xc.trim());break}case"ACTIVATE_SHEET":if(e.sheetIdFrom!==e.sheetIdTo){const{col:t,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),i=this.getters.expandZone(e.sheetIdTo,Yo({col:t,row:o}));this.selection.resetAnchor(this,{cell:{col:t,row:o},zone:i})}}}unsubscribe(){this.unfocus()}getSelectionInputValue(){return this.cleanInputs(this.ranges.map((e=>e.xc?e.xc:"")))}getSelectionInputHighlights(){return this.ranges.map((e=>this.inputToHighlights(e))).flat()}focus(e){this.focusedRangeIndex=e}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null}add(e){null!==this.focusedRangeIndex&&0!==e.length&&(this.willAddNewRange?(this.insertNewRange(this.ranges.length,e),this.focusLast(),this.willAddNewRange=!1):this.setRange(this.focusedRangeIndex,e))}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){this.ranges.splice(e,0,...t.map(((e,t)=>({xc:e,id:(this.ranges.length+t+1).toString(),color:ht[(this.ranges.length+t)%ht.length]}))))}setRange(e,t){const[,...o]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,o),o.length&&this.focus(e+o.length)}removeRange(e){this.ranges.splice(e,1),null!==this.focusedRangeIndex&&this.focusLast()}inputToHighlights({xc:e,color:t}){const o=this.cleanInputs([e]).filter((e=>this.getters.isRangeValid(e))).filter((e=>this.shouldBeHighlighted(this.activeSheet,e)));return o.map((e=>{const{sheetName:o}=Nt(e);return{zone:this.getters.getRangeFromSheetXC(this.activeSheet,e).zone,sheetId:o&&this.getters.getSheetIdByName(o)||this.activeSheet,color:t}}))}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:o}=Nt(t),i=this.getters.getSheetIdByName(o),n=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(i===n||void 0===i&&n===e)}getIndex(e){const t=this.ranges.findIndex((t=>t.id===e));return t>=0?t:null}}Wv.layers=[1],Wv.getters=[];class Gv extends Gu{constructor(e){super(e),this.config=e,this.inputs={},this.focusedInputId=null}get currentInput(){return this.focusedInputId?this.inputs[this.focusedInputId]:null}allowDispatch(e){var t,o;if("FOCUS_RANGE"===e.type){const i=null===(t=this.currentInput)||void 0===t?void 0:t.getIndex(e.rangeId);if(this.focusedInputId===e.id&&(null===(o=this.currentInput)||void 0===o?void 0:o.focusedRangeIndex)===i)return 29}return this.currentInput?this.currentInput.allowDispatch(e):0}handle(e){var t;switch(e.type){case"ENABLE_NEW_SELECTION_INPUT":this.initInput(e.id,e.initialRanges||[],e.hasSingleRange);break;case"DISABLE_SELECTION_INPUT":this.focusedInputId===e.id&&this.unfocus(),delete this.inputs[e.id];break;case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"ADD_EMPTY_RANGE":case"REMOVE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id];this.selection.capture(t,{cell:{col:0,row:0},zone:Yo({col:0,row:0})},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}break;case"FOCUS_RANGE":case"CHANGE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id],o=t.ranges.find((t=>t.id===e.rangeId)),i=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(i,(null==o?void 0:o.xc)||"A1").zone;this.selection.capture(t,{cell:{col:n.left,row:n.top},zone:n},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}}null===(t=this.currentInput)||void 0===t||t.handle(e)}unsubscribe(){this.unfocus()}getSelectionInput(e){return this.inputs[e]?this.inputs[e].ranges.map(((t,o)=>Object.assign({},t,{color:this.focusedInputId===e&&null!==this.inputs[e].focusedRangeIndex&&this.isRangeValid(t.xc)?t.color:null,isFocused:this.focusedInputId===e&&this.inputs[e].focusedRangeIndex===o}))):[]}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:o}=Nt(e);return null!==t.match(Rt)&&(!o||void 0!==this.getters.getSheetIdByName(o))}getSelectionInputValue(e){return this.inputs[e].getSelectionInputValue()}getSelectionInputHighlights(){return this.focusedInputId?this.inputs[this.focusedInputId].getSelectionInputHighlights():[]}initInput(e,t,o=!1){if(this.inputs[e]=new Wv(this.config,t,o),0===t.length){const t=this.inputs[e],o={zone:Yo({col:0,row:0}),cell:{col:0,row:0}};this.selection.capture(t,o,{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e}}unfocus(){this.selection.release(this.currentInput),this.focusedInputId=null}}Gv.layers=[1],Gv.getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];class qv{constructor(){this.subscriptions={}}on(e,t,o){if(!o)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:o})}trigger(e,t){const o=this.subscriptions[e]||[];for(let e=0,i=o.length;e<i;e++){const i=o[e];i.callback.call(i.owner,t)}}off(e,t){const o=this.subscriptions[e];o&&(this.subscriptions[e]=o.filter((e=>e.owner!==t)))}clear(){this.subscriptions={}}}function Zv(e,t){return{...e,definition:Xn(e.definition,t)}}function jv(e,t){if(e.sheetId!==t.sheetId)return e;if(("FREEZE_COLUMNS"===e.type?"COL":"ROW")!==t.dimension)return e;let o=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));for(let t of e)o>t&&o--}if("ADD_COLUMNS_ROWS"===t.type){o=o>("before"===t.position?t.base-1:t.base)?o+t.quantity:o}return o>0?{...e,quantity:o}:void 0}Kg.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],Zv),Kg.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],Zv),Kg.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const o=t.sheetId;if(e.targetSheetId===o||e.sheetId===o)return;return e})),Kg.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),Kg.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){var o;if(e.name===t.name)return{...e,name:(null===(o=e.name)||void 0===o?void 0:o.match(/\d+/))?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),Kg.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE","CREATE_FILTER_TABLE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const o=[];for(const i of e.target)for(const e of t.target)Uo(i,e)||o.push({...i});if(o.length)return{...e,target:o};return})),Kg.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],jv),Kg.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],jv),Kg.addTransformation("CREATE_FILTER_TABLE",["CREATE_FILTER_TABLE","ADD_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;for(const o of e.target)for(const e of t.target)if(Uo(e,o))return;return e}));const Xv=[{match:function(e){return"sheetId"in e},fn:Qv},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const o=Qv(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;const i=[];for(const o of e.target){const e=pi(o,t);e&&i.push(e)}if(!i.length)return"IGNORE_COMMAND";return{...e,target:i}}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const o=Qv(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const o="COL"===t.dimension?"col":"row";let i=e[o];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(i))return"IGNORE_COMMAND";for(let t of e)i>=t&&i--}"ADD_COLUMNS_ROWS"===t.type&&(i>t.base||i===t.base&&"before"===t.position)&&(i+=t.quantity);return{...e,[o]:i}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const o of t.target){if(!(e.col===o.left&&e.row===o.top)&&Vo(e.col,e.row,o))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e&&"sheetId"in e},fn:function(e,t){const o=Qv(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type){if(t.dimension!==e.dimension)return e;const o="ADD_COLUMNS_ROWS"===e.type,i=o?"base":"elements";let n=o?[e[i]]:e[i];if("REMOVE_COLUMNS_ROWS"===t.type&&(n=n.map((e=>{if(t.elements.includes(e))return;const o=t.elements.sort(((e,t)=>t-e));for(let t of o)e>t&&e--;return e})).filter(Qe)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;n=n.map((o=>o>e?o+t.quantity:o))}if(n.length){let t=n;return o&&(t=n[0]),{...e,[i]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}},{match:function(e){return"ranges"in e},fn:function(e,t){const o=[],i="DELETE_SHEET"===t.type&&t.sheetId;for(const n of e.ranges)if(n._sheetId!==t.sheetId)o.push({...n,_zone:n._zone});else{const e=pi(n._zone,t);e&&i!==n._sheetId&&o.push({...n,_zone:e})}if(!o.length)return"IGNORE_COMMAND";return{...e,ranges:o}}}];function Yv(e,t){const o=Kg.getTransformation(e.type,t.type);return o?o(e,t):function(e,t){for(const{match:o,fn:i}of Xv)if(o(e)){const o=i(e,t);if("SKIP_TRANSFORMATION"===o)continue;if("IGNORE_COMMAND"===o)return;e=o}return e}(e,t)}function Kv(e,t){let o=[...e];for(const e of t)o=o.map((t=>Yv(t,e))).filter(Qe);return o}function Qv(e,t){const o="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===o?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class Jv{constructor(e,t,o,i){this._commands=[],this._changes=[],this.id=e,this.clientId=t,this._commands=[...o],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class eb extends Error{}class tb extends qv{constructor(e,t,o=Y){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=o,this.clients={},this.clientId="local",this.pendingMessages=[],this.waitingAck=!1,this.waitingUndoRedoAck=!1,this.isReplayingInitialRevisions=!1,this.processedRevisions=new Set,this.uuidGenerator=new To,this.debouncedMove=function(e,t,o){let i;return function(){const n=this,r=arguments,s=o&&!i;clearTimeout(i),i=setTimeout((function(){i=null,o||e.apply(n,r)}),t),s&&e.apply(n,r)}}(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t){if(!e.length||!t.length||!this.canApplyOptimisticUpdate())return;const o=new Jv(this.uuidGenerator.uuidv4(),this.clientId,e,t);this.revisions.append(o.id,o),this.trigger("new-local-state-update",{id:o.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:o.id,clientId:o.clientId,commands:o.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 eb("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(Qe))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}_move(e){var t;if(!this.clients[this.clientId])return;const o=null===(t=this.clients[this.clientId])||void 0===t?void 0:t.position;if((null==o?void 0:o.col)===e.col&&o.row===e.row&&o.sheetId===e.sheetId)return;const i=o?"CLIENT_MOVED":"CLIENT_JOINED",n=this.getClient();this.clients[this.clientId]={...n,position:e},this.transportService.sendMessage({type:i,version:1,client:{...n,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:o}=e,i=new Jv(e.nextRevisionId,t,o);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:Kv(o,t)})}break;case"SNAPSHOT_CREATED":{const t=new Jv(e.nextRevisionId,"server",[]);this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger("snapshot");break}}this.acknowledge(e),this.trigger("collaborative-event-received")}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;const t=this.clients[this.clientId];if(t){const{position:e}=t;e&&this.transportService.sendMessage({type:"CLIENT_MOVED",version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),this.waitingAck||(this.waitingAck=!0,this.sendPendingMessage())}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if("REMOTE_REVISION"===e.type){const t=this.revisions.get(e.nextRevisionId);if(0===t.commands.length){this.revisions.drop(t.id);const e=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.nextRevisionId));return this.trigger("pending-revisions-dropped",{revisionIds:e}),this.waitingAck=!1,this.waitingUndoRedoAck=!1,void(this.pendingMessages=[])}e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw new Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.\n ${JSON.stringify(e)}`);this.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch("REVISION_UNDONE"!==e.type&&"REVISION_REDONE"!==e.type||(this.waitingUndoRedoAck=!1),e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":case"SNAPSHOT_CREATED":this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter((t=>t.nextRevisionId!==e.nextRevisionId)),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage()}}isAlreadyProcessed(e){if("CLIENT_MOVED"===e.type&&e.client.id===this.clientId)return!0;switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":case"SNAPSHOT_CREATED":return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter((({type:e})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e))}}const ob=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];class ib extends Gu{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 eb)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const o of this.getters.getConnectedClients())if(o.id!==this.getters.getClient().id&&o.position&&o.position.sheetId===e&&this.isPositionValid(o.position)){const e=o.position;this.colors[o.id]||(this.colors[o.id]=this.chooseNewColor());const i=this.colors[o.id];t.push({...o,position:e,color:i})}return t}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:o}=e,i=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:n,col:r}=e.position,s=this.getters.expandZone(i,{top:n,bottom:n,left:r,right:r}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(s);if(c<=0||h<=0)continue;const d=e.color,u=`${d}10`;t.fillStyle=u,t.lineWidth=4*o,t.strokeStyle=d,t.globalCompositeOperation="multiply",t.fillRect(a,l,c,h),t.globalCompositeOperation="source-over",t.strokeRect(a,l,c,h),t.font=`bold ${W+1}px ${G}`}}}ib.getters=["getClientsToDisplay"],ib.layers=[6];class nb extends Gu{allowDispatch(e){if("SORT_CELLS"===e.type){if(!Vo(e.col,e.row,e.zone))throw new Error(r("The anchor must be part of the provided zone"));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return 0}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{})}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;return qo(t).some((({col:t,row:o})=>!this.getters.isInMerge({sheetId:e,col:t,row:o})))?63:0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const o=this.getters.getMerges(e).filter((e=>Uo(e,t))),i=Wo(o[0]);let[n,r]=[i.width,i.height];return o.every((e=>{let[t,o]=[e.right-e.left+1,e.bottom-e.top+1];return t===n&&o===r}))?0:63}expand(e,t){const{left:o,right:i,top:n,bottom:r}=this.getters.expandZone(e,t);return{left:Math.max(0,o),right:Math.min(this.getters.getNumberCols(e)-1,i),top:Math.max(0,n),bottom:Math.min(this.getters.getNumberRows(e)-1,r)}}checkExpandedValues(e,t){const o=this.expand(e,t);let i;if(this.getters.doesIntersectMerge(e,o)){const{left:t,right:n,top:r,bottom:s}=o;for(let o=t;o<=n;o++)for(let t=r;t<=s;t++){const{col:n,row:r}=this.getters.getMainCellPosition({sheetId:e,col:o,row:t});if(i=this.getters.getEvaluatedCell({sheetId:e,col:n,row:r}),i.formattedValue)return!0}}else for(let t of this.getters.getEvaluatedCellsInZone(e,o))if(t.formattedValue)return!0;return!1}getContiguousZone(e,t){let o,{top:i,bottom:n,left:r,right:s}=t,a=!1;for(;!a;)a=!0,i>0&&(o=this.checkExpandedValues(e,{left:r-1,right:s+1,top:i-1,bottom:i-1}),o&&(a=!1,i--)),r>0&&(o=this.checkExpandedValues(e,{left:r-1,right:r-1,top:i-1,bottom:n+1}),o&&(a=!1,r--)),s<this.getters.getNumberCols(e)-1&&(o=this.checkExpandedValues(e,{left:s+1,right:s+1,top:i-1,bottom:n+1}),o&&(a=!1,s++)),n<this.getters.getNumberRows(e)-1&&(o=this.checkExpandedValues(e,{left:r-1,right:s+1,top:n+1,bottom:n+1}),o&&(a=!1,n++));return{left:r,right:s,top:i,bottom:n}}hasHeader(e,t){if(1===t[0].length)return!1;let o=t.map((t=>t.map((({col:t,row:o})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:o}).type))));return o[0][0]===mi.empty&&(o=o.slice(1)),!o.some((e=>e[0]===mi.empty))&&!!o.some((e=>e[1]!==mi.empty&&e[0]!==e[1]))}sortZone(e,t,o,i,n){const[r,s]=this.mainCellsSteps(e,o);let a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},o),c=this.mainCells(e,o);!n.sortHeaders&&this.hasHeader(e,c)&&(l.top+=s),c=this.mainCells(e,l);const h=function(e,t,o){const i=e.map(((e,t)=>({index:t,type:e.type,value:e.value})));let n=i.filter((e=>e.type===mi.empty)),r=i.filter((e=>e.type!==mi.empty));o&&(r.push(...n.map((e=>({...e,type:mi.number,value:0})))),n=[]);const s="descending"===t?-1:1;return r.sort(((e,t)=>{let o=Qn.indexOf(e.type)-Qn.indexOf(t.type);return 0===o&&(o=e.type===mi.text||e.type===mi.error?e.value.localeCompare(t.value):e.value-t.value),s*o})).concat(n)}(c[a-l.left].map((e=>this.getters.getEvaluatedCell(e))),i,Boolean(n.emptyCellAsZero)),d=h.map((e=>e.index)),[u,g]=[c.length,c[0].length],p=[];for(let e=0;e<u;e++){for(let t=0;t<g;t++){let{col:o,row:i,sheetId:n}=c[e][d[t]];const a=this.getters.getCell({sheetId:n,col:o,row:i});let h=l.left+e*r,u=l.top+t*s,g={sheetId:n,col:h,row:u,content:""};if(a){let e=a.content;if(a.isFormula){const t=u-this.getters.getCellPosition(a.id).row,o=this.getters.createAdaptedRanges(a.dependencies,0,t,n);e=this.getters.buildFormulaContent(n,a,o)}g.style=a.style,g.content=e,g.format=a.format}p.push(g)}for(const e of p)this.dispatch("UPDATE_CELL",e)}}mainCellsSteps(e,t){const o=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[o?o.right-o.left+1:1,o?o.bottom-o.top+1:1]}mainCells(e,t){const[o,i]=this.mainCellsSteps(e,t),n=[],r=Le(t.left,t.right+1,o),s=Le(t.top,t.bottom+1,i);for(const t of r){const o=[];n.push(o);for(const i of s)o.push({sheetId:e,col:t,row:i})}return n}}nb.getters=["getContiguousZone"];class rb extends Gu{constructor(){super(...arguments),this.showFormulas=!1}handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}rb.getters=["shouldShowFormulas"];class sb extends Gu{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 o=this.getColMaxWidth(e.sheetId,t);0!==o&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:o,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":for(let t of e.rows)this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"ROW",size:null,sheetId:e.sheetId})}}getCellWidth(e){let t=this.getTextWidth(e);this.getters.getConditionalIcon(e)&&(t+=Pe(this.getters.getCellStyle(e))+2*$);if(this.getters.isFilterHeader(e)&&(t+=20),t>0&&(t+=2*U,"wrap"===this.getters.getCellStyle(e).wrapping)){const o=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(o,t)}return t}getTextWidth(e){const t=this.getters.getCellText(e,this.getters.shouldShowFormulas());return ke(this.ctx,t,this.getters.getCellComputedStyle(e))}getCellText(e,t=!1){const o=this.getters.getCell(e);return t&&(null==o?void 0:o.isFormula)?o.content:this.getters.getEvaluatedCell(e).formattedValue}getCellMultiLineText(e,t){const o=this.getters.getCellStyle(e),i=this.getters.getCellText(e).split(" "),n=[];let r="",s=t;for(let e of i){const i=this.splitWordToSpecificWidth(this.ctx,e,t,o),a=i.pop(),l=ke(this.ctx,a,o);if(i.length)""!==r&&(n.push(r),r="",s=t),i.forEach((e=>{n.push(e)})),r=a,s=t-l;else{const e=""===r?a:" "+a,i=ke(this.ctx,e,o);i<=s?(r+=e,s-=i):(n.push(r),r=a,s=t-l)}}return""!==r&&n.push(r),n}getColDimensions(e,t){const o=this.getColRowOffset("COL",0,t,e),i=this.getters.getColSize(e,t);return{start:o,size:i,end:o+(this.getters.isColHidden(e,t)?0:i)}}getRowDimensions(e,t){const o=this.getColRowOffset("ROW",0,t,e),i=this.getters.getRowSize(e,t);return{start:o,size:i,end:o+(this.getters.isRowHidden(e,t)?0:i)}}getColRowOffset(e,t,o,i=this.getters.getActiveSheetId()){if(o<t)return-this.getColRowOffset(e,o,t);let n=0;for(let r=t;r<o;r++)this.getters.isHeaderHidden(i,e,r)||(n+="COL"===e?this.getters.getColSize(i,r):this.getters.getRowSize(i,r));return n}getColMaxWidth(e,t){const o=qo(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,...o)}splitWordToSpecificWidth(e,t,o,i){if(ke(e,t,i)<=o)return[t];const n=[];let r="";for(let s of t){ke(e,r+s,i)>o?(n.push(r),r=s):r+=s}return n.push(r),n}}sb.getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getColDimensions","getRowDimensions","getColRowOffset"];class ab{constructor(e,t,o,i){this.getters=t,this.dispatch=o,this.selection=i,this.operation=e,this.sheetId=t.getActiveSheetId()}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0}addMissingDimensions(e,t,o,i){const n=this.getters.getActiveSheetId(),r=t+i-this.getters.getNumberRows(n);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(n)-1,sheetId:n,quantity:r,position:"after"});const s=e+o-this.getters.getNumberCols(n);s>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(n)-1,sheetId:n,quantity:s,position:"after"})}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class lb extends ab{constructor(e,t,o,i,n){if(super(t,o,i,n),!e.length)return this.cells=[[]],this.zones=[],void(this.copiedTables=[]);const r=new Set(e.map((e=>e.left))),s=new Set(e.map((e=>e.right))),a=new Set(e.map((e=>e.top))),l=new Set(e.map((e=>e.bottom))),c=1===a.size&&1===l.size||1===r.size&&1===s.size?function(e){return e.reduce(((e,t)=>{const o=e.length;for(let i=0;i<o;i++)if(Uo(e[i],t))return e[i]=$o(e[i],t),e;return e[o]=t,e}),[])}(e):[e[e.length-1]],h=c.map((e=>qo(e))).flat(),d=[...new Set(h.map((e=>e.col)))].sort(((e,t)=>e-t)),u=[...new Set(h.map((e=>e.row)))].sort(((e,t)=>e-t)),g=[],p=o.getActiveSheetId();for(let e of u){let t=[];for(let i of d){const n={col:i,row:e,sheetId:p};t.push({cell:o.getCell(n),style:o.getCellComputedStyle(n),evaluatedCell:o.getEvaluatedCell(n),border:o.getCellBorder(n)||void 0,position:n})}g.push(t)}const m=[];for(const t of e)for(const e of this.getters.getFilterTablesInZone(p,t)){const t=[];for(const o of Le(e.zone.left,e.zone.right+1))t.push(this.getters.getFilterValues({sheetId:p,col:o,row:e.zone.top}));m.push({filtersValues:t,zone:e.zone})}this.cells=g,this.zones=c,this.copiedTables=m}isCutAllowed(e){return 1!==e.length?19:0}isPasteAllowed(e,t){const o=this.getters.getActiveSheetId();if("CUT"===this.operation&&void 0!==(null==t?void 0:t.pasteOption))return 21;if(e.length>1&&(this.cells.length>1||this.cells[0].length>1))return 20;const i=this.cells.length,n=this.cells[0].length;for(let t of this.getPasteZones(e))if(this.getters.doesIntersectMerge(o,t)&&(e.length>1||!this.getters.isSingleCellOrMerge(o,e[0])||i*n!=1))return 2;const{xSplit:r,ySplit:s}=this.getters.getPaneDivisions(o);for(const t of this.getPasteZones(e))if(t.left<r&&t.right>=r||t.top<s&&t.bottom>=s)return 75;return 0}paste(e,t){"COPY"===this.operation?this.pasteFromCopy(e,t):this.pasteFromCut(e,t);const o=this.cells.length,i=this.cells[0].length,n="CUT"===this.operation;(null==t?void 0:t.selectTarget)&&this.selectPastedZone(i,o,n,e)}pasteFromCopy(e,t){if(1===e.length){const o=this.cells.length,i=this.cells[0].length,n=this.pastedZones(e,i,o);for(const e of n)this.pasteZone(e.left,e.top,t)}else for(const o of e)for(let e=o.left;e<=o.right;e++)for(let i=o.top;i<=o.bottom;i++)this.pasteZone(e,i,t);void 0===(null==t?void 0:t.pasteOption)&&this.pasteCopiedTables(e)}pasteFromCut(e,t){this.clearClippedZones();const o=e[0];this.pasteZone(o.left,o.top,t),this.dispatch("MOVE_RANGES",{target:this.zones,sheetId:this.sheetId,targetSheetId:this.getters.getActiveSheetId(),col:o.left,row:o.top});for(const e of this.copiedTables)this.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.getters.getActiveSheetId(),target:[e.zone]});this.pasteCopiedTables(e)}pastedZones(e,t,o){const i=e[0],n=Math.max(1,Math.floor((i.right+1-i.left)/t)),r=Math.max(1,Math.floor((i.bottom+1-i.top)/o)),s=[];for(let e=0;e<n;e++)for(let n=0;n<r;n++){const r=i.top+n*o,a=i.left+e*t;s.push({left:a,top:r,bottom:r+o-1,right:a+t-1})}return s}getPasteZones(e){const t=this.cells;if(!t.length||!t[0].length)return e;const o=[],i=t.length,n=t[0].length,r=e[e.length-1],s=r.left,a=r.top,l=Math.max(1,Math.floor((r.right+1-s)/n)),c=Math.max(1,Math.floor((r.bottom+1-a)/i));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)o.push({left:s,top:a,right:s-1+e*n,bottom:a-1+t*i});return o}selectPastedZone(e,t,o,i){const n=i[0],r=n.left,s=n.top;if(t>1||e>1||o){const n=this.pastedZones(i,e,t),a=o?n[0]:$o(...n);this.selection.selectZone({cell:{col:r,row:s},zone:a})}}clearClippedZones(){for(const e of this.cells)for(const t of e)t.cell&&this.dispatch("CLEAR_CELL",t.position);this.dispatch("CLEAR_FORMATTING",{sheetId:this.sheetId,target:this.zones})}pasteZone(e,t,o){const i=this.cells.length,n=this.cells[0].length,r="onlyValue"!==(null==o?void 0:o.pasteOption)&&(null==o?void 0:o.shouldPasteCF),s=this.getters.getActiveSheetId();this.addMissingDimensions(n,i,e,t);for(let a=0;a<i;a++){const i=this.cells[a];for(let l=0;l<n;l++){const n=i[l],c={col:e+l,row:t+a,sheetId:s};"CUT"!==this.operation&&this.pasteMergeIfExist(n.position,c),this.pasteCell(n,c,this.operation,o),r&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{origin:n.position,target:c,operation:this.operation})}}}pasteCell(e,t,o,i){const{sheetId:n,col:r,row:s}=t,a=this.getters.getEvaluatedCell(t);if("onlyValue"!==(null==i?void 0:i.pasteOption)){const o=this.getters.getCellBorder(t),i=e.border,a={top:(null==o?void 0:o.top)||(null==i?void 0:i.top),bottom:(null==o?void 0:o.bottom)||(null==i?void 0:i.bottom),left:(null==o?void 0:o.left)||(null==i?void 0:i.left),right:(null==o?void 0:o.right)||(null==i?void 0:i.right)};this.dispatch("SET_BORDER",{sheetId:n,col:r,row:s,border:a})}if(e.cell){if("onlyFormat"===(null==i?void 0:i.pasteOption))return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.evaluatedCell.format});if("onlyValue"===(null==i?void 0:i.pasteOption)){const o=no(e.evaluatedCell.value);return void this.dispatch("UPDATE_CELL",{...t,content:o})}let a=e.cell.content;if(e.cell.isFormula&&"COPY"===o){const t=r-e.position.col,i=s-e.position.row;a=this.getUpdatedContent(n,e.cell,t,i,o)}this.dispatch("UPDATE_CELL",{...t,content:a,style:e.cell.style||null,format:e.cell.format})}else a&&("onlyValue"===(null==i?void 0:i.pasteOption)?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===(null==i?void 0:i.pasteOption)?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,o,i,n){const r=this.getters.createAdaptedRanges(t.dependencies,o,i,e);return this.getters.buildFormulaContent(e,t,r)}pasteMergeIfExist(e,t){let{sheetId:o,col:i,row:n}=e;const{col:r,row:s}=this.getters.getMainCellPosition(e);if(r===i&&s===n){const r=this.getters.getMerge(e);if(!r)return;({sheetId:o,col:i,row:n}=t),this.dispatch("ADD_MERGE",{sheetId:o,force:!0,target:[{left:i,top:n,right:i+r.right-r.left,bottom:n+r.bottom-r.top}]})}}pasteCopiedTables(e){const t=this.getters.getActiveSheetId(),o=e[0],i=this.zones[0],n=[o.left-i.left,o.top-i.top];for(const e of this.copiedTables){const o=Zo(e.zone,"both","MOVE",n);this.dispatch("CREATE_FILTER_TABLE",{sheetId:t,target:[o]});for(const i of Le(0,e.filtersValues.length))this.dispatch("UPDATE_FILTER",{sheetId:t,col:o.left+i,row:o.top,values:e.filtersValues[i]})}}getClipboardContent(){return{[fi.PlainText]:this.getPlainTextContent(),[fi.Html]:this.getHTMLContent()}}getPlainTextContent(){return this.cells.map((e=>e.map((e=>e.cell?this.getters.getCellText(e.position,this.getters.shouldShowFormulas()):"")).join("\t"))).join("\n")||"\t"}getHTMLContent(){if(1==this.cells.length&&1==this.cells[0].length)return this.getters.getCellText(this.cells[0][0].position);let e='<table border="1" style="border-collapse:collapse">';for(const t of this.cells){e+="<tr>";for(const o of t){e+=`<td style="${ai(ri(o.style),!1)}">`+Mf(this.getters.getCellText(o.position))+"</td>"}e+="</tr>"}return e+="</table>",e}isColRowDirtyingClipboard(e,t){if(!this.zones)return!1;for(let o of this.zones){if("COL"===t&&e<=o.right)return!0;if("ROW"===t&&e<=o.bottom)return!0}return!1}drawClipboard(e){const{ctx:t,thinLineWidth:o}=e;if(this.sheetId===this.getters.getActiveSheetId()&&this.zones&&this.zones.length){t.setLineDash([8,5]),t.strokeStyle=E,t.lineWidth=3.3*o;for(const e of this.zones){const{x:o,y:i,width:n,height:r}=this.getters.getVisibleRect(e);n>0&&r>0&&t.strokeRect(o,i,n,r)}}}}class cb{constructor(e,t,o){this.operation=e,this.getters=t,this.dispatch=o,this.sheetId=t.getActiveSheetId();const i=t.getSelectedFigureId();if(!i)throw new Error("No figure selected");const n=t.getFigure(this.sheetId,i);if(!n)throw new Error(`No figure for the given id: ${i}`);switch(this.copiedFigure={...n},n.tag){case"chart":this.copiedFigureContent=new hb(o,t,this.sheetId,i);break;case"image":this.copiedFigureContent=new db(o,t,this.sheetId,i);break;default:throw new Error(`Unknow tag '${n.tag}' for the given figure id: ${i}`)}}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0===e.length?73:void 0!==(null==t?void 0:t.pasteOption)?22:0}paste(e){const t=this.getters.getActiveSheetId(),o={x:this.getters.getColDimensions(t,e[0].left).start,y:this.getters.getRowDimensions(t,e[0].top).start},i={height:this.copiedFigure.height,width:this.copiedFigure.width},n=(new To).uuidv4();this.copiedFigureContent.paste(t,n,o,i),"CUT"===this.operation&&this.dispatch("DELETE_FIGURE",{sheetId:this.copiedFigureContent.sheetId,id:this.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{id:n})}getClipboardContent(){return{[fi.PlainText]:"\t"}}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class hb{constructor(e,t,o,i){this.dispatch=e,this.sheetId=o;const n=t.getChart(i);if(!n)throw new Error(`No chart for the given id: ${i}`);this.copiedChart=n.copyInSheetId(o)}paste(e,t,o,i){const n=this.copiedChart.copyInSheetId(e);this.dispatch("CREATE_CHART",{id:t,sheetId:e,position:o,size:i,definition:n.getDefinition()})}}class db{constructor(e,t,o,i){this.dispatch=e,this.sheetId=o;const n=t.getImage(i);this.copiedImage=Me(n)}paste(e,t,o,i){const n=Me(this.copiedImage);this.dispatch("CREATE_IMAGE",{figureId:t,sheetId:e,position:o,size:i,definition:n})}}class ub extends ab{constructor(e,t,o,i){super("COPY",t,o,i),this.values=e.replace(/\r/g,"").split("\n").map((e=>e.split("\t")))}isPasteAllowed(e,t){const o=this.getters.getActiveSheetId(),i=this.getPasteZone(e);return this.getters.doesIntersectMerge(o,i)?2:0}paste(e){const t=this.values,o=this.getPasteZone(e),{left:i,top:n}=o,{width:r,height:s}=Wo(o),a=this.getters.getActiveSheetId();this.addMissingDimensions(r,s,i,n);for(let e=0;e<t.length;e++)for(let o=0;o<t[e].length;o++)this.dispatch("UPDATE_CELL",{row:n+e,col:i+o,content:t[e][o],sheetId:a});const l={left:i,top:n,right:i+r-1,bottom:n+s-1};this.selection.selectZone({cell:{col:i,row:n},zone:l})}getClipboardContent(){return{[fi.PlainText]:this.values.map((e=>e.join("\t"))).join("\n")}}getPasteZone(e){const t=this.values.length,o=Math.max(...this.values.map((e=>e.length))),{left:i,top:n}=e[0];return{top:n,left:i,bottom:n+t-1,right:i+o-1}}}class gb extends Gu{constructor(){super(...arguments),this.status="invisible",this._isPaintingFormat=!1}allowDispatch(e){switch(e.type){case"CUT":const t=e.target||this.getters.getSelectedZones();return this.getClipboardState(t,e.type).isCutAllowed(t);case"PASTE":if(!this.state)return 23;const o=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);return this.state.isPasteAllowed(e.target,{pasteOption:o});case"PASTE_FROM_OS_CLIPBOARD":return new ub(e.text,this.getters,this.dispatch,this.selection).isPasteAllowed(e.target);case"INSERT_CELL":{const{cut:t,paste:o}=this.getInsertCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(o)}case"DELETE_CELL":{const{cut:t,paste:o}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(o)}}return 0}handle(e){var t,o;switch(e.type){case"COPY":case"CUT":const i="target"in e&&e.target||this.getters.getSelectedZones();this.state=this.getClipboardState(i,e.type),this.status="visible";break;case"PASTE":if(!this.state)break;const n=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);this._isPaintingFormat=!1,this.state.paste(e.target,{pasteOption:n,shouldPasteCF:!0,selectTarget:!0}),"CUT"===this.state.operation&&(this.state=void 0),this.status="invisible";break;case"CLEAN_CLIPBOARD_HIGHLIGHT":this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:o}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!Mo(t[0])){for(const{col:t,row:o}of qo(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:o,sheetId:this.getters.getActiveSheetId()});break}this.getClipboardStateForCopyCells(t,"CUT").paste(o);break}case"INSERT_CELL":{const{cut:t,paste:o}=this.getInsertCellsTargets(e.zone,e.shiftDimension);this.getClipboardStateForCopyCells(t,"CUT").paste(o);break}case"ADD_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(t=this.state)||void 0===t?void 0:t.operation))return;this.state.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.state=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(o=this.state)||void 0===o?void 0:o.operation))return;for(let t of e.elements){if(this.state.isColRowDirtyingClipboard(t,e.dimension)){this.state=void 0;break}}this.status="invisible";break;case"PASTE_FROM_OS_CLIPBOARD":new ub(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:Ei(e)&&(this.status="invisible")}}getClipboardContent(){var e;return(null===(e=this.state)||void 0===e?void 0:e.getClipboardContent())||{[fi.PlainText]:"\t"}}getClipboardTextContent(){var e;return(null===(e=this.state)||void 0===e?void 0:e.getClipboardContent()[fi.PlainText])||"\t"}isCutOperation(){return!!this.state&&"CUT"===this.state.operation}isPaintingFormat(){return this._isPaintingFormat}getDeleteCellsTargets(e,t){const o=this.getters.getActiveSheetId();let i;return i="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(o)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(o)-1},{cut:[i],paste:[e]}}getInsertCellsTargets(e,t){const o=this.getters.getActiveSheetId();let i,n;return"COL"===t?(i={...e,right:this.getters.getNumberCols(o)-1},n={...e,left:e.right+1,right:e.right+1}):(i={...e,bottom:this.getters.getNumberRows(o)-1},n={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(o)-1}),{cut:[i],paste:[n]}}getClipboardStateForCopyCells(e,t){return new lb(e,t,this.getters,this.dispatch,this.selection)}getClipboardState(e,t){return this.getters.getSelectedFigureId()?new cb(t,this.getters,this.dispatch):new lb(e,t,this.getters,this.dispatch,this.selection)}drawGrid(e){"visible"===this.status&&this.state&&this.state.drawClipboard(e)}}gb.layers=[2],gb.getters=["getClipboardContent","getClipboardTextContent","isCutOperation","isPaintingFormat"];const pb=[{name:r("Sum"),types:[mi.number],compute:e=>pa.compute([e])},{name:r("Avg"),types:[mi.number],compute:e=>Ia.compute([e])},{name:r("Min"),types:[mi.number],compute:e=>Ba.compute([e])},{name:r("Max"),types:[mi.number],compute:e=>La.compute([e])},{name:r("Count"),types:[mi.number,mi.text,mi.boolean,mi.error],compute:e=>Fa.compute([e])},{name:r("Count Numbers"),types:[mi.number,mi.text,mi.boolean,mi.error],compute:e=>_a.compute([e])}];class mb extends Gu{constructor(e){super(e),this.gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]},this.selectedFigureId=null,this.sheetsData={},this.activeSheet=null,this.moveClient=e.moveClient}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{this.getters.getSheet(e.sheetIdTo);break}catch(e){return 27}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return 0}handleEvent(e){const t=e.anchor;let o=[];switch(e.mode){case"overrideSelection":o=[t.zone];break;case"updateAnchor":o=[...this.gridSelection.zones];const i=o.findIndex((t=>Lo(t,e.previousAnchor.zone)));i>=0&&(o[i]=t.zone);break;case"newAnchor":o=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,o),this.selection.resetDefaultAnchor(this,Me(this.gridSelection.anchor));const{col:i,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:i,row:n}),this.selectedFigureId=null}handle(e){switch(e.type){case"START_EDITION":case"ACTIVATE_SHEET":this.selectedFigureId=null;break;case"DELETE_FIGURE":this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;case"DELETE_SHEET":this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null)}switch(e.type){case"START":const t=this.getters.getVisibleSheetIds()[0];this.dispatch("ACTIVATE_SHEET",{sheetIdTo:t,sheetIdFrom:t});const{col:o,row:i}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(o,i),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case"ACTIVATE_SHEET":if(this.getters.isSheetVisible(e.sheetIdTo)||this.dispatch("SHOW_SHEET",{sheetId:e.sheetIdTo}),this.setActiveSheet(e.sheetIdTo),this.sheetsData[e.sheetIdFrom]={gridSelection:Me(this.gridSelection)},e.sheetIdTo in this.sheetsData)Object.assign(this,this.sheetsData[e.sheetIdTo]),this.selection.resetDefaultAnchor(this,Me(this.gridSelection.anchor));else{const{col:t,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0});this.selectCell(t,o)}break;case"REMOVE_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);const{col:o,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:o,row:i})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:o,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:o,row:i})}break}case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"SELECT_FIGURE":this.selectedFigureId=e.id;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left");break;case"HIDE_SHEET":e.sheetId===this.getActiveSheetId()&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case"UNDO":case"REDO":case"DELETE_SHEET":const n=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of n)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:Me(t)}}if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){const e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){const{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);const{col:t,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:o})}const r=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map((e=>this.getters.expandZone(r,e))),this.gridSelection.anchor.zone=this.getters.expandZone(r,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones)}this.selection.resetDefaultAnchor(this,Me(this.gridSelection.anchor))}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){const e=new Set;for(let t of this.gridSelection.zones)if(0===t.top&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let o=t.left;o<=t.right;o++)e.add(o);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(let o of this.gridSelection.zones)if(0===o.left&&o.right===this.getters.getNumberCols(t)-1)for(let t=o.top;t<=o.bottom;t++)e.add(t);return e}getCurrentStyle(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return Me(this.gridSelection.zones)}getSelectedZone(){return Me(this.gridSelection.anchor.zone)}getSelection(){return Me(this.gridSelection)}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{const t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}getStatisticFnResults(){const e=new Set(this.gridSelection.zones.map((e=>this.getters.getEvaluatedCellsInZone(this.getters.getActiveSheetId(),e))).flat().filter((e=>e.type!==mi.empty)));let t=new Set,o=[];for(let i of e)t.add(i.type),o.push(i.value);let i={};for(let e of pb){let n;e.types.some((e=>t.has(e)))&&(n=e.compute(o)),i[e.name]=n}return i}getAggregate(){let e=0,t=0;const o=this.getters.getActiveSheetId(),i=this.gridSelection.zones.map(qo).flat();for(const{col:n,row:r}of i){const i=this.getters.getEvaluatedCell({sheetId:o,col:n,row:r});i.type===mi.number&&(t++,e+=i.value)}return t<2?null:no(e)}isSelected(e){return!!this.getters.getSelectedZones().find((t=>Lo(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 o=[];const i="COL"===e?"left":"top",n="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[n]-e[i]+1},((t,o)=>e[i]+o));o=o.concat(t)}return[...new Set(o)].sort()}setSelectionMixin(e,t){const{anchor:o,zones:i}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=o,this.gridSelection.zones=function(e){return e.reverse().filter(((e,t,o)=>t===o.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}(i)}selectCell(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.expandZone(o,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:i,cell:{col:e,row:t}},[i])}setActiveSheet(e){const t=this.getters.getSheet(e);this.activeSheet=t}activateNextSheet(e){const t=this.getters.getSheetIds(),o=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[o]})}onColumnsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,i=Do(o,"left",[...e.elements]);let n={left:t.col,right:t.col,top:t.row,bottom:t.row};n=Do(n,"left",[...e.elements]);const r={cell:{col:n.left,row:n.top},zone:i};this.setSelectionMixin(r,[i])}onRowsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,i=Do(o,"top",[...e.elements]);let n={left:t.col,right:t.col,top:t.row,bottom:t.row};n=Do(n,"top",[...e.elements]);const r={cell:{col:n.left,row:n.top},zone:i};this.setSelectionMixin(r,[i])}onAddElements(e){const t=Fo(this.gridSelection.anchor.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),o={cell:{col:t.left,row:t.top},zone:t};this.setSelectionMixin(o,[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:"before"});const o="COL"===e.dimension,i=e.elements[0],n=e.elements[t-1],r=e.base<i,s=r&&o?t:0,a=r&&!o?t:0;this.dispatch("CUT",{target:[{left:o?i+s:0,right:o?n+s:this.getters.getNumberCols(e.sheetId)-1,top:o?0:i+a,bottom:o?this.getters.getNumberRows(e.sheetId)-1:n+a}]}),this.dispatch("PASTE",{target:[{left:o?e.base:0,right:o?e.base+t-1:this.getters.getNumberCols(e.sheetId)-1,top:o?0:e.base,bottom:o?this.getters.getNumberRows(e.sheetId)-1:e.base+t-1}]});const l=r?e.elements.map((e=>e+t)):e.elements;let c=e.base;for(const t of l){const o="COL"===e.dimension?this.getters.getColSize(e.sheetId,t):this.getters.getRowSize(e.sheetId,t);this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:o,elements:[c]}),c+=1}this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,elements:l})}isMoveElementAllowed(e){const t="COL"===e.dimension,o=e.elements[0],i=e.elements[e.elements.length-1],n=e.sheetId,r=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;return r(n,o-1,o)||r(n,i,i+1)||r(n,e.base-1,e.base)?2:0}clipSelection(e,t){const o=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;return{zones:t.zones.map((e=>({left:Fe(e.left,0,o),right:Fe(e.right,0,o),top:Fe(e.top,0,i),bottom:Fe(e.bottom,0,i)}))),anchor:{cell:{col:Fe(t.anchor.cell.col,0,o),row:Fe(t.anchor.cell.row,0,i)},zone:{left:Fe(t.anchor.zone.left,0,o),right:Fe(t.anchor.zone.right,0,o),top:Fe(t.anchor.zone.top,0,i),bottom:Fe(t.anchor.zone.bottom,0,i)}}}}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:o}=e,i=this.getSelectedZones();t.fillStyle="#f3f7fe";const n=1===i.length&&i[0].left===i[0].right&&i[0].top===i[0].bottom;t.fillStyle=n?"#f3f7fe":"#e9f0ff",t.strokeStyle=E,t.lineWidth=1.5*o;for(const e of i){const{x:o,y:i,width:n,height:r}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(o,i,n,r),t.globalCompositeOperation="source-over",t.strokeRect(o,i,n,r)}t.globalCompositeOperation="source-over";const r=this.getActivePosition();let s;t.strokeStyle=E,t.lineWidth=3*o,s=this.getters.isInMerge(r)?this.getters.getMerge(r):Yo(r);const{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(s);c>0&&h>0&&t.strokeRect(a,l,c,h)}}mb.layers=[6],mb.getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getStatisticFnResults","getAggregate","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSelected","getElementsFromSelection"];const fb=(new xn).add("sheet",Rv).add("header visibility",Sv).add("filters",bv).add("cell",dv).add("merge",wv).add("headerSize",Cv).add("borders",cv).add("conditional formatting",pv).add("figures",mv).add("chart",uv).add("image",Ev),vb=(new xn).add("ui_sheet",sb).add("header_visibility_ui",zv).add("ui_options",rb).add("selectionInputManager",Gv).add("highlight",Bv).add("grid renderer",Hv).add("autofill",$v).add("find_and_replace",Vv).add("sort",nb).add("automatic_sum",Pv).add("format",class extends Gu{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,o){const i=this.searchNumberFormat(e,t);if(void 0!==i){const n=function(e,t){const o=io(e).map((e=>"NUMBER"===e.type?{...e,format:bo(e.format,t)}:e)),i=wo(o);return oo[i]=o,i}(i,o);this.dispatch("SET_FORMATTING",{sheetId:e,target:t,format:n})}}searchNumberFormat(e,t){var o;for(let i of t)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++){const i=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(i.type===mi.number&&!(null===(o=i.format)||void 0===o?void 0:o.match(j)))return i.format||mo(i.value)}}}).add("cell_popovers",Lv).add("selection_multiuser",ib),bb=(new xn).add("selection",mb).add("clipboard",gb).add("edition",Zu),Cb=(new xn).add("evaluation",Ov).add("evaluation_filter",_v).add("evaluation_chart",Mv).add("evaluation_cf",Nv).add("viewport",Dv).add("custom_colors",Tv),Sb=new xn;Sb.add("link",{condition:(e,t)=>!!t.model.getters.getEvaluatedCell(e).link,action:(e,t)=>bg(t.model.getters.getEvaluatedCell(e).link,t),sequence:5});class Eb{constructor(e){this.fileStore=e}async requestImage(){const e=await this.getImageFromUser(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageSize(t)}}getImageFromUser(){return new Promise(((e,t)=>{const o=document.createElement("input");o.setAttribute("type","file"),o.setAttribute("accept","image/*"),o.addEventListener("change",(async()=>{null===o.files||1!=o.files.length?t():e(o.files[0])})),o.click()}))}getImageSize(e){return new Promise(((t,o)=>{const i=new Image;i.src=e,i.addEventListener("load",(()=>{const e={width:i.width,height:i.height};t(e)})),i.addEventListener("error",o)}))}}ii`
1415
+ `}function kf(e){return new qp(e.join("\n"))}function $f(e,...t){let o=[e[0]];for(let i=0;i<t.length;i++){const n=t[i]instanceof qp?t[i]:Nf(t[i]);o.push(n+e[i+1])}return new qp(ot(o))}function Pf(e){return e.replace(/[a-z0-9]+:(?=[a-z0-9]+)/gi,"")}function Lf(e){return e.replace(/([a-z0-9]+):(?=[a-z0-9]+)/gi,"$1\\:")}class Uf{constructor(e){this.value=e}asString(){return km(String(this.value))}asBool(){return Boolean(Number(this.value))}asNum(){return Number(this.value)}}class Vf{constructor(e,t,o){this.currentFile=void 0,this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=o,this.areNamespaceIgnored=null!==(new DOMParser).parseFromString("<t:test xmlns:t='a'/>","text/xml").querySelector("test"),this.relationships={},e.rels&&this.extractRelationships(e.rels).map((e=>{this.relationships[e.id]=e}))}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:"Relationship"},(e=>({id:this.extractAttr(e,"Id",{required:!0}).asString(),target:this.extractAttr(e,"Target",{required:!0}).asString(),type:this.extractAttr(e,"Type",{required:!0}).asString()})))}getListOfFiles(){return Object.values(this.xlsxFileStructure).flat().filter(Je)}mapOnElements(e,t){var o;const i=[],n=this.currentFile;let r;if(e.children){const t=null===(o=this.querySelector(e.parent,e.query))||void 0===o?void 0:o.children;r=t||[]}else r=this.querySelectorAll(e.parent,e.query);if(r)for(let e of r)try{i.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=n,i}catchErrorOnElement(e,t){const o=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([o,e.message].join("\n"))}extractAttr(e,t,o){const i=e.attributes[t];i||this.handleMissingValue(e,`attribute "${t}"`,o);const n=(null==i?void 0:i.value)?i.value:null==o?void 0:o.default;return void 0===n?void 0:new Uf(n)}extractTextContent(e,t){var o;if(void 0!==(null==t?void 0:t.default)&&"string"!=typeof t.default)throw new Error("extractTextContent default value should be a string");const i="preserve"===(null===(o=null==e?void 0:e.attributes["xml:space"])||void 0===o?void 0:o.value);let n=null==e?void 0:e.textContent;return e&&null!==n||this.handleMissingValue(e,"text content",t),n&&(n=i?n:n.trim()),n?km(n):null==t?void 0:t.default}extractChildAttr(e,t,o,i){var n;let r;r="number"==typeof t?e.children[t]:this.querySelector(e,t),r||this.handleMissingValue(e,"number"==typeof t?`child at index ${t}`:`child <${t}>`,i);const s=r?null===(n=this.extractAttr(r,o,i))||void 0===n?void 0:n.asString():null==i?void 0:i.default;return void 0!==s?new Uf(s):void 0}extractChildTextContent(e,t,o){if(void 0!==(null==o?void 0:o.default)&&"string"!=typeof o.default)throw new Error("extractTextContent default value should be a string");let i=this.querySelector(e,t);return i||this.handleMissingValue(e,`child <${t}>`,o),i?this.extractTextContent(i,o):null==o?void 0:o.default}handleMissingValue(e,t,o){if(null==o?void 0:o.required){if(!(null==o?void 0:o.default))throw new Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`);this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${o.default}`)}}extractColor(e,t,o){var i,n,r,s,a;if(!e)return o?{rgb:o}:void 0;const l=null===(i=this.extractAttr(e,"theme"))||void 0===i?void 0:i.asString();let c;if(void 0!==l){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");c=this.getThemeColor(l,t.clrScheme)}else c=null===(n=this.extractAttr(e,"rgb"))||void 0===n?void 0:n.asString();return{rgb:c,auto:null===(r=this.extractAttr(e,"auto"))||void 0===r?void 0:r.asBool(),indexed:null===(s=this.extractAttr(e,"indexed"))||void 0===s?void 0:s.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 o=this.getListOfFiles().find((e=>e.file.fileName.endsWith(t)));if(!o||!o.file)throw new Error("Cannot find target file");return o}querySelector(e,t){return t=this.areNamespaceIgnored?Pf(t):Lf(t),e.querySelector(t)}querySelectorAll(e,t){return t=this.areNamespaceIgnored?Pf(t):Lf(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 zf extends Vf{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:jp}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:jp}).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 Bf extends Vf{constructor(e,t,o,i){super(e,t,o),this.theme=i}extractConditionalFormattings(){const e=this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > conditionalFormatting"},(e=>{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 o,i,n,r,s,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===(o=this.extractAttr(e,"dxfId"))||void 0===o?void 0:o.asNum(),stopIfTrue:null===(i=this.extractAttr(e,"stopIfTrue"))||void 0===i?void 0:i.asBool(),aboveAverage:null===(n=this.extractAttr(e,"aboveAverage"))||void 0===n?void 0:n.asBool(),percent:null===(r=this.extractAttr(e,"percent"))||void 0===r?void 0:r.asBool(),bottom:null===(s=this.extractAttr(e,"bottom"))||void 0===s?void 0:s.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 o=this.querySelector(e,"colorScale");if(o)return{colors:this.mapOnElements({parent:o,query:"color"},(e=>this.extractColor(e,t,"ffffff"))),cfvos:this.extractCFVos(o)}}extractCfIconSet(e){var t,o;const i=this.querySelector(e,"iconSet, x14:iconSet");if(i)return{iconSet:this.extractAttr(i,"iconSet",{default:"3TrafficLights1"}).asString(),showValue:this.extractAttr(i,"showValue",{default:!0}).asBool(),percent:this.extractAttr(i,"percent",{default:!0}).asBool(),reverse:null===(t=this.extractAttr(i,"reverse"))||void 0===t?void 0:t.asBool(),custom:null===(o=this.extractAttr(i,"custom"))||void 0===o?void 0:o.asBool(),cfvos:this.extractCFVos(i),cfIcons:this.extractCfIcons(i)}}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,o;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===(o=this.extractAttr(e,"val"))||void 0===o?void 0:o.asString():this.extractChildTextContent(e,"f, xm:f")}}))}}class Hf extends Vf{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},(e=>{const t=this.getChartType(e);if(!Rm[t])throw new Error(`Unsupported chart type ${t}`);const o=this.mapOnElements({parent:e,query:"c:title a:t"},(e=>e.textContent||"")).join(""),i=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString();return{title:o,type:Rm[t],dataSets:this.extractChartDatasets(this.querySelector(e,`c:${t}`)),backgroundColor:this.extractChildAttr(e,"c:chartSpace > c:spPr a:srgbClr","val",{default:"ffffff"}).asString(),verticalAxisPosition:"r"===this.extractChildAttr(e,"c:valAx > c:axPos","val",{default:"l"}).asString()?"right":"left",legendPosition:Im[this.extractChildAttr(e,"c:legendPos","val",{default:"b"}).asString()],stacked:"stacked"===i,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=Pf(e.tagName);if(Zp.some((e=>e===t)))return t}throw new Error("Unknown chart type")}}class Wf extends Vf{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},(e=>{if("twoCellAnchor"!==Pf(e.tagName))throw new Error("Only twoCellAnchor are supported for xlsx drawings.");const t=this.querySelector(e,"c:chart");if(!t)throw new Error("Only chart figures are currently supported.");return{anchors:[this.extractFigureAnchor("xdr:from",e),this.extractFigureAnchor("xdr:to",e)],data:this.extractChart(t)}}))}extractFigureAnchor(e,t){const o=this.querySelector(t,e);if(!o)throw new Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(o,"xdr:col",{required:!0})),colOffset:Number(this.extractChildTextContent(o,"xdr:colOff",{required:!0})),row:Number(this.extractChildTextContent(o,"xdr:row",{required:!0})),rowOffset:Number(this.extractChildTextContent(o,"xdr:rowOff",{required:!0}))}}extractChart(e){const t=this.extractAttr(e,"r:id",{required:!0}).asString(),o=this.getTargetXmlFile(this.relationships[t]),i=new Hf(o,this.xlsxFileStructure,this.warningManager).extractChart();if(!i)throw new Error("Unable to extract chart definition");return i}}class Gf extends Vf{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 qf extends Vf{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,o,i,n,r;return{name:null===(t=this.extractAttr(e,"name"))||void 0===t?void 0:t.asString(),showFirstColumn:null===(o=this.extractAttr(e,"showFirstColumn"))||void 0===o?void 0:o.asBool(),showLastColumn:null===(i=this.extractAttr(e,"showLastColumn"))||void 0===i?void 0:i.asBool(),showRowStripes:null===(n=this.extractAttr(e,"showRowStripes"))||void 0===n?void 0:n.asBool(),showColumnStripes:null===(r=this.extractAttr(e,"showColumnStripes"))||void 0===r?void 0:r.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 Zf extends Vf{constructor(e,t,o,i){super(e,t,o),this.theme=i}getSheet(){return this.mapOnElements({query:"worksheet",parent:this.rootFile.file.xml},(e=>{const t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:[...this.extractTables(e),...this.extractPivotTables()],isVisible:"visible"===t.state}}))[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:"sheetView"},(e=>{const t=this.querySelector(e,"pane");return{tabSelected:this.extractAttr(e,"tabSelected",{default:!1}).asBool(),showFormulas:this.extractAttr(e,"showFormulas",{default:!1}).asBool(),showGridLines:this.extractAttr(e,"showGridLines",{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,"showRowColHeaders",{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,"xSplit",{default:0}).asNum():0,ySplit:t?this.extractAttr(t,"ySplit",{default:0}).asNum():0}}}))}extractSheetName(){const e=_m(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=_m(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id,o=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:"sheet"},(e=>({relationshipId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetId:this.extractAttr(e,"sheetId",{required:!0}).asString(),sheetName:this.extractAttr(e,"name",{required:!0}).asString(),state:this.extractAttr(e,"state",{default:"visible"}).asString()}))).find((e=>e.relationshipId===t));if(!o)throw new Error("Cannot find corresponding workbook sheet");return o}extractConditionalFormats(){return new Bf(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractFigures(e){return this.mapOnElements({parent:e,query:"drawing"},(e=>{var t;const o=null===(t=this.extractAttr(e,"r:id",{required:!0}))||void 0===t?void 0:t.asString(),i=this.getTargetXmlFile(this.relationships[o]);return new Wf(i,this.xlsxFileStructure,this.warningManager).extractFigures()}))[0]||[]}extractTables(e){return this.mapOnElements({query:"tablePart",parent:e},(e=>{var t;const o=null===(t=this.extractAttr(e,"r:id",{required:!0}))||void 0===t?void 0:t.asString(),i=this.getTargetXmlFile(this.relationships[o]);return new qf(i,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 Gf(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:nm.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:rm.toString()}).asNum()}}extractCols(e){return this.mapOnElements({parent:e,query:"cols col"},(e=>{var t,o,i,n,r,s,a;return{width:null===(t=this.extractAttr(e,"width"))||void 0===t?void 0:t.asNum(),customWidth:null===(o=this.extractAttr(e,"customWidth"))||void 0===o?void 0:o.asBool(),bestFit:null===(i=this.extractAttr(e,"bestFit"))||void 0===i?void 0:i.asBool(),hidden:null===(n=this.extractAttr(e,"hidden"))||void 0===n?void 0:n.asBool(),min:null===(r=this.extractAttr(e,"min",{required:!0}))||void 0===r?void 0:r.asNum(),max:null===(s=this.extractAttr(e,"max",{required:!0}))||void 0===s?void 0:s.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,o,i,n,r;return{index:null===(t=this.extractAttr(e,"r",{required:!0}))||void 0===t?void 0:t.asNum(),cells:this.extractCells(e),height:null===(o=this.extractAttr(e,"ht"))||void 0===o?void 0:o.asNum(),customHeight:null===(i=this.extractAttr(e,"customHeight"))||void 0===i?void 0:i.asBool(),hidden:null===(n=this.extractAttr(e,"hidden"))||void 0===n?void 0:n.asBool(),styleIndex:null===(r=this.extractAttr(e,"s"))||void 0===r?void 0:r.asNum()}}))}extractCells(e){return this.mapOnElements({parent:e,query:"c"},(e=>{var t,o,i;return{xc:null===(t=this.extractAttr(e,"r",{required:!0}))||void 0===t?void 0:t.asString(),styleIndex:null===(o=this.extractAttr(e,"s"))||void 0===o?void 0:o.asNum(),type:Cm[null===(i=this.extractAttr(e,"t",{default:"n"}))||void 0===i?void 0:i.asString()],value:this.extractChildTextContent(e,"v"),formula:this.extractCellFormula(e)}}))}extractCellFormula(e){var t,o;const i=this.querySelector(e,"f");if(i)return{content:this.extractTextContent(i),sharedIndex:null===(t=this.extractAttr(i,"si"))||void 0===t?void 0:t.asNum(),ref:null===(o=this.extractAttr(i,"ref"))||void 0===o?void 0:o.asString()}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:"hyperlink"},(e=>{var t,o,i,n;const r=null===(t=this.extractAttr(e,"r:id"))||void 0===t?void 0:t.asString();return{xc:null===(o=this.extractAttr(e,"ref",{required:!0}))||void 0===o?void 0:o.asString(),location:null===(i=this.extractAttr(e,"location"))||void 0===i?void 0:i.asString(),display:null===(n=this.extractAttr(e,"display"))||void 0===n?void 0:n.asString(),relTarget:r?this.relationships[r].target:void 0}}))}extractSharedFormulas(e){const t=this.querySelectorAll(e,"f[si][ref]"),o={};for(let e of t){const t=this.extractAttr(e,"si",{required:!0}).asNum(),i=this.extractTextContent(e,{required:!0});o[t]=i}const i=[];for(let e=0;e<Object.keys(o).length;e++)o[e]?i.push(o[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),i.push(""));return i}}class jf extends Vf{constructor(e,t,o){super(e.styles,e,t),this.theme=o}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"numFmt"},(e=>this.extractNumFormats(e)))}extractNumFormats(e){return{id:this.extractAttr(e,"numFmtId",{required:!0}).asNum(),format:this.extractAttr(e,"formatCode",{required:!0,default:""}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"font"},(e=>this.extractFont(e)))}extractFont(e){var t,o,i,n;const r=this.extractChildAttr(e,"name","val",{default:"Arial"}).asString(),s=this.extractChildAttr(e,"sz","val",{default:W.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===(o=h.attributes.val)||void 0===o?void 0:o.value),u=this.querySelector(e,"strike")||void 0,g=u&&"0"!==(null===(i=u.attributes.val)||void 0===i?void 0:i.value),p=this.querySelector(e,"u")||void 0;return{name:r,size:s,color:a,italic:c,bold:d,underline:p&&"none"!==(null===(n=p.attributes.val)||void 0===n?void 0:n.value),strike:g}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"fill"},(e=>this.extractFill(e)))}extractFill(e){var t;const o=e.children[0];return"patternFill"===o.tagName?{patternType:null===(t=o.attributes.patternType)||void 0===t?void 0:t.value,bgColor:this.extractColor(this.querySelector(o,"bgColor"),this.theme),fgColor:this.extractColor(this.querySelector(o,"fgColor"),this.theme)}:{patternType:"solid",fgColor:this.extractColor(this.querySelectorAll(o,"color")[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"border"},(e=>this.extractBorder(e)))}extractBorder(e){var t,o;const i={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 i.diagonal&&(i.diagonalUp=null===(t=this.extractAttr(e,"diagonalUp"))||void 0===t?void 0:t.asBool(),i.diagonalDown=null===(o=this.extractAttr(e,"diagonalDown"))||void 0===o?void 0:o.asBool()),i}extractSingleBorder(e,t,o){const i=this.querySelector(e,t);if(i&&i.attributes.style)return{style:this.extractAttr(i,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(i.children[0],o,"000000")}}extractAlignment(e){var t,o,i,n,r,s,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===(o=this.extractAttr(e,"wrapText"))||void 0===o?void 0:o.asBool(),indent:null===(i=this.extractAttr(e,"indent"))||void 0===i?void 0:i.asNum(),relativeIndent:null===(n=this.extractAttr(e,"relativeIndent"))||void 0===n?void 0:n.asNum(),justifyLastLine:null===(r=this.extractAttr(e,"justifyLastLine"))||void 0===r?void 0:r.asBool(),shrinkToFit:null===(s=this.extractAttr(e,"shrinkToFit"))||void 0===s?void 0:s.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"),o=this.querySelector(e,"fill"),i=this.querySelector(e,"border"),n=this.querySelector(e,"numFmt"),r=this.querySelector(e,"alignment");return{font:t?this.extractFont(t):void 0,fill:o?this.extractFill(o):void 0,numFmt:n?this.extractNumFormats(n):void 0,alignment:r?this.extractAlignment(r):void 0,border:i?this.extractBorder(i):void 0}}))}getStyles(){return this.mapOnElements({query:"cellXfs xf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"alignment");return{fontId:this.extractAttr(e,"fontId",{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,"fillId",{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,"borderId",{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,"numFmtId",{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}}))}}class Xf extends Vf{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"externalBook"},(e=>({rId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:"sheetName"},(e=>this.extractAttr(e,"val",{required:!0}).asString())),datasets:this.extractExternalSheetData(e)})))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:"sheetData"},(e=>{const t=this.mapOnElements({parent:e,query:"cell"},(e=>({xc:this.extractAttr(e,"r",{required:!0}).asString(),value:this.extractChildTextContent(e,"v",{required:!0})}))),o={};for(let e of t)o[e.xc]=e.value;return{sheetId:this.extractAttr(e,"sheetId",{required:!0}).asNum(),data:o}}))}}function Yf(e,t){const o=function(e,t){const o=t[dm],i=o.querySelectorAll(`Override[ContentType="${e}"]`),n=[];for(let e of i){const t=null==e?void 0:e.attributes.PartName.value;n.push(t.substring(1))}return n}(e,t);return function(e,t){const o=[];for(let i of e){const e=Kf(i,t);o.push({file:{fileName:i,xml:t[i]},rels:e?{fileName:e,xml:t[e]}:void 0})}return o}(o,t)}function Kf(e,t){if(e===dm)return"_rels/.rels";let o="";const i=e.split("/");for(let e=0;e<i.length-1;e++)o+=i[e]+"/";return o+="_rels/",o+=i[i.length-1]+".rels",t[o]||(o=void 0),o}class Qf{constructor(e){this.warningManager=new gm,this.xmls={};for(let t of Object.keys(e))(t.endsWith(".xml")||t.endsWith(".rels"))&&(this.xmls[t]=Ff(new qp(e[t])))}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new zf(e.theme,e,this.warningManager).getTheme():void 0,o=e.sharedStrings?new zf(e.sharedStrings,e,this.warningManager).getSharedStrings():[],i=e.sheets.sort(((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0}))).map((o=>new Zf(o,e,this.warningManager,t).getSheet())),n=e.externalLinks.map((t=>new Xf(t,e,this.warningManager).getExternalBook())),r=new jf(e,this.warningManager,t);return{fonts:r.getFonts(),fills:r.getFills(),borders:r.getBorders(),dxfs:r.getDxfs(),numFmts:r.getNumFormats(),styles:r.getStyles(),sheets:i,sharedStrings:o,externalBooks:n}}buildXlsxFileStructure(){const e={sheets:Yf(Jp.sheet,this.xmls),workbook:Yf(Jp.workbook,this.xmls)[0],styles:Yf(Jp.styles,this.xmls)[0],sharedStrings:Yf(Jp.sharedStrings,this.xmls)[0],theme:Yf(Jp.themes,this.xmls)[0],charts:Yf(Jp.chart,this.xmls),figures:Yf(Jp.drawing,this.xmls),tables:Yf(Jp.table,this.xmls),pivots:Yf(Jp.pivot,this.xmls),externalLinks:Yf(Jp.externalLink,this.xmls)};if(!e.workbook.rels)throw Error(r("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:12,sheets:Cf(e,this.warningManager),styles:Vm(e,this.warningManager),formats:Bm(e,this.warningManager),borders:Lm(e,this.warningManager),entities:{},revisionId:Y};return Tf(t,e),Object.keys(e.styles).map((t=>{e.styles[t]=at(e.styles[t])})),t}}function Jf(e){const t=Du(e);let o=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&wt.test(e.value)){const t=e.value.trim();return o.includes(t)||o.push(t),`${re}${o.indexOf(t)}${re}`}return e.value}))),dependencies:o}}const ev=12,tv="Sheet1";function ov(e,t){if(!e)return av();if(e["[Content_Types].xml"]){const o=new Qf(e);if(e=o.convertXlsx(),t)for(let e of o.warningManager.warnings.sort())console.warn(e)}return"version"in(e=Me(e))&&e.version<ev&&(e=function(e){for(let t=iv.findIndex((t=>t.from===e.version));t<iv.length;t++)e=iv[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,o=new Ao;for(const i of e.sheets||[])for(const e of i.figures||[])t.has(e.id)&&(e.id+=o.uuidv4()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){e=Object.assign(av(),e,{version:ev}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(sv(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(sv(tv,"Sheet1"));return e}(e),e}(e),e}const iv=[{description:"add the `activeSheet` field on data",from:1,to:2,applyMigration:e=>(e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e)},{description:"add an id field in each sheet",from:2,to:3,applyMigration(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}},{description:"activeSheet is now an id, not the name of a sheet",from:3,to:4,applyMigration(e){if(e.sheets&&e.activeSheet){const t=e.sheets.find((t=>t.name===e.activeSheet));e.activeSheet=t.id}return e}},{description:"add figures object in each sheets",from:4,to:5,applyMigration(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}},{description:"normalize the content of the cell if it is a formula to avoid parsing all the formula that vary only by the cells they use",from:5,to:6,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const o=t.cells[e];o.content&&o.content.startsWith("=")&&(o.formula=Jf(o.content))}return e}},{description:"transform chart data structure",from:6,to:7,applyMigration(e){for(let t of e.sheets||[])for(let e in t.figures||[]){const{dataSets:o,...i}=t.figures[e].data,n=[];for(let e of o)if(e.labelCell){const t=Mo(e.dataRange),o=e.labelCell+":"+$t(t.right,t.bottom);n.push(o)}else n.push(e.dataRange);i.dataSetsHaveTitle=Boolean(o[0].labelCell),i.dataSets=n,t.figures[e].data=i}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){var t;const o=[],i=new RegExp(ne,"g");for(let n of e.sheets||[]){if(!n.name)continue;const e=n.name,r=e.replace(i,"_");let s=1,a=r;for(;o.includes(a);)a=`${r}${s}`,s++;n.name=a,o.push(a);const l=t=>{if(void 0===t)return t;let o=t.replace(e,a),i=t;for(;i!==o;)i=o,o=i.replace(e,a);return i};for(let e in n.cells){const t=n.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(l))}for(let e of n.figures||[])if("chart"===e.type){const t=e.data.dataSets.map(l),o=l(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:o}}for(let e of n.conditionalFormats||[]){e.ranges=e.ranges.map(l);for(const o of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===(null===(t=e.rule[o])||void 0===t?void 0:t.type)&&(e.rule[o].value=l(e.rule[o].value))}}return e}},{description:"transform chart data structure with design attributes",from:8,to:9,applyMigration(e){for(const t of e.sheets||[])for(const e of t.figures||[])e.data.background=w,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stacked=!1;return e}},{description:"de-normalize formula to reduce exported json size (~30%)",from:9,to:10,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const o=t.cells[e];if(o.formula){let{text:e,dependencies:t}=o.formula;for(let[o,i]of Object.entries(t)){const t=`\\${re}${o}\\${re}`;e=e.replace(new RegExp(t,"g"),i)}o.content=e,delete o.formula}}return e}},{description:"normalize the formats of the cells",from:10,to:11,applyMigration(e){const t={};for(let o of e.sheets||[])for(let e in o.cells||[]){const i=o.cells[e];i.format&&(i.format=tt(i.format,t))}return e.formats=t,e}},{description:"Add isVisible to sheets",from:11,to:12,applyMigration(e){for(let t of e.sheets||[])t.isVisible=!0;return e}}];function nv(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const o=[],i=[],n=e=>{if("CREATE_SHEET"===e.type)o.push(e.sheetId);else if("sheetId"in e&&!o.includes(e.sheetId))return{...e,sheetId:tv};return e};for(const e of t)"REMOTE_REVISION"===e.type?i.push({...e,commands:e.commands.map(n)}):i.push(e);return i}(e,t),t=rv(t,"SORT_CELLS"),t=function(e,t){var o;const i=[],n={};for(const t of e.sheets||[])null===(o=t.figures)||void 0===o||o.forEach((e=>{"chart"===e.tag&&(n[e.id]=e.data)}));for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const o of e.commands){let e=o;switch(o.type){case"CREATE_CHART":n[o.id]=o.definition;break;case"UPDATE_CHART":if(!n[o.id]){console.log(`Fix chart definition: chart with id ${o.id} not found.`);continue}const t={...n[o.id],...o.definition};e={...o,definition:t},n[o.id]=t}t.push(e)}i.push({...e,commands:t})}else i.push(e);return i}(e,t=rv(t,"SET_DECIMAL")),t}function rv(e,t){const o=[];for(const i of e)"REMOTE_REVISION"===i.type?o.push({...i,commands:i.commands.filter((e=>e.type!==t))}):o.push(i);return o}function sv(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[],filterTables:[],isVisible:!0}}function av(e="Sheet1"){return{version:ev,sheets:[sv(tv,e)],entities:{},styles:{},formats:{},borders:{},revisionId:Y,uniqueFigureIds:!0}}function lv(e,t){return{...sv(e,t),charts:[]}}class cv extends Gu{constructor({getters:e,stateObserver:t,range:o,dispatch:i,uuidGenerator:n}){super(t,i),this.range=o,o.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=n}import(e){}export(e){}adaptRanges(e,t){}garbageCollectExternalResources(){}}class hv extends cv{constructor(){super(...arguments),this.borders={}}handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":const t=this.borders[e.sheetId];if(t){const o=t.slice().map((e=>null==e?void 0:e.slice().map((e=>({...e})))));this.history.update("borders",e.sheetIdTo,o)}break;case"DELETE_SHEET":const o={...this.borders};delete o[e.sheetId],this.history.update("borders",o);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_FORMATTING":if(e.border){const t=e.target.map((t=>this.getters.expandZone(e.sheetId,t)));this.setBorders(e.sheetId,t,e.border)}break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target);break;case"REMOVE_COLUMNS_ROWS":for(let t of e.elements)"COL"===e.dimension?this.shiftBordersHorizontally(e.sheetId,t+1,-1):this.shiftBordersVertically(e.sheetId,t+1,-1);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumns(e):this.handleAddRows(e)}}handleAddColumns(e){let t,o;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),t=e.base-1,o=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),t=e.base,o=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,o)}handleAddRows(e){let t,o;"before"===e.position?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity,{moveFirstTopBorder:!0}),t=e.base-1,o=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity,{moveFirstTopBorder:!1}),t=e.base,o=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,o)}getCellBorder({sheetId:e,col:t,row:o}){var i,n,r,s,a,l,c,h,d,u,g,p;const m={top:null===(r=null===(n=null===(i=this.borders[e])||void 0===i?void 0:i[t])||void 0===n?void 0:n[o])||void 0===r?void 0:r.horizontal,bottom:null===(l=null===(a=null===(s=this.borders[e])||void 0===s?void 0:s[t])||void 0===a?void 0:a[o+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[o])||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[o])||void 0===p?void 0:p.vertical};return m.bottom||m.left||m.right||m.top?m:null}ensureColumnBorderContinuity(e,t,o){const i=Ue(t+1,o);for(let n=0;n<this.getters.getNumberRows(e);n++){const r=this.getCellBorder({sheetId:e,col:t,row:n}),s=this.getCellBorder({sheetId:e,col:o,row:n});if(r&&s){const t=this.getCommonSides(r,s);for(let o of i)this.addBorder(e,o,n,t)}}}ensureRowBorderContinuity(e,t,o){const i=Ue(t+1,o);for(let n=0;n<this.getters.getNumberCols(e);n++){const r=this.getCellBorder({sheetId:e,col:n,row:t}),s=this.getCellBorder({sheetId:e,col:n,row:o});if(r&&s){const t=this.getCommonSides(r,s);for(let o of i)this.addBorder(e,n,o,t)}}}getCommonSides(e,t){const o={};for(let i of["top","bottom","left","right"])e[i]&&e[i]===t[i]&&(o[i]=e[i]);return o}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsRange(e){return this.borders[e]?Ue(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,o,{moveFirstLeftBorder:i}={}){this.borders[e]&&(o<0&&this.moveBordersOfColumn(e,t,o,"vertical",{destructive:!1}),this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>o<0?e-t:t-e)).forEach((n=>{(n===t&&i||n!==t)&&this.moveBordersOfColumn(e,n,o,"vertical"),this.moveBordersOfColumn(e,n,o,"horizontal")})))}shiftBordersVertically(e,t,o,{moveFirstTopBorder:i}={}){this.borders[e]&&(o<0&&this.moveBordersOfRow(e,t,o,"horizontal",{destructive:!1}),this.getRowsRange(e).filter((e=>e>=t)).sort(((e,t)=>o<0?e-t:t-e)).forEach((n=>{(n===t&&i||n!==t)&&this.moveBordersOfRow(e,n,o,"horizontal"),this.moveBordersOfRow(e,n,o,"vertical")})))}moveBordersOfRow(e,t,o,i,{destructive:n}={destructive:!0}){const r=this.borders[e];r&&this.getColumnsWithBorders(e).forEach((s=>{var a,l,c,h;const d=null===(l=null===(a=r[s])||void 0===a?void 0:a[t+o])||void 0===l?void 0:l[i],u=null===(h=null===(c=r[s])||void 0===c?void 0:c[t])||void 0===h?void 0:h[i];this.history.update("borders",e,s,t+o,i,n?u:u||d),this.history.update("borders",e,s,t,i,void 0)}))}moveBordersOfColumn(e,t,o,i,{destructive:n}={destructive:!0}){const r=this.borders[e];r&&this.getRowsRange(e).forEach((s=>{var a,l,c,h;const d=null===(l=null===(a=r[t+o])||void 0===a?void 0:a[s])||void 0===l?void 0:l[i],u=null===(h=null===(c=r[t])||void 0===c?void 0:c[s])||void 0===h?void 0:h[i];this.history.update("borders",e,t+o,s,i,n?u:u||d),this.history.update("borders",e,t,s,i,void 0)}))}setBorder(e,t,o,i,n=!0){var r,s,a,l,c,h,d,u,g,p,m,f,v,b,C,S;!n&&(null===(l=null===(a=null===(s=null===(r=this.borders)||void 0===r?void 0:r[e])||void 0===s?void 0:s[t])||void 0===a?void 0:a[o])||void 0===l?void 0:l.vertical)||this.history.update("borders",e,t,o,"vertical",null==i?void 0:i.left),!n&&(null===(u=null===(d=null===(h=null===(c=this.borders)||void 0===c?void 0:c[e])||void 0===h?void 0:h[t])||void 0===d?void 0:d[o])||void 0===u?void 0:u.horizontal)||this.history.update("borders",e,t,o,"horizontal",null==i?void 0:i.top),!n&&(null===(f=null===(m=null===(p=null===(g=this.borders)||void 0===g?void 0:g[e])||void 0===p?void 0:p[t+1])||void 0===m?void 0:m[o])||void 0===f?void 0:f.vertical)||this.history.update("borders",e,t+1,o,"vertical",null==i?void 0:i.right),!n&&(null===(S=null===(C=null===(b=null===(v=this.borders)||void 0===v?void 0:v[e])||void 0===b?void 0:b[t])||void 0===C?void 0:C[o+1])||void 0===S?void 0:S.horizontal)||this.history.update("borders",e,t,o+1,"horizontal",null==i?void 0:i.bottom)}clearBorders(e,t){for(let o of t){for(let t=o.top;t<=o.bottom;t++){this.history.update("borders",e,o.right+1,t,"vertical",void 0);for(let i=o.left;i<=o.right;i++)this.history.update("borders",e,i,t,void 0)}for(let t=o.left;t<=o.right;t++)this.history.update("borders",e,t,o.bottom+1,"horizontal",void 0)}}addBorder(e,t,o,i){this.setBorder(e,t,o,{...this.getCellBorder({sheetId:e,col:t,row:o}),...i})}setBorders(e,t,o){if("clear"===o)return this.clearBorders(e,t);for(let i of t){if("h"===o||"hv"===o||"all"===o)for(let t=i.top+1;t<=i.bottom;t++)for(let o=i.left;o<=i.right;o++)this.addBorder(e,o,t,{top:q});if("v"===o||"hv"===o||"all"===o)for(let t=i.top;t<=i.bottom;t++)for(let o=i.left+1;o<=i.right;o++)this.addBorder(e,o,t,{left:q});if("left"===o||"all"===o||"external"===o)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:q});if("right"===o||"all"===o||"external"===o)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right+1,t,{left:q});if("top"===o||"all"===o||"external"===o)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:q});if("bottom"===o||"all"===o||"external"===o)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom+1,{top:q})}}addBordersToMerge(e,t){const{left:o,right:i,top:n,bottom:r}=t,s=this.getCellBorder({sheetId:e,col:o,row:n}),a=this.getCellBorder({sheetId:e,col:i,row:r});this.clearBorders(e,[t]),(null==s?void 0:s.top)&&this.setBorders(e,[{...t,bottom:n}],"top"),(null==s?void 0:s.left)&&this.setBorders(e,[{...t,right:o}],"left"),((null==a?void 0:a.bottom)||(null==s?void 0:s.bottom))&&this.setBorders(e,[{...t,top:r}],"bottom"),((null==a?void 0:a.right)||(null==s?void 0:s.right))&&this.setBorders(e,[{...t,left:i}],"right")}import(e){if(e.borders)for(let t of e.sheets)for(let[o,i]of Object.entries(t.cells))if(null==i?void 0:i.border){const n=e.borders[i.border],{col:r,row:s}=kt(o);this.setBorder(t.id,r,s,n,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Mo(e))}export(e){let t=0;const o={};function i(e){for(let[t,i]of Object.entries(o))if(Te(i)===Te(e))return parseInt(t,10);return o[++t]=e,t}for(let t of e.sheets)for(let e=0;e<t.colNumber;e++)for(let o=0;o<t.rowNumber;o++){const n=this.getCellBorder({sheetId:t.id,col:e,row:o});if(n){const r=$t(e,o),s=t.cells[r],a=i(n);s?s.border=a:t.cells[r]={border:a}}}e.borders=o}exportForExcel(e){this.export(e)}}hv.getters=["getCellBorder"];const dv=new RegExp(String.fromCharCode(160),"g");class uv extends cv{constructor(){super(...arguments),this.nextId=1,this.cells={}}adaptRanges(e,t){for(const o of Object.keys(this.cells))for(const i of Object.values(this.cells[o]||{}))if(i.isFormula)for(const n of i.dependencies)if(!t||n.sheetId===t){const t=e(n);"NONE"!==t.changeType&&this.history.update("cells",o,i.id,"dependencies",i.dependencies.indexOf(n),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":case"CLEAR_CELL":return this.checkCellOutOfSheet(e.sheetId,e.col,e.row);default:return 0}}handle(e){switch(e.type){case"SET_FORMATTING":"style"in e&&this.setStyle(e.sheetId,e.target,e.style),"format"in e&&void 0!==e.format&&this.setFormatter(e.sheetId,e.target,e.format);break;case"CLEAR_FORMATTING":this.clearFormatting(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case"UPDATE_CELL":this.updateCell(e.sheetId,e.col,e.row,e);break;case"CLEAR_CELL":this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col,row:e.row,content:"",style:null,format:""})}}setFormatter(e,t,o){for(let i of t)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,format:o})}clearFormatting(e,t){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,style:null,format:""})}handleAddColumnsRows(e,t){let o,i;"before"===e.position?(o=Ue(e.base,e.base+e.quantity),i=e.base+e.quantity):(o=Ue(e.base+1,e.base+e.quantity+1),i=e.base),t(e.sheetId,i,o)}import(e){for(let t of e.sheets)for(let o in t.cells){const i=t.cells[o],{col:n,row:r}=kt(o);if((null==i?void 0:i.content)||(null==i?void 0:i.format)||(null==i?void 0:i.style)){const o=this.importCell(t.id,i,e.styles,e.formats);this.history.update("cells",t.id,o.id,o),this.dispatch("UPDATE_CELL_POSITION",{cellId:o.id,col:n,row:r,sheetId:t.id})}}}export(e){const t={},o={};for(let i of e.sheets){const e={},n=Object.keys(this.cells[i.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const i of n){const n=this.getters.getCell(i);e[$t(i.col,i.row)]={style:n.style?tt(n.style,t):void 0,format:n.format?tt(n.format,o):void 0,content:n.content||void 0}}i.cells=e}e.styles=t,e.formats=o}importCell(e,t,o,i){const n=t.style&&o[t.style]||void 0,r=t.format&&i[t.format]||void 0,s=this.getNextUid();return this.createCell(s,(null==t?void 0:t.content)||"",r,n,e)}exportForExcel(e){this.export(e)}getCells(e){return this.cells[e]||{}}getCellById(e){for(const t in this.cells){const o=this.cells[t][e];if(o)return o}}buildFormulaContent(e,t,o){const i=o||[...t.dependencies];return ot(t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=i.shift();return this.getters.getRangeString(t,e)}return t.value})))}getFormulaCellContent(e,t){return this.buildFormulaContent(e,t)}getCellStyle(e){var t;return(null===(t=this.getters.getCell(e))||void 0===t?void 0:t.style)||{}}zoneToXC(e,t,o=[{colFixed:!1,rowFixed:!1}]){const i=$t((t=this.getters.expandZone(e,t)).left,t.top,o[0]),n=$t(t.right,t.bottom,o.length>1?o[1]:o[0]),r=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),s=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=r.col===s.col&&r.row===s.row;return i==n||a?i:i+":"+n}setStyle(e,t,o){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++){const i=this.getters.getCell({sheetId:e,col:t,row:n});this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,style:o?{...null==i?void 0:i.style,...o}:void 0})}}copyColumnStyle(e,t,o){for(let i=0;i<this.getters.getNumberRows(e);i++){const n=this.getFormat(e,t,i);if(n.style||n.format)for(let t of o)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,...n})}}copyRowStyle(e,t,o){for(let i=0;i<this.getters.getNumberCols(e);i++){const n=this.getFormat(e,i,t);if(n.style||n.format)for(let t of o)this.dispatch("UPDATE_CELL",{sheetId:e,col:i,row:t,...n})}}getFormat(e,t,o){const i={},n=this.getters.getMainCellPosition({sheetId:e,col:t,row:o}),r=this.getters.getCell(n);return r&&(r.style&&(i.style=r.style),r.format&&(i.format=r.format)),i}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,o,i){var n;const r=this.getters.getCell({sheetId:e,col:t,row:o}),s="content"in i||"formula"in i,a=s?(null===(n=i.content)||void 0===n?void 0:n.replace(dv,""))||"":(null==r?void 0:r.content)||"";let l;l=void 0!==i.style?i.style||void 0:r?r.style:void 0;let c=("format"in i?i.format:r&&r.format)||vo(a);if((s&&!a&&!i.formula||!s&&(!r||""===r.content))&&!l&&!c)return void(r&&(this.history.update("cells",e,r.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:o,sheetId:e})));const h=(null==r?void 0:r.id)||this.getNextUid(),d=this.createCell(h,a,c,l,e);this.history.update("cells",e,d.id,d),this.dispatch("UPDATE_CELL_POSITION",{cellId:d.id,col:t,row:o,sheetId:e})}createCell(e,t,o,i,n){if(!t.startsWith("="))return this.createLiteralCell(e,t,o,i);try{return this.createFormulaCell(e,t,o,i,n)}catch(n){return this.createErrorFormula(e,t,o,i,n)}}createLiteralCell(e,t,o,i){return{id:e,content:t,style:i,format:o,isFormula:!1}}createFormulaCell(e,t,o,i,n){const r=Vu(t);return r.dependencies.length?this.createFormulaCellWithDependencies(e,r,o,i,n):{id:e,content:t,style:i,format:o,isFormula:!0,compiledFormula:r,dependencies:[]}}createFormulaCellWithDependencies(e,t,o,i,n){const r=t.dependencies.map((e=>this.getters.getRangeFromSheetXC(n,e))),s=this.buildFormulaContent.bind(this);return{id:e,get content(){return s(n,{dependencies:this.dependencies,compiledFormula:this.compiledFormula})},style:i,format:o,isFormula:!0,compiledFormula:t,dependencies:r}}createErrorFormula(e,t,o,i,n){return{id:e,content:t,style:i,format:o,isFormula:!0,compiledFormula:{dependencies:[],tokens:tu(t),execute:function(){throw n}},dependencies:[]}}checkCellOutOfSheet(e,t,o){if(!this.getters.tryGetSheet(e))return 27;return zo(t,o,this.getters.getSheetZone(e))?0:18}}uv.getters=["zoneToXC","getCells","getFormulaCellContent","getCellStyle","buildFormulaContent","getCellById"];class gv extends cv{constructor(){super(...arguments),this.charts={},this.createChart=function(e){const t=Rn.getAll();return function(o,i,n){const r=t.find((e=>e.match(i.type)));if(!r)throw new Error(`No builder for this chart: ${i.type}`);return r.createChart(i,n,e)}}(this.getters),this.validateChartDefinition=e=>function(e,t){const o=Rn.getAll().find((e=>e.match(t.type)));if(!o)throw new Error("Unknown chart type.");return o.validateChartDefinition(e,t)}(this,e.definition)}adaptRanges(e){for(const[t,o]of Object.entries(this.charts))this.history.update("charts",t,null==o?void 0:o.updateRanges(e))}allowDispatch(e){switch(e.type){case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists));default:return 0}}handle(e){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 o=this.getters.getFigures(e.sheetId);for(const i of o)if("chart"===i.tag){const o=i.id.split(Q).pop(),n=`${e.sheetIdTo}${Q}${o}`,r=null===(t=this.charts[i.id])||void 0===t?void 0:t.copyForSheetId(e.sheetIdTo);r&&this.dispatch("CREATE_CHART",{id:n,position:{x:i.x,y:i.y},size:{width:i.width,height:i.height},definition:r.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 o=null===(t=this.charts[e])||void 0===t?void 0:t.type;if(!o)throw new Error("Chart not defined.");return o}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 o=null===(t=this.charts[e])||void 0===t?void 0:t.getDefinition();if(!o)throw new Error(`There is no chart with the given figureId: ${e}`);return o}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 o of e.sheets){const e=this.getters.getFigures(o.id),i=[];for(let o of e){const e=o;if(e&&"chart"===e.tag){const o=null===(t=this.charts[e.id])||void 0===t?void 0:t.getDefinition();o&&(e.data=o,i.push(e))}else i.push(e)}o.figures=i}}exportForExcel(e){var t;for(let o of e.sheets){const e=this.getters.getFigures(o.id),i=[];for(let o of e)if(o&&"chart"===o.tag){const e=null===(t=this.charts[o.id])||void 0===t?void 0:t.getDefinitionForExcel();e&&i.push({...o,data:e})}o.charts=i}}addFigure(e,t,o={x:0,y:0},i={width:536,height:335}){if(this.getters.getFigure(t,e))return;const n={id:e,x:o.x,y:o.y,width:i.width,height:i.height,tag:"chart"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:n})}addChart(e,t){const o=this.getters.getFigureSheetId(e);o&&this.history.update("charts",e,this.createChart(e,t,o))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.id)?84:0}checkChartExists(e){return this.getters.getFigureSheetId(e.id)?0:85}}function pv(e){return""===e?NaN:Number(e)}gv.getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];class mv extends cv{constructor(){super(...arguments),this.cfRules={}}loopThroughRangesOfSheet(e,t){for(const o of this.cfRules[e])for(const i of o.ranges){const n=t(i);switch(n.changeType){case"REMOVE":let t=o.ranges.slice();t.splice(o.ranges.indexOf(i),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"ranges",t):this.removeConditionalFormatting(o.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"ranges",o.ranges.indexOf(i),n.range)}}}adaptRanges(e,t){if(t)this.loopThroughRangesOfSheet(t,e);else for(const t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,e)}allowDispatch(e){switch(e.type){case"ADD_CONDITIONAL_FORMAT":return this.checkValidations(e,this.checkCFRule,this.checkEmptyRange);case"MOVE_CONDITIONAL_FORMAT":return this.checkValidReordering(e.cfId,e.direction,e.sheetId)}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const o={...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))};this.addConditionalFormatting(o,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId);break;case"MOVE_CONDITIONAL_FORMAT":this.reorderConditionalFormatting(e.cfId,e.direction,e.sheetId)}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map((e=>this.mapToConditionalFormatInternal(t.id,e)))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map((e=>this.mapToConditionalFormat(t.id,e))))}exportForExcel(e){this.export(e)}getConditionalFormats(e){var t;return(null===(t=this.cfRules[e])||void 0===t?void 0:t.map((t=>this.mapToConditionalFormat(e,t))))||[]}getRulesSelection(e,t){const o=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{o.add(e)}))})),Array.from(o)}getRulesByZone(e,t){const o=new Set;for(let i=t.top;i<=t.bottom;i++)for(let n=t.left;n<=t.right;n++){this.getRulesByCell(e,n,i).forEach((e=>{o.add(e.id)}))}return o}getRulesByCell(e,t,o){const i=[];for(let n of this.cfRules[e])for(let e of n.ranges)zo(t,o,e.zone)&&i.push(n);return new Set(i.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e)))}}mapToConditionalFormatInternal(e,t){const o={...t,ranges:t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)))};return o}addConditionalFormatting(e,t){const o=this.cfRules[t].slice(),i=o.findIndex((t=>t.id===e.id)),n=this.mapToConditionalFormatInternal(t,e);i>-1?o.splice(i,1,n):o.push(n),this.history.update("cfRules",t,o)}checkValidReordering(e,t,o){if(!this.cfRules[o])return 27;const i=this.cfRules[o].findIndex((t=>t.id===e));if(-1===i)return 71;const n="up"===t?i-1:i+1;return n<0||n>=this.cfRules[o].length?71:0}checkEmptyRange(e){return e.ranges.length?0:24}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber(2,["Between","NotBetween"]),this.checkOperatorArgsNumber(1,["BeginsWith","ContainsText","EndsWith","GreaterThan","GreaterThanOrEqual","LessThan","LessThanOrEqual","NotContains"]),this.checkOperatorArgsNumber(0,["IsEmpty","IsNotEmpty"]));case"ColorScaleRule":return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case"IconSetRule":return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)))}return 0}checkOperatorArgsNumber(e,t){if(e>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");return o=>{if(t.includes(o.operator)){const t=[],i=e=>void 0===e||""===e;return e>=1&&i(o.values[0])&&t.push(51),e>=2&&i(o.values[1])&&t.push(52),t.length?t:0}return 0}}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return 53;case"max":return 55;case"mid":return 54;case"upperInflectionPoint":return 56;case"lowerInflectionPoint":return 57}return 0}checkFormulaCompilation(e,t){if("formula"!==e.type)return 0;try{Vu(e.value||"")}catch(e){switch(t){case"min":return 58;case"max":return 60;case"mid":return 59;case"upperInflectionPoint":return 61;case"lowerInflectionPoint":return 62}}return 0}checkThresholds(e){return this.batchValidations((t=>e(t.minimum,"min")),(t=>e(t.maximum,"max")),(t=>t.midpoint?e(t.midpoint,"mid"):0))}checkInflectionPoints(e){return this.batchValidations((t=>e(t.lowerInflectionPoint,"lowerInflectionPoint")),(t=>e(t.upperInflectionPoint,"upperInflectionPoint")))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,o=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(o)?48:0}checkMinBiggerThanMax(e){const t=e.minimum.value,o=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&pv(t)>=pv(o)?47:0}checkMidBiggerThanMax(e){var t;const o=null===(t=e.midpoint)||void 0===t?void 0:t.value,i=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&pv(o)>=pv(i)?49:0}checkMinBiggerThanMid(e){var t;const o=e.minimum.value,i=null===(t=e.midpoint)||void 0===t?void 0:t.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&pv(o)>=pv(i)?50:0}removeConditionalFormatting(e,t){const o=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==o){const e=this.cfRules[t].slice();e.splice(o,1),this.history.update("cfRules",t,e)}}reorderConditionalFormatting(e,t,o){const i=this.cfRules[o].findIndex((t=>t.id===e)),n="up"===t?i-1:i+1;if(!(n<0||n>=this.cfRules[o].length)&&-1!==i&&-1!==n){const e=[...this.cfRules[o]],t=e[i];e[i]=e[n],e[n]=t,this.history.update("cfRules",o,e)}}}mv.getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];class fv extends cv{constructor(){super(...arguments),this.figures={}}allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkFigureDuplicate(e.figure.id);case"UPDATE_FIGURE":case"DELETE_FIGURE":return this.checkFigureExists(e.sheetId,e.id);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":this.addFigure(e.figure,e.sheetId);break;case"UPDATE_FIGURE":const{type:t,sheetId:o,...i}=e,n=i;this.updateFigure(o,n);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId)}}updateFigure(e,t){if("id"in t)for(const[o,i]of Object.entries(t))switch(o){case"x":case"y":void 0!==i&&this.history.update("figures",e,t.id,o,Math.max(i,0));break;case"width":case"height":void 0!==i&&this.history.update("figures",e,t.id,o,i)}}addFigure(e,t){this.history.update("figures",t,e.id,e)}deleteSheet(e){this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){var o;return void 0===(null===(o=this.figures[e])||void 0===o?void 0:o[t])?70:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>null==t?void 0:t[e]))?82:0}getFigures(e){return Object.values(this.figures[e]||{}).filter(Je)}getFigure(e,t){var o;return null===(o=this.figures[e])||void 0===o?void 0:o[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>{var o;return void 0!==(null===(o=this.figures[t])||void 0===o?void 0:o[e])}))}import(e){for(let t of e.sheets){const e={};t.figures.forEach((t=>{e[t.id]=t})),this.figures[t.id]=e}}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const o=void 0;t.figures.push({...e,data:o})}}exportForExcel(e){this.export(e)}}fv.getters=["getFigures","getFigure","getFigureSheetId"];class vv{constructor(e){this.filters=[],this.zone=e;const t=new Ao;this.id=t.uuidv4();for(const o of Ue(e.left,e.right+1)){const e={...this.zone,left:o,right:o};this.filters.push(new bv(t.uuidv4(),e))}}get contentZone(){if(this.zone.bottom!==this.zone.top)return{...this.zone,top:this.zone.top+1}}getFilterId(e){var t;return null===(t=this.filters.find((t=>t.col===e)))||void 0===t?void 0:t.id}clone(){return new vv(this.zone)}}class bv{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 Cv extends cv{constructor(){super(...arguments),this.tables={}}allowDispatch(e){switch(e.type){case"CREATE_FILTER_TABLE":if(!ei(...e.target))return 81;const t=Po(...e.target),o=()=>this.getFilterTables(e.sheetId).some((e=>Vo(e.zone,t)))?78:0,i=()=>{const o=this.getters.getMergesInZone(e.sheetId,t);for(let e of o)if(Vo(t,e))return 80;return 0};return this.checkValidations(e,o,i);case"ADD_MERGE":for(let t of e.target)for(let o of this.getFilterTables(e.sheetId))if(Vo(o.zone,t))return 80}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break;case"DUPLICATE_SHEET":const o={};for(const t of Object.values(this.tables[e.sheetId]||{}))if(t){const e=Me(t);o[e.id]=e}this.history.update("tables",e.sheetIdTo,o);break;case"ADD_COLUMNS_ROWS":this.onAddColumnsRows(e);break;case"REMOVE_COLUMNS_ROWS":this.onDeleteColumnsRows(e);break;case"CREATE_FILTER_TABLE":{const t=Po(...e.target),o=this.createFilterTable(t);this.history.update("tables",e.sheetId,o.id,o);break}case"REMOVE_FILTER_TABLE":{const t={};for(const o of this.getFilterTables(e.sheetId))e.target.every((e=>!Lo(e,o.zone)))&&(t[o.id]=o);this.history.update("tables",e.sheetId,t);break}case"UPDATE_CELL":{const t=e.sheetId;for(let o of this.getFilterTables(t))this.canUpdateCellCmdExtendTable(e,o)&&this.extendTableDown(t,o);break}}}getFilters(e){return this.getFilterTables(e).map((e=>e.filters)).flat()}getFilterTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(Je):[]}getFilter(e){var t;return null===(t=this.getFilterTable(e))||void 0===t?void 0:t.filters.find((t=>t.col===e.col))}getFilterId(e){var t;return null===(t=this.getFilter(e))||void 0===t?void 0:t.id}getFilterTable({sheetId:e,col:t,row:o}){return this.getFilterTables(e).find((e=>zo(t,o,e.zone)))}getFilterTablesInZone(e,t){return this.getFilterTables(e).filter((e=>Bo(e.zone,t)))}doesZonesContainFilter(e,t){for(const o of t)for(const t of this.getFilterTables(e))if(Lo(o,t.zone))return!0;return!1}onAddColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const o=Fo(t.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),i=[];for(const o of t.filters){const t=Fo(o.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);i.push(new bv(o.id,t))}if(i.length<Go(o).width){for(let e=o.left;e<=o.right;e++)i.find((t=>t.col===e))||i.push(new bv(this.uuidGenerator.uuidv4(),{...o,left:e,right:e}));i.sort(((e,t)=>e.col-t.col))}this.history.update("tables",e.sheetId,t.id,"zone",o),this.history.update("tables",e.sheetId,t.id,"filters",i)}}onDeleteColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const o=$o(t.zone,"COL"===e.dimension?"left":"top",e.elements);if(o){if(_o(o)!==_o(t.zone)){const i=[];for(const o of t.filters){const t=$o(o.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.elements);t&&i.push(new bv(o.id,t))}this.history.update("tables",e.sheetId,t.id,"zone",o),this.history.update("tables",e.sheetId,t.id,"filters",i)}}else{const o={...this.tables[e.sheetId]};delete o[t.id],this.history.update("tables",e.sheetId,o)}}}createFilterTable(e){return new vv(e)}extendTableDown(e,t){const o={...t.zone,bottom:t.zone.bottom+1};this.history.update("tables",e,t.id,"zone",o);for(let o=0;o<t.filters.length;o++){const i=t.filters[o],n={...i.zoneWithHeaders,bottom:i.zoneWithHeaders.bottom+1};this.history.update("tables",e,t.id,"filters",o,"zoneWithHeaders",n)}}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:o,row:i},n){var r;if(!e)return;const s=n.zone;if(!(s.bottom+1===i&&o>=s.left&&o<=s.right))return!1;for(const e of Ue(s.left,s.right+1)){const o={sheetId:t,col:e,row:i};if(null===(r=this.getters.getCell(o))||void 0===r?void 0:r.content)return!1;if(this.getters.getFilter(o))return!1;if(this.getters.isInMerge(o))return!1}return!0}import(e){for(const t of e.sheets)for(const e of t.filterTables||[]){const o=this.createFilterTable(Mo(e.range));this.history.update("tables",t.id,o.id,o)}}export(e){for(const t of e.sheets)for(const e of this.getFilterTables(t.id))t.filterTables.push({range:_o(e.zone)})}exportForExcel(e){this.export(e)}}Cv.getters=["doesZonesContainFilter","getFilter","getFilters","getFilterTable","getFilterTables","getFilterTablesInZone","getFilterId"];class Sv extends cv{constructor(){super(...arguments),this.sizes={}}handle(e){var t,o,i;switch(e.type){case"CREATE_SHEET":{const t=this.computeSheetSizes(e.sheetId),o={COL:t.COL.map((e=>({manualSize:void 0,computedSize:it(e)}))),ROW:t.ROW.map((e=>({manualSize:void 0,computedSize:it(e)})))};this.history.update("sizes",e.sheetId,o);break}case"DUPLICATE_SHEET":for(const t of this.sizes[e.sheetId].ROW)t.computedSize();for(const t of this.sizes[e.sheetId].COL)t.computedSize();this.history.update("sizes",e.sheetIdTo,Me(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 o of[...e.elements].sort(((e,t)=>t-e)))t.splice(o,1);const o=Math.min(...e.elements);t=t.map(((t,i)=>"ROW"===e.dimension&&i>=o?{manualSize:t.manualSize,computedSize:it((()=>this.getRowTallestCellSize(e.sheetId,i)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];const o=rt(e.position,e.base),i=t[e.base];t.splice(o,0,...Array(e.quantity).fill(i)),t=t.map(((t,o)=>"ROW"===e.dimension&&o>e.base+e.quantity?{manualSize:t.manualSize,computedSize:it((()=>this.getRowTallestCellSize(e.sheetId,o)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"RESIZE_COLUMNS_ROWS":for(let t of e.elements)if("ROW"===e.dimension){const o=this.getRowTallestCellSize(e.sheetId,t);this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:it(o)})}else this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:it(e.size||N)});break;case"UPDATE_CELL":if(!(null===(i=null===(o=null===(t=this.sizes[e.sheetId])||void 0===t?void 0:t.ROW)||void 0===o?void 0:o[e.row])||void 0===i?void 0:i.manualSize)){const{sheetId:t,row:o}=e;this.history.update("sizes",t,"ROW",o,"computedSize",it((()=>this.getRowTallestCellSize(t,o))))}break;case"ADD_MERGE":case"REMOVE_MERGE":for(let t of e.target)for(let o of Ue(t.top,t.bottom+1)){const t=this.getRowTallestCellSize(e.sheetId,o);t!==this.getRowSize(e.sheetId,o)&&this.history.update("sizes",e.sheetId,"ROW",o,"computedSize",it(t))}}}getColSize(e,t){return this.getHeaderSize(e,"COL",t)}getRowSize(e,t){return this.getHeaderSize(e,"ROW",t)}getHeaderSize(e,t,o){var i,n,r,s;return Math.round((null===(n=null===(i=this.sizes[e])||void 0===i?void 0:i[t][o])||void 0===n?void 0:n.manualSize)||(null===(s=null===(r=this.sizes[e])||void 0===r?void 0:r[t][o])||void 0===s?void 0:s.computedSize())||this.getDefaultHeaderSize(t))}computeSheetSizes(e){var t,o;const i={COL:[],ROW:[]};for(let t of Ue(0,this.getters.getNumberCols(e)))i.COL.push(this.getHeaderSize(e,"COL",t));for(let n of Ue(0,this.getters.getNumberRows(e))){let r=null===(o=null===(t=this.sizes[e])||void 0===t?void 0:t.ROW)||void 0===o?void 0:o[n].manualSize;if(!r){r=this.getRowTallestCellSize(e,n)}i.ROW.push(r)}return i}getDefaultHeaderSize(e){return"COL"===e?N:_}getCellHeight(e){const t=this.getters.getMerge(e);if(t&&t.bottom!==t.top)return _;const o=this.getters.getCell(e);return De(Le(null==o?void 0:o.style))+2*L}getRowTallestCellSize(e,t){const o=this.getters.getRowCells(e,t);let i=0;for(let e=0;e<o.length;e++){const t=this.getters.getCellById(o[e]);if(!t)continue;const n=this.getters.getCellPosition(t.id),r=this.getCellHeight(n);r>i&&r>_&&(i=r)}return i<=_?_:i}import(e){for(let t of e.sheets){const e={COL:[],ROW:[]};for(let[o,i]of Object.entries(t.rows))i.size&&(e.ROW[o]=i.size);for(let[o,i]of Object.entries(t.cols))i.size&&(e.COL[o]=i.size);const o=this.computeSheetSizes(t.id);this.sizes[t.id]={COL:o.COL.map(((t,o)=>({manualSize:e.COL[o],computedSize:it(t)}))),ROW:o.ROW.map(((t,o)=>({manualSize:e.ROW[o],computedSize:it(t)})))}}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){var o,i;for(let n of e.sheets){void 0===n.rows&&(n.rows={});for(let e of Ue(0,this.getters.getNumberRows(n.id)))(t||(null===(o=this.sizes[n.id].ROW[e])||void 0===o?void 0:o.manualSize))&&(n.rows[e]={...n.rows[e],size:this.getRowSize(n.id,e)});void 0===n.cols&&(n.cols={});for(let e of Ue(0,this.getters.getNumberCols(n.id)))(t||(null===(i=this.sizes[n.id].COL[e])||void 0===i?void 0:i.manualSize))&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}}Sv.getters=["getRowSize","getColSize"];class Ev extends cv{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),o="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=o?66:Math.min(...e.elements)<0||Math.max(...e.elements)>o?86:0}case"REMOVE_COLUMNS_ROWS":return this.getters.tryGetSheet(e.sheetId)?this.canRemoveHeaders(e.sheetId,e.dimension,e.elements)?0:8: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,Me(this.hiddenHeaders[e.sheetId]));break;case"DELETE_SHEET":this.history.update("hiddenHeaders",e.sheetId,void 0);break;case"REMOVE_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let o of[...e.elements].sort(((e,t)=>t-e)))t.splice(o,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]],o=rt(e.position,e.base);t.splice(o,0,...Array(e.quantity).fill(!1)),this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"HIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!0);break;case"UNHIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!1)}}canRemoveHeaders(e,t,o){const i=this.getAllVisibleHeaders(e,t);return n=o,!i.every((e=>n.includes(e)));var n}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]}getHiddenColsGroups(e){const t=[[]],o=this.hiddenHeaders[e].COL;for(let e=0;e<o.length;e++){o[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getHiddenRowsGroups(e){const t=[[]],o=this.hiddenHeaders[e].ROW;for(let e=0;e<o.length;e++){o[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getAllVisibleHeaders(e,t){return Ue(0,this.hiddenHeaders[e][t].length).filter((o=>!this.hiddenHeaders[e][t][o]))}import(e){var t,o;for(let i of e.sheets){this.hiddenHeaders[i.id]={COL:[],ROW:[]};for(let e=0;e<i.rowNumber;e++)this.hiddenHeaders[i.id].ROW[e]=Boolean(null===(t=i.rows[e])||void 0===t?void 0:t.isHidden);for(let e=0;e<i.colNumber;e++)this.hiddenHeaders[i.id].COL[e]=Boolean(null===(o=i.cols[e])||void 0===o?void 0:o.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let o of e.sheets){void 0===o.rows&&(o.rows={});for(let e=0;e<this.getters.getNumberRows(o.id);e++)(t||this.hiddenHeaders[o.id].ROW[e])&&(void 0===o.rows[e]&&(o.rows[e]={}),o.rows[e].isHidden=this.hiddenHeaders[o.id].ROW[e]);void 0===o.cols&&(o.cols={});for(let e=0;e<this.getters.getNumberCols(o.id);e++)(t||this.hiddenHeaders[o.id].COL[e])&&(void 0===o.cols[e]&&(o.cols[e]={}),o.cols[e].isHidden=this.hiddenHeaders[o.id].COL[e])}}}Ev.getters=["canRemoveHeaders","getHiddenColsGroups","getHiddenRowsGroups","isRowHiddenByUser","isColHiddenByUser"];class wv extends cv{constructor(e){super(e),this.images={},this.syncedImages=new Set,this.fileStore=e.external.fileStore}allowDispatch(e){return"CREATE_IMAGE"===e.type&&this.getters.getFigure(e.sheetId,e.figureId)?28:0}handle(e){switch(e.type){case"CREATE_IMAGE":this.addFigure(e.figureId,e.sheetId,e.position,e.size),this.history.update("images",e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const o of t)if("image"===o.tag){const t=o.id.split(Q).pop(),i=`${e.sheetIdTo}${Q}${t}`,n=this.getImage(o.id);if(n){const t={width:o.width,height:o.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:i,position:{x:o.x,y:o.y},size:t,definition:Me(n)})}}break}case"DELETE_FIGURE":this.history.update("images",e.sheetId,e.id,void 0);break;case"DELETE_SHEET":this.history.update("images",e.sheetId,void 0)}}garbageCollectExternalResources(){var e;const t=new Set(this.getAllImages().map((e=>e.path)));for(const o of this.syncedImages)t.has(o)||null===(e=this.fileStore)||void 0===e||e.delete(o)}getImage(e){for(const t of Object.values(this.images))if(t&&t[e])return t[e];throw new Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,o,i){const n={id:e,x:o.x,y:o.y,width:i.width,height:i.height,tag:"image"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:n})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter((e=>"image"===e.tag));for(const o of e)this.history.update("images",t.id,o.id,o.data),this.syncedImages.add(o.data.path)}}export(e){var t;for(const o of e.sheets){const e=o.figures.filter((e=>"image"===e.tag));for(const i of e)i.data=null===(t=this.images[o.id])||void 0===t?void 0:t[i.id]}}getAllImages(){const e=[];for(const t in this.images)e.push(...Object.values(this.images[t]||{}).filter(Je));return e}}wv.getters=["getImage","getImagePath","getImageSize"];class yv extends cv{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 o of Object.values(t).filter(Je))this.addMerge(e.sheetIdTo,o.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(e.sheetId,t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){const o=t?[t]:Object.keys(this.merges);for(const t of o)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(Je)}getMerge({sheetId:e,col:t,row:o}){var i;const n=this.mergeCellMap[e],r=n?t in n&&(null===(i=n[t])||void 0===i?void 0:i[o]):void 0;return r?this.getMergeById(e,r):void 0}getMergesInZone(e,t){var o;const i=this.mergeCellMap[e];if(!i)return[];const n=new Set;for(const{col:e,row:r}of Zo(t)){const t=null===(o=i[e])||void 0===o?void 0:o[r];t&&n.add(t)}return Array.from(n).map((t=>this.getMergeById(e,t))).filter(Je)}doesIntersectMerge(e,t){return Zo(t).some((({col:t,row:o})=>void 0!==this.getMerge({sheetId:e,col:t,row:o})))}doesColumnsHaveCommonMerges(e,t,o){const i=this.getters.getSheet(e);for(let n=0;n<this.getters.getNumberRows(e);n++)if(this.isInSameMerge(i.id,t,n,o,n))return!0;return!1}doesRowsHaveCommonMerges(e,t,o){const i=this.getters.getSheet(e);for(let n=0;n<=this.getters.getNumberCols(e);n++)if(this.isInSameMerge(i.id,n,t,n,o))return!0;return!1}expandZone(e,t){let{left:o,right:i,top:n,bottom:r}=t,s={left:o,right:i,top:n,bottom:r};for(let t in this.merges[e]){const o=this.getMergeById(e,parseInt(t));o&&Vo(o,s)&&(s=Po(o,s))}return Uo(s,t)?s:this.expandZone(e,s)}isInSameMerge(e,t,o,i,n){const r=this.getMerge({sheetId:e,col:t,row:o}),s=this.getMerge({sheetId:e,col:i,row:n});return!(!r||!s)&&Uo(r,s)}isInMerge({sheetId:e,col:t,row:o}){var i;const n=this.mergeCellMap[e];return!!n&&(t in n&&Boolean(null===(i=n[t])||void 0===i?void 0:i[o]))}getMainCellPosition(e){if(!this.isInMerge(e))return e;const t=this.getMerge(e).topLeft;return{sheetId:e.sheetId,col:t.col,row:t.row}}getBottomLeftCell(e){if(!this.isInMerge(e))return e;const{bottom:t,left:o}=this.getMerge(e);return{sheetId:e.sheetId,col:o,row:t}}isMergeHidden(e,t){const o=this.getters.getHiddenColsGroups(e),i=this.getters.getHiddenRowsGroups(e);for(let e of o)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of i)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const o=this.getMerge({sheetId:e,col:t.left,row:t.top});if(o)return Uo(t,o);const{width:i,height:n}=Go(t);return 1===i&&1===n}isMergeDestructive(e,t){let{left:o,right:i,top:n,bottom:r}=t;i=Fe(i,0,this.getters.getNumberCols(e)-1),r=Fe(r,0,this.getters.getNumberRows(e)-1);for(let t=n;t<=r;t++)for(let r=o;r<=i;r++)if(r!==o||t!==n){const o=this.getters.getCell({sheetId:e,col:r,row:t});if(o&&""!==o.content)return!0}return!1}getMergeById(e,t){var o;const i=null===(o=this.merges[e])||void 0===o?void 0:o[t];return void 0!==i?Iv(t,i):void 0}checkDestructiveMerge({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;return t.some((t=>this.isMergeDestructive(e,t)))?3:0}checkOverlap({target:e}){for(const t of e)for(const o of e)if(t!==o&&Vo(t,o))return 65;return 0}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;const{xSplit:o,ySplit:i}=this.getters.getPaneDivisions(e);for(const e of t)if(e.left<o&&e.right>=o||e.top<i&&e.bottom>=i)return 75;return 0}checkMergedContentUpdate(e){const{col:t,row:o,content:i}=e;if(void 0===i)return 0;const{col:n,row:r}=this.getMainCellPosition(e);return n===t&&r===o?0:4}checkMergeExists(e){const{sheetId:t,target:o}=e;for(const e of o){const{left:o,top:i}=e,n=this.getMerge({sheetId:t,col:o,row:i});if(void 0===n||!Uo(e,n))return 5}return 0}addMerge(e,t){let{left:o,right:i,top:n,bottom:r}=t;i=Fe(i,0,this.getters.getNumberCols(e)-1),r=Fe(r,0,this.getters.getNumberRows(e)-1);if($t(o,n)===$t(i,r))return;const s=this.getters.getCell({sheetId:e,col:o,row:n});let a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,_o({left:o,top:n,right:i,bottom:r})));let l=new Set;for(let t=n;t<=r;t++)for(let r=o;r<=i;r++){r===o&&t===n||this.dispatch("UPDATE_CELL",{sheetId:e,col:r,row:t,style:s?s.style:null,content:""});const i=this.getMerge({sheetId:e,col:r,row:t});i&&l.add(i.id),this.history.update("mergeCellMap",e,r,t,a)}for(let t of l){const{top:o,bottom:i,left:n,right:r}=this.getMergeById(e,t);for(let t=o;t<=i;t++)for(let o=n;o<=r;o++){const i={sheetId:e,col:o,row:t},n=this.getMerge(i);n&&n.id===a||(this.history.update("mergeCellMap",e,o,t,void 0),this.dispatch("CLEAR_CELL",i))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:o,top:i,bottom:n,right:r}=t,s=this.getMerge({sheetId:e,col:o,row:i});if(void 0!==s&&Uo(t,s)){this.history.update("merges",e,s.id,void 0);for(let t=i;t<=n;t++)for(let i=o;i<=r;i++)this.history.update("mergeCellMap",e,i,t,void 0)}}applyRangeChangeOnSheet(e,t){const o=Object.entries(this.merges[e]||{});for(const[i,n]of o)if(n){const o=n.zone,r=t(n);switch(r.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,o);break;default:const{width:t,height:n}=Go(r.range.zone);1===t&&1===n?this.removeMerge(e,o):this.history.update("merges",e,parseInt(i,10),r.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:o,row:i}of Zo(t))this.history.update("mergeCellMap",e,o,i,t.id)}import(e){const t=e.sheets||[];for(let e of t)this.history.update("merges",e.id,{}),this.history.update("mergeCellMap",e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let o of t)this.addMerge(e,Mo(o))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...xv(e))}}exportForExcel(e){this.export(e)}}function xv(e){return Object.entries(e).map((([e,t])=>t?Iv(parseInt(e,10),t):void 0)).filter(Je).map((e=>$t(e.left,e.top)+":"+$t(e.right,e.bottom)))}function Iv(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}yv.getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge"];class Rv{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",o="COL"===e.dimension?"right":"bottom",i="COL"===e.dimension?"columns":"rows";const n=[...e.elements];n.sort(((e,t)=>t-e));const r=Ve(n);this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};let s=n,a="NONE";for(let e of r){const r=Math.min(...e),l=Math.max(...e);if(n.zone[t]<=r&&r<=n.zone[o]){const e=Math.min(n.zone[o],l)-r+1;a="RESIZE",s=this.createAdaptedRange(s,i,a,-e)}else if(n.zone[t]>=r&&n.zone[o]<=l)a="REMOVE",s=n.clone({...this.getInvalidRange()});else if(n.zone[t]<=l&&n.zone[o]>=l){const e=l-n.zone[t]+1;a="RESIZE",s=this.createAdaptedRange(s,i,a,-e),s=this.createAdaptedRange(s,i,"MOVE",-(n.zone[t]-r))}else r<n.zone[t]&&(a="MOVE",s=this.createAdaptedRange(s,i,a,-(l-r+1)))}return"NONE"!==a?{changeType:a,range:s}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",o="COL"===e.dimension?"right":"bottom",i="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(n.zone[t]<=e.base&&e.base<n.zone[o])return{changeType:"RESIZE",range:this.createAdaptedRange(n,i,"RESIZE",e.quantity)};if(e.base<n.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(n,i,"MOVE",e.quantity)}}else{if(n.zone[t]<e.base&&e.base<=n.zone[o])return{changeType:"RESIZE",range:this.createAdaptedRange(n,i,"RESIZE",e.quantity)};if(e.base<=n.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(n,i,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId!==e.sheetId)return{changeType:"NONE"};const o=this.getters.getSheetName(e.sheetId);return{changeType:"REMOVE",range:t=t.clone({...this.getInvalidRange(),invalidSheetName:o})}}),e.sheetId);break;case"RENAME_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.name&&t.invalidSheetName===e.name){const o=void 0,i=e.sheetId;return{changeType:"CHANGE",range:t.clone({sheetId:i,invalidSheetName:o})}}return{changeType:"NONE"}}));break;case"MOVE_RANGES":{const t=e.target[0];this.executeOnAllRanges((o=>{if(o.sheetId!==e.sheetId||!Bo(o.zone,t))return{changeType:"NONE"};const i=e.targetSheetId,n=e.col-t.left,r=e.row-t.top,s=this.createAdaptedRange(o,"both","MOVE",[n,r]),a=e.sheetId!==i||s.prefixSheet;return{changeType:"MOVE",range:s.clone({sheetId:i,prefixSheet:a})}}));break}}}finalize(){}verifyRangeRemoved(e){return t=>{const o=e(t);return"NONE"===o.changeType||No(o.range.zone)?o:{range:o.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,o,i){const n=jo(e.unboundedZone,t,o,i);return e.clone({zone:n})}executeOnAllRanges(e,t){const o=this.verifyRangeRemoved(e);for(const e of this.providers)e(o,t)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,o,i){const n=e.map((e=>xo.fromRange(e,this.getters)));return n.map((e=>{if(!No(e.zone))return e;const n=e.prefixSheet?e.sheetId:i,r={...e.unboundedZone,left:e.isFullRow&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:e.isFullRow?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.isFullCol&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:o),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:o)};return e.clone({sheetId:n,zone:r}).orderZone()}))}getRangeFromSheetXC(e,t){if(!Tt.test(t))return new xo({sheetId:"",zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let o,i=t,n=!1;t.includes("!")&&(({xc:i,sheetName:o}=_t(t)),o&&(n=!0));const r=Oo(i),s=xo.getRangeParts(i,r),a=o&&!this.getters.getSheetIdByName(o)?o:void 0,l=this.getters.getSheetIdByName(o)||e;return new xo({prefixSheet:n,zone:r,sheetId:l,invalidSheetName:a,parts:s},this.getters.getSheetSize).orderZone()}getSelectionRangeString(e,t){const o=xo.fromRange(e,this.getters),i=this.getters.expandZone(o.sheetId,o.zone),n=o.clone({zone:{...i,bottom:o.isFullCol?void 0:i.bottom,right:o.isFullRow?void 0:i.right}});return this.getRangeString(n,t)}getRangeString(e,t){if(!e)return X;if(e.invalidXc)return e.invalidXc;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 o=xo.fromRange(e,this.getters);let i=o.sheetId!==t||o.invalidSheetName||o.prefixSheet,n="";if(i&&(n=o.invalidSheetName?o.invalidSheetName:_e(this.getters.getSheetName(o.sheetId))),i&&!n)return X;let r=this.getRangePartString(o,0);return o.parts&&2===o.parts.length&&(o.zone.top!==o.zone.bottom||o.zone.left!==o.zone.right||o.parts[0].rowFixed||o.parts[0].colFixed||o.parts[1].rowFixed||o.parts[1].colFixed)&&(r+=":",r+=this.getRangePartString(o,1)),`${i?n+"!":""}${r}`}getRangeDataFromXc(e,t){return this.getters.getRangeFromSheetXC(e,t).rangeData}getRangeDataFromZone(e,t){return{_sheetId:e,_zone:t}}getRangeFromRangeData(e){const t={prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]};return new xo(t,this.getters.getSheetSize)}getRangePartString(e,t){const o=e.parts&&e.parts[t].colFixed?"$":"",i=Ft(0===t?e.zone.left:e.zone.right),n=e.parts&&e.parts[t].rowFixed?"$":"",r=String(0===t?e.zone.top+1:e.zone.bottom+1);let s="";return s=e.isFullCol?0===t&&e.unboundedZone.hasHeader?o+i+n+r:o+i:e.isFullRow?0===t&&e.unboundedZone.hasHeader?o+i+n+r:n+r:o+i+n+r,s}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:X}}}Rv.getters=["getRangeString","getSelectionRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData"];class Tv extends cv{constructor(){super(...arguments),this.sheetIdsMapName={},this.orderedSheetIds=[],this.sheets={},this.cellPosition={}}allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZones)(e);if(0!==t)return t;switch(e.type){case"HIDE_SHEET":return 1===this.getVisibleSheetIds().length?9:0;case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"MOVE_SHEET":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.orderedSheetIds.length>1?0:9;case"ADD_COLUMNS_ROWS":const o="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return e.base<0||e.base>o?86:e.quantity<=0?87:0;case"REMOVE_COLUMNS_ROWS":{const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return Math.min(...e.elements)<0||Math.max(...e.elements)>t?86: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,o;for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let i of e.sheets){const e=i.name||n("Sheet")+(Object.keys(this.sheets).length+1),{colNumber:r,rowNumber:s}=this.getImportedSheetSize(i),a={id:i.id,name:e,numberOfCols:r,rows:To(s),areGridLinesVisible:void 0===i.areGridLinesVisible||i.areGridLinesVisible,isVisible:i.isVisible,panes:{xSplit:(null===(t=i.panes)||void 0===t?void 0:t.xSplit)||0,ySplit:(null===(o=i.panes)||void 0===o?void 0:o.ySplit)||0}};this.orderedSheetIds.push(a.id),this.sheets[a.id]=a}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(Je).map((e=>{const t=this.sheets[e],o={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},conditionalFormats:[],figures:[],filterTables:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible};return(t.panes.xSplit||t.panes.ySplit)&&(o.panes=t.panes),o}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){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(e.toUpperCase()===t.toUpperCase())return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}getEvaluationSheets(){return this.sheets}doesHeaderExist(e,t,o){return"COL"===t?o>=0&&o<this.getNumberCols(e):o>=0&&o<this.getNumberRows(e)}getRow(e,t){const o=this.getSheet(e).rows[t];if(!o)throw new Error(`Row ${o} not found.`);return o}getCell({sheetId:e,col:t,row:o}){var i;const n=this.tryGetSheet(e),r=null===(i=null==n?void 0:n.rows[o])||void 0===i?void 0:i.cells[t];if(void 0!==r)return this.getters.getCellById(r)}getColsZone(e,t,o){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:o}}getRowCells(e,t){var o;return Object.values(null===(o=this.getSheet(e).rows[t])||void 0===o?void 0:o.cells).filter(Je)}getRowsZone(e,t,o){return{top:t,bottom:o,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){let t=1;const o=this.orderedSheetIds.map(this.getSheetName.bind(this));let i=`${e}${t}`;for(;o.includes(i);)i=`${e}${t}`,t++;return i}getSheetSize(e){return{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,o){const i={...this.getPaneDivisions(e)};"COL"===o?i.xSplit=t:"ROW"===o&&(i.ySplit=t),this.history.update("sheets",e,"panes",i)}isEmpty(e,t){return Zo(t).map((({col:t,row:o})=>this.getCell({sheetId:e,col:t,row:o}))).every((e=>!e||""===e.content))}updateCellPosition(e){const{sheetId:t,cellId:o,col:i,row:n}=e;o?this.setNewPosition(o,t,i,n):this.clearPosition(t,i,n)}setNewPosition(e,t,o,i){const n=this.cellPosition[e];n&&this.clearPosition(t,n.col,n.row),this.history.update("cellPosition",e,{row:i,col:o,sheetId:t}),this.history.update("sheets",t,"rows",i,"cells",o,e)}clearPosition(e,t,o){var i;const n=null===(i=this.sheets[e])||void 0===i?void 0:i.rows[o].cells[t];n&&(this.history.update("cellPosition",n,void 0),this.history.update("sheets",e,"rows",o,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}clearZones(e,t){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let i=o.top;i<=o.bottom;i++){this.sheets[e].rows[i].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:i})}}createSheet(e,t,o,i,n){const r={id:e,name:t,numberOfCols:o,rows:To(i),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},s=this.orderedSheetIds.slice();s.splice(n,0,r.id);const a=this.sheets;return this.history.update("orderedSheetIds",s),this.history.update("sheets",Object.assign({},a,{[r.id]:r})),r}moveSheet(e,t){const o=this.orderedSheetIds.slice(),i=o.findIndex((t=>t===e)),n=o.splice(i,1);let r="left"===t?this.findIndexOfPreviousVisibleSheet(i-1,o):this.findIndexOfNextVisibleSheet(i+1,o);void 0===r&&(r=o.length),o.splice(r,0,n[0]),this.history.update("orderedSheetIds",o)}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:o}=this,i=e.name&&e.name.trim().toLowerCase();return t.find((e=>{var t;return(null===(t=o[e])||void 0===t?void 0:t.name.toLowerCase())===i}))?11:ne.test(i)?13:0}checkSheetPosition(e){const{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?15:0}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?0:74}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?0:74}checkRowFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let o of t)if(o.top<e.quantity&&e.quantity<=o.bottom)return 65;return 0}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let o of t)if(o.left<e.quantity&&e.quantity<=o.right)return 65;return 0}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):10}renameSheet(e,t){const o=e.name;this.history.update("sheets",e.id,"name",t.trim());const i=Object.assign({},this.sheetIdsMapName);i[t]=e.id,delete i[o],this.history.update("sheetIdsMapName",i)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t){const o=this.getSheet(e),i=this.getDuplicateSheetName(o.name),n=Me(o);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 r=this.orderedSheetIds.slice(),s=r.indexOf(e);r.splice(s+1,0,n.id),this.history.update("orderedSheetIds",r),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:o}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:n.id,col:e,row:o,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIdsMapName);a[n.name]=n.id,this.history.update("sheetIdsMapName",a)}getDuplicateSheetName(e){let t=1;const o=this.orderedSheetIds.map(this.getSheetName.bind(this)),i=r("Copy of %s",e);let n=i.toString();for(;o.includes(n);)n=`${i} (${t})`,t++;return n}deleteSheet(e){const t=e.name,o=Object.assign({},this.sheets);delete o[e.id],this.history.update("sheets",o);const i=this.orderedSheetIds.slice(),n=i.indexOf(e.id);i.splice(n,1),this.history.update("orderedSheetIds",i);const r=Object.assign({},this.sheetIdsMapName);delete r[t],this.history.update("sheetIdsMapName",r)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(let o of t)this.moveCellOnColumnsDeletion(e,o);const o=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",o-t.length);const i=t.filter((t=>t<e.panes.xSplit)).length;i&&this.setPaneDivisions(e.id,e.panes.xSplit-i,"COL")}removeRows(e,t){t.sort(((e,t)=>t-e));for(let o of Ve(t))this.moveCellOnRowsDeletion(e,o[o.length-1],o[0]),o.map((t=>this.updateRowsStructureOnDeletion(t,e)));const o=t.filter((t=>t<e.panes.ySplit)).length;o&&this.setPaneDivisions(e.id,e.panes.ySplit-o,"ROW")}addColumns(e,t,o,i){const n="before"===o?t:t+1;this.moveCellsOnAddition(e,n,i,"columns");const r=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",r+i),n<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+i,"COL")}addRows(e,t,o,i){const n="before"===o?t:t+1;this.addEmptyRows(e,i),this.moveCellsOnAddition(e,n,i,"rows"),this.updateRowsStructureOnAddition(e,t,i),n<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+i,"ROW")}moveCellOnColumnsDeletion(e,t){for(let o=0;o<e.rows.length;o++){const i=e.rows[o];for(let n in i.cells){const r=Number(n),s=i.cells[n];s&&(r===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:r,row:o}),r>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:s,col:r-1,row:o}))}}}moveCellsOnAddition(e,t,o,i){const n=[];for(let r=0;r<e.rows.length;r++){const s=e.rows[r];if("rows"!==i||r>=t)for(let a in s.cells){const l=Number(a),c=s.cells[a];c&&("rows"===i||l>=t)&&n.push({type:"UPDATE_CELL_POSITION",sheetId:e.id,cellId:c,col:l+("columns"===i?o:0),row:r+("rows"===i?o:0)})}}for(let e of n.reverse())this.dispatch(e.type,e)}moveCellOnRowsDeletion(e,t,o){const i=o-t+1;for(let n=0;n<e.rows.length;n++){const r=e.rows[n];if(n>=t&&n<=o)for(let t in r.cells){const o=Number(t);r.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:o,row:n})}if(n>o)for(let t in r.cells){const o=Number(t),s=r.cells[t];s&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:s,col:o,row:n-i})}}}updateRowsStructureOnDeletion(e,t){const o=[],i=t.rows.map((e=>e.cells));for(let n in t.rows)Number(n)!==e&&o.push({cells:i.shift()});this.history.update("sheets",t.id,"rows",o)}updateRowsStructureOnAddition(e,t,o){const i=[],n=e.rows.map((e=>e.cells));e.rows.forEach((()=>i.push({cells:n.shift()}))),this.history.update("sheets",e.id,"rows",i)}addEmptyRows(e,t){const o=e.rows.slice();for(let e=0;e<t;e++)o.push({cells:{}});this.history.update("sheets",e.id,"rows",o)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(kt);let o=e.rowNumber,i=e.colNumber;for(let{col:e,row:n}of t)o=Math.max(o,n+1),i=Math.max(i,e+1);return{rowNumber:o,colNumber:i}}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?27:"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?12:0}checkZones(e){const t=[];if("zone"in e&&t.push(e.zone),"target"in e&&Array.isArray(e.target)&&t.push(...e.target),"ranges"in e&&Array.isArray(e.ranges)&&t.push(...e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone))),!t.every(No))return 25;if(t.length&&"sheetId"in e){const o=this.getSheetZone(e.sheetId);return t.every((e=>Bo(e,o)))?0:18}return 0}}Tv.getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheetIds","getVisibleSheetIds","isSheetVisible","getEvaluationSheets","doesHeaderExist","getCell","getCellPosition","getColsZone","getRowCells","getRowsZone","getNumberCols","getNumberRows","getNumberHeaders","getGridLinesVisibility","getNextSheetName","isEmpty","getSheetSize","getSheetZone","getPaneDivisions"];class Av extends qu{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 o=Object.values(this.getters.getCells(t));e=e.concat(this.getColorsFromCells(o),this.getFormattingColors(t),this.getChartColors(t))}return function(e){const t=[{leadColor:ft(255,0,0),colors:[]},{leadColor:ft(255,128,0),colors:[]},{leadColor:ft(128,128,0),colors:[]},{leadColor:ft(128,255,0),colors:[]},{leadColor:ft(0,255,0),colors:[]},{leadColor:ft(0,255,128),colors:[]},{leadColor:ft(0,255,255),colors:[]},{leadColor:ft(0,127,255),colors:[]},{leadColor:ft(0,0,255),colors:[]},{leadColor:ft(127,0,255),colors:[]},{leadColor:ft(128,0,128),colors:[]},{leadColor:ft(255,0,128),colors:[]}];for(const o of e.map(Ct)){let e=500,i=0;t.forEach(((t,n)=>{const r=(s=o,a=t.leadColor,Math.sqrt(Math.pow(s.r-a.r,2)+Math.pow(s.g-a.g,2)+Math.pow(s.b-a.b,2)));var s,a;e>r&&(e=r,i=n)})),t[i].colors.push(o)}return t.map((e=>e.colors.sort(((e,t)=>Et(e).s-Et(t).s)))).flat().map(bt)}([...new Set([...new Set([...e,...this.customColors])].filter(pt).map(gt))]).filter((e=>!A.includes(e)))}getColorsFromCells(e){var t,o;const i=new Set;for(const n of e)(null===(t=n.style)||void 0===t?void 0:t.textColor)&&i.add(n.style.textColor),(null===(o=n.style)||void 0===o?void 0:o.fillColor)&&i.add(n.style.fillColor);return[...i]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),o=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(o.push(t.style.textColor),o.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(o.push(ut(t.minimum.color)),o.push(t.midpoint?ut(t.midpoint.color):void 0),o.push(ut(t.maximum.color)))}return o.filter(Je)}getChartColors(e){const t=this.getters.getChartIds(e).map((e=>this.getters.getChart(e)));let o=new Set;for(let e of t){if(void 0===e)continue;const t=e.getDefinition().background;switch(void 0!==t&&o.add(t),e.type){case"gauge":const t=e.sectionRule.colors;o.add(t.lowerColor),o.add(t.middleColor),o.add(t.upperColor);break;case"scorecard":const i=e;o.add(i.baselineColorDown),o.add(i.baselineColorUp)}}return[...o]}tryToAddColor(e){const t=gt(e);e&&!A.includes(t)&&this.customColors.add(t)}}Av.getters=["getCustomColors"];const Ov=Kd.mapping;class Mv extends qu{constructor(e){super(e),this.isUpToDate=!1,this.evaluatedCells={},this.evalContext=e.custom,this.lazyEvaluation=e.lazyEvaluation}handle(e){switch(bi.has(e.type)&&(this.isUpToDate=!1),e.type){case"UPDATE_CELL":("content"in e||"format"in e)&&(this.isUpToDate=!1);break;case"EVALUATE_CELLS":this.evaluate()}}finalize(){this.isUpToDate||(this.evaluate(),this.isUpToDate=!0)}evaluateFormula(e,t=this.getters.getActiveSheetId()){const o=Vu(e),i=this.getCompilationParameters((e=>this.getEvaluatedCell(this.getters.getCellPosition(e.id)))),n=[];for(let e of o.dependencies)n.push(this.getters.getRangeFromSheetXC(t,e));return o.execute(n,...i).value}getRangeFormattedValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.formattedValue))}getRangeValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.value))}getEvaluatedCell({sheetId:e,col:t,row:o}){var i,n,r;return void 0===this.getters.getCell({sheetId:e,col:t,row:o})?yg(""):(null===(r=null===(n=null===(i=this.evaluatedCells[e])||void 0===i?void 0:i[t])||void 0===n?void 0:n[o])||void 0===r?void 0:r.call(n))||yg("")}getEvaluatedCells(e){const t=this.getters.getCells(e)||{},o={};for(let e of Object.keys(t)){const t=this.getters.getCellPosition(e);o[e]=this.getEvaluatedCell(t)}return o}getColEvaluatedCells(e,t){var o;return Object.values((null===(o=this.evaluatedCells[e])||void 0===o?void 0:o[t])||[]).filter(Je).map((e=>e()))}getEvaluatedCellsInZone(e,t){return Zo(t).map((({col:t,row:o})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:o})))}setEvaluatedCell(e,t){const{col:o,row:i,sheetId:n}=this.getters.getCellPosition(e);this.evaluatedCells[n]||(this.evaluatedCells[n]={}),this.evaluatedCells[n][o]||(this.evaluatedCells[n][o]={}),this.evaluatedCells[n][o][i]=t,this.lazyEvaluation||this.evaluatedCells[n][o][i]()}*getAllCells(){for(const e of this.getters.getSheetIds()){const t=this.getters.getCells(e);for(const e in t)yield t[e]}}evaluate(){this.evaluatedCells={};const e=new Set,t=e=>{var t,n;const r=e.id,{col:s,row:a,sheetId:l}=this.getters.getCellPosition(r),c=null===(n=null===(t=this.evaluatedCells[l])||void 0===t?void 0:t[s])||void 0===n?void 0:n[a];return c||it((()=>{try{switch(e.isFormula){case!0:return i(e);case!1:return Eg(e.content,e.format)}}catch(t){return o(t,e)}}))},o=(e,t)=>{e instanceof Error||(e=new Error(e));const o=(null==e?void 0:e.errorType)||a.GenericError,i=n[2].__lastFnCalled||"",r=new c(o,e.message.replace("[[FUNCTION_NAME]]",i),void 0!==e.logLevel?e.logLevel:l.error);return Tg(t.content,r)},i=t=>{const o=t.id;if(e.has(o))throw new d;n[2].__originCellXC=()=>{const e=n[2].getters.getCellPosition(o);return $t(e.col,e.row)},e.add(o);const i=t.compiledFormula.execute(t.dependencies,...n);if(e.delete(o),Array.isArray(i.value))throw new Error(r("This formula depends on invalid values"));return yg(i.value,t.format||i.format)},n=this.getCompilationParameters((e=>t(e)()));for(const e of this.getAllCells())this.setEvaluatedCell(e.id,t(e))}getCompilationParameters(e){const t=Object.assign(Object.create(Ov),this.evalContext,{getters:this.getters}),o=this.getters;const i=t=>{const o=e(t);if(o.type===fi.error)throw o.error;return o};return[function(e,t,n,s){if(t)return{value:_o(e.zone)};if(!No(e.zone))throw new u;if(e.zone.bottom!==e.zone.top||e.zone.left!==e.zone.right)throw new Error(s?r("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",n.toString(),s.toString()):r("Function %s expects its parameters to be single values or single cell references, not ranges.",n.toString()));if(e.invalidSheetName)throw new Error(r("Invalid sheet name: %s",e.invalidSheetName));return function(e){let t;if(!o.tryGetSheet(e.sheetId))throw new Error(r("Invalid sheet name"));return t=o.getCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}),t&&""!==t.content?i(t):{value:null,format:null==t?void 0:t.format}}(e)},function(e){const n=e.sheetId;if(!No(e.zone))throw new u;const r=o.getSheetZone(n),s=[],a=Lo(e.zone,r);if(!a)return s.push([]),s;for(let o=a.left;o<=a.right;o++){const n=[];for(let r=a.top;r<=a.bottom;r++){const s=t.getters.getCell({sheetId:e.sheetId,col:o,row:r});n.push(s?i(s):void 0)}s.push(n)}return s},t]}exportForExcel(e){for(let t of e.sheets)for(const e in t.cells){const o={sheetId:t.id,...kt(e)},i=this.getters.getCell(o);if(i){const n=t.cells[e],r=this.getEvaluatedCell(o);n.value=r.value,n.isFormula=i.isFormula&&!this.isBadExpression(i.content),i.format!==r.format&&(n.computedFormat=r.format)}}}isBadExpression(e){try{return Vu(e),!1}catch(e){return!0}}}Mv.getters=["evaluateFormula","getRangeFormattedValues","getRangeValues","getEvaluatedCell","getEvaluatedCells","getColEvaluatedCells","getEvaluatedCellsInZone"];class Nv extends qu{constructor(){super(...arguments),this.charts={},this.createRuntimeChart=function(e){const t=Rn.getAll();return function(o){const i=t.find((e=>e.match(o.type)));if(!i)throw new Error("No runtime builder for this chart.");return i.getChartRuntime(o,e)}}(this.getters)}handle(e){if(bi.has(e.type)||Ci.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]}getBackgroundOfSingleCellChart(e,t){if(e)return e;if(!t)return w;const o=t.zone.left,i=t.zone.top,n=t.sheetId;return this.getters.getCellComputedStyle({sheetId:n,col:o,row:i}).fillColor||w}}Nv.getters=["getChartRuntime","getBackgroundOfSingleCellChart"];class _v extends qu{constructor(){super(...arguments),this.isStale=!0,this.computedStyles={},this.computedIcons={},this.rulePredicate={CellIsRule:(e,t)=>{if(e.type===fi.error)return!1;const o=t.values.map(wg);switch(t.operator){case"IsEmpty":return""===e.value.toString().trim();case"IsNotEmpty":return""!==e.value.toString().trim();case"BeginsWith":return""!==o[0]&&e.value.toString().startsWith(o[0].toString());case"EndsWith":return""!==o[0]&&e.value.toString().endsWith(o[0].toString());case"Between":return e.value>=o[0]&&e.value<=o[1];case"NotBetween":return!(e.value>=o[0]&&e.value<=o[1]);case"ContainsText":return e.value.toString().indexOf(o[0].toString())>-1;case"NotContains":return!e.value||-1==e.value.toString().indexOf(o[0].toString());case"GreaterThan":return e.value>o[0];case"GreaterThanOrEqual":return e.value>=o[0];case"LessThan":return e.value<o[0];case"LessThanOrEqual":return e.value<=o[0];case"NotEqual":return""!==o[0]&&e.value!==o[0];case"Equal":return""===o[0]||e.value===o[0];default:console.warn(r("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}}}handle(e){switch((Ci.has(e.type)||"UPDATE_CELL"===e.type&&"content"in e)&&(this.isStale=!0),e.type){case"ACTIVATE_SHEET":const t=e.sheetIdTo;this.computedStyles[t]=this.computedStyles[t]||{},this.computedIcons[t]=this.computedIcons[t]||{},this.isStale=!0;break;case"AUTOFILL_CELL":const o=this.getters.getActiveSheetId(),i=this.getters.getRulesByCell(o,e.originCol,e.originRow);for(const t of i)this.adaptRules(o,t,[$t(e.col,e.row)],[]);break;case"PASTE_CONDITIONAL_FORMAT":this.pasteCf(e.origin,e.target,e.operation)}}finalize(){this.isStale&&(this.computeStyles(),this.isStale=!1)}getCellComputedStyle(e){var t;const{sheetId:o,col:i,row:n}=e,r=this.getters.getCell(e),s=this.computedStyles[o],a=s&&(null===(t=s[i])||void 0===t?void 0:t[n]),l={...null==r?void 0:r.style,...a};return this.getters.getEvaluatedCell(e).link&&!l.textColor&&(l.textColor=x),this.getters.isFilterHeader(e)&&(l.bold=!0),l}getConditionalIcon({col:e,row:t}){var o;const i=this.getters.getActiveSheetId(),n=this.computedIcons[i];return n&&(null===(o=n[e])||void 0===o?void 0:o[t])}computeStyles(){var e;const t=this.getters.getActiveSheetId();this.computedStyles[t]={},this.computedIcons[t]={};const o=this.computedStyles[t];for(let i of this.getters.getConditionalFormats(t).reverse())try{switch(i.rule.type){case"ColorScaleRule":for(let e of i.ranges)this.applyColorScale(e,i.rule);break;case"IconSetRule":for(let e of i.ranges)this.applyIcon(e,i.rule);break;default:for(let n of i.ranges){const r=this.getters.getRangeFromSheetXC(t,n).zone;for(let n=r.top;n<=r.bottom;n++)for(let s=r.left;s<=r.right;s++){const r=this.rulePredicate[i.rule.type];let a=this.getters.getEvaluatedCell({sheetId:t,col:s,row:n});r&&r(a,i.rule)&&(o[s]||(o[s]=[]),o[s][n]=Object.assign((null===(e=o[s])||void 0===e?void 0:e[n])||{},i.rule.style))}}}}catch(e){}}parsePoint(e,t,o){const i=this.getters.getActiveSheetId(),n=this.getters.getEvaluatedCellsInZone(i,this.getters.getRangeFromSheetXC(i,e).zone).filter((e=>e.type===fi.number)).map((e=>e.value));switch(t.type){case"value":return"max"===o?Math.max(...n):Math.min(...n);case"number":return Number(t.value);case"percentage":const e=Math.min(...n);return e+(Math.max(...n)-e)*Number(t.value)/100;case"percentile":return Yt(n,Number(t.value)/100,!0);case"formula":const i=t.value&&this.getters.evaluateFormula(t.value);return i instanceof Promise?null:i;default:return null}}applyIcon(e,t){const o=this.parsePoint(e,t.lowerInflectionPoint),i=this.parsePoint(e,t.upperInflectionPoint);if(null===o||null===i||o>i)return;const n=this.getters.getActiveSheetId(),r=this.getters.getRangeFromSheetXC(n,e).zone,s=this.computedIcons[n],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=r.top;e<=r.bottom;e++)for(let l=r.left;l<=r.right;l++){const r=this.getters.getEvaluatedCell({sheetId:n,col:l,row:e});if(r.type!==fi.number)continue;const c=this.computeIcon(r.value,i,t.upperInflectionPoint.operator,o,t.lowerInflectionPoint.operator,a);s[l]||(s[l]=[]),s[l][e]=c}}computeIcon(e,t,o,i,n,r){return"ge"===o&&e>=t||"gt"===o&&e>t?r[0]:"ge"===n&&e>=i||"gt"===n&&e>i?r[1]:r[2]}applyColorScale(e,t){var o;const i=this.parsePoint(e,t.minimum,"min"),n=t.midpoint?this.parsePoint(e,t.midpoint):null,r=this.parsePoint(e,t.maximum,"max");if(null===i||null===r||i>=r||n&&(i>=n||n>=r))return;const s=this.getters.getActiveSheetId(),a=this.getters.getRangeFromSheetXC(s,e).zone,l=this.computedStyles[s],c=[];t.midpoint&&n?(c.push({minValue:i,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(i,n,t.minimum.color,t.midpoint.color)}),c.push({minValue:n,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(n,r,t.midpoint.color,t.maximum.color)})):c.push({minValue:i,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(i,r,t.minimum.color,t.maximum.color)});for(let e=a.top;e<=a.bottom;e++)for(let t=a.left;t<=a.right;t++){const a=this.getters.getEvaluatedCell({sheetId:s,col:t,row:e});if(a.type===fi.number){const s=Fe(a.value,i,r);let h;h=2===c.length&&n?s<=n?this.colorCell(s,c[0].minValue,c[0].minColor,c[0].colorDiffUnit):this.colorCell(s,c[1].minValue,c[1].minColor,c[1].colorDiffUnit):this.colorCell(s,c[0].minValue,c[0].minColor,c[0].colorDiffUnit),l[t]||(l[t]=[]),l[t][e]=(null===(o=l[t])||void 0===o?void 0:o[e])||{},l[t][e].fillColor=ut(h)}}}computeColorDiffUnits(e,t,o,i){const n=t-e;return[((o>>16)%256-(i>>16)%256)/n,((o>>8)%256-(i>>8)%256)/n,(o%256-i%256)/n]}colorCell(e,t,o,i){const[n,r,s]=i;return Math.round((o>>16)%256-n*(e-t))<<16|Math.round((o>>8)%256-r*(e-t))<<8|Math.round(o%256-s*(e-t))}adaptRules(e,t,o,i){if(0===o.length&&0===i.length)return;const n=this.getters.getConditionalFormats(e),r=n.findIndex((e=>e.id===t.id));let s=[];r>-1&&(s=n[r].ranges),s=s.concat(o);const a=Ho(s,i);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})}pasteCf(e,t,o){const i=$t(t.col,t.row);for(let n of this.getters.getConditionalFormats(e.sheetId))for(let r of n.ranges)if(zo(e.col,e.row,this.getters.getRangeFromSheetXC(e.sheetId,r).zone)){const r=n,s=[];"CUT"===o&&s.push($t(e.col,e.row)),e.sheetId===t.sheetId?this.adaptRules(e.sheetId,r,[i],s):(this.adaptRules(t.sheetId,r,[i],[]),this.adaptRules(e.sheetId,r,[],s))}}}_v.getters=["getConditionalIcon","getCellComputedStyle"];class Fv extends qu{constructor(){super(...arguments),this.filterValues={},this.hiddenRows=new Set,this.isEvaluationDirty=!1}allowDispatch(e){if("UPDATE_FILTER"===e.type)if(!this.getters.getFilterId(e))return 79;return 0}handle(e){switch(e.type){case"UNDO":case"REDO":case"UPDATE_CELL":case"EVALUATE_CELLS":case"ACTIVATE_SHEET":case"REMOVE_FILTER_TABLE":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":this.updateHiddenRows();break;case"UPDATE_FILTER":this.updateFilter(e),this.updateHiddenRows();break;case"DUPLICATE_SHEET":const t={};for(const o of this.getters.getFilters(e.sheetIdTo)){const i=o.zoneWithHeaders;t[o.id]=this.getFilterValues({sheetId:e.sheetId,col:i.left,row:i.top})}this.filterValues[e.sheetIdTo]=t}}finalize(){this.isEvaluationDirty&&(this.updateHiddenRows(),this.isEvaluationDirty=!1)}isRowFiltered(e,t){return e===this.getters.getActiveSheetId()&&this.hiddenRows.has(t)}getCellBorderWithFilterBorder(e){const{sheetId:t,col:o,row:i}=e;let n;for(let e of this.getters.getFilterTables(t)){const r=e.zone;if(zo(o,i,r)){const e=this.intersectZoneWithViewport(t,r);n={top:i===e.top?Z:void 0,bottom:i===e.bottom?Z:void 0,left:o===e.left?Z:void 0,right:o===e.right?Z:void 0}}}const r=this.getters.getCellBorder(e),s={...n,...at(r||{})};return et(s)?null:s}getFilterHeaders(e){const t=[];for(let o of this.getters.getFilterTables(e)){const i=o.zone;if(!i)continue;const n=i.top;for(let o=i.left;o<=i.right;o++)this.getters.isColHidden(e,o)||this.getters.isRowHidden(e,n)||t.push({col:o,row:n})}return t}getFilterValues(e){const t=this.getters.getFilterId(e),o=e.sheetId;return t&&this.filterValues[o]&&this.filterValues[o][t]||[]}isFilterHeader({sheetId:e,col:t,row:o}){return this.getFilterHeaders(e).some((e=>e.col===t&&e.row===o))}isFilterActive(e){var t,o;const i=this.getters.getFilterId(e),n=e.sheetId;return Boolean(i&&(null===(o=null===(t=this.filterValues[n])||void 0===t?void 0:t[i])||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:o,sheetId:i}){const n=this.getters.getFilterId({sheetId:i,col:e,row:t});n&&(this.filterValues[i]||(this.filterValues[i]={}),this.filterValues[i][n]=o)}updateHiddenRows(){var e,t;const o=this.getters.getActiveSheetId(),i=this.getters.getFilters(o).sort(((e,t)=>e.zoneWithHeaders.top-t.zoneWithHeaders.top)),n=new Set;for(let r of i){if(this.getters.isRowHiddenByUser(o,r.zoneWithHeaders.top))continue;if(n.has(r.zoneWithHeaders.top))continue;const i=null===(t=null===(e=this.filterValues[o])||void 0===e?void 0:e[r.id])||void 0===t?void 0:t.map(lt);if(i&&r.filteredZone)for(let e=r.filteredZone.top;e<=r.filteredZone.bottom;e++){const t=this.getCellValueAsString(o,r.col,e);i.includes(t)&&n.add(e)}}this.hiddenRows=n}getCellValueAsString(e,t,o){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:o}).formattedValue.toLowerCase()}exportForExcel(e){for(const t of e.sheets){const e=t.id;for(const o of t.filterTables){const i=Mo(o.range),n=[],r=[];for(const o of Ue(0,Go(i).width)){const s={sheetId:t.id,col:i.left+o,row:i.top},a=this.getFilterValues(s),l=this.getters.getFilter(s);if(!l)continue;const c=l.filteredZone?Zo(l.filteredZone).map((t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue)):[];if(a.length){const e=c.filter((e=>e)).filter((e=>!a.includes(e)));n.push({colId:o,displayedValues:[...new Set(e)],displayBlanks:!a.includes("")&&c.some((e=>!e))})}const h={col:l.col,row:l.zoneWithHeaders.top,sheetId:e},d=this.getters.getEvaluatedCell(h).formattedValue,u=this.getUniqueColNameForExcel(o,d,r);r.push(u),t.cells[$t(h.col,h.row)]={...t.cells[$t(h.col,h.row)],content:u,value:u,isFormula:!1}}o.filters=n}}}getUniqueColNameForExcel(e,t,o){t||(t=`Column${e}`);let i=t,n=2;for(;o.includes(i);)i=t+String(n),n++;return i}}Fv.getters=["getCellBorderWithFilterBorder","getFilterHeaders","getFilterValues","isFilterHeader","isRowFiltered","isFilterActive"];class Dv{constructor(e,t,o,i,n,r){this.getters=e,this.sheetId=t,this.boundaries=o,this.viewportWidth=i.width,this.viewportHeight=i.height,this.offsetScrollbarX=r.x,this.offsetScrollbarY=r.y,this.canScrollVertically=n.canScrollVertically,this.canScrollHorizontally=n.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){const e=this.getters.findLastVisibleColRowIndex(this.sheetId,"COL",{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,"ROW",{first:this.boundaries.top,last:this.boundaries.bottom}),{end:o,size:i}=this.getters.getColDimensions(this.sheetId,e),{end:n,size:r}=this.getters.getRowDimensions(this.sheetId,t),s=this.searchHeaderIndex("COL",o-this.viewportWidth,0),a=this.getters.getColSize(this.sheetId,s),l=this.searchHeaderIndex("ROW",n-this.viewportHeight,0),c=this.getters.getRowSize(this.sheetId,l);let h=o-this.offsetCorrectionX;this.canScrollHorizontally&&(h+=Math.max(N,Math.min(a,this.viewportWidth-i)),h=Math.max(h,this.viewportWidth));let d=n-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(_+5,Math.min(c,this.viewportHeight-r)),d=Math.max(d,this.viewportHeight)),{width:h,height:d}}getColIndex(e,t=!1){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex("COL",e-this.offsetCorrectionX,this.left,t)}getRowIndex(e,t=!1){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex("ROW",e-this.offsetCorrectionY,this.top,t)}adjustPosition(e){const t=this.sheetId;e||(e=this.getters.getSheetPosition(t));const o=this.getters.getMainCellPosition({sheetId:t,...e}),{col:i,row:n}=this.getters.getNextVisibleCellPosition(o);zo(i,this.boundaries.top,this.boundaries)&&this.adjustPositionX(i),zo(this.boundaries.left,n,this.boundaries)&&this.adjustPositionY(n)}adjustPositionX(e){const t=this.sheetId,{end:o}=this.getters.getColDimensions(t,e),i=this.getters.getNumberCols(t);if(this.offsetX+this.offsetCorrectionX+this.viewportWidth<o)for(let e=this.left;this.offsetX+this.offsetCorrectionX+this.viewportWidth<o&&!(e>i);e++)this.getters.isColHidden(t,e)||(this.offsetX=this.getters.getColDimensions(t,e).end-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX());else if(this.left>e)for(let o=this.left;o>=e&&!(o<0);o--)this.getters.isColHidden(t,o)||(this.offsetX=this.getters.getColDimensions(t,o).start-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX())}adjustPositionY(e){const t=this.sheetId,{end:o}=this.getters.getRowDimensions(t,e),i=this.getters.getNumberRows(t);if(this.offsetY+this.viewportHeight+this.offsetCorrectionY<o)for(let e=this.top;this.offsetY+this.viewportHeight+this.offsetCorrectionY<o&&!(e>i);e++)this.getters.isRowHidden(t,e)||(this.offsetY=this.getters.getRowDimensions(t,e).end-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY());else if(this.top>e)for(let o=this.top;o>=e&&!(o<0);o--)this.getters.isRowHidden(t,o)||(this.offsetY=this.getters.getRowDimensions(t,o).start-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY())}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getRect(e){const t=Lo(e,this.zone);if(t){return{x:this.getters.getColRowOffset("COL",this.zone.left,t.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset("ROW",this.zone.top,t.top)+this.offsetCorrectionY,width:Math.min(this.getters.getColRowOffset("COL",t.left,t.right+1),this.viewportWidth),height:Math.min(this.getters.getColRowOffset("ROW",t.top,t.bottom+1),this.viewportHeight)}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,o=0,i=!1){let n=0;const r=this.sheetId,s=this.getters.getNumberHeaders(r,e);for(let a=o;a<=s-1;a++){const o=i||"COL"!==e?a<this.top&&a>this.bottom:a<this.left&&a>this.right;if(!this.getters.isHeaderHidden(r,e,a)&&!o&&(n+="COL"===e?this.getters.getColSize(r,a):this.getters.getRowSize(r,a),n>t))return a}return-1}get zone(){return{left:this.left,right:this.right,top:this.top,bottom:this.bottom}}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetScrollbarX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetScrollbarY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){const{width:e}=this.getMaxSize();this.viewportWidth+this.offsetScrollbarX>e&&(this.offsetScrollbarX=Math.max(0,e-this.viewportWidth))}this.left=this.getColIndex(this.offsetScrollbarX,!0),this.right=this.getColIndex(this.offsetScrollbarX+this.viewportWidth,!0),-1===this.right&&(this.right=this.boundaries.right),this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){const{height:e}=this.getMaxSize();this.viewportHeight+this.offsetScrollbarY>e&&(this.offsetScrollbarY=Math.max(0,e-this.viewportHeight))}this.top=this.getRowIndex(this.offsetScrollbarY,!0),this.bottom=this.getRowIndex(this.offsetScrollbarY+this.viewportWidth,!0),-1===this.bottom&&(this.bottom=this.boundaries.bottom),this.adjustViewportZoneY()}adjustViewportZoneX(){const e=this.sheetId;this.left=this.searchHeaderIndex("COL",this.offsetScrollbarX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex("COL",this.viewportWidth,this.left)),-1===this.right&&(this.right=this.getters.getNumberCols(e)-1),this.offsetX=this.getters.getColDimensions(e,this.left).start-this.getters.getColDimensions(e,this.boundaries.left).start}adjustViewportZoneY(){const e=this.sheetId;this.top=this.searchHeaderIndex("ROW",this.offsetScrollbarY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex("ROW",this.viewportHeight,this.top)),-1===this.bottom&&(this.bottom=this.getters.getNumberRows(e)-1),this.offsetY=this.getters.getRowDimensions(e,this.top).start-this.getters.getRowDimensions(e,this.boundaries.top).start}}class kv extends qu{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":let{col:t,row:o}=Xo(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const i=e.previousAnchor.zone,n=e.anchor.zone,{top:r,bottom:s,left:a,right:l}=this.getters.getActiveMainViewport();i.left===n.left&&i.right===n.right&&(t=a>t||t>l?a:t),i.top===n.top&&i.bottom===n.bottom&&(o=r>o||o>s?r:o)}const i=this.getters.getActiveSheetId();t=Math.min(t,this.getters.getNumberCols(i)-1),o=Math.min(o,this.getters.getNumberRows(i)-1),this.refreshViewport(this.getters.getActiveSheetId(),{col:t,row:o})}}handle(e){var t;switch(this.cleanViewports(),e.type){case"START":this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case"UNDO":case"REDO":this.resetSheetViews();break;case"RESIZE_SHEETVIEW":this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case"SET_VIEWPORT_OFFSET":this.setSheetViewOffset(e.offsetX,e.offsetY);break;case"SHIFT_VIEWPORT_DOWN":const{top:o}=this.getActiveMainViewport(),i=this.getters.getActiveSheetId(),n=this.clipOffsetY(this.getters.getRowDimensions(i,o).start+this.sheetViewHeight);this.shiftVertically(n);break;case"SHIFT_VIEWPORT_UP":{const{top:e}=this.getActiveMainViewport(),t=this.getters.getActiveSheetId(),o=this.clipOffsetY(this.getters.getRowDimensions(t,e).end-this.sheetViewHeight);this.shiftVertically(o);break}case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"UPDATE_FILTER":this.resetViewports(e.sheetId);break;case"UPDATE_CELL":("content"in e||"format"in e||void 0!==(null===(t=e.style)||void 0===t?void 0:t.fontSize))&&this.sheetsWithDirtyViewports.add(e.sheetId);break;case"ACTIVATE_SHEET":this.setViewports(),this.refreshViewport(e.sheetIdTo);break;case"UNFREEZE_ROWS":case"UNFREEZE_COLUMNS":case"FREEZE_COLUMNS":case"FREEZE_ROWS":case"UNFREEZE_COLUMNS_ROWS":this.resetViewports(this.getters.getActiveSheetId());break;case"DELETE_SHEET":this.sheetsWithDirtyViewports.delete(e.sheetId);break;case"START_EDITION":const{col:r,row:s}=this.getters.getActivePosition();this.refreshViewport(this.getters.getActiveSheetId(),{col:r,row:s})}}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 o of t)(null===(e=this.viewports[o])||void 0===e?void 0:e.bottomRight)||this.resetViewports(o)}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=>Ue(e.left,e.right+1))).flat())].filter((t=>!this.getters.isHeaderHidden(e,"COL",t)))}getSheetViewVisibleRows(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>Ue(e.top,e.bottom+1))).flat())].filter((t=>!this.getters.isHeaderHidden(e,"ROW",t)))}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:o,ySplit:i}=this.getters.getPaneDivisions(e);let{width:n,height:r}=t.getMaxSize();return{x:this.getters.getColDimensions(e,o).start,y:this.getters.getRowDimensions(e,i).start,width:n,height:r}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:o}=this.getMainViewportRect(),i=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-i.viewportWidth+1),maxOffsetY:Math.max(0,o-i.viewportHeight+1)}}getColRowOffsetInViewport(e,t,o){const i=this.getters.getActiveSheetId(),n=this.getters.getSheetViewVisibleCols(),r=this.getters.getSheetViewVisibleRows();if(o<t)return-this.getColRowOffsetInViewport(e,o,t);let s=0;const a="COL"===e?n:r;for(let n=t;n<o;n++)a.includes(n)&&(s+="COL"===e?this.getters.getColSize(i,n):this.getters.getRowSize(i,n));return s}isVisibleInViewport({sheetId:e,col:t,row:o}){return this.getSubViewports(e).some((e=>e.isVisible(t,o)))}getEdgeScrollCol(e,t,o){let i=!1,n=0,r=0;const{xSplit:s}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(i=!0,r=Vt(e-a),n=1):e<l&&o>=l&&c>0?(i=!0,r=Vt(l-e),n=-1):s&&t<l&&e>l&&(i=!0,r=Vt(e),n="reset"),{canEdgeScroll:i,direction:n,delay:r}}getEdgeScrollRow(e,t,o){let i=!1,n=0,r=0;const{ySplit:s}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(i=!0,r=Vt(e-a),n=1):e<l&&o>=l&&c>0?(i=!0,r=Vt(l-e),n=-1):s&&t<l&&e>l&&(i=!0,r=Vt(e),n="reset"),{canEdgeScroll:i,direction:n,delay:r}}getVisibleRect(e){const t=this.getters.getActiveSheetId(),o=this.getSubViewports(t).map((t=>t.getRect(e))).filter(Je);if(0===o.length)return{x:0,y:0,width:0,height:0};const i=Math.min(...o.map((e=>e.x))),n=Math.min(...o.map((e=>e.y))),r=Math.max(...o.map((e=>e.x+e.width)))-i,s=Math.max(...o.map((e=>e.y+e.height)))-n;return{x:i+this.gridOffsetX,y:n+this.gridOffsetY,width:r,height:s}}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,o).start}}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(Je)}checkPositiveDimension(e){return e.width<0||e.height<0?68:0}checkValuesAreDifferent(e){const{height:t,width:o}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===o&&e.height===t?76:0}checkScrollingDirection({offsetX:e,offsetY:t}){const o=this.getMainInternalViewport(this.getters.getActiveSheetId());return!o.canScrollHorizontally&&e>0||!o.canScrollVertically&&t>0?69:0}getMainViewport(e){const t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){const e=this.getters.getSheetIds();for(let t of Object.keys(this.viewports))e.includes(t)||delete this.viewports[t]}resetSheetViews(){for(let e of Object.keys(this.viewports)){const t=this.getters.getSheetPosition(e);this.resetViewports(e);const o=this.getSubViewports(e);Object.values(o).forEach((e=>{e.adjustPosition(t)}))}}resizeSheetView(e,t,o=0,i=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=o,this.gridOffsetY=i,this.recomputeViewports()}recomputeViewports(){for(let e of Object.keys(this.viewports))this.resetViewports(e)}setSheetViewOffset(e,t){const o=this.getters.getActiveSheetId(),{maxOffsetX:i,maxOffsetY:n}=this.getMaximumSheetOffset();Object.values(this.getSubViewports(o)).forEach((o=>o.setViewportOffset(Fe(e,0,i),Fe(t,0,n))))}clipOffsetY(e){const{height:t}=this.getMainViewportRect(),o=t-this.sheetViewHeight;return e=Math.min(e,o),e=Math.max(e,0)}getViewportOffset(e){var t,o;return{x:(null===(t=this.viewports[e])||void 0===t?void 0:t.bottomRight.offsetScrollbarX)||0,y:(null===(o=this.viewports[e])||void 0===o?void 0:o.bottomRight.offsetScrollbarY)||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e),i=this.getters.getNumberCols(e),n=this.getters.getNumberRows(e),r=this.getters.getColRowOffset("COL",0,t,e),s=this.getters.getColRowOffset("ROW",0,o,e),{xRatio:a,yRatio:l}=this.getFrozenSheetViewRatio(e),c=a<1,h=l<1,d=this.getViewportOffset(e),u={topLeft:o&&t&&new Dv(this.getters,e,{left:0,right:t-1,top:0,bottom:o-1},{width:r,height:s},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:o&&new Dv(this.getters,e,{left:t,right:i-1,top:0,bottom:o-1},{width:this.sheetViewWidth-r,height:s},{canScrollHorizontally:c,canScrollVertically:!1},{x:c?d.x:0,y:0})||void 0,bottomLeft:t&&new Dv(this.getters,e,{left:0,right:t-1,top:o,bottom:n-1},{width:r,height:this.sheetViewHeight-s},{canScrollHorizontally:!1,canScrollVertically:h},{x:0,y:h?d.y:0})||void 0,bottomRight:new Dv(this.getters,e,{left:t,right:i-1,top:o,bottom:n-1},{width:this.sheetViewWidth-r,height:this.sheetViewHeight-s},{canScrollHorizontally:c,canScrollVertically:h},{x:c?d.x:0,y:h?d.y:0})};this.viewports[e]=u}refreshViewport(e,t){Object.values(this.getSubViewports(e)).forEach((e=>{e.adjustViewportZone(),e.adjustPosition(t)}))}shiftVertically(e){const{top:t}=this.getActiveMainViewport(),{scrollX:o}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(o,e);const{anchor:i}=this.getters.getSelection(),n=this.getActiveMainViewport().top-t;this.selection.selectCell(i.cell.col,i.cell.row+n)}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],o=this.getters.getFigures(e),{scrollX:i,scrollY:n}=this.getActiveSheetScrollInfo(),{x:r,y:s}=this.getters.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const e of o)e.x>=r&&(e.x+e.width<=r+i||e.x>=a+i+r)||e.y>=s&&(e.y+e.height<=s+n||e.y>=l+n+s)||t.push(e);return t}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e),i=this.getters.getColDimensions(e,t).start,n=this.getters.getRowDimensions(e,o).start;return{xRatio:i/(this.sheetViewWidth+this.gridOffsetX),yRatio:n/(this.sheetViewHeight+this.gridOffsetY)}}}kv.getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getActiveSheetDOMScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio"];class $v{constructor(e,t,o){this.index=0,this.cells=e,this.getters=t,this.direction=o}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:o,tooltip:i}=Og.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:o,tooltip:i,origin:{col:e.data.col,row:e.data.row}}}}class Pv extends qu{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:Fe(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:Fe(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?0:45;case"AUTOFILL_AUTO":const o=this.getters.getSelectedZone();return o.top===o.bottom?0:1}return 0}handle(e){switch(e.type){case"AUTOFILL":this.autofill(!0);break;case"AUTOFILL_SELECT":this.select(e.col,e.row);break;case"AUTOFILL_AUTO":this.autofillAuto();break;case"AUTOFILL_CELL":this.autoFillMerge(e.originCol,e.originRow,e.col,e.row);const t=this.getters.getActiveSheetId();this.dispatch("UPDATE_CELL",{sheetId:t,col:e.col,row:e.row,style:e.style||null,content:e.content||"",format:e.format||""}),this.dispatch("SET_BORDER",{sheetId:t,col:e.col,row:e.row,border:e.border})}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),o=this.autofillZone;switch(this.direction){case"down":for(let i=t.left;i<=t.right;i++){const n=[];for(let e=t.top;e<=t.bottom;e++)n.push($t(i,e));const r=this.createGenerator(n);for(let t=o.top;t<=o.bottom;t++)this.computeNewCell(r,i,t,e)}break;case"up":for(let i=t.left;i<=t.right;i++){const n=[];for(let e=t.bottom;e>=t.top;e--)n.push($t(i,e));const r=this.createGenerator(n);for(let t=o.bottom;t>=o.top;t--)this.computeNewCell(r,i,t,e)}break;case"left":for(let i=t.top;i<=t.bottom;i++){const n=[];for(let e=t.right;e>=t.left;e--)n.push($t(e,i));const r=this.createGenerator(n);for(let t=o.right;t>=o.left;t--)this.computeNewCell(r,t,i,e)}break;case"right":for(let i=t.top;i<=t.bottom;i++){const n=[];for(let e=t.left;e<=t.right;e++)n.push($t(e,i));const r=this.createGenerator(n);for(let t=o.left;t<=o.right;t++)this.computeNewCell(r,t,i,e)}}e&&(this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0)}select(e,t){const o=this.getters.getSelectedZone();if(zo(e,t,o))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,o.top-1,o.left,o.right),this.steps=o.top-t;break;case"down":this.saveZone(o.bottom+1,t,o.left,o.right),this.steps=t-o.bottom;break;case"left":this.saveZone(o.top,o.bottom,e,o.left-1),this.steps=o.left-e;break;case"right":this.saveZone(o.top,o.bottom,o.right+1,e),this.steps=e-o.right}this.autofill(!1)}}autofillAuto(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let o=e.left,i=e.bottom;if(o>0){let e=this.getters.getEvaluatedCell({sheetId:t,col:o-1,row:i});for(;e.type!==fi.empty;)i+=1,e=this.getters.getEvaluatedCell({sheetId:t,col:o-1,row:i})}if(i===e.bottom&&(o=e.right,o<=this.getters.getNumberCols(t))){let e=this.getters.getEvaluatedCell({sheetId:t,col:o+1,row:i});for(;e.type!==fi.empty;)i+=1,e=this.getters.getEvaluatedCell({sheetId:t,col:o+1,row:i})}i!==e.bottom&&(this.select(e.left,i-1),this.autofill(!0))}computeNewCell(e,t,o,i){const{cellData:n,tooltip:r,origin:s}=e.next(),{content:a,style:l,border:c,format:h}=n;this.tooltip=r,i&&this.dispatch("AUTOFILL_CELL",{originCol:s.col,originRow:s.row,col:t,row:o,content:a,style:l,border:c,format:h})}getRule(e,t){const o=Mg.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((o=>o.condition(e,t)));return o&&o.generateRule(e,t)}createGenerator(e){const t=[],o=[],i=this.getters.getActiveSheetId();for(let t of e){const{col:e,row:n}=kt(t),r=this.getters.getCell({sheetId:i,col:e,row:n});o.push({col:e,row:n,cell:r,sheetId:i})}const n=o.map((e=>e.cell));for(let e of o){let o={type:"COPY_MODIFIER"};if(e&&e.cell){o=this.getRule(e.cell,n)||o}const i=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:i},rule:o})}return new $v(t,this.getters,this.direction)}saveZone(e,t,o,i){this.autofillZone={top:e,bottom:t,left:o,right:i}}getDirection(e,t){const o=this.getters.getSelectedZone(),i={up:{number:o.top-t,value:"up"},down:{number:t-o.bottom,value:"down"},left:{number:o.left-e,value:"left"},right:{number:e-o.right,value:"right"}};if(1===Object.values(i).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(i).find((e=>e.number>0?1:0)).value;const n=i.up.number>0?"up":"down",r=i.left.number>0?"left":"right";return Math.abs(i[n].number)>=Math.abs(i[r].number)?i[n].value:i[r].value}autoFillMerge(e,t,o,i){const n=this.getters.getActiveSheetId(),r={sheetId:n,col:o,row:i},s={sheetId:n,col:e,row:t};if(this.getters.isInMerge(r)&&!this.getters.isInMerge(s)){const e=this.getters.getMerge(r);e&&this.dispatch("REMOVE_MERGE",{sheetId:n,target:[e]})}const a=this.getters.getMerge(s);(null==a?void 0:a.topLeft.col)===e&&(null==a?void 0:a.topLeft.row)===t&&this.dispatch("ADD_MERGE",{sheetId:n,target:[{top:i,bottom:i+a.bottom-a.top,left:o,right:o+a.right-a.left}]})}drawGrid(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:o}=e,{x:i,y:n,width:r,height:s}=this.getters.getVisibleRect(this.autofillZone);r>0&&s>0&&(t.strokeStyle="black",t.lineWidth=o,t.setLineDash([3]),t.strokeRect(i,n,r,s),t.setLineDash([]))}}Pv.layers=[5],Pv.getters=["getAutofillTooltip"];class Lv extends qu{handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:o}=this.getters.getSelection();for(const i of t){const t=this.getAutomaticSums(e,i,o.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,o){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,o):this.sumData(e,t)}sumData(e,t){const o=this.dimensionsToSum(e,t),i=this.sumDimensions(e,t,o).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return o.has("ROW")&&o.has("COL")&&i.push(this.sumTotal(t)),i}sumAdjacentData(e,t,o){const{col:i,row:n}=zo(o.col,o.row,t)?o:{col:t.left,row:t.top},r=this.findAdjacentData(e,i,n);return r?this.getters.isSingleCellOrMerge(e,t)||qo(Po(r,t))?[{position:{col:i,row:n},zone:r}]:this.sumDimensions(e,Po(r,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,o){const i=this.getters.getSheet(e),n=this.getters.getMainCellPosition({sheetId:e,col:t,row:o}),r=this.findSuitableZoneToSum(i,n.col,n.row);if(r)return this.getters.expandZone(e,r)}findSuitableZoneToSum(e,t,o){const i=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:o-1}),n=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:o});if(this.isNumber(n)&&!this.isNumber(i))return this.findHorizontalZone(e,t,o);const r=this.findVerticalZone(e,t,o);if(this.isZoneValid(r))return r;const s=this.findHorizontalZone(e,t,o);return this.isZoneValid(s)?s:void 0}findVerticalZone(e,t,o){const i={top:0,bottom:o-1,left:t,right:t},n=this.reduceZoneStart(e,i,i.bottom);return{...i,top:n}}findHorizontalZone(e,t,o){const i={top:o,bottom:o,left:0,right:t-1},n=this.reduceZoneStart(e,i,i.right);return{...i,left:n}}reduceZoneStart(e,t,o){const i=this.getters.getEvaluatedCellsInZone(e.id,t),n=Ue(o,-1,-1),r=n.filter((e=>i[e]&&!i[e].isAutoSummable)),s=Math.max(...r),a=Ve(n.filter((e=>this.isNumber(i[e]))))[0]||[];return Math.max(...a)<s?1/0:Math.min(...a)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){var t;return e.type===fi.number&&!(null===(t=e.format)||void 0===t?void 0:t.match(j))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){const o=new Set;return qo(t)?(o.add(1===Go(t).width?"COL":"ROW"),o):(this.lastColIsEmpty(e,t)&&o.add("ROW"),this.lastRowIsEmpty(e,t)&&o.add("COL"),0===o.size&&o.add("COL"),o)}sumDimensions(e,t,o){return[...o.has("COL")?this.sumColumns(t,e):[],...o.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:o}=e;return{position:{col:o,row:t},zone:{...e,top:t,right:o-1}}}sumColumns(e,t){const o=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,o.bottom-1)},Zo(o).map((t=>({position:t,zone:{...e,right:t.col,left:t.col}})))}sumRows(e,t){const o=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,o.right-1)},Zo(o).map((t=>({position:t,zone:{...e,top:t.row,bottom:t.row}})))}dispatchCellUpdates(e,t){for(const o of t){const{col:t,row:i}=o.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,content:`=SUM(${this.getters.zoneToXC(e,o.zone)})`})}}nextEmptyRow(e,t){let o=t.bottom+1;const{left:i,right:n}=t;for(;!this.getters.isEmpty(e,{bottom:o,top:o,left:i,right:n});)o++;return{...t,top:o,bottom:o}}nextEmptyCol(e,t){let o=t.right+1;const{top:i,bottom:n}=t;for(;!this.getters.isEmpty(e,{left:o,right:o,top:i,bottom:n});)o++;return{...t,left:o,right:o}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}Lv.getters=["getAutomaticSums"];class Uv extends qu{allowDispatch(e){if("OPEN_CELL_POPOVER"===e.type){try{Bg.get(e.popoverType)}catch(e){return 72}return 0}return 0}handle(e){switch(e.type){case"ACTIVATE_SHEET":case"CLOSE_CELL_POPOVER":this.persistentPopover=void 0;break;case"OPEN_CELL_POPOVER":this.persistentPopover={col:e.col,row:e.row,sheetId:this.getters.getActiveSheetId(),type:e.popoverType}}}getCellPopover({col:e,row:t}){var o,i;const n=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){const e=this.getters.getMainCellPosition(this.persistentPopover),t=null===(i=(o=Bg.get(this.persistentPopover.type)).onOpen)||void 0===i?void 0:i.call(o,e,this.getters);return(null==t?void 0:t.isOpen)?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}if(void 0===e||void 0===t||!this.getters.isVisibleInViewport({sheetId:n,col:e,row:t}))return{isOpen:!1};const r=this.getters.getMainCellPosition({sheetId:n,col:e,row:t}),s=Bg.getAll().map((e=>{var t;return null===(t=e.onHover)||void 0===t?void 0:t.call(e,r,this.getters)})).find((e=>null==e?void 0:e.isOpen));return(null==s?void 0:s.isOpen)?{...s,anchorRect:this.computePopoverAnchorRect(r)}:{isOpen:!1}}hasOpenedPopover(){return void 0!==this.persistentPopover}getPersistentPopoverTypeAtPosition({col:e,row:t}){if(this.persistentPopover&&this.persistentPopover.col===e&&this.persistentPopover.row===t)return this.persistentPopover.type}computePopoverAnchorRect({col:e,row:t}){const o=this.getters.getActiveSheetId(),i=this.getters.getMerge({sheetId:o,col:e,row:t});return i?this.getters.getVisibleRect(i):this.getters.getVisibleRect(Ko({col:e,row:t}))}}Uv.getters=["getCellPopover","getPersistentPopoverTypeAtPosition","hasOpenedPopover"];var Vv;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(Vv||(Vv={}));class zv extends qu{constructor(){super(...arguments),this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1},this.toSearch=""}handle(e){switch(e.type){case"UPDATE_SEARCH":this.updateSearch(e.toSearch,e.searchOptions);break;case"CLEAR_SEARCH":case"UNDO":case"REDO":case"REMOVE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":this.clearSearch();break;case"SELECT_SEARCH_PREVIOUS_MATCH":this.selectNextCell(Vv.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(Vv.next);break;case"REPLACE_SEARCH":this.replace(e.replaceWith);break;case"REPLACE_ALL_SEARCH":this.replaceAll(e.replaceWith);break;case"ACTIVATE_SHEET":case"REFRESH_SEARCH":this.refreshSearch()}}getSearchMatches(){return this.searchMatches}getCurrentSelectedMatchIndex(){return this.selectedMatchIndex}updateSearch(e,t){this.searchOptions=t,e!==this.toSearch&&(this.selectedMatchIndex=null),this.toSearch=e,this.updateRegex(),this.refreshSearch()}refreshSearch(){const e=this.findMatches();this.searchMatches=e,this.selectNextCell(Vv.current)}updateRegex(){let e=Oe(this.toSearch);const t=this.searchOptions.matchCase?"":"i";this.searchOptions.exactMatch&&(e=`^${e}$`),this.currentSearchRegex=RegExp(e,t)}findMatches(){const e=this.getters.getActiveSheetId(),t=this.getters.getCells(e),o=[];if(this.toSearch)for(const i of Object.values(t)){const{col:t,row:n}=this.getters.getCellPosition(i.id);if(i&&this.currentSearchRegex&&this.currentSearchRegex.test(this.getSearchableString({sheetId:e,col:t,row:n}))){const e={col:t,row:n,selected:!1};o.push(e)}}return o.sort(this.sortByRowThenColumn)}sortByRowThenColumn(e,t){return e.row===t.row?e.col-t.col:e.row>t.row?1:-1}selectNextCell(e){const t=this.searchMatches;if(!t.length)return void(this.selectedMatchIndex=null);let o;o=null===this.selectedMatchIndex?0:this.selectedMatchIndex+e,o=(o%t.length+t.length)%t.length,this.selectedMatchIndex=o,this.selection.selectCell(t[o].col,t[o].row);for(let e=0;e<this.searchMatches.length;e++)this.searchMatches[e].selected=e===this.selectedMatchIndex}clearSearch(){this.toSearch="",this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1}}replace(e){if(null===this.selectedMatchIndex||!this.currentSearchRegex)return;const t=this.searchMatches[this.selectedMatchIndex],o=this.getters.getActiveSheetId(),i=this.getters.getCell({sheetId:o,...t});if((null==i?void 0:i.isFormula)&&!this.searchOptions.searchFormulas)this.selectNextCell(Vv.next);else{const i=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),n=this.getSearchableString({sheetId:o,col:t.col,row:t.row}).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(Vv.current)}}replaceAll(e){const t=this.searchMatches.length;for(let o=0;o<t;o++)this.replace(e)}getSearchableString(e){const t=this.getters.getCell(e);return this.searchOptions.searchFormulas&&(null==t?void 0:t.isFormula)?t.content:this.getters.getEvaluatedCell(e).formattedValue}drawGrid(e){const{ctx:t}=e,o=this.getters.getActiveSheetId();for(const e of this.searchMatches){const i=this.getters.getMerge({sheetId:o,col:e.col,row:e.row}),n=i?i.left:e.col,r=i?i.right:e.col,s=i?i.top:e.row,a=i?i.bottom:e.row,{x:l,y:c,width:h,height:d}=this.getters.getVisibleRect({top:s,left:n,right:r,bottom:a});h>0&&d>0&&(t.fillStyle="#8B008B33",t.fillRect(l,c,h,d),e.selected&&(t.strokeStyle="#8B008B",t.strokeRect(l,c,h,d)))}}}zv.layers=[3],zv.getters=["getSearchMatches","getCurrentSelectedMatchIndex"];class Bv extends qu{isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,o){return"COL"===t?this.isColHidden(e,o):this.isRowHidden(e,o)}getNextVisibleCellPosition({sheetId:e,col:t,row:o}){return{sheetId:e,col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",o,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,o,i){if(o<=i)for(let n=o;n<=i;n++)if(this.getters.doesHeaderExist(e,t,n)&&!this.isHeaderHidden(e,t,n))return n;if(o>i)for(let n=o;n>=i;n--)if(this.getters.doesHeaderExist(e,t,n)&&!this.isHeaderHidden(e,t,n))return n}findLastVisibleColRowIndex(e,t,{last:o,first:i}){return Ue(o,i,-1).find((o=>!this.isHeaderHidden(e,t,o)))||i}findFirstVisibleColRowIndex(e,t){const o=this.getters.getNumberHeaders(e,t);for(let i=0;i<o;i++){if("COL"===t&&!this.isColHidden(e,i))return i;if("ROW"===t&&!this.isRowHidden(e,i))return i}}exportForExcel(e){for(const t of e.sheets)for(const[e,o]of Object.entries(t.rows)){const i=this.isRowHidden(t.id,Number(e));o.isHidden=i}}}Bv.getters=["getNextVisibleCellPosition","findVisibleHeader","findLastVisibleColRowIndex","findFirstVisibleColRowIndex","isRowHidden","isColHidden","isHeaderHidden"];class Hv extends qu{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:o}=Go(e.zone),i=t*o==1?this.getters.expandZone(e.sheetId,e.zone):e.zone;return{...e,zone:i}}))}drawGrid(e){const{ctx:t,thinLineWidth:o}=e,i=this.getters.getActiveSheetId(),n=3*o;t.lineWidth=n;const r=this.getHighlights();for(let e of r.filter(((e,t)=>r.findIndex((t=>Uo(t.zone,e.zone)&&t.sheetId===i))===t))){const{x:o,y:i,width:r,height:s}=this.getters.getVisibleRect(e.zone);r>0&&s>0&&(t.strokeStyle=e.color,t.strokeRect(o+n/2,i+n/2,r-n,s-n),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(o+n,i+n,r-2*n,s-2*n))}}}Hv.layers=[1],Hv.getters=["getHighlights"];class Wv extends qu{constructor(){super(...arguments),this.boxes=[]}getColDimensionsInViewport(e,t){const o=Math.min(...this.getters.getSheetViewVisibleCols()),i=this.getters.getColRowOffsetInViewport("COL",o,t),n=this.getters.getColSize(e,t);return{start:i,size:n,end:i+(this.getters.isColHidden(e,t)?0:n)}}getRowDimensionsInViewport(e,t){const o=Math.min(...this.getters.getSheetViewVisibleRows()),i=this.getters.getColRowOffsetInViewport("ROW",o,t),n=this.getters.getRowSize(e,t);return{start:i,size:n,end:i+(this.getters.isRowHidden(e,t)?0:n)}}getHeaderOffset(e,t,o){let i=this.getters.getColRowOffsetInViewport(e,t,o);return this.getters.isDashboard()||(i+="ROW"===e?O:M),i}drawGrid(e,t){switch(t){case 0:this.boxes=this.getGridBoxes(),this.drawBackground(e),this.drawOverflowingCellBackground(e),this.drawCellBackground(e),this.drawBorders(e),this.drawTexts(e),this.drawIcon(e),this.drawFrozenPanes(e);break;case 7:this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e))}}drawBackground(e){const{ctx:t,thinLineWidth:o}=e,{width:i,height:n}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle="#ffffff",t.fillRect(0,0,i+m,n+m);const r=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),s=r?.1*o:0;if(r)for(const e of this.boxes)t.strokeStyle="#E2E3E3",t.lineWidth=o,t.strokeRect(e.x+s,e.y+s,e.width-2*s,e.height-2*s)}drawCellBackground(e){const{ctx:t}=e;for(const e of this.boxes){let o=e.style;o.fillColor&&"#ffffff"!==o.fillColor&&(t.fillStyle=o.fillColor||"#ffffff",t.fillRect(e.x,e.y,e.width,e.height)),e.error&&(t.fillStyle="red",t.beginPath(),t.moveTo(e.x+e.width-5,e.y),t.lineTo(e.x+e.width,e.y),t.lineTo(e.x+e.width,e.y+5),t.fill())}}drawOverflowingCellBackground(e){var t,o;const{ctx:i,thinLineWidth:n}=e;for(const e of this.boxes)if(e.content&&e.isOverflow){const r=e.content.align||"left";let s,a;const l=e.y+n/2,c=e.height-n,h=Math.min((null===(t=e.clipRect)||void 0===t?void 0:t.width)||1/0,e.content.width);"left"===r?(s=e.x+n/2,a=h-2*n):"right"===r?(s=e.x+e.width-n/2,a=2*n-h):(s=((null===(o=e.clipRect)||void 0===o?void 0:o.x)||e.x+e.width/2-e.content.width/2)+n/2,a=h-2*n),i.fillStyle="#ffffff",i.fillRect(s,l,a,c)}}drawBorders(e){const{ctx:t,thinLineWidth:o}=e;for(let e of this.boxes){const t=e.border;if(t){const{x:o,y:n,width:r,height:s}=e;t.left&&i(t.left,o,n,o,n+s),t.top&&i(t.top,o,n,o+r,n),t.right&&i(t.right,o+r,n,o+r,n+s),t.bottom&&i(t.bottom,o,n+s,o+r,n+s)}}function i([e,i],n,r,s,a){t.strokeStyle=i,t.lineWidth=("thin"===e?2:3)*o,t.beginPath(),t.moveTo(n,r),t.lineTo(s,a),t.stroke()}}drawTexts(e){const{ctx:t,thinLineWidth:o}=e;let i;t.textBaseline="top";for(let e of this.boxes)if(e.content){const n=e.style||{},r=e.content.align||"left",s=Pe(n);s!==i&&(i=s,t.font=s),t.fillStyle=n.textColor||"#000";let a=e.x;if(a+="left"===r?P+(e.image?e.image.size+$:0):"right"===r?e.width-P-(e.isFilterHeader?20:0):e.width/2,t.textAlign=r,e.clipRect){t.save(),t.beginPath();const{x:o,y:i,width:n,height:r}=e.clipRect;t.rect(o,i,n,r),t.clip()}const l=Le(n),c=e.content.textLines.length;let h=this.computeTextYCoordinate(e,l,c);for(let i of e.content.textLines){if(t.fillText(i,Math.round(a),Math.round(h)),n.strikethrough||n.underline){const e=ke(t,i,n);let s=a;"right"===r?s-=e:"center"===r&&(s-=e/2),n.strikethrough&&t.fillRect(s,h+l/2,e,2.6*o),n.underline&&t.fillRect(s,h+l+1,e,1.3*o)}h+=P+l}e.clipRect&&t.restore()}}drawIcon(e){const{ctx:t}=e;for(const e of this.boxes)if(e.image){const o=e.image.image;if(e.image.clipIcon){t.save(),t.beginPath();const{x:o,y:i,width:n,height:r}=e.image.clipIcon;t.rect(o,i,n,r),t.clip()}const i=e.image.size,n=this.computeTextYCoordinate(e,i);t.drawImage(o,e.x+$,n,i,i),e.image.clipIcon&&t.restore()}}computeTextYCoordinate(e,t,o=1){const i=e.y+1,n=De(t,o),r=e.height>n+2*P,s=e.verticalAlign||"middle";if(r){if("middle"===s)return i+(e.height-n)/2;if("bottom"===s)return i+e.height-n-P}return i+P}drawHeaders(e){const{ctx:t,thinLineWidth:o}=e,i=this.getters.getSheetViewVisibleCols(),n=i[0],r=i[i.length-1],s=this.getters.getSheetViewVisibleRows(),a=s[0],l=s[s.length-1],{width:c,height:h}=this.getters.getSheetViewDimensionWithHeaders(),d=this.getters.getSelectedZones(),u=function(e){const t=new Set;for(let o of e)for(let e of Ue(o.left,o.right+1))t.add(e);return t}(d),g=function(e){const t=new Set;for(let o of e)for(let e of Ue(o.top,o.bottom+1))t.add(e);return t}(d),p=this.getters.getActiveSheetId(),m=this.getters.getNumberCols(p),f=this.getters.getNumberRows(p),E=this.getters.getActiveCols(),w=this.getters.getActiveRows();t.font=`400 11px ${G}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=o,t.strokeStyle="#333";for(let e=n;e<=r;e++){const o={left:e,right:e,top:0,bottom:f-1},{x:i,width:n}=this.getters.getVisibleRect(o),r=this.getters.doesZonesContainFilter(p,[o]),s=E.has(e),a=u.has(e);t.fillStyle=s?r?I:C:a?r?T:b:r?R:v,t.fillRect(i,0,n,O)}for(let e=a;e<=l;e++){const o={top:e,bottom:e,left:0,right:m-1},{y:i,height:n}=this.getters.getVisibleRect(o),r=this.getters.doesZonesContainFilter(p,[o]),s=w.has(e),a=g.has(e);t.fillStyle=s?r?I:C:a?r?T:b:r?R:v,t.fillRect(0,i,M,n)}t.beginPath(),t.moveTo(M,0),t.lineTo(M,h),t.moveTo(0,O),t.lineTo(c,O),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(const e of i){const o=this.getters.getColSize(p,e),i=Ft(e);t.fillStyle=E.has(e)?"#fff":S;let r=this.getHeaderOffset("COL",n,e);t.fillText(i,r+o/2,13),t.moveTo(r+o,0),t.lineTo(r+o,O)}for(const e of s){const o=this.getters.getRowSize(p,e);t.fillStyle=w.has(e)?"#fff":S;let i=this.getHeaderOffset("ROW",a,e);t.fillText(String(e+1),24,i+o/2),t.moveTo(0,i+o),t.lineTo(M,i+o)}t.stroke()}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:o}=e,{x:i,y:n}=this.getters.getMainViewportCoordinates(),r=this.getters.isDashboard()?0:M,s=this.getters.isDashboard()?0:O;t.lineWidth=6*o,t.strokeStyle="#BCBCBC",t.beginPath(),i&&(t.moveTo(r+i,0),t.lineTo(r+i,s)),n&&(t.moveTo(0,s+n),t.lineTo(r,s+n)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:o}=e,{x:i,y:n}=this.getters.getMainViewportCoordinates(),r=this.getters.getSheetViewVisibleCols(),s=r[0],a=r[r.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:s,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*o,t.strokeStyle="#DADFE8",t.beginPath(),i&&(t.moveTo(d+i,u),t.lineTo(d+i,h.height+u)),n&&(t.moveTo(d,u+n),t.lineTo(h.width+d,u+n)),t.stroke()}findNextEmptyCol(e,t,o){const i=this.getters.getActiveSheetId();let n=e;for(;n<t;){const e={sheetId:i,col:n+1,row:o},t=this.getters.getEvaluatedCell(e),r=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==fi.empty||this.getters.isInMerge(e)||(null==r?void 0:r.left))return n;n++}return n}findPreviousEmptyCol(e,t,o){const i=this.getters.getActiveSheetId();let n=e;for(;n>t;){const e={sheetId:i,col:n-1,row:o},t=this.getters.getEvaluatedCell(e),r=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==fi.empty||this.getters.isInMerge(e)||(null==r?void 0:r.right))return n;n--}return n}computeCellAlignment(e,t){const o=this.getters.getCell(e);if((null==o?void 0:o.isFormula)&&this.getters.shouldShowFormulas())return"left";const{align:i}=this.getters.getCellStyle(e),n=this.getters.getEvaluatedCell(e);return t&&n.type===fi.number?"center"!==i?"left":i:i||n.defaultAlign}createZoneBox(e,t,o){const{left:i,right:n}=o,r=t.left,s=t.top,a={sheetId:e,col:r,row:s},c=this.getters.getEvaluatedCell(a),h=this.getters.shouldShowFormulas(),{x:d,y:u,width:g,height:p}=this.getters.getVisibleRect(t),{verticalAlign:m}=this.getters.getCellStyle(a),f={x:d,y:u,width:g,height:p,border:this.getters.getCellBorderWithFilterBorder(a)||void 0,style:this.getters.getCellComputedStyle(a),verticalAlign:m};if(c.type===fi.empty)return f;const v=this.getters.getConditionalIcon(a),b=Le(f.style),C=v?$+b:0;v&&(f.image={type:"icon",size:b,clipIcon:{x:f.x,y:f.y,width:Math.min(C,g),height:p},image:bp[v].img}),f.isFilterHeader=this.getters.isFilterHeader(a);const S=f.isFilterHeader?19:0,E=this.getters.getCellText(a,h),w=this.getters.getTextWidth(a)+P,y=this.getters.getCellStyle(a).wrapping||"overflow",x="wrap"===y?this.getters.getCellMultiLineText(a,g-2*P):[E],I=C+w+S,R=this.computeCellAlignment(a,I>g);f.content={textLines:x,width:"overflow"===y?w:g,align:R},c.type===fi.error&&c.error.logLevel>l.silent&&(f.error=c.error.message);const T=I>g||b>p;if(v||f.isFilterHeader)f.clipRect={x:f.x+C,y:f.y,width:Math.max(0,g-C-S),height:p};else if(T&&"overflow"===y){let e,o;switch(this.getters.isInMerge(a)?(e=this.getters.getMerge(a).right,o=r):(e=this.findNextEmptyCol(r,n,s),o=this.findPreviousEmptyCol(r,i,s),f.isOverflow=!0),R){case"left":{const o=Ko({col:e,row:s}),{x:i,y:n,width:r,height:a}=this.getters.getVisibleRect(Po(t,o));(r<I||b>a)&&(f.clipRect={x:i,y:n,width:r,height:a});break}case"right":{const e=Ko({col:o,row:s}),{x:i,y:n,width:r,height:a}=this.getters.getVisibleRect(Po(t,e));(r<I||b>a)&&(f.clipRect={x:i,y:n,width:r,height:a});break}case"center":{const i={...t,left:o,right:e},{x:n,y:r,height:s,width:a}=this.getters.getVisibleRect(i),l=I/2,c=f.x+f.width/2;if(n+a<c+l||n>c-l||b>s){const e=n>c-l?n:c-l,t=n+a-e;f.clipRect={x:e,y:r,width:t,height:s}}break}}}else"clip"!==y&&"wrap"!==y||(f.clipRect={x:f.x,y:f.y,width:g,height:p});return f}getGridBoxes(){const e=[],t=this.getters.getSheetViewVisibleCols(),o=t[0],i=t[t.length-1],n=this.getters.getSheetViewVisibleRows(),r={left:o,right:i,top:n[0],bottom:n[n.length-1]},s=this.getters.getActiveSheetId();for(const o of n)for(const i of t){const t={sheetId:s,col:i,row:o};this.getters.isInMerge(t)||e.push(this.createZoneBox(s,Ko(t),r))}for(const t of this.getters.getMerges(s))if(!this.getters.isMergeHidden(s,t)&&Vo(t,r)){const o=this.createZoneBox(s,t,r),i=this.getters.getCellBorder({sheetId:s,col:t.right,row:t.bottom});o.border={...o.border,bottom:i?i.bottom:void 0,right:i?i.right:void 0},o.isMerge=!0,e.push(o)}return e}}Wv.layers=[0,7],Wv.getters=["getColDimensionsInViewport","getRowDimensionsInViewport"];class Gv extends qu{constructor(e,t,o){if(o&&t.length>1)throw new Error("Input with a single range cannot be instantiated with several range references.");super(e),this.inputHasSingleRange=o,this.ranges=[],this.focusedRangeIndex=null,this.willAddNewRange=!1,this.insertNewRange(0,t),this.activeSheet=this.getters.getActiveSheetId(),0===this.ranges.length&&(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}allowDispatch(e){switch(e.type){case"ADD_EMPTY_RANGE":if(this.inputHasSingleRange&&1===this.ranges.length)return 30;break;case"CHANGE_RANGE":if(this.inputHasSingleRange&&e.value.split(",").length>1)return 30}return 0}handleEvent(e){const t=_o(e.anchor.zone),o=this.activeSheet,i=this.getters.getActiveSheetId(),n=this.getters.getSheetName(i);this.add([i===o?t:`${_e(n)}!${t}`])}handle(e){switch(e.type){case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"FOCUS_RANGE":this.focus(this.getIndex(e.rangeId));break;case"CHANGE_RANGE":{const t=this.getIndex(e.rangeId);if(null!==t&&this.focusedRangeIndex!==t&&this.focus(t),null!==t){const o=e.value.split(",").map((e=>e.trim()));this.setRange(t,o)}break}case"ADD_EMPTY_RANGE":this.insertNewRange(this.ranges.length,[""]),this.focusLast();break;case"REMOVE_RANGE":const t=this.getIndex(e.rangeId);null!==t&&this.removeRange(t);break;case"STOP_SELECTION_INPUT":this.willAddNewRange=!1;break;case"PREPARE_SELECTION_INPUT_EXPANSION":{const e=this.focusedRangeIndex;null===e||this.inputHasSingleRange||(this.willAddNewRange=""!==this.ranges[e].xc.trim());break}case"ACTIVATE_SHEET":if(e.sheetIdFrom!==e.sheetIdTo){const{col:t,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),i=this.getters.expandZone(e.sheetIdTo,Ko({col:t,row:o}));this.selection.resetAnchor(this,{cell:{col:t,row:o},zone:i})}}}unsubscribe(){this.unfocus()}getSelectionInputValue(){return this.cleanInputs(this.ranges.map((e=>e.xc?e.xc:"")))}getSelectionInputHighlights(){return this.ranges.map((e=>this.inputToHighlights(e))).flat()}focus(e){this.focusedRangeIndex=e}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null}add(e){null!==this.focusedRangeIndex&&0!==e.length&&(this.willAddNewRange?(this.insertNewRange(this.ranges.length,e),this.focusLast(),this.willAddNewRange=!1):this.setRange(this.focusedRangeIndex,e))}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){this.ranges.splice(e,0,...t.map(((e,t)=>({xc:e,id:(this.ranges.length+t+1).toString(),color:dt[(this.ranges.length+t)%dt.length]}))))}setRange(e,t){const[,...o]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,o),o.length&&this.focus(e+o.length)}removeRange(e){this.ranges.splice(e,1),null!==this.focusedRangeIndex&&this.focusLast()}inputToHighlights({xc:e,color:t}){const o=this.cleanInputs([e]).filter((e=>this.getters.isRangeValid(e))).filter((e=>this.shouldBeHighlighted(this.activeSheet,e)));return o.map((e=>{const{sheetName:o}=_t(e);return{zone:this.getters.getRangeFromSheetXC(this.activeSheet,e).zone,sheetId:o&&this.getters.getSheetIdByName(o)||this.activeSheet,color:t}}))}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:o}=_t(t),i=this.getters.getSheetIdByName(o),n=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(i===n||void 0===i&&n===e)}getIndex(e){const t=this.ranges.findIndex((t=>t.id===e));return t>=0?t:null}}Gv.layers=[1],Gv.getters=[];class qv extends qu{get currentInput(){return this.focusedInputId?this.inputs[this.focusedInputId]:null}constructor(e){super(e),this.config=e,this.inputs={},this.focusedInputId=null}allowDispatch(e){var t,o;if("FOCUS_RANGE"===e.type){const i=null===(t=this.currentInput)||void 0===t?void 0:t.getIndex(e.rangeId);if(this.focusedInputId===e.id&&(null===(o=this.currentInput)||void 0===o?void 0:o.focusedRangeIndex)===i)return 29}return this.currentInput?this.currentInput.allowDispatch(e):0}handle(e){var t;switch(e.type){case"ENABLE_NEW_SELECTION_INPUT":this.initInput(e.id,e.initialRanges||[],e.hasSingleRange);break;case"DISABLE_SELECTION_INPUT":this.focusedInputId===e.id&&this.unfocus(),delete this.inputs[e.id];break;case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"ADD_EMPTY_RANGE":case"REMOVE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id];this.selection.capture(t,{cell:{col:0,row:0},zone:Ko({col:0,row:0})},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}break;case"FOCUS_RANGE":case"CHANGE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id],o=t.ranges.find((t=>t.id===e.rangeId)),i=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(i,(null==o?void 0:o.xc)||"A1").zone;this.selection.capture(t,{cell:{col:n.left,row:n.top},zone:n},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}}null===(t=this.currentInput)||void 0===t||t.handle(e)}unsubscribe(){this.unfocus()}getSelectionInput(e){return this.inputs[e]?this.inputs[e].ranges.map(((t,o)=>Object.assign({},t,{color:this.focusedInputId===e&&null!==this.inputs[e].focusedRangeIndex&&this.isRangeValid(t.xc)?t.color:null,isFocused:this.focusedInputId===e&&this.inputs[e].focusedRangeIndex===o}))):[]}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:o}=_t(e);return null!==t.match(Tt)&&(!o||void 0!==this.getters.getSheetIdByName(o))}getSelectionInputValue(e){return this.inputs[e].getSelectionInputValue()}getSelectionInputHighlights(){return this.focusedInputId?this.inputs[this.focusedInputId].getSelectionInputHighlights():[]}initInput(e,t,o=!1){if(this.inputs[e]=new Gv(this.config,t,o),0===t.length){const t=this.inputs[e],o={zone:Ko({col:0,row:0}),cell:{col:0,row:0}};this.selection.capture(t,o,{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e}}unfocus(){this.selection.release(this.currentInput),this.focusedInputId=null}}qv.layers=[1],qv.getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];class Zv{constructor(){this.subscriptions={}}on(e,t,o){if(!o)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:o})}trigger(e,t){const o=this.subscriptions[e]||[];for(let e=0,i=o.length;e<i;e++){const i=o[e];i.callback.call(i.owner,t)}}off(e,t){const o=this.subscriptions[e];o&&(this.subscriptions[e]=o.filter((e=>e.owner!==t)))}clear(){this.subscriptions={}}}function jv(e,t){return{...e,definition:Yn(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 o=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));for(let t of e)o>t&&o--}if("ADD_COLUMNS_ROWS"===t.type){o=o>("before"===t.position?t.base-1:t.base)?o+t.quantity:o}return o>0?{...e,quantity:o}:void 0}Qg.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],jv),Qg.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],jv),Qg.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const o=t.sheetId;if(e.targetSheetId===o||e.sheetId===o)return;return e})),Qg.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),Qg.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){var o;if(e.name===t.name)return{...e,name:(null===(o=e.name)||void 0===o?void 0:o.match(/\d+/))?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),Qg.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE","CREATE_FILTER_TABLE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const o=[];for(const i of e.target)for(const e of t.target)Vo(i,e)||o.push({...i});if(o.length)return{...e,target:o};return})),Qg.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],Xv),Qg.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],Xv),Qg.addTransformation("CREATE_FILTER_TABLE",["CREATE_FILTER_TABLE","ADD_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;for(const o of e.target)for(const e of t.target)if(Vo(e,o))return;return e}));const Yv=[{match:function(e){return"sheetId"in e},fn:Jv},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const o=Jv(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;const i=[];for(const o of e.target){const e=mi(o,t);e&&i.push(e)}if(!i.length)return"IGNORE_COMMAND";return{...e,target:i}}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const o=Jv(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const o="COL"===t.dimension?"col":"row";let i=e[o];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(i))return"IGNORE_COMMAND";for(let t of e)i>=t&&i--}"ADD_COLUMNS_ROWS"===t.type&&(i>t.base||i===t.base&&"before"===t.position)&&(i+=t.quantity);return{...e,[o]:i}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const o of t.target){if(!(e.col===o.left&&e.row===o.top)&&zo(e.col,e.row,o))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e&&"sheetId"in e},fn:function(e,t){const o=Jv(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type){if(t.dimension!==e.dimension)return e;const o="ADD_COLUMNS_ROWS"===e.type,i=o?"base":"elements";let n=o?[e[i]]:e[i];if("REMOVE_COLUMNS_ROWS"===t.type&&(n=n.map((e=>{if(t.elements.includes(e))return;const o=t.elements.sort(((e,t)=>t-e));for(let t of o)e>t&&e--;return e})).filter(Je)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;n=n.map((o=>o>e?o+t.quantity:o))}if(n.length){let t=n;return o&&(t=n[0]),{...e,[i]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}},{match:function(e){return"ranges"in e},fn:function(e,t){const o=[],i="DELETE_SHEET"===t.type&&t.sheetId;for(const n of e.ranges)if(n._sheetId!==t.sheetId)o.push({...n,_zone:n._zone});else{const e=mi(n._zone,t);e&&i!==n._sheetId&&o.push({...n,_zone:e})}if(!o.length)return"IGNORE_COMMAND";return{...e,ranges:o}}}];function Kv(e,t){const o=Qg.getTransformation(e.type,t.type);return o?o(e,t):function(e,t){for(const{match:o,fn:i}of Yv)if(o(e)){const o=i(e,t);if("SKIP_TRANSFORMATION"===o)continue;if("IGNORE_COMMAND"===o)return;e=o}return e}(e,t)}function Qv(e,t){let o=[...e];for(const e of t)o=o.map((t=>Kv(t,e))).filter(Je);return o}function Jv(e,t){const o="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===o?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class eb{constructor(e,t,o,i){this._commands=[],this._changes=[],this.id=e,this.clientId=t,this._commands=[...o],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class tb extends Error{}class ob extends Zv{constructor(e,t,o=Y){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=o,this.clients={},this.clientId="local",this.pendingMessages=[],this.waitingAck=!1,this.waitingUndoRedoAck=!1,this.isReplayingInitialRevisions=!1,this.processedRevisions=new Set,this.uuidGenerator=new Ao,this.debouncedMove=function(e,t,o){let i;return function(){const n=this,r=arguments,s=o&&!i;clearTimeout(i),i=setTimeout((function(){i=null,o||e.apply(n,r)}),t),s&&e.apply(n,r)}}(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t){if(!e.length||!t.length||!this.canApplyOptimisticUpdate())return;const o=new eb(this.uuidGenerator.uuidv4(),this.clientId,e,t);this.revisions.append(o.id,o),this.trigger("new-local-state-update",{id:o.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:o.id,clientId:o.clientId,commands:o.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_UNDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_REDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:"local",name:"local"},this.clientId="local"),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this))}loadInitialMessages(e){this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1}leave(){delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}snapshot(e){const t=this.uuidGenerator.uuidv4();this.transportService.sendMessage({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){const e=this.clients[this.clientId];if(!e)throw new tb("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(Je))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}_move(e){var t;if(!this.clients[this.clientId])return;const o=null===(t=this.clients[this.clientId])||void 0===t?void 0:t.position;if((null==o?void 0:o.col)===e.col&&o.row===e.row&&o.sheetId===e.sheetId)return;const i=o?"CLIENT_MOVED":"CLIENT_JOINED",n=this.getClient();this.clients[this.clientId]={...n,position:e},this.transportService.sendMessage({type:i,version:1,client:{...n,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:o}=e,i=new eb(e.nextRevisionId,t,o);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:Qv(o,t)})}break;case"SNAPSHOT_CREATED":{const t=new eb(e.nextRevisionId,"server",[]);this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger("snapshot");break}}this.acknowledge(e),this.trigger("collaborative-event-received")}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;const t=this.clients[this.clientId];if(t){const{position:e}=t;e&&this.transportService.sendMessage({type:"CLIENT_MOVED",version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),this.waitingAck||(this.waitingAck=!0,this.sendPendingMessage())}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if("REMOTE_REVISION"===e.type){const t=this.revisions.get(e.nextRevisionId);if(0===t.commands.length){this.revisions.drop(t.id);const e=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.nextRevisionId));return this.trigger("pending-revisions-dropped",{revisionIds:e}),this.waitingAck=!1,this.waitingUndoRedoAck=!1,void(this.pendingMessages=[])}e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw new Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.\n ${JSON.stringify(e)}`);this.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch("REVISION_UNDONE"!==e.type&&"REVISION_REDONE"!==e.type||(this.waitingUndoRedoAck=!1),e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":case"SNAPSHOT_CREATED":this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter((t=>t.nextRevisionId!==e.nextRevisionId)),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage()}}isAlreadyProcessed(e){if("CLIENT_MOVED"===e.type&&e.client.id===this.clientId)return!0;switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":case"SNAPSHOT_CREATED":return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter((({type:e})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e))}}const ib=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];class nb extends qu{constructor(){super(...arguments),this.availableColors=new Set(ib),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(ib));const e=(t=[...this.availableColors.values()])[Math.floor(Math.random()*t.length)];var t;return this.availableColors.delete(e),e}getClientsToDisplay(){try{this.getters.getClient()}catch(e){if(e instanceof tb)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const o of this.getters.getConnectedClients())if(o.id!==this.getters.getClient().id&&o.position&&o.position.sheetId===e&&this.isPositionValid(o.position)){const e=o.position;this.colors[o.id]||(this.colors[o.id]=this.chooseNewColor());const i=this.colors[o.id];t.push({...o,position:e,color:i})}return t}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:o}=e,i=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:n,col:r}=e.position,s=this.getters.expandZone(i,{top:n,bottom:n,left:r,right:r}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(s);if(c<=0||h<=0)continue;const d=e.color,u=`${d}10`;t.fillStyle=u,t.lineWidth=4*o,t.strokeStyle=d,t.globalCompositeOperation="multiply",t.fillRect(a,l,c,h),t.globalCompositeOperation="source-over",t.strokeRect(a,l,c,h),t.font=`bold ${W+1}px ${G}`}}}nb.getters=["getClientsToDisplay"],nb.layers=[6];class rb extends qu{allowDispatch(e){if("SORT_CELLS"===e.type){if(!zo(e.col,e.row,e.zone))throw new Error(r("The anchor must be part of the provided zone"));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return 0}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{})}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;return Zo(t).some((({col:t,row:o})=>!this.getters.isInMerge({sheetId:e,col:t,row:o})))?63:0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const o=this.getters.getMerges(e).filter((e=>Vo(e,t))),i=Go(o[0]);let[n,r]=[i.width,i.height];return o.every((e=>{let[t,o]=[e.right-e.left+1,e.bottom-e.top+1];return t===n&&o===r}))?0:63}expand(e,t){const{left:o,right:i,top:n,bottom:r}=this.getters.expandZone(e,t);return{left:Math.max(0,o),right:Math.min(this.getters.getNumberCols(e)-1,i),top:Math.max(0,n),bottom:Math.min(this.getters.getNumberRows(e)-1,r)}}checkExpandedValues(e,t){const o=this.expand(e,t);let i;if(this.getters.doesIntersectMerge(e,o)){const{left:t,right:n,top:r,bottom:s}=o;for(let o=t;o<=n;o++)for(let t=r;t<=s;t++){const{col:n,row:r}=this.getters.getMainCellPosition({sheetId:e,col:o,row:t});if(i=this.getters.getEvaluatedCell({sheetId:e,col:n,row:r}),i.formattedValue)return!0}}else for(let t of this.getters.getEvaluatedCellsInZone(e,o))if(t.formattedValue)return!0;return!1}getContiguousZone(e,t){let o,{top:i,bottom:n,left:r,right:s}=t,a=!1;for(;!a;)a=!0,i>0&&(o=this.checkExpandedValues(e,{left:r-1,right:s+1,top:i-1,bottom:i-1}),o&&(a=!1,i--)),r>0&&(o=this.checkExpandedValues(e,{left:r-1,right:r-1,top:i-1,bottom:n+1}),o&&(a=!1,r--)),s<this.getters.getNumberCols(e)-1&&(o=this.checkExpandedValues(e,{left:s+1,right:s+1,top:i-1,bottom:n+1}),o&&(a=!1,s++)),n<this.getters.getNumberRows(e)-1&&(o=this.checkExpandedValues(e,{left:r-1,right:s+1,top:n+1,bottom:n+1}),o&&(a=!1,n++));return{left:r,right:s,top:i,bottom:n}}hasHeader(e,t){if(1===t[0].length)return!1;let o=t.map((t=>t.map((({col:t,row:o})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:o}).type))));return o[0][0]===fi.empty&&(o=o.slice(1)),!o.some((e=>e[0]===fi.empty))&&!!o.some((e=>e[1]!==fi.empty&&e[0]!==e[1]))}sortZone(e,t,o,i,n){const[r,s]=this.mainCellsSteps(e,o);let a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},o),c=this.mainCells(e,o);!n.sortHeaders&&this.hasHeader(e,c)&&(l.top+=s),c=this.mainCells(e,l);const h=function(e,t,o){const i=e.map(((e,t)=>({index:t,type:e.type,value:e.value})));let n=i.filter((e=>e.type===fi.empty)),r=i.filter((e=>e.type!==fi.empty));o&&(r.push(...n.map((e=>({...e,type:fi.number,value:0})))),n=[]);const s="descending"===t?-1:1;return r.sort(((e,t)=>{let o=Jn.indexOf(e.type)-Jn.indexOf(t.type);return 0===o&&(o=e.type===fi.text||e.type===fi.error?e.value.localeCompare(t.value):e.value-t.value),s*o})).concat(n)}(c[a-l.left].map((e=>this.getters.getEvaluatedCell(e))),i,Boolean(n.emptyCellAsZero)),d=h.map((e=>e.index)),[u,g]=[c.length,c[0].length],p=[];for(let e=0;e<u;e++){for(let t=0;t<g;t++){let{col:o,row:i,sheetId:n}=c[e][d[t]];const a=this.getters.getCell({sheetId:n,col:o,row:i});let h=l.left+e*r,u=l.top+t*s,g={sheetId:n,col:h,row:u,content:""};if(a){let e=a.content;if(a.isFormula){const t=u-this.getters.getCellPosition(a.id).row,o=this.getters.createAdaptedRanges(a.dependencies,0,t,n);e=this.getters.buildFormulaContent(n,a,o)}g.style=a.style,g.content=e,g.format=a.format}p.push(g)}for(const e of p)this.dispatch("UPDATE_CELL",e)}}mainCellsSteps(e,t){const o=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[o?o.right-o.left+1:1,o?o.bottom-o.top+1:1]}mainCells(e,t){const[o,i]=this.mainCellsSteps(e,t),n=[],r=Ue(t.left,t.right+1,o),s=Ue(t.top,t.bottom+1,i);for(const t of r){const o=[];n.push(o);for(const i of s)o.push({sheetId:e,col:t,row:i})}return n}}rb.getters=["getContiguousZone"];class sb extends qu{constructor(){super(...arguments),this.showFormulas=!1}handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}sb.getters=["shouldShowFormulas"];class ab extends qu{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 o=this.getColMaxWidth(e.sheetId,t);0!==o&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:o,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":for(let t of e.rows)this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"ROW",size:null,sheetId:e.sheetId})}}getCellWidth(e){let t=this.getTextWidth(e);this.getters.getConditionalIcon(e)&&(t+=Le(this.getters.getCellStyle(e))+2*$);if(this.getters.isFilterHeader(e)&&(t+=20),t>0&&(t+=2*U,"wrap"===this.getters.getCellStyle(e).wrapping)){const o=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(o,t)}return t}getTextWidth(e){const t=this.getters.getCellText(e,this.getters.shouldShowFormulas());return ke(this.ctx,t,this.getters.getCellComputedStyle(e))}getCellText(e,t=!1){const o=this.getters.getCell(e);return t&&(null==o?void 0:o.isFormula)?o.content:this.getters.getEvaluatedCell(e).formattedValue}getCellMultiLineText(e,t){const o=this.getters.getCellStyle(e),i=this.getters.getCellText(e).split(" "),n=[];let r="",s=t;for(let e of i){const i=this.splitWordToSpecificWidth(this.ctx,e,t,o),a=i.pop(),l=ke(this.ctx,a,o);if(i.length)""!==r&&(n.push(r),r="",s=t),i.forEach((e=>{n.push(e)})),r=a,s=t-l;else{const e=""===r?a:" "+a,i=ke(this.ctx,e,o);i<=s?(r+=e,s-=i):(n.push(r),r=a,s=t-l)}}return""!==r&&n.push(r),n}getColDimensions(e,t){const o=this.getColRowOffset("COL",0,t,e),i=this.getters.getColSize(e,t);return{start:o,size:i,end:o+(this.getters.isColHidden(e,t)?0:i)}}getRowDimensions(e,t){const o=this.getColRowOffset("ROW",0,t,e),i=this.getters.getRowSize(e,t);return{start:o,size:i,end:o+(this.getters.isRowHidden(e,t)?0:i)}}getColRowOffset(e,t,o,i=this.getters.getActiveSheetId()){if(o<t)return-this.getColRowOffset(e,o,t);let n=0;for(let r=t;r<o;r++)this.getters.isHeaderHidden(i,e,r)||(n+="COL"===e?this.getters.getColSize(i,r):this.getters.getRowSize(i,r));return n}getColMaxWidth(e,t){const o=Zo(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,...o)}splitWordToSpecificWidth(e,t,o,i){if(ke(e,t,i)<=o)return[t];const n=[];let r="";for(let s of t){ke(e,r+s,i)>o?(n.push(r),r=s):r+=s}return n.push(r),n}}ab.getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getColDimensions","getRowDimensions","getColRowOffset"];class lb{constructor(e,t,o,i){this.getters=t,this.dispatch=o,this.selection=i,this.operation=e,this.sheetId=t.getActiveSheetId()}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0}addMissingDimensions(e,t,o,i){const n=this.getters.getActiveSheetId(),r=t+i-this.getters.getNumberRows(n);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(n)-1,sheetId:n,quantity:r,position:"after"});const s=e+o-this.getters.getNumberCols(n);s>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(n)-1,sheetId:n,quantity:s,position:"after"})}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class cb extends lb{constructor(e,t,o,i,n){if(super(t,o,i,n),!e.length)return this.cells=[[]],this.zones=[],void(this.copiedTables=[]);const r=new Set(e.map((e=>e.left))),s=new Set(e.map((e=>e.right))),a=new Set(e.map((e=>e.top))),l=new Set(e.map((e=>e.bottom))),c=1===a.size&&1===l.size||1===r.size&&1===s.size?function(e){return e.reduce(((e,t)=>{const o=e.length;for(let i=0;i<o;i++)if(Vo(e[i],t))return e[i]=Po(e[i],t),e;return e[o]=t,e}),[])}(e):[e[e.length-1]],h=c.map((e=>Zo(e))).flat(),d=[...new Set(h.map((e=>e.col)))].sort(((e,t)=>e-t)),u=[...new Set(h.map((e=>e.row)))].sort(((e,t)=>e-t)),g=[],p=o.getActiveSheetId();for(let e of u){let t=[];for(let i of d){const n={col:i,row:e,sheetId:p};t.push({cell:o.getCell(n),style:o.getCellComputedStyle(n),evaluatedCell:o.getEvaluatedCell(n),border:o.getCellBorder(n)||void 0,position:n})}g.push(t)}const m=[];for(const t of e)for(const e of this.getters.getFilterTablesInZone(p,t)){const t=[];for(const o of Ue(e.zone.left,e.zone.right+1))t.push(this.getters.getFilterValues({sheetId:p,col:o,row:e.zone.top}));m.push({filtersValues:t,zone:e.zone})}this.cells=g,this.zones=c,this.copiedTables=m}isCutAllowed(e){return 1!==e.length?19:0}isPasteAllowed(e,t){const o=this.getters.getActiveSheetId();if("CUT"===this.operation&&void 0!==(null==t?void 0:t.pasteOption))return 21;if(e.length>1&&(this.cells.length>1||this.cells[0].length>1))return 20;const i=this.cells.length,n=this.cells[0].length;for(let t of this.getPasteZones(e))if(this.getters.doesIntersectMerge(o,t)&&(e.length>1||!this.getters.isSingleCellOrMerge(o,e[0])||i*n!=1))return 2;const{xSplit:r,ySplit:s}=this.getters.getPaneDivisions(o);for(const t of this.getPasteZones(e))if(t.left<r&&t.right>=r||t.top<s&&t.bottom>=s)return 75;return 0}paste(e,t){"COPY"===this.operation?this.pasteFromCopy(e,t):this.pasteFromCut(e,t);const o=this.cells.length,i=this.cells[0].length,n="CUT"===this.operation;(null==t?void 0:t.selectTarget)&&this.selectPastedZone(i,o,n,e)}pasteFromCopy(e,t){if(1===e.length){const o=this.cells.length,i=this.cells[0].length,n=this.pastedZones(e,i,o);for(const e of n)this.pasteZone(e.left,e.top,t)}else for(const o of e)for(let e=o.left;e<=o.right;e++)for(let i=o.top;i<=o.bottom;i++)this.pasteZone(e,i,t);void 0===(null==t?void 0:t.pasteOption)&&this.pasteCopiedTables(e)}pasteFromCut(e,t){this.clearClippedZones();const o=e[0];this.pasteZone(o.left,o.top,t),this.dispatch("MOVE_RANGES",{target:this.zones,sheetId:this.sheetId,targetSheetId:this.getters.getActiveSheetId(),col:o.left,row:o.top});for(const e of this.copiedTables)this.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.getters.getActiveSheetId(),target:[e.zone]});this.pasteCopiedTables(e)}pastedZones(e,t,o){const i=e[0],n=Math.max(1,Math.floor((i.right+1-i.left)/t)),r=Math.max(1,Math.floor((i.bottom+1-i.top)/o)),s=[];for(let e=0;e<n;e++)for(let n=0;n<r;n++){const r=i.top+n*o,a=i.left+e*t;s.push({left:a,top:r,bottom:r+o-1,right:a+t-1})}return s}getPasteZones(e){const t=this.cells;if(!t.length||!t[0].length)return e;const o=[],i=t.length,n=t[0].length,r=e[e.length-1],s=r.left,a=r.top,l=Math.max(1,Math.floor((r.right+1-s)/n)),c=Math.max(1,Math.floor((r.bottom+1-a)/i));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)o.push({left:s,top:a,right:s-1+e*n,bottom:a-1+t*i});return o}selectPastedZone(e,t,o,i){const n=i[0],r=n.left,s=n.top;if(t>1||e>1||o){const n=this.pastedZones(i,e,t),a=o?n[0]:Po(...n);this.selection.selectZone({cell:{col:r,row:s},zone:a})}}clearClippedZones(){for(const e of this.cells)for(const t of e)t.cell&&this.dispatch("CLEAR_CELL",t.position);this.dispatch("CLEAR_FORMATTING",{sheetId:this.sheetId,target:this.zones})}pasteZone(e,t,o){const i=this.cells.length,n=this.cells[0].length,r="onlyValue"!==(null==o?void 0:o.pasteOption)&&(null==o?void 0:o.shouldPasteCF),s=this.getters.getActiveSheetId();this.addMissingDimensions(n,i,e,t);for(let a=0;a<i;a++){const i=this.cells[a];for(let l=0;l<n;l++){const n=i[l],c={col:e+l,row:t+a,sheetId:s};"CUT"!==this.operation&&this.pasteMergeIfExist(n.position,c),this.pasteCell(n,c,this.operation,o),r&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{origin:n.position,target:c,operation:this.operation})}}}pasteCell(e,t,o,i){const{sheetId:n,col:r,row:s}=t,a=this.getters.getEvaluatedCell(t);if("onlyValue"!==(null==i?void 0:i.pasteOption)){const o=this.getters.getCellBorder(t),i=e.border,a={top:(null==o?void 0:o.top)||(null==i?void 0:i.top),bottom:(null==o?void 0:o.bottom)||(null==i?void 0:i.bottom),left:(null==o?void 0:o.left)||(null==i?void 0:i.left),right:(null==o?void 0:o.right)||(null==i?void 0:i.right)};this.dispatch("SET_BORDER",{sheetId:n,col:r,row:s,border:a})}if(e.cell){if("onlyFormat"===(null==i?void 0:i.pasteOption))return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.evaluatedCell.format});if("onlyValue"===(null==i?void 0:i.pasteOption)){const o=ro(e.evaluatedCell.value);return void this.dispatch("UPDATE_CELL",{...t,content:o})}let a=e.cell.content;if(e.cell.isFormula&&"COPY"===o){const t=r-e.position.col,i=s-e.position.row;a=this.getUpdatedContent(n,e.cell,t,i,o)}this.dispatch("UPDATE_CELL",{...t,content:a,style:e.cell.style||null,format:e.cell.format})}else a&&("onlyValue"===(null==i?void 0:i.pasteOption)?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===(null==i?void 0:i.pasteOption)?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,o,i,n){const r=this.getters.createAdaptedRanges(t.dependencies,o,i,e);return this.getters.buildFormulaContent(e,t,r)}pasteMergeIfExist(e,t){let{sheetId:o,col:i,row:n}=e;const{col:r,row:s}=this.getters.getMainCellPosition(e);if(r===i&&s===n){const r=this.getters.getMerge(e);if(!r)return;({sheetId:o,col:i,row:n}=t),this.dispatch("ADD_MERGE",{sheetId:o,force:!0,target:[{left:i,top:n,right:i+r.right-r.left,bottom:n+r.bottom-r.top}]})}}pasteCopiedTables(e){const t=this.getters.getActiveSheetId(),o=e[0],i=this.zones[0],n=[o.left-i.left,o.top-i.top];for(const e of this.copiedTables){const o=jo(e.zone,"both","MOVE",n);this.dispatch("CREATE_FILTER_TABLE",{sheetId:t,target:[o]});for(const i of Ue(0,e.filtersValues.length))this.dispatch("UPDATE_FILTER",{sheetId:t,col:o.left+i,row:o.top,values:e.filtersValues[i]})}}getClipboardContent(){return{[vi.PlainText]:this.getPlainTextContent(),[vi.Html]:this.getHTMLContent()}}getPlainTextContent(){return this.cells.map((e=>e.map((e=>e.cell?this.getters.getCellText(e.position,this.getters.shouldShowFormulas()):"")).join("\t"))).join("\n")||"\t"}getHTMLContent(){if(1==this.cells.length&&1==this.cells[0].length)return this.getters.getCellText(this.cells[0][0].position);let e='<table border="1" style="border-collapse:collapse">';for(const t of this.cells){e+="<tr>";for(const o of t){e+=`<td style="${li(si(o.style),!1)}">`+Nf(this.getters.getCellText(o.position))+"</td>"}e+="</tr>"}return e+="</table>",e}isColRowDirtyingClipboard(e,t){if(!this.zones)return!1;for(let o of this.zones){if("COL"===t&&e<=o.right)return!0;if("ROW"===t&&e<=o.bottom)return!0}return!1}drawClipboard(e){const{ctx:t,thinLineWidth:o}=e;if(this.sheetId===this.getters.getActiveSheetId()&&this.zones&&this.zones.length){t.setLineDash([8,5]),t.strokeStyle=E,t.lineWidth=3.3*o;for(const e of this.zones){const{x:o,y:i,width:n,height:r}=this.getters.getVisibleRect(e);n>0&&r>0&&t.strokeRect(o,i,n,r)}}}}class hb{constructor(e,t,o){this.operation=e,this.getters=t,this.dispatch=o,this.sheetId=t.getActiveSheetId();const i=t.getSelectedFigureId();if(!i)throw new Error("No figure selected");const n=t.getFigure(this.sheetId,i);if(!n)throw new Error(`No figure for the given id: ${i}`);switch(this.copiedFigure={...n},n.tag){case"chart":this.copiedFigureContent=new db(o,t,this.sheetId,i);break;case"image":this.copiedFigureContent=new ub(o,t,this.sheetId,i);break;default:throw new Error(`Unknow tag '${n.tag}' for the given figure id: ${i}`)}}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0===e.length?73:void 0!==(null==t?void 0:t.pasteOption)?22:0}paste(e){const t=this.getters.getActiveSheetId(),o={x:this.getters.getColDimensions(t,e[0].left).start,y:this.getters.getRowDimensions(t,e[0].top).start},i={height:this.copiedFigure.height,width:this.copiedFigure.width},n=(new Ao).uuidv4();this.copiedFigureContent.paste(t,n,o,i),"CUT"===this.operation&&this.dispatch("DELETE_FIGURE",{sheetId:this.copiedFigureContent.sheetId,id:this.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{id:n})}getClipboardContent(){return{[vi.PlainText]:"\t"}}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class db{constructor(e,t,o,i){this.dispatch=e,this.sheetId=o;const n=t.getChart(i);if(!n)throw new Error(`No chart for the given id: ${i}`);this.copiedChart=n.copyInSheetId(o)}paste(e,t,o,i){const n=this.copiedChart.copyInSheetId(e);this.dispatch("CREATE_CHART",{id:t,sheetId:e,position:o,size:i,definition:n.getDefinition()})}}class ub{constructor(e,t,o,i){this.dispatch=e,this.sheetId=o;const n=t.getImage(i);this.copiedImage=Me(n)}paste(e,t,o,i){const n=Me(this.copiedImage);this.dispatch("CREATE_IMAGE",{figureId:t,sheetId:e,position:o,size:i,definition:n})}}class gb extends lb{constructor(e,t,o,i){super("COPY",t,o,i),this.values=e.replace(/\r/g,"").split("\n").map((e=>e.split("\t")))}isPasteAllowed(e,t){const o=this.getters.getActiveSheetId(),i=this.getPasteZone(e);return this.getters.doesIntersectMerge(o,i)?2:0}paste(e){const t=this.values,o=this.getPasteZone(e),{left:i,top:n}=o,{width:r,height:s}=Go(o),a=this.getters.getActiveSheetId();this.addMissingDimensions(r,s,i,n);for(let e=0;e<t.length;e++)for(let o=0;o<t[e].length;o++)this.dispatch("UPDATE_CELL",{row:n+e,col:i+o,content:t[e][o],sheetId:a});const l={left:i,top:n,right:i+r-1,bottom:n+s-1};this.selection.selectZone({cell:{col:i,row:n},zone:l})}getClipboardContent(){return{[vi.PlainText]:this.values.map((e=>e.join("\t"))).join("\n")}}getPasteZone(e){const t=this.values.length,o=Math.max(...this.values.map((e=>e.length))),{left:i,top:n}=e[0];return{top:n,left:i,bottom:n+t-1,right:i+o-1}}}class pb extends qu{constructor(){super(...arguments),this.status="invisible",this._isPaintingFormat=!1}allowDispatch(e){switch(e.type){case"CUT":const t=e.target||this.getters.getSelectedZones();return this.getClipboardState(t,e.type).isCutAllowed(t);case"PASTE":if(!this.state)return 23;const o=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);return this.state.isPasteAllowed(e.target,{pasteOption:o});case"PASTE_FROM_OS_CLIPBOARD":return new gb(e.text,this.getters,this.dispatch,this.selection).isPasteAllowed(e.target);case"INSERT_CELL":{const{cut:t,paste:o}=this.getInsertCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(o)}case"DELETE_CELL":{const{cut:t,paste:o}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(o)}}return 0}handle(e){var t,o;switch(e.type){case"COPY":case"CUT":const i="target"in e&&e.target||this.getters.getSelectedZones();this.state=this.getClipboardState(i,e.type),this.status="visible";break;case"PASTE":if(!this.state)break;const n=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);this._isPaintingFormat=!1,this.state.paste(e.target,{pasteOption:n,shouldPasteCF:!0,selectTarget:!0}),"CUT"===this.state.operation&&(this.state=void 0),this.status="invisible";break;case"CLEAN_CLIPBOARD_HIGHLIGHT":this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:o}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!No(t[0])){for(const{col:t,row:o}of Zo(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:o,sheetId:this.getters.getActiveSheetId()});break}this.getClipboardStateForCopyCells(t,"CUT").paste(o);break}case"INSERT_CELL":{const{cut:t,paste:o}=this.getInsertCellsTargets(e.zone,e.shiftDimension);this.getClipboardStateForCopyCells(t,"CUT").paste(o);break}case"ADD_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(t=this.state)||void 0===t?void 0:t.operation))return;this.state.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.state=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(o=this.state)||void 0===o?void 0:o.operation))return;for(let t of e.elements){if(this.state.isColRowDirtyingClipboard(t,e.dimension)){this.state=void 0;break}}this.status="invisible";break;case"PASTE_FROM_OS_CLIPBOARD":new gb(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:wi(e)&&(this.status="invisible")}}getClipboardContent(){var e;return(null===(e=this.state)||void 0===e?void 0:e.getClipboardContent())||{[vi.PlainText]:"\t"}}getClipboardTextContent(){var e;return(null===(e=this.state)||void 0===e?void 0:e.getClipboardContent()[vi.PlainText])||"\t"}isCutOperation(){return!!this.state&&"CUT"===this.state.operation}isPaintingFormat(){return this._isPaintingFormat}getDeleteCellsTargets(e,t){const o=this.getters.getActiveSheetId();let i;return i="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(o)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(o)-1},{cut:[i],paste:[e]}}getInsertCellsTargets(e,t){const o=this.getters.getActiveSheetId();let i,n;return"COL"===t?(i={...e,right:this.getters.getNumberCols(o)-1},n={...e,left:e.right+1,right:e.right+1}):(i={...e,bottom:this.getters.getNumberRows(o)-1},n={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(o)-1}),{cut:[i],paste:[n]}}getClipboardStateForCopyCells(e,t){return new cb(e,t,this.getters,this.dispatch,this.selection)}getClipboardState(e,t){return this.getters.getSelectedFigureId()?new hb(t,this.getters,this.dispatch):new cb(e,t,this.getters,this.dispatch,this.selection)}drawGrid(e){"visible"===this.status&&this.state&&this.state.drawClipboard(e)}}pb.layers=[2],pb.getters=["getClipboardContent","getClipboardTextContent","isCutOperation","isPaintingFormat"];const mb=[{name:r("Sum"),types:[fi.number],compute:e=>ma.compute([e])},{name:r("Avg"),types:[fi.number],compute:e=>Ra.compute([e])},{name:r("Min"),types:[fi.number],compute:e=>Ha.compute([e])},{name:r("Max"),types:[fi.number],compute:e=>Ua.compute([e])},{name:r("Count"),types:[fi.number,fi.text,fi.boolean,fi.error],compute:e=>Da.compute([e])},{name:r("Count Numbers"),types:[fi.number,fi.text,fi.boolean,fi.error],compute:e=>Fa.compute([e])}];class fb extends qu{constructor(e){super(e),this.gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]},this.selectedFigureId=null,this.sheetsData={},this.activeSheet=null,this.moveClient=e.moveClient}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{this.getters.getSheet(e.sheetIdTo);break}catch(e){return 27}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return 0}handleEvent(e){const t=e.anchor;let o=[];switch(e.mode){case"overrideSelection":o=[t.zone];break;case"updateAnchor":o=[...this.gridSelection.zones];const i=o.findIndex((t=>Uo(t,e.previousAnchor.zone)));i>=0&&(o[i]=t.zone);break;case"newAnchor":o=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,o),this.selection.resetDefaultAnchor(this,Me(this.gridSelection.anchor));const{col:i,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:i,row:n}),this.selectedFigureId=null}handle(e){switch(e.type){case"START_EDITION":case"ACTIVATE_SHEET":this.selectedFigureId=null;break;case"DELETE_FIGURE":this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;case"DELETE_SHEET":this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null)}switch(e.type){case"START":const t=this.getters.getVisibleSheetIds()[0];this.dispatch("ACTIVATE_SHEET",{sheetIdTo:t,sheetIdFrom:t});const{col:o,row:i}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(o,i),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case"ACTIVATE_SHEET":if(this.getters.isSheetVisible(e.sheetIdTo)||this.dispatch("SHOW_SHEET",{sheetId:e.sheetIdTo}),this.setActiveSheet(e.sheetIdTo),this.sheetsData[e.sheetIdFrom]={gridSelection:Me(this.gridSelection)},e.sheetIdTo in this.sheetsData)Object.assign(this,this.sheetsData[e.sheetIdTo]),this.selection.resetDefaultAnchor(this,Me(this.gridSelection.anchor));else{const{col:t,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0});this.selectCell(t,o)}break;case"REMOVE_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);const{col:o,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:o,row:i})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:o,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:o,row:i})}break}case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"SELECT_FIGURE":this.selectedFigureId=e.id;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left");break;case"HIDE_SHEET":e.sheetId===this.getActiveSheetId()&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case"UNDO":case"REDO":case"DELETE_SHEET":const n=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of n)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:Me(t)}}if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){const e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){const{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);const{col:t,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:o})}const r=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map((e=>this.getters.expandZone(r,e))),this.gridSelection.anchor.zone=this.getters.expandZone(r,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones)}this.selection.resetDefaultAnchor(this,Me(this.gridSelection.anchor))}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){const e=new Set;for(let t of this.gridSelection.zones)if(0===t.top&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let o=t.left;o<=t.right;o++)e.add(o);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(let o of this.gridSelection.zones)if(0===o.left&&o.right===this.getters.getNumberCols(t)-1)for(let t=o.top;t<=o.bottom;t++)e.add(t);return e}getCurrentStyle(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return Me(this.gridSelection.zones)}getSelectedZone(){return Me(this.gridSelection.anchor.zone)}getSelection(){return Me(this.gridSelection)}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{const t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}getStatisticFnResults(){const e=new Set(this.gridSelection.zones.map((e=>this.getters.getEvaluatedCellsInZone(this.getters.getActiveSheetId(),e))).flat().filter((e=>e.type!==fi.empty)));let t=new Set,o=[];for(let i of e)t.add(i.type),o.push(i.value);let i={};for(let e of mb){let n;e.types.some((e=>t.has(e)))&&(n=e.compute(o)),i[e.name]=n}return i}getAggregate(){let e=0,t=0;const o=this.getters.getActiveSheetId(),i=this.gridSelection.zones.map(Zo).flat();for(const{col:n,row:r}of i){const i=this.getters.getEvaluatedCell({sheetId:o,col:n,row:r});i.type===fi.number&&(t++,e+=i.value)}return t<2?null:ro(e)}isSelected(e){return!!this.getters.getSelectedZones().find((t=>Uo(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 o=[];const i="COL"===e?"left":"top",n="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[n]-e[i]+1},((t,o)=>e[i]+o));o=o.concat(t)}return[...new Set(o)].sort()}setSelectionMixin(e,t){const{anchor:o,zones:i}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=o,this.gridSelection.zones=function(e){return e.reverse().filter(((e,t,o)=>t===o.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}(i)}selectCell(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.expandZone(o,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:i,cell:{col:e,row:t}},[i])}setActiveSheet(e){const t=this.getters.getSheet(e);this.activeSheet=t}activateNextSheet(e){const t=this.getters.getSheetIds(),o=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[o]})}onColumnsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,i=ko(o,"left",[...e.elements]);let n={left:t.col,right:t.col,top:t.row,bottom:t.row};n=ko(n,"left",[...e.elements]);const r={cell:{col:n.left,row:n.top},zone:i};this.setSelectionMixin(r,[i])}onRowsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,i=ko(o,"top",[...e.elements]);let n={left:t.col,right:t.col,top:t.row,bottom:t.row};n=ko(n,"top",[...e.elements]);const r={cell:{col:n.left,row:n.top},zone:i};this.setSelectionMixin(r,[i])}onAddElements(e){const t=Do(this.gridSelection.anchor.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),o={cell:{col:t.left,row:t.top},zone:t};this.setSelectionMixin(o,[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:"before"});const o="COL"===e.dimension,i=e.elements[0],n=e.elements[t-1],r=e.base<i,s=r&&o?t:0,a=r&&!o?t:0;this.dispatch("CUT",{target:[{left:o?i+s:0,right:o?n+s:this.getters.getNumberCols(e.sheetId)-1,top:o?0:i+a,bottom:o?this.getters.getNumberRows(e.sheetId)-1:n+a}]}),this.dispatch("PASTE",{target:[{left:o?e.base:0,right:o?e.base+t-1:this.getters.getNumberCols(e.sheetId)-1,top:o?0:e.base,bottom:o?this.getters.getNumberRows(e.sheetId)-1:e.base+t-1}]});const l=r?e.elements.map((e=>e+t)):e.elements;let c=e.base;for(const t of l){const o="COL"===e.dimension?this.getters.getColSize(e.sheetId,t):this.getters.getRowSize(e.sheetId,t);this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:o,elements:[c]}),c+=1}this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,elements:l})}isMoveElementAllowed(e){const t="COL"===e.dimension,o=e.elements[0],i=e.elements[e.elements.length-1],n=e.sheetId,r=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;return r(n,o-1,o)||r(n,i,i+1)||r(n,e.base-1,e.base)?2:0}clipSelection(e,t){const o=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;return{zones:t.zones.map((e=>({left:Fe(e.left,0,o),right:Fe(e.right,0,o),top:Fe(e.top,0,i),bottom:Fe(e.bottom,0,i)}))),anchor:{cell:{col:Fe(t.anchor.cell.col,0,o),row:Fe(t.anchor.cell.row,0,i)},zone:{left:Fe(t.anchor.zone.left,0,o),right:Fe(t.anchor.zone.right,0,o),top:Fe(t.anchor.zone.top,0,i),bottom:Fe(t.anchor.zone.bottom,0,i)}}}}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:o}=e,i=this.getSelectedZones();t.fillStyle="#f3f7fe";const n=1===i.length&&i[0].left===i[0].right&&i[0].top===i[0].bottom;t.fillStyle=n?"#f3f7fe":"#e9f0ff",t.strokeStyle=E,t.lineWidth=1.5*o;for(const e of i){const{x:o,y:i,width:n,height:r}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(o,i,n,r),t.globalCompositeOperation="source-over",t.strokeRect(o,i,n,r)}t.globalCompositeOperation="source-over";const r=this.getActivePosition();let s;t.strokeStyle=E,t.lineWidth=3*o,s=this.getters.isInMerge(r)?this.getters.getMerge(r):Ko(r);const{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(s);c>0&&h>0&&t.strokeRect(a,l,c,h)}}fb.layers=[6],fb.getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getStatisticFnResults","getAggregate","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSelected","getElementsFromSelection"];const vb=(new In).add("sheet",Tv).add("header visibility",Ev).add("filters",Cv).add("cell",uv).add("merge",yv).add("headerSize",Sv).add("borders",hv).add("conditional formatting",mv).add("figures",fv).add("chart",gv).add("image",wv),bb=(new In).add("ui_sheet",ab).add("header_visibility_ui",Bv).add("ui_options",sb).add("selectionInputManager",qv).add("highlight",Hv).add("grid renderer",Wv).add("autofill",Pv).add("find_and_replace",zv).add("sort",rb).add("automatic_sum",Lv).add("format",class extends qu{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,o){const i=this.searchNumberFormat(e,t);if(void 0!==i){const n=function(e,t){const o=no(e).map((e=>"NUMBER"===e.type?{...e,format:Co(e.format,t)}:e)),i=yo(o);return io[i]=o,i}(i,o);this.dispatch("SET_FORMATTING",{sheetId:e,target:t,format:n})}}searchNumberFormat(e,t){var o;for(let i of t)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++){const i=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(i.type===fi.number&&!(null===(o=i.format)||void 0===o?void 0:o.match(j)))return i.format||fo(i.value)}}}).add("cell_popovers",Uv).add("selection_multiuser",nb),Cb=(new In).add("selection",fb).add("clipboard",pb).add("edition",ju),Sb=(new In).add("evaluation",Mv).add("evaluation_filter",Fv).add("evaluation_chart",Nv).add("evaluation_cf",_v).add("viewport",kv).add("custom_colors",Av),Eb=new In;Eb.add("link",{condition:(e,t)=>!!t.model.getters.getEvaluatedCell(e).link,action:(e,t)=>Cg(t.model.getters.getEvaluatedCell(e).link,t),sequence:5});class wb{constructor(e){this.fileStore=e}async requestImage(){const e=await this.getImageFromUser(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageSize(t)}}getImageFromUser(){return new Promise(((e,t)=>{const o=document.createElement("input");o.setAttribute("type","file"),o.setAttribute("accept","image/*"),o.addEventListener("change",(async()=>{null===o.files||1!=o.files.length?t():e(o.files[0])})),o.click()}))}getImageSize(e){return new Promise(((t,o)=>{const i=new Image;i.src=e,i.addEventListener("load",(()=>{const e={width:i.width,height:i.height};t(e)})),i.addEventListener("error",o)}))}}ni`
1416
1416
  .o-spreadsheet-bottom-bar {
1417
1417
  background-color: ${f};
1418
1418
  padding-left: ${M}px;
@@ -1501,12 +1501,12 @@
1501
1501
  opacity: 0;
1502
1502
  }
1503
1503
  }
1504
- `;class wb 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,o=this.env.model.uuidGenerator.uuidv4(),i=this.env.model.getters.getNextSheetName(this.env._t("Sheet"));this.env.model.dispatch("CREATE_SHEET",{sheetId:o,position:t,name:i}),this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:o})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map((e=>this.env.model.getters.getSheet(e)))}listSheets(e){const t=new Mn,o=this.env.model.getters.getActiveSheetId();let i=0;for(const e of this.env.model.getters.getSheetIds()){const n=this.env.model.getters.getSheet(e);t.add(e,{name:n.name,sequence:i,isReadonlyAllowed:!0,textColor:n.isVisible?void 0:"grey",action:t=>{t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:o,sheetIdTo:e})}}),i++}const n=e.currentTarget,{top:r,left:s}=n.getBoundingClientRect();this.openContextMenu(s,r,t)}activateSheet(e){this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:e})}onDblClick(e){Zg(this.env,e)}openContextMenu(e,t,o,i){this.menuState.isOpen=!0,this.menuState.menuItems=o.getAll(),this.menuState.position={x:e,y:t},this.menuState.menuId=i}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 o=t.currentTarget.parentElement,{top:i,left:n}=o.getBoundingClientRect();this.openContextMenu(n,i,jg,e)}}onContextMenu(e,t){this.env.model.getters.getActiveSheetId()!==e&&this.activateSheet(e);const o=t.currentTarget,{top:i,left:n}=o.getBoundingClientRect();this.openContextMenu(n,i,jg,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 Mn;let o=0;for(let[e,i]of Object.entries(this.env.model.getters.getStatisticFnResults()))t.add(e,{name:this.getComposedFnName(e,i),sequence:o,isReadonlyAllowed:!0,action:()=>{this.selectedStatisticFn=e}}),o++;const i=e.currentTarget,{top:n,left:r,width:s}=i.getBoundingClientRect();this.openContextMenu(r+s,n,t)}getComposedFnName(e,t){return e+": "+(void 0!==t?no(t):"__")}}wb.template="o-spreadsheet-BottomBar",wb.components={Menu:Bn},wb.props={onClick:Function},ii`
1504
+ `;class yb 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,o=this.env.model.uuidGenerator.uuidv4(),i=this.env.model.getters.getNextSheetName(this.env._t("Sheet"));this.env.model.dispatch("CREATE_SHEET",{sheetId:o,position:t,name:i}),this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e,sheetIdTo:o})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map((e=>this.env.model.getters.getSheet(e)))}listSheets(e){const t=new Nn,o=this.env.model.getters.getActiveSheetId();let i=0;for(const e of this.env.model.getters.getSheetIds()){const n=this.env.model.getters.getSheet(e);t.add(e,{name:n.name,sequence:i,isReadonlyAllowed:!0,textColor:n.isVisible?void 0:"grey",action:t=>{t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:o,sheetIdTo:e})}}),i++}const n=e.currentTarget,{top:r,left:s}=n.getBoundingClientRect();this.openContextMenu(s,r,t)}activateSheet(e){this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:e})}onDblClick(e){jg(this.env,e)}openContextMenu(e,t,o,i){this.menuState.isOpen=!0,this.menuState.menuItems=o.getAll(),this.menuState.position={x:e,y:t},this.menuState.menuId=i}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 o=t.currentTarget.parentElement,{top:i,left:n}=o.getBoundingClientRect();this.openContextMenu(n,i,Xg,e)}}onContextMenu(e,t){this.env.model.getters.getActiveSheetId()!==e&&this.activateSheet(e);const o=t.currentTarget,{top:i,left:n}=o.getBoundingClientRect();this.openContextMenu(n,i,Xg,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 Nn;let o=0;for(let[e,i]of Object.entries(this.env.model.getters.getStatisticFnResults()))t.add(e,{name:this.getComposedFnName(e,i),sequence:o,isReadonlyAllowed:!0,action:()=>{this.selectedStatisticFn=e}}),o++;const i=e.currentTarget,{top:n,left:r,width:s}=i.getBoundingClientRect();this.openContextMenu(r+s,n,t)}getComposedFnName(e,t){return e+": "+(void 0!==t?ro(t):"__")}}yb.template="o-spreadsheet-BottomBar",yb.components={Menu:Hn},yb.props={onClick:Function},ni`
1505
1505
  .o-dashboard-clickable-cell {
1506
1506
  position: absolute;
1507
1507
  cursor: pointer;
1508
1508
  }
1509
- `;let yb=1;class xb extends t.Component{setup(){const e=t.useRef("grid");this.canvasPosition=_n(e),this.hoveredCell=t.useState({col:void 0,row:void 0}),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),Dp("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimension())),this.onMouseWheel=kp(((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.col=void 0,this.hoveredCell.row=void 0}))}onCellHovered({col:e,row:t}){this.hoveredCell.col=e,this.hoveredCell.row=t}get gridContainer(){const e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e),{end:o}=this.env.model.getters.getColDimensions(e,t);return`\n max-width: ${o}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 o of this.env.model.getters.getSheetViewVisibleCols())for(const i of this.env.model.getters.getSheetViewVisibleRows()){const n={sheetId:t,col:o,row:i},r=this.getClickableAction(n);if(!r)continue;let s;s=this.env.model.getters.isInMerge(n)?this.env.model.getters.getMerge(n):Yo({col:o,row:i});const a=this.env.model.getters.getVisibleRect(s);e.push({coordinates:a,position:{col:o,row:i},action:r,tKey:`${yb}-${o}-${i}`})}return yb++,e}getClickableAction(e){for(const t of Sb.getAll().sort(((e,t)=>e.sequence-t.sequence)))if(t.condition(e,this.env))return t.action;return!1}selectClickableCell(e){const{position:t,action:o}=e;o({...t,sheetId:this.env.model.getters.getActiveSheetId()},this.env)}onClosePopover(){this.env.model.dispatch("CLOSE_CELL_POPOVER")}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t,height:e,gridOffsetX:0,gridOffsetY:0})}moveCanvas(e,t){const{scrollX:o,scrollY:i}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o+e,offsetY:i+t})}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}}xb.template="o-spreadsheet-SpreadsheetDashboard",xb.components={GridOverlay:Ap,GridPopover:Op,Popover:Ln,VerticalScrollBar:Bp,HorizontalScrollBar:zp,FilterIconsOverlay:dg},xb.props={},ii`
1509
+ `;let xb=1;class Ib extends t.Component{setup(){const e=t.useRef("grid");this.canvasPosition=Fn(e),this.hoveredCell=t.useState({col:void 0,row:void 0}),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),kp("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimension())),this.onMouseWheel=$p(((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.col=void 0,this.hoveredCell.row=void 0}))}onCellHovered({col:e,row:t}){this.hoveredCell.col=e,this.hoveredCell.row=t}get gridContainer(){const e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e),{end:o}=this.env.model.getters.getColDimensions(e,t);return`\n max-width: ${o}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 o of this.env.model.getters.getSheetViewVisibleCols())for(const i of this.env.model.getters.getSheetViewVisibleRows()){const n={sheetId:t,col:o,row:i},r=this.getClickableAction(n);if(!r)continue;let s;s=this.env.model.getters.isInMerge(n)?this.env.model.getters.getMerge(n):Ko({col:o,row:i});const a=this.env.model.getters.getVisibleRect(s);e.push({coordinates:a,position:{col:o,row:i},action:r,tKey:`${xb}-${o}-${i}`})}return xb++,e}getClickableAction(e){for(const t of Eb.getAll().sort(((e,t)=>e.sequence-t.sequence)))if(t.condition(e,this.env))return t.action;return!1}selectClickableCell(e){const{position:t,action:o}=e;o({...t,sheetId:this.env.model.getters.getActiveSheetId()},this.env)}onClosePopover(){this.env.model.dispatch("CLOSE_CELL_POPOVER")}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t,height:e,gridOffsetX:0,gridOffsetY:0})}moveCanvas(e,t){const{scrollX:o,scrollY:i}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o+e,offsetY:i+t})}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}}Ib.template="o-spreadsheet-SpreadsheetDashboard",Ib.components={GridOverlay:Op,GridPopover:Mp,Popover:Un,VerticalScrollBar:Hp,HorizontalScrollBar:Bp,FilterIconsOverlay:ug},Ib.props={},ni`
1510
1510
  .o-sidePanel {
1511
1511
  display: flex;
1512
1512
  flex-direction: column;
@@ -1744,7 +1744,7 @@
1744
1744
  }
1745
1745
  }
1746
1746
  }
1747
- `;class Ib extends t.Component{setup(){this.state=t.useState({panel:yp.get(this.props.component)}),t.onWillUpdateProps((e=>this.state.panel=yp.get(e.component)))}getTitle(){return"function"==typeof this.state.panel.title?this.state.panel.title(this.env):this.state.panel.title}}Ib.template="o-spreadsheet-SidePanel",Ib.props={component:String,panelProps:{type:Object,optional:!0},onCloseSidePanel:Function};const Rb={MergeIsDestructive:r("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),MergeInFilter:r("You can't merge cells inside of an existing filter.")};const Tb=[{name:"automatic",text:Gi.Automatic},{name:"number",text:Gi.Number,description:"1,000.12",value:"#,##0.00"},{name:"percent",text:Gi.Percent,description:"10.12%",value:"0.00%"},{name:"currency",text:Gi.Currency,description:"$1,000.12",value:"[$$]#,##0.00"},{name:"currency_rounded",text:Gi.CurrencyRounded,description:"$1,000",value:"[$$]#,##0"},{name:"date",text:Gi.Date,description:"9/26/2008",value:"m/d/yyyy"},{name:"time",text:Gi.Time,description:"10:43:00 PM",value:"hh:mm:ss a"},{name:"datetime",text:Gi.DateTime,description:"9/26/2008 22:43:00",value:"m/d/yyyy hh:mm:ss"},{name:"duration",text:Gi.Duration,description:"27:51:38",value:"hhhh:mm:ss"}],Ab=[{name:"custom_currency",text:Gi.CustomCurrency,sidePanel:"CustomCurrency"}];ii`
1747
+ `;class Rb extends t.Component{setup(){this.state=t.useState({panel:xp.get(this.props.component)}),t.onWillUpdateProps((e=>this.state.panel=xp.get(e.component)))}getTitle(){return"function"==typeof this.state.panel.title?this.state.panel.title(this.env):this.state.panel.title}}Rb.template="o-spreadsheet-SidePanel",Rb.props={component:String,panelProps:{type:Object,optional:!0},onCloseSidePanel:Function};const Tb={MergeIsDestructive:r("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),MergeInFilter:r("You can't merge cells inside of an existing filter.")};const Ab=[{name:"automatic",text:qi.Automatic},{name:"number",text:qi.Number,description:"1,000.12",value:"#,##0.00"},{name:"percent",text:qi.Percent,description:"10.12%",value:"0.00%"},{name:"currency",text:qi.Currency,description:"$1,000.12",value:"[$$]#,##0.00"},{name:"currency_rounded",text:qi.CurrencyRounded,description:"$1,000",value:"[$$]#,##0"},{name:"date",text:qi.Date,description:"9/26/2008",value:"m/d/yyyy"},{name:"time",text:qi.Time,description:"10:43:00 PM",value:"hh:mm:ss a"},{name:"datetime",text:qi.DateTime,description:"9/26/2008 22:43:00",value:"m/d/yyyy hh:mm:ss"},{name:"duration",text:qi.Duration,description:"27:51:38",value:"hhhh:mm:ss"}],Ob=[{name:"custom_currency",text:qi.CustomCurrency,sidePanel:"CustomCurrency"}];ni`
1748
1748
  .o-spreadsheet-topbar {
1749
1749
  background-color: white;
1750
1750
  line-height: 1.2;
@@ -1951,7 +1951,7 @@
1951
1951
  }
1952
1952
  }
1953
1953
  }
1954
- `;class Ob extends t.Component{constructor(){super(...arguments),this.DEFAULT_FONT_SIZE=W,this.commonFormats=Tb,this.customFormats=Ab,this.currentFormatName="automatic",this.fontSizes=le,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.onExternalClick),t.onWillStart((()=>this.updateCellState())),t.onWillUpdateProps((()=>this.updateCellState()))}get topbarComponents(){return xp.getAll().filter((e=>!e.isVisible||e.isVisible(this.env)))}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onClick(){this.props.onClick(),this.closeMenus()}toggleStyle(e){rr(this.env,{[e]:!this.style[e]})}toggleFormat(e){const t=Tb.find((t=>t.name===e)),o=t&&t.value||"";nr(this.env,o)}toggleAlign(e){rr(this.env,{align:e}),this.onClick()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.openMenu(e,t)}toggleDropdownTool(e,t){const o=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=o?"":e,this.openedEl=o?null:t.target}toggleContextMenu(e,t){this.state.menuState.isOpen?this.closeMenus():this.openMenu(e,t)}openMenu(e,t){const{left:o,top:i,height:n}=t.target.getBoundingClientRect();this.state.menuState.isOpen=!0,this.state.menuState.position={x:o,y:i+n},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(),{col:t,row:o,sheetId:i}=this.env.model.getters.getActivePosition();this.inMerge=!1;const{top:n,left:r,right:s,bottom:a}=this.env.model.getters.getSelectedZone(),{xSplit:l,ySplit:c}=this.env.model.getters.getPaneDivisions(i);if(this.cannotMerge=e.length>1||n===a&&r===s||r<l&&l<=s||n<c&&c<=a,!this.cannotMerge){const n=this.env.model.getters.expandZone(i,Yo({col:t,row:o}));this.inMerge=Lo(e[0],n)}this.undoTool=this.env.model.getters.canUndo(),this.redoTool=this.env.model.getters.canRedo(),this.paintFormatTool=this.env.model.getters.isPaintingFormat();const h=this.env.model.getters.getActiveCell();if(h.format){const e=this.commonFormats.find((e=>e.value===h.format));this.currentFormatName=e?e.name:""}else this.currentFormatName="automatic";this.style={...this.env.model.getters.getCurrentStyle()},this.style.align=this.style.align||h.defaultAlign,this.fillColor=this.style.fillColor||"#ffffff",this.textColor=this.style.textColor||"#000000",this.menus=Yg.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]],o=this.env.model.getters.getActiveSheetId();this.inMerge?this.env.model.dispatch("REMOVE_MERGE",{sheetId:o,target:t}):function(e,t,o){const i=e.model.dispatch("ADD_MERGE",{sheetId:t,target:o});i.isCancelledBecause(80)?e.raiseError(Rb.MergeInFilter):i.isCancelledBecause(3)&&e.askConfirmation(Rb.MergeIsDestructive,(()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:o,force:!0})}))}(this.env,o,t)}setColor(e,t){rr(this.env,{[e]:t}),this.onClick()}setBorder(e){this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),border:e}),this.onClick()}setFormat(e,t){t?this.openCustomFormatSidePanel(e):this.toggleFormat(e),this.onClick()}openCustomFormatSidePanel(e){const t=Ab.find((t=>t.name===e)),o=t&&t.sidePanel||"";this.env.openSidePanel(o)}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);rr(this.env,{fontSize:t}),this.onClick()}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!Jo(...this.env.model.getters.getSelectedZones())}createFilter(){if(this.cannotCreateFilter)return;const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones();tr(this.env,e,t)}removeFilter(){this.env.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}}Ob.template="o-spreadsheet-TopBar",Ob.components={ColorPicker:rp,Menu:Bn,Composer:rg},Ob.props={onClick:Function,focusComposer:String,onComposerContentFocused:Function,dropdownMaxHeight:Number};class Mb{constructor(e){this.clipboard=e}async write(e){var t;try{null===(t=this.clipboard)||void 0===t||t.write(this.getClipboardItems(e))}catch(e){}}async writeText(e){var t;try{null===(t=this.clipboard)||void 0===t||t.writeText(e)}catch(e){}}async readText(){let e;try{e=await navigator.permissions.query({name:"clipboard-read"})}catch(e){}try{return{status:"ok",content:await this.clipboard.readText()}}catch(t){return{status:"denied"===(null==e?void 0:e.state)?"permissionDenied":"notImplemented"}}}getClipboardItems(e){return[new ClipboardItem({[fi.PlainText]:this.getBlob(e,fi.PlainText),[fi.Html]:this.getBlob(e,fi.Html)})]}getBlob(e,t){return new Blob([e[t]||""],{type:t})}}ii`
1954
+ `;class Mb extends t.Component{constructor(){super(...arguments),this.DEFAULT_FONT_SIZE=W,this.commonFormats=Ab,this.customFormats=Ob,this.currentFormatName="automatic",this.fontSizes=le,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.onExternalClick),t.onWillStart((()=>this.updateCellState())),t.onWillUpdateProps((()=>this.updateCellState()))}get topbarComponents(){return Ip.getAll().filter((e=>!e.isVisible||e.isVisible(this.env)))}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onClick(){this.props.onClick(),this.closeMenus()}toggleStyle(e){sr(this.env,{[e]:!this.style[e]})}toggleFormat(e){const t=Ab.find((t=>t.name===e)),o=t&&t.value||"";rr(this.env,o)}toggleAlign(e){sr(this.env,{align:e}),this.onClick()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.openMenu(e,t)}toggleDropdownTool(e,t){const o=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=o?"":e,this.openedEl=o?null:t.target}toggleContextMenu(e,t){this.state.menuState.isOpen?this.closeMenus():this.openMenu(e,t)}openMenu(e,t){const{left:o,top:i,height:n}=t.target.getBoundingClientRect();this.state.menuState.isOpen=!0,this.state.menuState.position={x:o,y:i+n},this.state.menuState.menuItems=Dn(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(),{col:t,row:o,sheetId:i}=this.env.model.getters.getActivePosition();this.inMerge=!1;const{top:n,left:r,right:s,bottom:a}=this.env.model.getters.getSelectedZone(),{xSplit:l,ySplit:c}=this.env.model.getters.getPaneDivisions(i);if(this.cannotMerge=e.length>1||n===a&&r===s||r<l&&l<=s||n<c&&c<=a,!this.cannotMerge){const n=this.env.model.getters.expandZone(i,Ko({col:t,row:o}));this.inMerge=Uo(e[0],n)}this.undoTool=this.env.model.getters.canUndo(),this.redoTool=this.env.model.getters.canRedo(),this.paintFormatTool=this.env.model.getters.isPaintingFormat();const h=this.env.model.getters.getActiveCell();if(h.format){const e=this.commonFormats.find((e=>e.value===h.format));this.currentFormatName=e?e.name:""}else this.currentFormatName="automatic";this.style={...this.env.model.getters.getCurrentStyle()},this.style.align=this.style.align||h.defaultAlign,this.fillColor=this.style.fillColor||"#ffffff",this.textColor=this.style.textColor||"#000000",this.menus=Kg.getAll()}getMenuName(e){return kn(e,this.env)}toggleMerge(){if(this.cannotMerge)return;const e=this.env.model.getters.getSelectedZones(),t=[e[e.length-1]],o=this.env.model.getters.getActiveSheetId();this.inMerge?this.env.model.dispatch("REMOVE_MERGE",{sheetId:o,target:t}):function(e,t,o){const i=e.model.dispatch("ADD_MERGE",{sheetId:t,target:o});i.isCancelledBecause(80)?e.raiseError(Tb.MergeInFilter):i.isCancelledBecause(3)&&e.askConfirmation(Tb.MergeIsDestructive,(()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:o,force:!0})}))}(this.env,o,t)}setColor(e,t){sr(this.env,{[e]:t}),this.onClick()}setBorder(e){this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),border:e}),this.onClick()}setFormat(e,t){t?this.openCustomFormatSidePanel(e):this.toggleFormat(e),this.onClick()}openCustomFormatSidePanel(e){const t=Ob.find((t=>t.name===e)),o=t&&t.sidePanel||"";this.env.openSidePanel(o)}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);sr(this.env,{fontSize:t}),this.onClick()}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!ei(...this.env.model.getters.getSelectedZones())}createFilter(){if(this.cannotCreateFilter)return;const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones();or(this.env,e,t)}removeFilter(){this.env.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}}Mb.template="o-spreadsheet-TopBar",Mb.components={ColorPicker:sp,Menu:Hn,Composer:sg},Mb.props={onClick:Function,focusComposer:String,onComposerContentFocused:Function,dropdownMaxHeight:Number};class Nb{constructor(e){this.clipboard=e}async write(e){var t;try{null===(t=this.clipboard)||void 0===t||t.write(this.getClipboardItems(e))}catch(e){}}async writeText(e){var t;try{null===(t=this.clipboard)||void 0===t||t.writeText(e)}catch(e){}}async readText(){let e;try{e=await navigator.permissions.query({name:"clipboard-read"})}catch(e){}try{return{status:"ok",content:await this.clipboard.readText()}}catch(t){return{status:"denied"===(null==e?void 0:e.state)?"permissionDenied":"notImplemented"}}}getClipboardItems(e){return[new ClipboardItem({[vi.PlainText]:this.getBlob(e,vi.PlainText),[vi.Html]:this.getBlob(e,vi.Html)})]}getBlob(e,t){return new Blob([e[t]||""],{type:t})}}ni`
1955
1955
  .o-spreadsheet {
1956
1956
  position: relative;
1957
1957
  display: grid;
@@ -1996,7 +1996,7 @@
1996
1996
  height: ${15}px;
1997
1997
  vertical-align: sub;
1998
1998
  }
1999
- `,ii`
1999
+ `,ni`
2000
2000
  .o-grid {
2001
2001
  position: relative;
2002
2002
  overflow: hidden;
@@ -2025,23 +2025,23 @@
2025
2025
  outline: none;
2026
2026
  }
2027
2027
  }
2028
- `;class Nb extends t.Component{constructor(){super(...arguments),this.isViewportTooSmall=!1}get model(){return this.props.model}getStyle(){return this.env.isDashboard()?"grid-template-rows: auto;":"grid-template-rows: 63px auto 37px"}setup(){this.sidePanel=t.useState({isOpen:!1,panelProps:{}}),this.composer=t.useState({topBarFocus:"inactive",gridFocusMode:"inactive"}),this.keyDownMapping={"CTRL+H":()=>this.toggleSidePanel("FindAndReplace",{}),"CTRL+F":()=>this.toggleSidePanel("FindAndReplace",{})};const e=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:e?new Eb(e):void 0,loadCurrencies:this.model.config.external.loadCurrencies,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.openSidePanel.bind(this),toggleSidePanel:this.toggleSidePanel.bind(this),_t:Nb._t,clipboard:this.env.clipboard||new Mb(navigator.clipboard)}),t.useExternalListener(window,"resize",(()=>this.render(!0))),t.useExternalListener(window,"beforeunload",this.unbindModelEvents.bind(this)),this.bindModelEvents(),t.onMounted((()=>{this.checkViewportSize()})),t.onWillUnmount((()=>this.unbindModelEvents())),t.onPatched((()=>{this.checkViewportSize()}))}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}bindModelEvents(){this.model.on("update",this,(()=>this.render(!0))),this.model.on("notify-ui",this,this.onNotifyUI)}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.env.notifyUser({text:r("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),tag:"viewportTooSmall"}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}onNotifyUI(e){if("ERROR"===e.type)this.env.raiseError(e.text)}openSidePanel(e,t){this.sidePanel.component=e,this.sidePanel.panelProps=t,this.sidePanel.isOpen=!0}closeSidePanel(){this.sidePanel.isOpen=!1,this.focusGrid()}toggleSidePanel(e,t){this.sidePanel.isOpen&&e===this.sidePanel.component?(this.sidePanel.isOpen=!1,this.focusGrid()):this.openSidePanel(e,t)}focusGrid(){if(!this._focusGrid)throw new Error("_focusGrid should be exposed by the grid component");this._focusGrid()}onKeydown(e){let t="";(e.ctrlKey||e.metaKey)&&(t+="CTRL+"),t+=e.key.toUpperCase();let o=this.keyDownMapping[t];if(o)return e.preventDefault(),e.stopPropagation(),void o()}onTopBarComposerFocused(e){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="contentFocus",this.composer.gridFocusMode="inactive",this.setComposerContent({selection:e}||{}))}onGridComposerContentFocused(){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="contentFocus",this.setComposerContent({}))}onGridComposerCellFocused(e,t){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="cellFocus",this.setComposerContent({content:e,selection:t}||{}))}setComposerContent({content:e,selection:t}){"inactive"===this.model.getters.getEditionMode()?this.model.dispatch("START_EDITION",{text:e,selection:t}):e&&this.model.dispatch("SET_CURRENT_CONTENT",{content:e,selection:t})}get gridHeight(){const{height:e}=this.env.model.getters.getSheetViewDimension();return e}}Nb.template="o-spreadsheet-Spreadsheet",Nb.components={TopBar:Ob,Grid:Wp,BottomBar:wb,SidePanel:Ib,SpreadsheetDashboard:xb},Nb._t=e=>e,Nb.props={model:Object};class _b{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 Fb(e){return Gg.get(e.type)(e)}function Db(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class kb{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 o of this.operations){if(o.id===e)return e;if(o.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const o=this.buildTransformation.with(e.data),{before:i,operation:n,after:r}=this.locateOperation(t);this.operations=[...i,n,e,...r.map((e=>e.transformed(o)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new kb(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:o}=this.locateOperation(e);this.operations=t.concat([o])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class $b{constructor(e,t){this.id=e,this.data=t}transformed(e){return new Pb(this.id,ot((()=>e(this.data))))}}class Pb{constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new Pb(this.id,this.lazyData.map(e))}}class Lb{constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new Lb(function*(e,t){for(const o of e)if(yield o,o.operation.id===t)return}(this.operations,e))}stopBefore(e){return new Lb(function*(e,t){for(const o of e){if(o.operation.id===t)return;yield o}}(this.operations,e))}startAfter(e){return new Lb(function*(e,t){let o=!0;for(const i of e)o||(yield i),i.operation.id===t&&(o=!1)}(this.operations,e))}}class Ub{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 Lb(Ve(this._execution(e),this._execution(e)))}revertedExecution(e){return new Lb(Ve(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){var o;const i=e.getLastOperationId()||(null===(o=this.previousBranch(e))||void 0===o?void 0:o.getLastOperationId());e.append(t),i&&this.insertPrevious(e,t,i)}insertOperationAfter(e,t,o){e.insert(t,o),this.updateNextWith(e,t,o),this.insertPrevious(e,t,o)}undo(e,t){const o=this.buildTransformation.without(t.data),i=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const n=e.fork(t.id);i&&this.branchingOperationIds.set(n,i),this.insertBranchAfter(e,n),this.transform(n,o)}redo(e){const t=this.nextBranch(e);if(!t)return;const o=this.nextBranch(t);this.removeBranchFromTree(t);const i=this.branchingOperationIds.get(t);i?this.branchingOperationIds.set(e,i):this.branchingOperationIds.delete(e),o&&this.rebaseUp(o)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const o of this.revertedExecution(e))if(o.operation.id===t)return o;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:o}=this.findPreviousBranchingOperation(e);if(!t||!o)return;const i=this.buildTransformation.without(o.data),n=t.fork(o.id);this.branchingOperationIds.set(n,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,n),n.transform(i);const r=this.nextBranch(n);r&&this.rebaseUp(r)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const o=this.branches.findIndex((t=>t===e));this.branches.splice(o+1,0,t)}updateNextWith(e,t,o){const i=this.branchingOperationIds.get(e),n=this.nextBranch(e);if(i&&n)if(e.getFirstOperationAmong(o,i)===i){const r=this.addToNextBranch(e,n,i,t,o);this.updateNextWith(n,r,o)}else{const e=this.buildTransformation.with(t.data);this.transform(n,e)}}addToNextBranch(e,t,o,i,n){let r=i;return n===o?(r=this.getTransformedOperation(e,o,i),t.prepend(r)):t.contains(n)?(r=this.getTransformedOperation(e,o,i),t.insert(r,n)):t.append(i),r}getTransformedOperation(e,t,o){const i=e.getOperation(t),n=this.buildTransformation.without(i.data);return o.transformed(n)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const o=this.nextBranch(e);o&&this.transform(o,t)}insertPrevious(e,t,o){const{previousBranch:i,branchingOperation:n}=this.findPreviousBranchingOperation(e);if(!i||!n)return;const r=this.buildTransformation.with(n.data),s=e.fork(o);s.transform(r),i.cutAfter(o),i.appendBranch(s);const a=t.transformed(r);this.insertPrevious(i,a,o)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const o=this.branchingOperationIds.get(t);return o?{previousBranch:t,branchingOperation:t.getOperation(o)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let o=!!t;const i=e.getOperations();for(let n=i.length-1;n>=0;n--){const r=i[n];r.id===t&&(o=!1),o||(yield{operation:r,branch:e,isCancelled:!this.shouldExecute(e,r)})}const n=this.previousBranch(e);yield*n?this._revertedExecution(n):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class Vb{constructor(e,t,o,i,n){this.applyOperation=t,this.revertOperation=o,this.buildEmpty=i,this.buildTransformation=n,this.HEAD_BRANCH=new kb(this.buildTransformation),this.tree=new Ub(n,this.HEAD_BRANCH);const r=new $b(e,i(e));this.tree.insertOperationLast(this.HEAD_BRANCH,r),this.HEAD_OPERATION=r}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const o=new $b(e,t),i=this.tree.getLastBranch();this.tree.insertOperationLast(i,o),this.HEAD_BRANCH=i,this.HEAD_OPERATION=o}insert(e,t,o){const i=new $b(e,t);this.revertTo(o),this.tree.insertOperationAfter(this.HEAD_BRANCH,i,o),this.fastForward()}undo(e,t,o){const{branch:i,operation:n}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(i,n),this.fastForward(),this.insert(t,this.buildEmpty(t),o)}redo(e,t,o){const{branch:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(i),this.fastForward(),this.insert(t,this.buildEmpty(t),o)}drop(e){this.revertBefore(e),this.tree.drop(e)}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:o,isCancelled:i}of e)i||this.revertOperation(o.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:o,isCancelled:i}of e)i||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=o}}function zb(e,t,o){return new Vb(e,(e=>{const i=e.commands.slice(),{changes:n}=t((()=>{for(const e of i)o(e)}));e.setChanges(n)}),(e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){Bb(t.changes[e],"before")}}([e])),(e=>new Jv(e,"empty",[],[])),{with:e=>t=>new Jv(t.id,t.clientId,Kv(t.commands,e.commands)),without:e=>t=>new Jv(t.id,t.clientId,Kv(t.commands,e.commands.map(Fb).flat()))})}function Bb(e,t){let o=e.root,i=e.path[e.path.length-1];for(let t=0;t<e.path.slice(0,-1).length;t++){const i=e.path[t];if(void 0===o[i]){const n=e.path[t+1];o[i]=Db(n)}o=o[i]}void 0===e[t]?delete o[i]:o[i]=e[t]}class Hb extends t.EventBus{constructor(e,t){super(),this.dispatch=e,this.session=t,this.undoStack=[],this.redoStack=[],this.session.on("new-local-state-update",this,this.onNewLocalStateUpdate),this.session.on("revision-undone",this,(({commands:e})=>this.selectiveUndo(e))),this.session.on("revision-redone",this,(({commands:e})=>this.selectiveRedo(e))),this.session.on("pending-revisions-dropped",this,(({revisionIds:e})=>this.drop(e))),this.session.on("snapshot",this,(()=>{this.undoStack=[],this.redoStack=[]}))}allowDispatch(e){switch(e.type){case"REQUEST_UNDO":if(!this.canUndo())return 6;break;case"REQUEST_REDO":if(!this.canRedo())return 7}return 0}beforeHandle(e){}handle(e){switch(e.type){case"REQUEST_UNDO":case"REQUEST_REDO":this.requestHistoryChange("REQUEST_UNDO"===e.type?"UNDO":"REDO")}}finalize(){}requestHistoryChange(e){const t="UNDO"===e?this.undoStack.pop():this.redoStack.pop();t&&("UNDO"===e?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t)))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}drop(e){this.undoStack=this.undoStack.filter((t=>!e.includes(t))),this.redoStack=[]}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}selectiveUndo(e){this.dispatch("UNDO",{commands:e})}selectiveRedo(e){this.dispatch("REDO",{commands:e})}}class Wb{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 o,i,n;if(this.observers.find((t=>t.owner===e)))throw new Error("You are already subscribed forever");(null===(o=this.mainSubscription)||void 0===o?void 0:o.owner)&&(null===(n=(i=this.mainSubscription.callbacks).release)||void 0===n||n.call(i)),this.mainSubscription={owner:e,callbacks:t}}release(e){var t,o,i,n;(null===(t=this.mainSubscription)||void 0===t?void 0:t.owner)!==e||this.observers.find((t=>t.owner===e))||(null===(n=null===(o=this.mainSubscription)||void 0===o?void 0:(i=o.callbacks).release)||void 0===n||n.call(i),this.mainSubscription=this.defaultSubscription)}getBackToDefault(){var e,t,o;this.mainSubscription!==this.defaultSubscription&&(null===(o=null===(e=this.mainSubscription)||void 0===e?void 0:(t=e.callbacks).release)||void 0===o||o.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 Gb{constructor(e){this.getters=e,this.stream=new Wb,this.anchor={cell:{col:0,row:0},zone:Yo({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,o){this.stream.capture(e,o),this.anchor=t}registerAsDefault(e,t,o){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,o),this.defaultAnchor=t,this.capture(e,t,o)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}selectZone(e,t="overrideSelection"){const o=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(o,e.zone)},this.processEvent({type:"ZonesSelected",anchor:e,mode:t})}selectCell(e,t){const o=Yo({col:e,row:t});return this.selectZone({zone:o,cell:{col:e,row:t}})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new wi(83);const{col:o,row:i}=this.getNextAvailablePosition(e,t);return this.selectCell(o,i)}setAnchorCorner(e,t){const o=this.getters.getActiveSheetId(),{col:i,row:n}=this.anchor.cell,r={left:Math.min(i,e),top:Math.min(n,t),right:Math.max(i,e),bottom:Math.max(n,t)},s={zone:this.getters.expandZone(o,r),cell:{col:i,row:n}};return this.processEvent({type:"AlterZoneCorner",mode:"updateAnchor",anchor:s})}addCellToSelection(e,t){const o=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:o,col:e,row:t}));const i=this.getters.expandZone(o,Yo({col:e,row:t}));return this.processEvent({type:"ZonesSelected",anchor:{zone:i,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new wi(83);const o=this.getters.getActiveSheetId(),i=this.anchor,{col:n,row:r}=i.cell,{left:s,right:a,top:l,bottom:c}=i.zone,h=this.getStartingPosition(e);let[d,u]=this.deltaToTarget(h,e,t);if(0===d&&0===u)return wi.Success;let g=i.zone;const p=e=>{e=Xo(e);const{left:t,right:i,top:n,bottom:r}=this.getters.expandZone(o,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(o)-1,i),top:Math.max(0,n),bottom:Math.min(this.getters.getNumberRows(o)-1,r)}},{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:s,bottom:c,right:e}):null}if(d>0){const e=this.getNextAvailableCol(d,s+(v-1),f);g=s+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:s,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:s,bottom:c,right:a}):null}if(g=g?Xo(g):g,g&&!Lo(g,i.zone))return this.processEvent({type:"ZonesSelected",mode:"updateAnchor",anchor:{zone:g,cell:{col:n,row:r}}})}g=p($o({top:r,bottom:r,left:n,right:n},Xo({top:this.getNextAvailableRow(u,m,l),left:this.getNextAvailableCol(d,s,f),bottom:this.getNextAvailableRow(u,m,c),right:this.getNextAvailableCol(d,a,f)})));const b={zone:g,cell:{col:n,row:r}};return this.processEvent({type:"ZonesSelected",anchor:b,mode:"updateAnchor"})}selectColumn(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.getNumberRows(o)-1;let n={left:e,right:e,top:0,bottom:i};const r=this.getters.findFirstVisibleColRowIndex(o,"ROW");let s,a;switch(t){case"overrideSelection":case"newAnchor":s=e,a=r;break;case"updateAnchor":({col:s,row:a}=this.anchor.cell),n=$o(n,{left:s,right:s,top:r,bottom:i})}return this.processEvent({type:"HeadersSelected",anchor:{zone:n,cell:{col:s,row:a}},mode:t})}selectRow(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.getNumberCols(o)-1;let n={top:e,bottom:e,left:0,right:i};const r=this.getters.findFirstVisibleColRowIndex(o,"COL");let s,a;switch(t){case"overrideSelection":case"newAnchor":s=r,a=e;break;case"updateAnchor":({col:s,row:a}=this.anchor.cell),n=$o(n,{left:r,right:i,top:a,bottom:a})}return this.processEvent({type:"HeadersSelected",anchor:{zone:n,cell:{col:s,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(Lo(this.anchor.zone,this.getters.getSheetZone(e)))return this.selectZone({...t,zone:Yo(t.cell)});const o=this.expandZoneToTable(t.zone);return rt(o,t.zone)?this.selectAll():this.selectZone({...t,zone:o})}selectTableAroundSelection(){const e=this.expandZoneToTable(this.anchor.zone);return this.selectZone({...this.anchor,zone:e},"updateAnchor")}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}})}processEvent(e){const t={...e,previousAnchor:Me(this.anchor)},o=this.checkEventAnchorZone(t);return 0!==o?new wi(o):(this.anchor=t.anchor,this.stream.send(t),wi.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:o}=e;if(!Vo(t.col,t.row,o))return 16;const{left:i,right:n,top:r,bottom:s}=o,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",i,n);return void 0===this.getters.findVisibleHeader(a,"ROW",r,s)||void 0===l?17:0}checkAnchorZoneOrThrow(e){if(16===this.checkAnchorZone(e))throw new Error(n("The provided anchor is invalid. The cell must be part of the zone."))}getNextAvailablePosition(e,t=1){const{col:o,row:i}=this.anchor.cell,n=this.deltaToTarget({col:o,row:i},e,t);return{col:this.getNextAvailableCol(n[0],o,i),row:this.getNextAvailableRow(n[1],o,i)}}getNextAvailableCol(e,t,o){const i=this.getters.getActiveSheetId(),n={col:t,row:o};return this.getNextAvailableHeader(e,"COL",t,n,(e=>this.getters.isInSameMerge(i,t,o,e,o)))}getNextAvailableRow(e,t,o){const i=this.getters.getActiveSheetId(),n={col:t,row:o};return this.getNextAvailableHeader(e,"ROW",o,n,(e=>this.getters.isInSameMerge(i,t,o,t,e)))}getNextAvailableHeader(e,t,o,i,n){const r=this.getters.getActiveSheetId();if(0===e)return o;const s=Math.sign(e);let a=o+e;for(;n(a);)a+=s;for(;this.getters.isHeaderHidden(r,t,a);)a+=s;return a<0||a>this.getters.getNumberHeaders(r,t)-1?this.getters.isHeaderHidden(r,t,o)?this.getNextAvailableHeader(-s,t,o,i,n):o:a}getReferencePosition(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:o,right:i,top:n,bottom:r}=t.zone,{col:s,row:a}=t.cell;return{col:this.getters.isColHidden(e,s)&&this.getters.findVisibleHeader(e,"COL",o,i)||s,row:this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",n,r)||a}}deltaToTarget(e,t,o){switch(t){case"up":return"end"!==o?[0,-o]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==o?[0,o]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==o?[-o,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==o?[o,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:o}=this.getPosition();const i=this.anchor.zone;switch(e){case"down":case"up":o=o===i.top?i.bottom:i.top;break;case"left":case"right":t=t===i.right?i.left:i.right}return{col:t,row:o}}getEndOfCluster(e,t,o){const i=this.getters.getActiveSheet();let n=e;const r=this.getNextCellPosition(e,t,o);let s=this.isCellEmpty(n,i.id)||this.isCellEmpty(r,i.id)?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(n,t,o);if(n.col===e.col&&n.row===e.row)break;const r=this.isCellEmpty(e,i.id);if("endOfCluster"===s&&r)break;if("nextCluster"===s&&!r){n=e;break}n=e}return"cols"===t?n.col:n.row}isCellEmpty({col:e,row:t},o=this.getters.getActiveSheetId()){const i=this.getters.getMainCellPosition({sheetId:o,col:e,row:t});return this.getters.getEvaluatedCell(i).type===mi.empty}getNextCellPosition(e,t,o){const i="cols"===t?"col":"row",n={...e},r="cols"===t?this.getNextAvailableCol(o,n.col,n.row):this.getNextAvailableRow(o,n.col,n.row);return n[i]=r,{col:n.col,row:n.row}}getPosition(){return{...this.anchor.cell}}expandZoneToTable(e){const t=e=>{for(const t of Le(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 Le(e.top,e.bottom+1)){if(!this.isCellEmpty({col:e.left-1,row:t}))return{...e,left:e.left-1};if(!this.isCellEmpty({col:e.right+1,row:t}))return{...e,right:e.right+1}}return e};let o=!1,i=e;do{o=!1;const e=t(i);Lo(i,e)||(o=!0,i=e)}while(o);return i}}class qb{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(),[o,...i]=e;let n=o,r=i[i.length-1];for(let e=0;e<=i.length-2;e++){const t=i[e];if(void 0===n[t]){const o=i[e+1];n[t]=Db(o)}n=n[t]}n[r]!==t&&(this.changes.push({root:o,path:i,before:n[r],after:t}),void 0===t?delete n[r]:n[r]=t)}}const Zb=17781237,jb=88853993;function Xb(e,t,o){const i=[["xmlns:r",em],["xmlns:a",Yp],["xmlns:c",Kp]],n=Yb({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let r=kf``;e.data.title&&(r=kf`
2028
+ `;class _b extends t.Component{constructor(){super(...arguments),this.isViewportTooSmall=!1}get model(){return this.props.model}getStyle(){return this.env.isDashboard()?"grid-template-rows: auto;":"grid-template-rows: 63px auto 37px"}setup(){this.sidePanel=t.useState({isOpen:!1,panelProps:{}}),this.composer=t.useState({topBarFocus:"inactive",gridFocusMode:"inactive"}),this.keyDownMapping={"CTRL+H":()=>this.toggleSidePanel("FindAndReplace",{}),"CTRL+F":()=>this.toggleSidePanel("FindAndReplace",{})};const e=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:e?new wb(e):void 0,loadCurrencies:this.model.config.external.loadCurrencies,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.openSidePanel.bind(this),toggleSidePanel:this.toggleSidePanel.bind(this),_t:_b._t,clipboard:this.env.clipboard||new Nb(navigator.clipboard)}),t.useExternalListener(window,"resize",(()=>this.render(!0))),t.useExternalListener(window,"beforeunload",this.unbindModelEvents.bind(this)),this.bindModelEvents(),t.onMounted((()=>{this.checkViewportSize()})),t.onWillUnmount((()=>this.unbindModelEvents())),t.onPatched((()=>{this.checkViewportSize()}))}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}bindModelEvents(){this.model.on("update",this,(()=>this.render(!0))),this.model.on("notify-ui",this,this.onNotifyUI)}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.env.notifyUser({text:r("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),tag:"viewportTooSmall"}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}onNotifyUI(e){if("ERROR"===e.type)this.env.raiseError(e.text)}openSidePanel(e,t){this.sidePanel.component=e,this.sidePanel.panelProps=t,this.sidePanel.isOpen=!0}closeSidePanel(){this.sidePanel.isOpen=!1,this.focusGrid()}toggleSidePanel(e,t){this.sidePanel.isOpen&&e===this.sidePanel.component?(this.sidePanel.isOpen=!1,this.focusGrid()):this.openSidePanel(e,t)}focusGrid(){if(!this._focusGrid)throw new Error("_focusGrid should be exposed by the grid component");this._focusGrid()}onKeydown(e){let t="";(e.ctrlKey||e.metaKey)&&(t+="CTRL+"),t+=e.key.toUpperCase();let o=this.keyDownMapping[t];if(o)return e.preventDefault(),e.stopPropagation(),void o()}onTopBarComposerFocused(e){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="contentFocus",this.composer.gridFocusMode="inactive",this.setComposerContent({selection:e}||{}))}onGridComposerContentFocused(){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="contentFocus",this.setComposerContent({}))}onGridComposerCellFocused(e,t){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="cellFocus",this.setComposerContent({content:e,selection:t}||{}))}setComposerContent({content:e,selection:t}){"inactive"===this.model.getters.getEditionMode()?this.model.dispatch("START_EDITION",{text:e,selection:t}):e&&this.model.dispatch("SET_CURRENT_CONTENT",{content:e,selection:t})}get gridHeight(){const{height:e}=this.env.model.getters.getSheetViewDimension();return e}}_b.template="o-spreadsheet-Spreadsheet",_b.components={TopBar:Mb,Grid:Gp,BottomBar:yb,SidePanel:Rb,SpreadsheetDashboard:Ib},_b._t=e=>e,_b.props={model:Object};class Fb{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 Db(e){return qg.get(e.type)(e)}function kb(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class $b{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 o of this.operations){if(o.id===e)return e;if(o.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const o=this.buildTransformation.with(e.data),{before:i,operation:n,after:r}=this.locateOperation(t);this.operations=[...i,n,e,...r.map((e=>e.transformed(o)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new $b(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:o}=this.locateOperation(e);this.operations=t.concat([o])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class Pb{constructor(e,t){this.id=e,this.data=t}transformed(e){return new Lb(this.id,it((()=>e(this.data))))}}class Lb{constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new Lb(this.id,this.lazyData.map(e))}}class Ub{constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new Ub(function*(e,t){for(const o of e)if(yield o,o.operation.id===t)return}(this.operations,e))}stopBefore(e){return new Ub(function*(e,t){for(const o of e){if(o.operation.id===t)return;yield o}}(this.operations,e))}startAfter(e){return new Ub(function*(e,t){let o=!0;for(const i of e)o||(yield i),i.operation.id===t&&(o=!1)}(this.operations,e))}}class Vb{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 Ub(ze(this._execution(e),this._execution(e)))}revertedExecution(e){return new Ub(ze(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){var o;const i=e.getLastOperationId()||(null===(o=this.previousBranch(e))||void 0===o?void 0:o.getLastOperationId());e.append(t),i&&this.insertPrevious(e,t,i)}insertOperationAfter(e,t,o){e.insert(t,o),this.updateNextWith(e,t,o),this.insertPrevious(e,t,o)}undo(e,t){const o=this.buildTransformation.without(t.data),i=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const n=e.fork(t.id);i&&this.branchingOperationIds.set(n,i),this.insertBranchAfter(e,n),this.transform(n,o)}redo(e){const t=this.nextBranch(e);if(!t)return;const o=this.nextBranch(t);this.removeBranchFromTree(t);const i=this.branchingOperationIds.get(t);i?this.branchingOperationIds.set(e,i):this.branchingOperationIds.delete(e),o&&this.rebaseUp(o)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const o of this.revertedExecution(e))if(o.operation.id===t)return o;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:o}=this.findPreviousBranchingOperation(e);if(!t||!o)return;const i=this.buildTransformation.without(o.data),n=t.fork(o.id);this.branchingOperationIds.set(n,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,n),n.transform(i);const r=this.nextBranch(n);r&&this.rebaseUp(r)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const o=this.branches.findIndex((t=>t===e));this.branches.splice(o+1,0,t)}updateNextWith(e,t,o){const i=this.branchingOperationIds.get(e),n=this.nextBranch(e);if(i&&n)if(e.getFirstOperationAmong(o,i)===i){const r=this.addToNextBranch(e,n,i,t,o);this.updateNextWith(n,r,o)}else{const e=this.buildTransformation.with(t.data);this.transform(n,e)}}addToNextBranch(e,t,o,i,n){let r=i;return n===o?(r=this.getTransformedOperation(e,o,i),t.prepend(r)):t.contains(n)?(r=this.getTransformedOperation(e,o,i),t.insert(r,n)):t.append(i),r}getTransformedOperation(e,t,o){const i=e.getOperation(t),n=this.buildTransformation.without(i.data);return o.transformed(n)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const o=this.nextBranch(e);o&&this.transform(o,t)}insertPrevious(e,t,o){const{previousBranch:i,branchingOperation:n}=this.findPreviousBranchingOperation(e);if(!i||!n)return;const r=this.buildTransformation.with(n.data),s=e.fork(o);s.transform(r),i.cutAfter(o),i.appendBranch(s);const a=t.transformed(r);this.insertPrevious(i,a,o)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const o=this.branchingOperationIds.get(t);return o?{previousBranch:t,branchingOperation:t.getOperation(o)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let o=!!t;const i=e.getOperations();for(let n=i.length-1;n>=0;n--){const r=i[n];r.id===t&&(o=!1),o||(yield{operation:r,branch:e,isCancelled:!this.shouldExecute(e,r)})}const n=this.previousBranch(e);yield*n?this._revertedExecution(n):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class zb{constructor(e,t,o,i,n){this.applyOperation=t,this.revertOperation=o,this.buildEmpty=i,this.buildTransformation=n,this.HEAD_BRANCH=new $b(this.buildTransformation),this.tree=new Vb(n,this.HEAD_BRANCH);const r=new Pb(e,i(e));this.tree.insertOperationLast(this.HEAD_BRANCH,r),this.HEAD_OPERATION=r}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const o=new Pb(e,t),i=this.tree.getLastBranch();this.tree.insertOperationLast(i,o),this.HEAD_BRANCH=i,this.HEAD_OPERATION=o}insert(e,t,o){const i=new Pb(e,t);this.revertTo(o),this.tree.insertOperationAfter(this.HEAD_BRANCH,i,o),this.fastForward()}undo(e,t,o){const{branch:i,operation:n}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(i,n),this.fastForward(),this.insert(t,this.buildEmpty(t),o)}redo(e,t,o){const{branch:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(i),this.fastForward(),this.insert(t,this.buildEmpty(t),o)}drop(e){this.revertBefore(e),this.tree.drop(e)}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:o,isCancelled:i}of e)i||this.revertOperation(o.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:o,isCancelled:i}of e)i||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=o}}function Bb(e,t,o){return new zb(e,(e=>{const i=e.commands.slice(),{changes:n}=t((()=>{for(const e of i)o(e)}));e.setChanges(n)}),(e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){Hb(t.changes[e],"before")}}([e])),(e=>new eb(e,"empty",[],[])),{with:e=>t=>new eb(t.id,t.clientId,Qv(t.commands,e.commands)),without:e=>t=>new eb(t.id,t.clientId,Qv(t.commands,e.commands.map(Db).flat()))})}function Hb(e,t){let o=e.root,i=e.path[e.path.length-1];for(let t=0;t<e.path.slice(0,-1).length;t++){const i=e.path[t];if(void 0===o[i]){const n=e.path[t+1];o[i]=kb(n)}o=o[i]}void 0===e[t]?delete o[i]:o[i]=e[t]}class Wb extends t.EventBus{constructor(e,t){super(),this.dispatch=e,this.session=t,this.undoStack=[],this.redoStack=[],this.session.on("new-local-state-update",this,this.onNewLocalStateUpdate),this.session.on("revision-undone",this,(({commands:e})=>this.selectiveUndo(e))),this.session.on("revision-redone",this,(({commands:e})=>this.selectiveRedo(e))),this.session.on("pending-revisions-dropped",this,(({revisionIds:e})=>this.drop(e))),this.session.on("snapshot",this,(()=>{this.undoStack=[],this.redoStack=[]}))}allowDispatch(e){switch(e.type){case"REQUEST_UNDO":if(!this.canUndo())return 6;break;case"REQUEST_REDO":if(!this.canRedo())return 7}return 0}beforeHandle(e){}handle(e){switch(e.type){case"REQUEST_UNDO":case"REQUEST_REDO":this.requestHistoryChange("REQUEST_UNDO"===e.type?"UNDO":"REDO")}}finalize(){}requestHistoryChange(e){const t="UNDO"===e?this.undoStack.pop():this.redoStack.pop();t&&("UNDO"===e?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t)))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}drop(e){this.undoStack=this.undoStack.filter((t=>!e.includes(t))),this.redoStack=[]}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}selectiveUndo(e){this.dispatch("UNDO",{commands:e})}selectiveRedo(e){this.dispatch("REDO",{commands:e})}}class Gb{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 o,i,n;if(this.observers.find((t=>t.owner===e)))throw new Error("You are already subscribed forever");(null===(o=this.mainSubscription)||void 0===o?void 0:o.owner)&&(null===(n=(i=this.mainSubscription.callbacks).release)||void 0===n||n.call(i)),this.mainSubscription={owner:e,callbacks:t}}release(e){var t,o,i,n;(null===(t=this.mainSubscription)||void 0===t?void 0:t.owner)!==e||this.observers.find((t=>t.owner===e))||(null===(n=null===(o=this.mainSubscription)||void 0===o?void 0:(i=o.callbacks).release)||void 0===n||n.call(i),this.mainSubscription=this.defaultSubscription)}getBackToDefault(){var e,t,o;this.mainSubscription!==this.defaultSubscription&&(null===(o=null===(e=this.mainSubscription)||void 0===e?void 0:(t=e.callbacks).release)||void 0===o||o.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 qb{constructor(e){this.getters=e,this.stream=new Gb,this.anchor={cell:{col:0,row:0},zone:Ko({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,o){this.stream.capture(e,o),this.anchor=t}registerAsDefault(e,t,o){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,o),this.defaultAnchor=t,this.capture(e,t,o)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}selectZone(e,t="overrideSelection"){const o=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(o,e.zone)},this.processEvent({type:"ZonesSelected",anchor:e,mode:t})}selectCell(e,t){const o=Ko({col:e,row:t});return this.selectZone({zone:o,cell:{col:e,row:t}})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new yi(83);const{col:o,row:i}=this.getNextAvailablePosition(e,t);return this.selectCell(o,i)}setAnchorCorner(e,t){const o=this.getters.getActiveSheetId(),{col:i,row:n}=this.anchor.cell,r={left:Math.min(i,e),top:Math.min(n,t),right:Math.max(i,e),bottom:Math.max(n,t)},s={zone:this.getters.expandZone(o,r),cell:{col:i,row:n}};return this.processEvent({type:"AlterZoneCorner",mode:"updateAnchor",anchor:s})}addCellToSelection(e,t){const o=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:o,col:e,row:t}));const i=this.getters.expandZone(o,Ko({col:e,row:t}));return this.processEvent({type:"ZonesSelected",anchor:{zone:i,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new yi(83);const o=this.getters.getActiveSheetId(),i=this.anchor,{col:n,row:r}=i.cell,{left:s,right:a,top:l,bottom:c}=i.zone,h=this.getStartingPosition(e);let[d,u]=this.deltaToTarget(h,e,t);if(0===d&&0===u)return yi.Success;let g=i.zone;const p=e=>{e=Yo(e);const{left:t,right:i,top:n,bottom:r}=this.getters.expandZone(o,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(o)-1,i),top:Math.max(0,n),bottom:Math.min(this.getters.getNumberRows(o)-1,r)}},{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:s,bottom:c,right:e}):null}if(d>0){const e=this.getNextAvailableCol(d,s+(v-1),f);g=s+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:s,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:s,bottom:c,right:a}):null}if(g=g?Yo(g):g,g&&!Uo(g,i.zone))return this.processEvent({type:"ZonesSelected",mode:"updateAnchor",anchor:{zone:g,cell:{col:n,row:r}}})}g=p(Po({top:r,bottom:r,left:n,right:n},Yo({top:this.getNextAvailableRow(u,m,l),left:this.getNextAvailableCol(d,s,f),bottom:this.getNextAvailableRow(u,m,c),right:this.getNextAvailableCol(d,a,f)})));const b={zone:g,cell:{col:n,row:r}};return this.processEvent({type:"ZonesSelected",anchor:b,mode:"updateAnchor"})}selectColumn(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.getNumberRows(o)-1;let n={left:e,right:e,top:0,bottom:i};const r=this.getters.findFirstVisibleColRowIndex(o,"ROW");let s,a;switch(t){case"overrideSelection":case"newAnchor":s=e,a=r;break;case"updateAnchor":({col:s,row:a}=this.anchor.cell),n=Po(n,{left:s,right:s,top:r,bottom:i})}return this.processEvent({type:"HeadersSelected",anchor:{zone:n,cell:{col:s,row:a}},mode:t})}selectRow(e,t){const o=this.getters.getActiveSheetId(),i=this.getters.getNumberCols(o)-1;let n={top:e,bottom:e,left:0,right:i};const r=this.getters.findFirstVisibleColRowIndex(o,"COL");let s,a;switch(t){case"overrideSelection":case"newAnchor":s=r,a=e;break;case"updateAnchor":({col:s,row:a}=this.anchor.cell),n=Po(n,{left:r,right:i,top:a,bottom:a})}return this.processEvent({type:"HeadersSelected",anchor:{zone:n,cell:{col:s,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(Uo(this.anchor.zone,this.getters.getSheetZone(e)))return this.selectZone({...t,zone:Ko(t.cell)});const o=this.expandZoneToTable(t.zone);return st(o,t.zone)?this.selectAll():this.selectZone({...t,zone:o})}selectTableAroundSelection(){const e=this.expandZoneToTable(this.anchor.zone);return this.selectZone({...this.anchor,zone:e},"updateAnchor")}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}})}processEvent(e){const t={...e,previousAnchor:Me(this.anchor)},o=this.checkEventAnchorZone(t);return 0!==o?new yi(o):(this.anchor=t.anchor,this.stream.send(t),yi.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:o}=e;if(!zo(t.col,t.row,o))return 16;const{left:i,right:n,top:r,bottom:s}=o,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",i,n);return void 0===this.getters.findVisibleHeader(a,"ROW",r,s)||void 0===l?17:0}checkAnchorZoneOrThrow(e){if(16===this.checkAnchorZone(e))throw new Error(n("The provided anchor is invalid. The cell must be part of the zone."))}getNextAvailablePosition(e,t=1){const{col:o,row:i}=this.anchor.cell,n=this.deltaToTarget({col:o,row:i},e,t);return{col:this.getNextAvailableCol(n[0],o,i),row:this.getNextAvailableRow(n[1],o,i)}}getNextAvailableCol(e,t,o){const i=this.getters.getActiveSheetId(),n={col:t,row:o};return this.getNextAvailableHeader(e,"COL",t,n,(e=>this.getters.isInSameMerge(i,t,o,e,o)))}getNextAvailableRow(e,t,o){const i=this.getters.getActiveSheetId(),n={col:t,row:o};return this.getNextAvailableHeader(e,"ROW",o,n,(e=>this.getters.isInSameMerge(i,t,o,t,e)))}getNextAvailableHeader(e,t,o,i,n){const r=this.getters.getActiveSheetId();if(0===e)return o;const s=Math.sign(e);let a=o+e;for(;n(a);)a+=s;for(;this.getters.isHeaderHidden(r,t,a);)a+=s;return a<0||a>this.getters.getNumberHeaders(r,t)-1?this.getters.isHeaderHidden(r,t,o)?this.getNextAvailableHeader(-s,t,o,i,n):o:a}getReferencePosition(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:o,right:i,top:n,bottom:r}=t.zone,{col:s,row:a}=t.cell;return{col:this.getters.isColHidden(e,s)&&this.getters.findVisibleHeader(e,"COL",o,i)||s,row:this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",n,r)||a}}deltaToTarget(e,t,o){switch(t){case"up":return"end"!==o?[0,-o]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==o?[0,o]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==o?[-o,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==o?[o,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:o}=this.getPosition();const i=this.anchor.zone;switch(e){case"down":case"up":o=o===i.top?i.bottom:i.top;break;case"left":case"right":t=t===i.right?i.left:i.right}return{col:t,row:o}}getEndOfCluster(e,t,o){const i=this.getters.getActiveSheet();let n=e;const r=this.getNextCellPosition(e,t,o);let s=this.isCellEmpty(n,i.id)||this.isCellEmpty(r,i.id)?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(n,t,o);if(n.col===e.col&&n.row===e.row)break;const r=this.isCellEmpty(e,i.id);if("endOfCluster"===s&&r)break;if("nextCluster"===s&&!r){n=e;break}n=e}return"cols"===t?n.col:n.row}isCellEmpty({col:e,row:t},o=this.getters.getActiveSheetId()){const i=this.getters.getMainCellPosition({sheetId:o,col:e,row:t});return this.getters.getEvaluatedCell(i).type===fi.empty}getNextCellPosition(e,t,o){const i="cols"===t?"col":"row",n={...e},r="cols"===t?this.getNextAvailableCol(o,n.col,n.row):this.getNextAvailableRow(o,n.col,n.row);return n[i]=r,{col:n.col,row:n.row}}getPosition(){return{...this.anchor.cell}}expandZoneToTable(e){const t=e=>{for(const t of Ue(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 Ue(e.top,e.bottom+1)){if(!this.isCellEmpty({col:e.left-1,row:t}))return{...e,left:e.left-1};if(!this.isCellEmpty({col:e.right+1,row:t}))return{...e,right:e.right+1}}return e};let o=!1,i=e;do{o=!1;const e=t(i);Uo(i,e)||(o=!0,i=e)}while(o);return i}}class Zb{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(),[o,...i]=e;let n=o,r=i[i.length-1];for(let e=0;e<=i.length-2;e++){const t=i[e];if(void 0===n[t]){const o=i[e+1];n[t]=kb(o)}n=n[t]}n[r]!==t&&(this.changes.push({root:o,path:i,before:n[r],after:t}),void 0===t?delete n[r]:n[r]=t)}}const jb=17781237,Xb=88853993;function Yb(e,t,o){const i=[["xmlns:r",tm],["xmlns:a",Kp],["xmlns:c",Qp]],n=Kb({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let r=$f``;e.data.title&&(r=$f`
2029
2029
  <c:title>
2030
- ${Qb(e.data.title,e.data.fontColor)}
2030
+ ${Jb(e.data.title,e.data.fontColor)}
2031
2031
  <c:overlay val="0" />
2032
2032
  </c:title>
2033
- `);let s=kf``;switch(e.data.type){case"bar":s=function(e){const t=new ki,o=[];for(const[i,n]of Object.entries(e.dataSets)){const r=ui(t.next()),s=Yb({backgroundColor:r,line:{color:r}});o.push(kf`
2033
+ `);let s=$f``;switch(e.data.type){case"bar":s=function(e){const t=new $i,o=[];for(const[i,n]of Object.entries(e.dataSets)){const r=gi(t.next()),s=Kb({backgroundColor:r,line:{color:r}});o.push($f`
2034
2034
  <c:ser>
2035
2035
  <c:idx val="${i}"/>
2036
2036
  <c:order val="${i}"/>
2037
- ${n.label?kf`<c:tx>${oC(n.label)}</c:tx>`:""}
2037
+ ${n.label?$f`<c:tx>${iC(n.label)}</c:tx>`:""}
2038
2038
  ${s}
2039
- ${e.labelRange?kf`<c:cat>${oC(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
2039
+ ${e.labelRange?$f`<c:cat>${iC(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
2040
2040
  <c:val> <!-- x-coordinate values -->
2041
- ${iC(n.range)}
2041
+ ${nC(n.range)}
2042
2042
  </c:val>
2043
2043
  </c:ser>
2044
- `)}const i="left"===e.verticalAxisPosition?"l":"r",n=e.stacked?"stacked":"clustered",r=e.stacked?100:-20;return kf`
2044
+ `)}const i="left"===e.verticalAxisPosition?"l":"r",n=e.stacked?"stacked":"clustered",r=e.stacked?100:-20;return $f`
2045
2045
  <c:barChart>
2046
2046
  <c:barDir val="col"/>
2047
2047
  <c:grouping val="${n}"/>
@@ -2049,13 +2049,13 @@
2049
2049
  <c:gapWidth val="70"/>
2050
2050
  <!-- each data marker in the series does not have a different color -->
2051
2051
  <c:varyColors val="0"/>
2052
- ${Df(o)}
2053
- <c:axId val="${Zb}" />
2052
+ ${kf(o)}
2054
2053
  <c:axId val="${jb}" />
2054
+ <c:axId val="${Xb}" />
2055
2055
  </c:barChart>
2056
- ${tC("b","c:catAx",Zb,jb,{fontColor:e.fontColor})}
2057
- ${tC(i,"c:valAx",jb,Zb,{fontColor:e.fontColor})}
2058
- `}(e.data);break;case"line":s=function(e){const t=new ki,o=[];for(const[i,n]of Object.entries(e.dataSets)){const r=Yb({line:{width:2.5,style:"solid",color:ui(t.next())}});o.push(kf`
2056
+ ${oC("b","c:catAx",jb,Xb,{fontColor:e.fontColor})}
2057
+ ${oC(i,"c:valAx",Xb,jb,{fontColor:e.fontColor})}
2058
+ `}(e.data);break;case"line":s=function(e){const t=new $i,o=[];for(const[i,n]of Object.entries(e.dataSets)){const r=Kb({line:{width:2.5,style:"solid",color:gi(t.next())}});o.push($f`
2059
2059
  <c:ser>
2060
2060
  <c:idx val="${i}"/>
2061
2061
  <c:order val="${i}"/>
@@ -2064,50 +2064,50 @@
2064
2064
  <c:symbol val="circle" />
2065
2065
  <c:size val="5"/>
2066
2066
  </c:marker>
2067
- ${n.label?kf`<c:tx>${oC(n.label)}</c:tx>`:""}
2067
+ ${n.label?$f`<c:tx>${iC(n.label)}</c:tx>`:""}
2068
2068
  ${r}
2069
- ${e.labelRange?kf`<c:cat>${oC(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
2069
+ ${e.labelRange?$f`<c:cat>${iC(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
2070
2070
  <c:val> <!-- x-coordinate values -->
2071
- ${iC(n.range)}
2071
+ ${nC(n.range)}
2072
2072
  </c:val>
2073
2073
  </c:ser>
2074
- `)}const i="left"===e.verticalAxisPosition?"l":"r",n=e.stacked?"stacked":"standard";return kf`
2074
+ `)}const i="left"===e.verticalAxisPosition?"l":"r",n=e.stacked?"stacked":"standard";return $f`
2075
2075
  <c:lineChart>
2076
2076
  <c:grouping val="${n}"/>
2077
2077
  <!-- each data marker in the series does not have a different color -->
2078
2078
  <c:varyColors val="0"/>
2079
- ${Df(o)}
2080
- <c:axId val="${Zb}" />
2079
+ ${kf(o)}
2081
2080
  <c:axId val="${jb}" />
2081
+ <c:axId val="${Xb}" />
2082
2082
  </c:lineChart>
2083
- ${tC("b","c:catAx",Zb,jb,{fontColor:e.fontColor})}
2084
- ${tC(i,"c:valAx",jb,Zb,{fontColor:e.fontColor})}
2085
- `}(e.data);break;case"pie":s=function(e,t,o,{holeSize:i}={holeSize:50}){const n=new ki,r=Math.max(...e.dataSets.map((e=>sf(e.range,t,o)))),s=Le(0,r).map((()=>ui(n.next()))),a=[];for(const[i,n]of Object.entries(e.dataSets).reverse()){const r=sf(n.range,t,o),l=[];for(const e of Le(0,r)){const t=Yb({backgroundColor:s[e],line:{color:"FFFFFF",width:1.5}});l.push(kf`
2083
+ ${oC("b","c:catAx",jb,Xb,{fontColor:e.fontColor})}
2084
+ ${oC(i,"c:valAx",Xb,jb,{fontColor:e.fontColor})}
2085
+ `}(e.data);break;case"pie":s=function(e,t,o,{holeSize:i}={holeSize:50}){const n=new $i,r=Math.max(...e.dataSets.map((e=>af(e.range,t,o)))),s=Ue(0,r).map((()=>gi(n.next()))),a=[];for(const[i,n]of Object.entries(e.dataSets).reverse()){const r=af(n.range,t,o),l=[];for(const e of Ue(0,r)){const t=Kb({backgroundColor:s[e],line:{color:"FFFFFF",width:1.5}});l.push($f`
2086
2086
  <c:dPt>
2087
2087
  <c:idx val="${e}"/>
2088
2088
  ${t}
2089
2089
  </c:dPt>
2090
- `)}a.push(kf`
2090
+ `)}a.push($f`
2091
2091
  <c:ser>
2092
2092
  <c:idx val="${i}"/>
2093
2093
  <c:order val="${i}"/>
2094
- ${n.label?kf`<c:tx>${oC(n.label)}</c:tx>`:""}
2095
- ${Df(l)}
2096
- ${eC({showLeaderLines:!0})}
2097
- ${e.labelRange?kf`<c:cat>${oC(e.labelRange)}</c:cat>`:""}
2094
+ ${n.label?$f`<c:tx>${iC(n.label)}</c:tx>`:""}
2095
+ ${kf(l)}
2096
+ ${tC({showLeaderLines:!0})}
2097
+ ${e.labelRange?$f`<c:cat>${iC(e.labelRange)}</c:cat>`:""}
2098
2098
  <c:val>
2099
- ${iC(n.range)}
2099
+ ${nC(n.range)}
2100
2100
  </c:val>
2101
2101
  </c:ser>
2102
- `)}return kf`
2102
+ `)}return $f`
2103
2103
  <c:doughnutChart>
2104
2104
  <c:varyColors val="1" />
2105
2105
  <c:holeSize val="${i}" />
2106
- ${eC()}
2107
- ${Df(a)}
2106
+ ${tC()}
2107
+ ${kf(a)}
2108
2108
  </c:doughnutChart>
2109
- `}(e.data,t,o,{holeSize:0})}let a="t";switch(e.data.legendPosition){case"bottom":a="b";break;case"left":a="l";break;case"right":a="r";break;case"top":a="t"}const l=e.data.fontColor,c=kf`
2110
- <c:chartSpace ${Nf(i)}>
2109
+ `}(e.data,t,o,{holeSize:0})}let a="t";switch(e.data.legendPosition){case"bottom":a="b";break;case"left":a="l";break;case"right":a="r";break;case"top":a="t"}const l=e.data.fontColor,c=$f`
2110
+ <c:chartSpace ${_f(i)}>
2111
2111
  <c:roundedCorners val="0" />
2112
2112
  <!-- <manualLayout/> to manually position the chart in the figure container -->
2113
2113
  ${n}
@@ -2118,32 +2118,32 @@
2118
2118
  <!-- how the chart element is placed on the chart -->
2119
2119
  <c:layout />
2120
2120
  ${s}
2121
- ${Yb({backgroundColor:e.data.backgroundColor})}
2121
+ ${Kb({backgroundColor:e.data.backgroundColor})}
2122
2122
  </c:plotArea>
2123
- ${function(e,t){return kf`
2123
+ ${function(e,t){return $f`
2124
2124
  <c:legend>
2125
2125
  <c:legendPos val="${e}"/>
2126
2126
  <c:overlay val="0"/>
2127
- ${Jb(10,t)}
2127
+ ${eC(10,t)}
2128
2128
  </c:legend>
2129
2129
  `}(a,l)}
2130
2130
  </c:chart>
2131
2131
  </c:chartSpace>
2132
- `;return _f(c)}function Yb(e){return kf`
2132
+ `;return Ff(c)}function Kb(e){return $f`
2133
2133
  <c:spPr>
2134
- ${e.backgroundColor?Kb(e.backgroundColor):""}
2135
- ${e.line?function(e){const t=[["cmpd","sng"]];e.width&&t.push(["w",rf(e.width)]);const o=e.style?kf`<a:prstDash val="${e.style}"/>`:"";return kf`
2136
- <a:ln ${Nf(t)}>
2137
- ${Kb(e.color)}
2134
+ ${e.backgroundColor?Qb(e.backgroundColor):""}
2135
+ ${e.line?function(e){const t=[["cmpd","sng"]];e.width&&t.push(["w",sf(e.width)]);const o=e.style?$f`<a:prstDash val="${e.style}"/>`:"";return $f`
2136
+ <a:ln ${_f(t)}>
2137
+ ${Qb(e.color)}
2138
2138
  ${o}
2139
2139
  </a:ln>
2140
2140
  `}(e.line):""}
2141
2141
  </c:spPr>
2142
- `}function Kb(e){return kf`
2142
+ `}function Qb(e){return $f`
2143
2143
  <a:solidFill>
2144
2144
  <a:srgbClr val="${e}"/>
2145
2145
  </a:solidFill>
2146
- `}function Qb(e,t="000000",o=22){return kf`
2146
+ `}function Jb(e,t="000000",o=22){return $f`
2147
2147
  <c:tx>
2148
2148
  <c:rich>
2149
2149
  <a:bodyPr />
@@ -2151,7 +2151,7 @@
2151
2151
  <a:p>
2152
2152
  <a:pPr lvl="0">
2153
2153
  <a:defRPr b="0">
2154
- ${Kb(t)}
2154
+ ${Qb(t)}
2155
2155
  <a:latin typeface="+mn-lt"/>
2156
2156
  </a:defRPr>
2157
2157
  </a:pPr>
@@ -2162,20 +2162,20 @@
2162
2162
  </a:p>
2163
2163
  </c:rich>
2164
2164
  </c:tx>
2165
- `}function Jb(e=12,t="000000",o=!1,i=!1){return kf`
2165
+ `}function eC(e=12,t="000000",o=!1,i=!1){return $f`
2166
2166
  <c:txPr>
2167
2167
  <a:bodyPr/>
2168
2168
  <a:lstStyle/>
2169
2169
  <a:p>
2170
2170
  <a:pPr lvl="0">
2171
- <a:defRPr ${Nf([["b",o?"1":"0"],["i",i?"1":"0"],["sz",100*e]])}>
2172
- ${Kb(t)}
2171
+ <a:defRPr ${_f([["b",o?"1":"0"],["i",i?"1":"0"],["sz",100*e]])}>
2172
+ ${Qb(t)}
2173
2173
  <a:latin typeface="+mn-lt"/>
2174
2174
  </a:defRPr>
2175
2175
  </a:pPr>
2176
2176
  </a:p>
2177
2177
  </c:txPr>
2178
- `}function eC({showLeaderLines:e}={showLeaderLines:!1}){return kf`
2178
+ `}function tC({showLeaderLines:e}={showLeaderLines:!1}){return $f`
2179
2179
  <dLbls>
2180
2180
  <c:showLegendKey val="0"/>
2181
2181
  <c:showVal val="0"/>
@@ -2185,7 +2185,7 @@
2185
2185
  <c:showBubbleSize val="0"/>
2186
2186
  <c:showLeaderLines val="${e?"1":"0"}"/>
2187
2187
  </dLbls>
2188
- `}function tC(e,t,o,i,{fontColor:n}){return kf`
2188
+ `}function oC(e,t,o,i,{fontColor:n}){return $f`
2189
2189
  <${t}>
2190
2190
  <c:axId val="${o}"/>
2191
2191
  <c:crossAx val="${i}"/> <!-- reference to the other axe of the chart -->
@@ -2194,58 +2194,58 @@
2194
2194
  <c:orientation val="minMax" />
2195
2195
  </c:scaling>
2196
2196
  <c:axPos val="${e}" />
2197
- ${function(e="B7B7B7"){return kf`
2197
+ ${function(e="B7B7B7"){return $f`
2198
2198
  <c:majorGridlines>
2199
- ${Yb({line:{color:e}})}
2199
+ ${Kb({line:{color:e}})}
2200
2200
  </c:majorGridlines>
2201
2201
  `}()}
2202
2202
  <c:majorTickMark val="out" />
2203
2203
  <c:minorTickMark val="none" />
2204
2204
  <c:numFmt formatCode="General" sourceLinked="1" />
2205
2205
  <c:title>
2206
- ${Qb("")}
2206
+ ${Jb("")}
2207
2207
  </c:title>
2208
- ${Jb(10,n)}
2208
+ ${eC(10,n)}
2209
2209
  </${t}>
2210
2210
  <!-- <tickLblPos/> omitted -->
2211
- `}function oC(e){return kf`
2211
+ `}function iC(e){return $f`
2212
2212
  <c:strRef>
2213
2213
  <c:f>${e}</c:f>
2214
2214
  </c:strRef>
2215
- `}function iC(e){return kf`
2215
+ `}function nC(e){return $f`
2216
2216
  <c:numRef>
2217
2217
  <c:f>${e}</c:f>
2218
2218
  <c:numCache />
2219
2219
  </c:numRef>
2220
- `}function nC(e){const t=e.content,o=Yd.content,i=[];let n=kf``;if(eu(t).filter((e=>"FUNCTION"===e.type)).every((e=>o[e.value.toUpperCase()].isExported))){let o=kf``;const r=sC(t);return e.value===a.CircularDependency&&(i.push(["t","str"]),o=kf`<v>${e.value}</v>`),n=kf`
2220
+ `}function rC(e){const t=e.content,o=Kd.content,i=[];let n=$f``;if(tu(t).filter((e=>"FUNCTION"===e.type)).every((e=>o[e.value.toUpperCase()].isExported))){let o=$f``;const r=aC(t);return e.value===a.CircularDependency&&(i.push(["t","str"]),o=$f`<v>${e.value}</v>`),n=$f`
2221
2221
  <f>
2222
2222
  ${r}
2223
2223
  </f>
2224
2224
  ${o}
2225
- `,{attrs:i,node:n}}{const t=e.value,o=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n"}}(t);return i.push(["t",o]),n=kf`<v>${t}</v>`,{attrs:i,node:n}}}function rC(e,t,o=!1){let i=e;const n=[];if(!o&&["TRUE","FALSE"].includes(i.trim()))i="TRUE"===i?"1":"0",n.push(["t","b"]);else if(o||!qt(i)){const{id:o}=tf(e,t);i=o.toString(),n.push(["t","s"])}return{attrs:n,node:kf`<v>${i}</v>`}}function sC(e){let t;"="===e[0]&&(e=e.slice(1));try{t=wu(e)}catch(t){return e}return t=xu(t,"STRING",aC),t=xu(t,"FUNCALL",(e=>(e=function(e){const t=e.value.toUpperCase(),o=e.args,i=lm[t];if(i){const n=Yd.content[t].args.filter((e=>!e.optional)),r=n.length-e.args.length;if(r)for(let t=e.args.length;t<n.length;t++){const e=i[t-r];o.push({type:e.type,value:e.value})}}return{...e,args:o}}(e=function(e){const t=e.value.toUpperCase();return{...e,value:cm.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()})),e))),t?Iu(t):e}function aC(e){const t=e.value.replace(new RegExp('"',"g"),""),o=be(t);if(o){let i=[];return(t.match(me)||t.match(fe))&&i.push("yyyy-mm-dd"),t.match(ve)&&i.push("hh:mm:ss"),{...e,value:no(o.value,i.join(" "))}}return{...e,value:e.value.replace(/\\"/g,'""')}}function lC(e,t){const o=[];for(const i of t)switch(i.rule.type){case"CellIsRule":o.push(cC(i,i.rule,e));break;case"ColorScaleRule":o.push(hC(i,i.rule));break;case"IconSetRule":o.push(dC(i,i.rule));break;default:console.warn(`Conditional formatting ${i.rule.type} not implemented`)}return o}function cC(e,t,o){const i=uC(e),n=jm(t.operator);i.push(...function(e){const t=jm(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",n]);const r=function(e,t){const o=e[0].split(":")[0],i=t.values;switch(t.operator){case"ContainsText":return[`NOT(ISERROR(SEARCH("${i[0]}",${o})))`];case"NotContains":return[`ISERROR(SEARCH("${i[0]}",${o}))`];case"BeginsWith":return[`LEFT(${o},LEN("${i[0]}"))="${i[0]}"`];case"EndsWith":return[`RIGHT(${o},LEN("${i[0]}"))="${i[0]}"`];case"IsEmpty":return[`LEN(TRIM(${o}))=0`];case"IsNotEmpty":return[`LEN(TRIM(${o}))>0`];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":return[i[0]];case"Between":case"NotBetween":return[i[0],i[1]]}}(e.ranges,t).map((e=>kf`<formula>${e}</formula>`)),s={font:{color:{rgb:t.style.textColor},bold:t.style.bold,italic:t.style.italic,strike:t.style.strikethrough,underline:t.style.underline}};t.style.fillColor&&(s.fill={fgColor:{rgb:t.style.fillColor}});const{id:a}=tf(s,o);return i.push(["dxfId",a]),kf`
2225
+ `,{attrs:i,node:n}}{const t=e.value,o=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n"}}(t);return i.push(["t",o]),n=$f`<v>${t}</v>`,{attrs:i,node:n}}}function sC(e,t,o=!1){let i=e;const n=[];if(!o&&["TRUE","FALSE"].includes(i.trim()))i="TRUE"===i?"1":"0",n.push(["t","b"]);else if(o||!Zt(i)){const{id:o}=of(e,t);i=o.toString(),n.push(["t","s"])}return{attrs:n,node:$f`<v>${i}</v>`}}function aC(e){let t;"="===e[0]&&(e=e.slice(1));try{t=yu(e)}catch(t){return e}return t=Iu(t,"STRING",lC),t=Iu(t,"FUNCALL",(e=>(e=function(e){const t=e.value.toUpperCase(),o=e.args,i=cm[t];if(i){const n=Kd.content[t].args.filter((e=>!e.optional)),r=n.length-e.args.length;if(r)for(let t=e.args.length;t<n.length;t++){const e=i[t-r];o.push({type:e.type,value:e.value})}}return{...e,args:o}}(e=function(e){const t=e.value.toUpperCase();return{...e,value:hm.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()})),e))),t?Ru(t):e}function lC(e){const t=e.value.replace(new RegExp('"',"g"),""),o=be(t);if(o){let i=[];return(t.match(me)||t.match(fe))&&i.push("yyyy-mm-dd"),t.match(ve)&&i.push("hh:mm:ss"),{...e,value:ro(o.value,i.join(" "))}}return{...e,value:e.value.replace(/\\"/g,'""')}}function cC(e,t){const o=[];for(const i of t)switch(i.rule.type){case"CellIsRule":o.push(hC(i,i.rule,e));break;case"ColorScaleRule":o.push(dC(i,i.rule));break;case"IconSetRule":o.push(uC(i,i.rule));break;default:console.warn(`Conditional formatting ${i.rule.type} not implemented`)}return o}function hC(e,t,o){const i=gC(e),n=Xm(t.operator);i.push(...function(e){const t=Xm(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",n]);const r=function(e,t){const o=e[0].split(":")[0],i=t.values;switch(t.operator){case"ContainsText":return[`NOT(ISERROR(SEARCH("${i[0]}",${o})))`];case"NotContains":return[`ISERROR(SEARCH("${i[0]}",${o}))`];case"BeginsWith":return[`LEFT(${o},LEN("${i[0]}"))="${i[0]}"`];case"EndsWith":return[`RIGHT(${o},LEN("${i[0]}"))="${i[0]}"`];case"IsEmpty":return[`LEN(TRIM(${o}))=0`];case"IsNotEmpty":return[`LEN(TRIM(${o}))>0`];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":return[i[0]];case"Between":case"NotBetween":return[i[0],i[1]]}}(e.ranges,t).map((e=>$f`<formula>${e}</formula>`)),s={font:{color:{rgb:t.style.textColor},bold:t.style.bold,italic:t.style.italic,strike:t.style.strikethrough,underline:t.style.underline}};t.style.fillColor&&(s.fill={fgColor:{rgb:t.style.fillColor}});const{id:a}=of(s,o);return i.push(["dxfId",a]),$f`
2226
2226
  <conditionalFormatting sqref="${e.ranges.join(" ")}">
2227
- <cfRule ${Nf(i)}>
2228
- ${Df(r)}
2227
+ <cfRule ${_f(i)}>
2228
+ ${kf(r)}
2229
2229
  </cfRule>
2230
2230
  </conditionalFormatting>
2231
- `}function hC(e,t){const o=uC(e);o.push(["type","colorScale"]);const i=[];for(const n of e.ranges){const e=[],r=[];let s=!0;for(let o of["minimum","midpoint","maximum"]){const i=t[o];i&&("formula"!==i.type?(e.push(pC(i,o)),r.push([["rgb",ui(dt(i.color))]])):s=!1)}if(!s){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const a=e.map((e=>kf`<cfvo ${Nf(e)}/>`)),l=r.map((e=>kf`<color ${Nf(e)}/>`));i.push(kf`
2231
+ `}function dC(e,t){const o=gC(e);o.push(["type","colorScale"]);const i=[];for(const n of e.ranges){const e=[],r=[];let s=!0;for(let o of["minimum","midpoint","maximum"]){const i=t[o];i&&("formula"!==i.type?(e.push(mC(i,o)),r.push([["rgb",gi(ut(i.color))]])):s=!1)}if(!s){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 ${_f(e)}/>`)),l=r.map((e=>$f`<color ${_f(e)}/>`));i.push($f`
2232
2232
  <conditionalFormatting sqref="${n}">
2233
- <cfRule ${Nf(o)}>
2233
+ <cfRule ${_f(o)}>
2234
2234
  <colorScale>
2235
- ${Df(a)}
2236
- ${Df(l)}
2235
+ ${kf(a)}
2236
+ ${kf(l)}
2237
2237
  </colorScale>
2238
2238
  </cfRule>
2239
2239
  </conditionalFormatting>
2240
- `)}return Df(i)}function dC(e,t){const o=uC(e);o.push(["type","iconSet"]);const i=[];for(const n of e.ranges){const e=[[["type","percent"],["val",0]]];let r=!0;for(let o of["lowerInflectionPoint","upperInflectionPoint"]){if("formula"===t[o].type){r=!1;continue}const i=t[o];e.push([...pC(i,o),["gte","ge"===i.operator?"1":"0"]])}if(!r){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const s=e.map((e=>kf`<cfvo ${Nf(e)} />`));i.push(kf`
2240
+ `)}return kf(i)}function uC(e,t){const o=gC(e);o.push(["type","iconSet"]);const i=[];for(const n of e.ranges){const e=[[["type","percent"],["val",0]]];let r=!0;for(let o of["lowerInflectionPoint","upperInflectionPoint"]){if("formula"===t[o].type){r=!1;continue}const i=t[o];e.push([...mC(i,o),["gte","ge"===i.operator?"1":"0"]])}if(!r){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const s=e.map((e=>$f`<cfvo ${_f(e)} />`));i.push($f`
2241
2241
  <conditionalFormatting sqref="${n}">
2242
- <cfRule ${Nf(o)}>
2243
- <iconSet iconSet="${gC(t.icons)}">
2244
- ${Df(s)}
2242
+ <cfRule ${_f(o)}>
2243
+ <iconSet iconSet="${pC(t.icons)}">
2244
+ ${kf(s)}
2245
2245
  </iconSet>
2246
2246
  </cfRule>
2247
2247
  </conditionalFormatting>
2248
- `)}return Df(i)}function uC(e){return[["priority",1],["stopIfTrue",e.stopIfTrue?1:0]]}function gC(e){return jp[Object.keys(jp).find((t=>e.upper.toLowerCase().startsWith(t)))||"dots"]}function pC(e,t){const o=function(e,t){switch(e){case"value":return"minimum"===t?"min":"max";case"number":return"num";case"percentage":return"percent";default:return e}}(e.type,t),i=[["type",o]];if("min"!==o&&"max"!==o){let t=e.value;if("formula"===o)try{t=sC(e.value)}catch(o){t=e.value}i.push(["val",t])}return i}function mC(e,t,o){const i=[["xmlns:xdr",Xp.drawing],["xmlns:r",em],["xmlns:a",Yp],["xmlns:c",Kp]],n=[];for(const[i,r]of Object.entries(o)){const{from:o,to:s}=fC(r,t),a=nf(r.id),l=[["id",a],["name",`Chart ${a}`],["title","Chart"]];n.push(kf`
2248
+ `)}return kf(i)}function gC(e){return[["priority",1],["stopIfTrue",e.stopIfTrue?1:0]]}function pC(e){return Xp[Object.keys(Xp).find((t=>e.upper.toLowerCase().startsWith(t)))||"dots"]}function mC(e,t){const o=function(e,t){switch(e){case"value":return"minimum"===t?"min":"max";case"number":return"num";case"percentage":return"percent";default:return e}}(e.type,t),i=[["type",o]];if("min"!==o&&"max"!==o){let t=e.value;if("formula"===o)try{t=aC(e.value)}catch(o){t=e.value}i.push(["val",t])}return i}function fC(e,t,o){const i=[["xmlns:xdr",Yp.drawing],["xmlns:r",tm],["xmlns:a",Kp],["xmlns:c",Qp]],n=[];for(const[i,r]of Object.entries(o)){const{from:o,to:s}=vC(r,t),a=rf(r.id),l=[["id",a],["name",`Chart ${a}`],["title","Chart"]];n.push($f`
2249
2249
  <xdr:twoCellAnchor>
2250
2250
  <xdr:from>
2251
2251
  <xdr:col>${o.col}</xdr:col>
@@ -2261,7 +2261,7 @@
2261
2261
  </xdr:to>
2262
2262
  <xdr:graphicFrame>
2263
2263
  <xdr:nvGraphicFramePr>
2264
- <xdr:cNvPr ${Nf(l)} />
2264
+ <xdr:cNvPr ${_f(l)} />
2265
2265
  <xdr:cNvGraphicFramePr />
2266
2266
  </xdr:nvGraphicFramePr>
2267
2267
  <xdr:xfrm>
@@ -2269,80 +2269,80 @@
2269
2269
  <a:ext cx="0" cy="0"/>
2270
2270
  </xdr:xfrm>
2271
2271
  <a:graphic>
2272
- <a:graphicData uri="${Kp}">
2272
+ <a:graphicData uri="${Qp}">
2273
2273
  <c:chart r:id="${e[i]}" />
2274
2274
  </a:graphicData>
2275
2275
  </a:graphic>
2276
2276
  </xdr:graphicFrame>
2277
2277
  <xdr:clientData fLocksWithSheet="0"/>
2278
2278
  </xdr:twoCellAnchor>
2279
- `)}return _f(kf`
2280
- <xdr:wsDr ${Nf(i)}>
2281
- ${Df(n)}
2279
+ `)}return Ff($f`
2280
+ <xdr:wsDr ${_f(i)}>
2281
+ ${kf(n)}
2282
2282
  </xdr:wsDr>
2283
- `)}function fC(e,t){const{x:o,y:i,height:n,width:r}=e,s=Object.values(t.cols),a=Object.values(t.rows),{index:l,offset:c}=vC(s,o),{index:h,offset:d}=vC(s,o+r),{index:u,offset:g}=vC(a,i),{index:p,offset:m}=vC(a,i+n);return{from:{col:l,colOff:c,row:u,rowOff:g},to:{col:h,colOff:d,row:p,rowOff:m}}}function vC(e,t){let o=0;for(const[i,n]of Object.entries(e)){if(o<=t&&t<o+n.size)return{index:parseInt(i),offset:rf(t-o+B)};o+=n.size}return{index:e.length-1,offset:rf(t-o+B)}}function bC(e){return Je(e)?kf``:kf`
2283
+ `)}function vC(e,t){const{x:o,y:i,height:n,width:r}=e,s=Object.values(t.cols),a=Object.values(t.rows),{index:l,offset:c}=bC(s,o),{index:h,offset:d}=bC(s,o+r),{index:u,offset:g}=bC(a,i),{index:p,offset:m}=bC(a,i+n);return{from:{col:l,colOff:c,row:u,rowOff:g},to:{col:h,colOff:d,row:p,rowOff:m}}}function bC(e,t){let o=0;for(const[i,n]of Object.entries(e)){if(o<=t&&t<o+n.size)return{index:parseInt(i),offset:sf(t-o+B)};o+=n.size}return{index:e.length-1,offset:sf(t-o+B)}}function CC(e){return et(e)?$f``:$f`
2284
2284
  <font>
2285
- ${e.bold?kf`<b />`:""}
2286
- ${e.italic?kf`<i />`:""}
2287
- ${e.underline?kf`<u />`:""}
2288
- ${e.strike?kf`<strike />`:""}
2289
- ${e.size?kf`<sz val="${e.size}" />`:""}
2290
- ${e.color&&e.color.rgb?kf`<color rgb="${ui(e.color.rgb)}" />`:""}
2291
- ${e.name?kf`<name val="${e.name}" />`:""}
2285
+ ${e.bold?$f`<b />`:""}
2286
+ ${e.italic?$f`<i />`:""}
2287
+ ${e.underline?$f`<u />`:""}
2288
+ ${e.strike?$f`<strike />`:""}
2289
+ ${e.size?$f`<sz val="${e.size}" />`:""}
2290
+ ${e.color&&e.color.rgb?$f`<color rgb="${gi(e.color.rgb)}" />`:""}
2291
+ ${e.name?$f`<name val="${e.name}" />`:""}
2292
2292
  </font>
2293
- `}function CC(e){return e?Nf([["style",e.style],["color",ui(e.color.rgb)]]):kf``}const SC=kf`<tableStyleInfo name="TableStyleLight8" showFirstColumn="0" showLastColumn="0" showRowStripes="0" showColumnStripes="0"/>`;function EC(e,t,o){const i=kf`
2294
- <table ${Nf([["id",t],["name",`Table${t}`],["displayName",`Table${t}`],["ref",e.range],["xmlns",Xp.table],["xmlns:xr",Xp.revision],["xmlns:xr3",Xp.revision3],["xmlns:mc",Xp.markupCompatibility]])}>
2295
- ${function(e){const t=[["ref",e.range]];return kf`
2296
- <autoFilter ${Nf(t)}>
2297
- ${Df(function(e){const t=Oo(e.range),o=[];for(const i of Le(0,Wo(t).width)){const t=e.filters[i];if(!t||!t.filteredValues.length)continue;const n=kf`
2298
- <filterColumn ${Nf([["colId",i]])}>
2299
- ${wC(t)}
2293
+ `}function SC(e){return e?_f([["style",e.style],["color",gi(e.color.rgb)]]):$f``}const EC=$f`<tableStyleInfo name="TableStyleLight8" showFirstColumn="0" showLastColumn="0" showRowStripes="0" showColumnStripes="0"/>`;function wC(e,t,o){const i=$f`
2294
+ <table ${_f([["id",t],["name",`Table${t}`],["displayName",`Table${t}`],["ref",e.range],["xmlns",Yp.table],["xmlns:xr",Yp.revision],["xmlns:xr3",Yp.revision3],["xmlns:mc",Yp.markupCompatibility]])}>
2295
+ ${function(e){const t=[["ref",e.range]];return $f`
2296
+ <autoFilter ${_f(t)}>
2297
+ ${kf(function(e){const t=[];for(const o of e.filters){const e=$f`
2298
+ <filterColumn ${_f([["colId",o.colId]])}>
2299
+ ${yC(o)}
2300
2300
  </filterColumn>
2301
- `;o.push(n)}return o}(e))}
2301
+ `;t.push(e)}return t}(e))}
2302
2302
  </autoFilter>
2303
2303
  `}(e)}
2304
- ${function(e,t){var o;const i=Oo(e.range),n=[];for(const e of Le(0,Wo(i).width)){const r=kt(i.left+e,i.top),s=[["id",e+1],["name",(null===(o=t.cells[r])||void 0===o?void 0:o.content)||`col${e}`]];n.push(kf`<tableColumn ${Nf(s)}/>`)}return kf`
2305
- <tableColumns ${Nf([["count",n.length]])}>
2306
- ${Df(n)}
2304
+ ${function(e,t){var o;const i=Mo(e.range),n=[];for(const e of Ue(0,Go(i).width)){const r=$t(i.left+e,i.top),s=[["id",e+1],["name",(null===(o=t.cells[r])||void 0===o?void 0:o.content)||`col${e}`]];n.push($f`<tableColumn ${_f(s)}/>`)}return $f`
2305
+ <tableColumns ${_f([["count",n.length]])}>
2306
+ ${kf(n)}
2307
2307
  </tableColumns>
2308
2308
  `}(e,o)}
2309
- ${SC}
2309
+ ${EC}
2310
2310
  </table>
2311
- `;return _f(i)}function wC(e){return kf`
2312
- <filters>
2313
- ${Df(e.filteredValues.map((e=>kf`<filter ${Nf([["val",e]])}/>`)))}
2311
+ `;return Ff(i)}function yC(e){const t=e.displayedValues.map((e=>$f`<filter ${_f([["val",e]])}/>`));return $f`
2312
+ <filters ${_f(e.displayBlanks?[["blank",1]]:[])}>
2313
+ ${kf(t)}
2314
2314
  </filters>
2315
- `}function yC(e){if(!Object.values(e).length)return kf``;const t=[];for(let[o,i]of Object.entries(e)){const e=[["min",parseInt(o)+1],["max",parseInt(o)+1],["width",Ym(i.size||N)],["customWidth",1],["hidden",i.isHidden?1:0]];t.push(kf`
2316
- <col ${Nf(e)}/>
2317
- `)}return kf`
2315
+ `}function xC(e){if(!Object.values(e).length)return $f``;const t=[];for(let[o,i]of Object.entries(e)){const e=[["min",parseInt(o)+1],["max",parseInt(o)+1],["width",Km(i.size||N)],["customWidth",1],["hidden",i.isHidden?1:0]];t.push($f`
2316
+ <col ${_f(e)}/>
2317
+ `)}return $f`
2318
2318
  <cols>
2319
- ${Df(t)}
2319
+ ${kf(t)}
2320
2320
  </cols>
2321
- `}function xC(e,t,o){const i=[];for(let n=0;n<o.rowNumber;n++){const r=[["r",n+1]],s=o.rows[n]||{};r.push(["ht",Xm(s.size||_)],["customHeight",1],["hidden",s.isHidden?1:0]);const a=[];for(let i=0;i<o.colNumber;i++){const r=kt(i,n),s=o.cells[r];if(s){const l=[["r",r]],c=Jm(e,Qm(s,t));l.push(["s",c]);let h=[],d=kf``;if(s.isFormula)({attrs:h,node:d}=nC(s));else if(s.content&&We(s.content)){const{label:t}=Ze(s.content);({attrs:h,node:d}=rC(t,e.sharedStrings))}else if(s.content&&""!==s.content){const t=IC(i,n,o);({attrs:h,node:d}=rC(s.content,e.sharedStrings,t))}l.push(...h),a.push(kf`
2322
- <c ${Nf(l)}>
2321
+ `}function IC(e,t,o){const i=[];for(let n=0;n<o.rowNumber;n++){const r=[["r",n+1]],s=o.rows[n]||{};r.push(["ht",Ym(s.size||_)],["customHeight",1],["hidden",s.isHidden?1:0]);const a=[];for(let i=0;i<o.colNumber;i++){const r=$t(i,n),s=o.cells[r];if(s){const l=[["r",r]],c=ef(e,Jm(s,t));l.push(["s",c]);let h=[],d=$f``;if(s.isFormula)({attrs:h,node:d}=rC(s));else if(s.content&&Ge(s.content)){const{label:t}=je(s.content);({attrs:h,node:d}=sC(t,e.sharedStrings))}else if(s.content&&""!==s.content){const t=RC(i,n,o);({attrs:h,node:d}=sC(s.content,e.sharedStrings,t))}l.push(...h),a.push($f`
2322
+ <c ${_f(l)}>
2323
2323
  ${d}
2324
2324
  </c>
2325
- `)}}(a.length||s.size!==_||s.isHidden)&&i.push(kf`
2326
- <row ${Nf(r)}>
2327
- ${Df(a)}
2325
+ `)}}(a.length||s.size!==_||s.isHidden)&&i.push($f`
2326
+ <row ${_f(r)}>
2327
+ ${kf(a)}
2328
2328
  </row>
2329
- `)}return kf`
2329
+ `)}return $f`
2330
2330
  <sheetData>
2331
- ${Df(i)}
2331
+ ${kf(i)}
2332
2332
  </sheetData>
2333
- `}function IC(e,t,o){return o.filterTables.some((o=>{const i=Oo(o.range),n={...i,bottom:i.top};return Vo(e,t,n)}))}function RC(e,t,o){var i;const n=t.sheets[o].cells,r=[];for(const s in n){const a=null===(i=n[s])||void 0===i?void 0:i.content;if(a&&We(a)){const{label:i,url:n}=Ze(a);if(Xe(n)){const e=Ke(n),o=t.sheets.find((t=>t.id===e)),a=o?`${o.name}!A1`:X;r.push(kf`
2333
+ `}function RC(e,t,o){return o.filterTables.some((o=>{const i=Mo(o.range),n={...i,bottom:i.top};return zo(e,t,n)}))}function TC(e,t,o){var i;const n=t.sheets[o].cells,r=[];for(const s in n){const a=null===(i=n[s])||void 0===i?void 0:i.content;if(a&&Ge(a)){const{label:i,url:n}=je(a);if(Ye(n)){const e=Qe(n),o=t.sheets.find((t=>t.id===e)),a=o?`${o.name}!A1`:X;r.push($f`
2334
2334
  <hyperlink display="${i}" location="${a}" ref="${s}"/>
2335
- `)}else{const t=ef(e.relsFiles,`xl/worksheets/_rels/sheet${o}.xml.rels`,{target:ug(n),type:Jp.hyperlink,targetMode:"External"});r.push(kf`
2335
+ `)}else{const t=tf(e.relsFiles,`xl/worksheets/_rels/sheet${o}.xml.rels`,{target:gg(n),type:em.hyperlink,targetMode:"External"});r.push($f`
2336
2336
  <hyperlink r:id="${t}" ref="${s}"/>
2337
- `)}}}return r.length?kf`
2337
+ `)}}}return r.length?$f`
2338
2338
  <hyperlinks>
2339
- ${Df(r)}
2339
+ ${kf(r)}
2340
2340
  </hyperlinks>
2341
- `:kf``}function TC(e){if(e.length){const t=e.map((e=>kf`<mergeCell ref="${e}" />`));return kf`
2341
+ `:$f``}function AC(e){if(e.length){const t=e.map((e=>$f`<mergeCell ref="${e}" />`));return $f`
2342
2342
  <mergeCells count="${e.length}">
2343
- ${Df(t)}
2343
+ ${kf(t)}
2344
2344
  </mergeCells>
2345
- `}return kf``}function AC(e){const t=e.panes;let o=kf``;if(t&&(t.xSplit||t.ySplit)){const e=kt(t.xSplit,t.ySplit),i=t.xSplit?kf`xSplit="${t.xSplit}"`:"",n=t.ySplit?kf`ySplit="${t.ySplit}"`:"",r=t.xSplit?kf`<selection pane="topRight"/>`:"",s=t.ySplit?kf`<selection pane="bottomLeft"/>`:"",a=t.xSplit&&t.ySplit?kf`<selection pane="bottomRight"/>`:"";o=kf`
2345
+ `}return $f``}function OC(e){const t=e.panes;let o=$f``;if(t&&(t.xSplit||t.ySplit)){const e=$t(t.xSplit,t.ySplit),i=t.xSplit?$f`xSplit="${t.xSplit}"`:"",n=t.ySplit?$f`ySplit="${t.ySplit}"`:"",r=t.xSplit?$f`<selection pane="topRight"/>`:"",s=t.ySplit?$f`<selection pane="bottomLeft"/>`:"",a=t.xSplit&&t.ySplit?$f`<selection pane="bottomRight"/>`:"";o=$f`
2346
2346
  <pane
2347
2347
  ${i}
2348
2348
  ${n}
@@ -2352,123 +2352,123 @@
2352
2352
  ${r}
2353
2353
  ${s}
2354
2354
  ${a}
2355
- `}return kf`
2355
+ `}return $f`
2356
2356
  <sheetViews>
2357
2357
  <sheetView showGridLines="${e.areGridLinesVisible?1:0}" workbookViewId="0">
2358
2358
  ${o}
2359
2359
  </sheetView>
2360
2360
  </sheetViews>
2361
- `}function OC(e){const t=[],o={relsFiles:[],sharedStrings:[],styles:[{fontId:0,fillId:0,numFmtId:0,borderId:0,alignment:{vertical:"center"}}],fonts:[{size:W,family:2,color:{rgb:"000000"},name:"Calibri"}],fills:[{reservedAttribute:"none"},{reservedAttribute:"gray125"}],borders:[{}],numFmts:[],dxfs:[]};return t.push(function(e,t){const o=[["xmlns",Xp.workbook],["xmlns:r",em]],i=[];for(const[o,n]of Object.entries(e.sheets)){const e=[["state",n.isVisible?"visible":"hidden"],["name",n.name],["sheetId",parseInt(o)+1],["r:id",`rId${parseInt(o)+1}`]];i.push(kf`
2362
- <sheet ${Nf(e)} />
2363
- `),ef(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Jp.sheet,target:`worksheets/sheet${o}.xml`})}return Of(_f(kf`
2364
- <workbook ${Nf(o)}>
2361
+ `}function MC(e){const t=[],o={relsFiles:[],sharedStrings:[],styles:[{fontId:0,fillId:0,numFmtId:0,borderId:0,alignment:{vertical:"center"}}],fonts:[{size:W,family:2,color:{rgb:"000000"},name:"Calibri"}],fills:[{reservedAttribute:"none"},{reservedAttribute:"gray125"}],borders:[{}],numFmts:[],dxfs:[]};return t.push(function(e,t){const o=[["xmlns",Yp.workbook],["xmlns:r",tm]],i=[];for(const[o,n]of Object.entries(e.sheets)){const e=[["state",n.isVisible?"visible":"hidden"],["name",n.name],["sheetId",parseInt(o)+1],["r:id",`rId${parseInt(o)+1}`]];i.push($f`
2362
+ <sheet ${_f(e)} />
2363
+ `),tf(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:em.sheet,target:`worksheets/sheet${o}.xml`})}return Mf(Ff($f`
2364
+ <workbook ${_f(o)}>
2365
2365
  <sheets>
2366
- ${Df(i)}
2366
+ ${kf(i)}
2367
2367
  </sheets>
2368
2368
  </workbook>
2369
- `),"xl/workbook.xml","workbook")}(e,o)),t.push(...function(e,t){const o=[];let i=1;for(const[n,r]of Object.entries(e.sheets)){const s=[["xmlns",Xp.worksheet],["xmlns:r",em]],a=[["defaultRowHeight",Xm(_)],["defaultColWidth",Ym(N)]],l=MC(r,n,i,t,o);i+=r.filterTables.length;let c=kf``;const h=r.charts;if(h.length){const i=[];for(const r of h){const s=nf(r.id),a=ef(t.relsFiles,`xl/drawings/_rels/drawing${n}.xml.rels`,{target:`../charts/chart${s}.xml`,type:Jp.chart});i.push(a),o.push(Of(Xb(r,n,e),`xl/charts/chart${s}.xml`,"chart"))}const s=ef(t.relsFiles,`xl/worksheets/_rels/sheet${n}.xml.rels`,{target:`../drawings/drawing${n}.xml`,type:Jp.drawing});o.push(Of(mC(i,r,h),`xl/drawings/drawing${n}.xml`,"drawing")),c=kf`<drawing r:id="${s}" />`}const d=kf`
2370
- <worksheet ${Nf(s)}>
2371
- ${AC(r)}
2372
- <sheetFormatPr ${Nf(a)} />
2373
- ${yC(r.cols)}
2374
- ${xC(t,e,r)}
2375
- ${TC(r.merges)}
2376
- ${Df(lC(t.dxfs,r.conditionalFormats))}
2377
- ${RC(t,e,n)}
2369
+ `),"xl/workbook.xml","workbook")}(e,o)),t.push(...function(e,t){const o=[];let i=1;for(const[n,r]of Object.entries(e.sheets)){const s=[["xmlns",Yp.worksheet],["xmlns:r",tm]],a=[["defaultRowHeight",Ym(_)],["defaultColWidth",Km(N)]],l=NC(r,n,i,t,o);i+=r.filterTables.length;let c=$f``;const h=r.charts;if(h.length){const i=[];for(const r of h){const s=rf(r.id),a=tf(t.relsFiles,`xl/drawings/_rels/drawing${n}.xml.rels`,{target:`../charts/chart${s}.xml`,type:em.chart});i.push(a),o.push(Mf(Yb(r,n,e),`xl/charts/chart${s}.xml`,"chart"))}const s=tf(t.relsFiles,`xl/worksheets/_rels/sheet${n}.xml.rels`,{target:`../drawings/drawing${n}.xml`,type:em.drawing});o.push(Mf(fC(i,r,h),`xl/drawings/drawing${n}.xml`,"drawing")),c=$f`<drawing r:id="${s}" />`}const d=$f`
2370
+ <worksheet ${_f(s)}>
2371
+ ${OC(r)}
2372
+ <sheetFormatPr ${_f(a)} />
2373
+ ${xC(r.cols)}
2374
+ ${IC(t,e,r)}
2375
+ ${AC(r.merges)}
2376
+ ${kf(cC(t.dxfs,r.conditionalFormats))}
2377
+ ${TC(t,e,n)}
2378
2378
  ${c}
2379
2379
  ${l}
2380
2380
  </worksheet>
2381
- `;o.push(Of(_f(d),`xl/worksheets/sheet${n}.xml`,"sheet"))}return ef(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Jp.sharedStrings,target:"sharedStrings.xml"}),ef(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Jp.styles,target:"styles.xml"}),o}(e,o)),t.push(function(e){const t=kf`
2382
- <styleSheet ${Nf([["xmlns",Xp.styleSheet],["xmlns:r",em]])}>
2383
- ${function(e){const t=[];for(let[o,i]of Object.entries(e)){const e=[["numFmtId",parseInt(o)+am],["formatCode",i.format]];t.push(kf`
2384
- <numFmt ${Nf(e)}/>
2385
- `)}return kf`
2381
+ `;o.push(Mf(Ff(d),`xl/worksheets/sheet${n}.xml`,"sheet"))}return tf(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:em.sharedStrings,target:"sharedStrings.xml"}),tf(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:em.styles,target:"styles.xml"}),o}(e,o)),t.push(function(e){const t=$f`
2382
+ <styleSheet ${_f([["xmlns",Yp.styleSheet],["xmlns:r",tm]])}>
2383
+ ${function(e){const t=[];for(let[o,i]of Object.entries(e)){const e=[["numFmtId",parseInt(o)+lm],["formatCode",i.format]];t.push($f`
2384
+ <numFmt ${_f(e)}/>
2385
+ `)}return $f`
2386
2386
  <numFmts count="${e.length}">
2387
- ${Df(t)}
2387
+ ${kf(t)}
2388
2388
  </numFmts>
2389
2389
  `}(e.numFmts)}
2390
- ${o=e.fonts,kf`
2390
+ ${o=e.fonts,$f`
2391
2391
  <fonts count="${o.length}">
2392
- ${Df(Object.values(o).map(bC))}
2392
+ ${kf(Object.values(o).map(CC))}
2393
2393
  </fonts>
2394
2394
  `}
2395
- ${function(e){const t=[];for(let o of Object.values(e))void 0!==o.reservedAttribute?t.push(kf`
2395
+ ${function(e){const t=[];for(let o of Object.values(e))void 0!==o.reservedAttribute?t.push($f`
2396
2396
  <fill>
2397
2397
  <patternFill patternType="${o.reservedAttribute}" />
2398
2398
  </fill>
2399
- `):t.push(kf`
2399
+ `):t.push($f`
2400
2400
  <fill>
2401
2401
  <patternFill patternType="solid">
2402
- <fgColor rgb="${ui(o.fgColor.rgb)}" />
2402
+ <fgColor rgb="${gi(o.fgColor.rgb)}" />
2403
2403
  <bgColor indexed="64" />
2404
2404
  </patternFill>
2405
2405
  </fill>
2406
- `);return kf`
2406
+ `);return $f`
2407
2407
  <fills count="${e.length}">
2408
- ${Df(t)}
2408
+ ${kf(t)}
2409
2409
  </fills>
2410
2410
  `}(e.fills)}
2411
- ${function(e){const t=[];for(let o of Object.values(e))t.push(kf`
2411
+ ${function(e){const t=[];for(let o of Object.values(e))t.push($f`
2412
2412
  <border>
2413
- <left ${CC(o.left)} />
2414
- <right ${CC(o.right)} />
2415
- <top ${CC(o.top)} />
2416
- <bottom ${CC(o.bottom)} />
2417
- <diagonal ${CC(o.diagonal)} />
2413
+ <left ${SC(o.left)} />
2414
+ <right ${SC(o.right)} />
2415
+ <top ${SC(o.top)} />
2416
+ <bottom ${SC(o.bottom)} />
2417
+ <diagonal ${SC(o.diagonal)} />
2418
2418
  </border>
2419
- `);return kf`
2419
+ `);return $f`
2420
2420
  <borders count="${e.length}">
2421
- ${Df(t)}
2421
+ ${kf(t)}
2422
2422
  </borders>
2423
2423
  `}(e.borders)}
2424
- ${function(e){const t=[];for(let o of e){const e=[["numFmtId",o.numFmtId],["fillId",o.fillId],["fontId",o.fontId],["borderId",o.borderId]],i=[];o.alignment&&o.alignment.vertical&&i.push(["vertical",o.alignment.vertical]),o.alignment&&o.alignment.horizontal&&i.push(["horizontal",o.alignment.horizontal]),t.push(kf`
2425
- <xf ${Nf(e)}>
2426
- ${i?kf`<alignment ${Nf(i)} />`:""}
2424
+ ${function(e){const t=[];for(let o of e){const e=[["numFmtId",o.numFmtId],["fillId",o.fillId],["fontId",o.fontId],["borderId",o.borderId]],i=[];o.alignment&&o.alignment.vertical&&i.push(["vertical",o.alignment.vertical]),o.alignment&&o.alignment.horizontal&&i.push(["horizontal",o.alignment.horizontal]),t.push($f`
2425
+ <xf ${_f(e)}>
2426
+ ${i?$f`<alignment ${_f(i)} />`:""}
2427
2427
  </xf>
2428
- `)}return kf`
2428
+ `)}return $f`
2429
2429
  <cellXfs count="${e.length}">
2430
- ${Df(t)}
2430
+ ${kf(t)}
2431
2431
  </cellXfs>
2432
2432
  `}(e.styles)}
2433
- ${function(e){const t=[];for(const o of e){let e=kf``;o.font&&(e=bC(o.font));let i=kf``;o.fill&&(i=kf`
2433
+ ${function(e){const t=[];for(const o of e){let e=$f``;o.font&&(e=CC(o.font));let i=$f``;o.fill&&(i=$f`
2434
2434
  <fill>
2435
2435
  <patternFill>
2436
- <bgColor rgb="${ui(o.fill.fgColor.rgb)}" />
2436
+ <bgColor rgb="${gi(o.fill.fgColor.rgb)}" />
2437
2437
  </patternFill>
2438
2438
  </fill>
2439
- `),t.push(kf`
2439
+ `),t.push($f`
2440
2440
  <dxf>
2441
2441
  ${e}
2442
2442
  ${i}
2443
2443
  </dxf>
2444
- `)}return kf`
2444
+ `)}return $f`
2445
2445
  <dxfs count="${e.length}">
2446
- ${Df(t)}
2446
+ ${kf(t)}
2447
2447
  </dxfs>
2448
2448
  `}(e.dxfs)}
2449
2449
  </styleSheet>
2450
- `;var o;return Of(_f(t),"xl/styles.xml","styles")}(o)),t.push(function(e){const t=[["xmlns",Xp.sst],["count",e.length],["uniqueCount",e.length]],o=e.map((e=>kf`<si><t>${e}</t></si>`));return Of(_f(kf`
2451
- <sst ${Nf(t)}>
2452
- ${Df(o)}
2450
+ `;var o;return Mf(Ff(t),"xl/styles.xml","styles")}(o)),t.push(function(e){const t=[["xmlns",Yp.sst],["count",e.length],["uniqueCount",e.length]],o=e.map((e=>$f`<si><t>${e}</t></si>`));return Mf(Ff($f`
2451
+ <sst ${_f(t)}>
2452
+ ${kf(o)}
2453
2453
  </sst>
2454
- `),"xl/sharedStrings.xml","sharedStrings")}(o.sharedStrings)),t.push(...function(e){const t=[];for(const o of e){const e=[];for(const t of o.rels){const o=[["Id",t.id],["Target",t.target],["Type",t.type]];t.targetMode&&o.push(["TargetMode",t.targetMode]),e.push(kf`
2455
- <Relationship ${Nf(o)} />
2456
- `)}const i=kf`
2457
- <Relationships xmlns="${Xp.Relationships}">
2458
- ${Df(e)}
2454
+ `),"xl/sharedStrings.xml","sharedStrings")}(o.sharedStrings)),t.push(...function(e){const t=[];for(const o of e){const e=[];for(const t of o.rels){const o=[["Id",t.id],["Target",t.target],["Type",t.type]];t.targetMode&&o.push(["TargetMode",t.targetMode]),e.push($f`
2455
+ <Relationship ${_f(o)} />
2456
+ `)}const i=$f`
2457
+ <Relationships xmlns="${Yp.Relationships}">
2458
+ ${kf(e)}
2459
2459
  </Relationships>
2460
- `;t.push(Of(_f(i),o.path))}return t}(o.relsFiles)),t.push(function(e){const t=[];for(const o of e)o.contentType&&t.push(Ff("/"+o.path,Qp[o.contentType]));return Of(_f(kf`
2461
- <Types xmlns="${Xp.Types}">
2460
+ `;t.push(Mf(Ff(i),o.path))}return t}(o.relsFiles)),t.push(function(e){const t=[];for(const o of e)o.contentType&&t.push(Df("/"+o.path,Jp[o.contentType]));return Mf(Ff($f`
2461
+ <Types xmlns="${Yp.Types}">
2462
2462
  <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />
2463
2463
  <Default Extension="xml" ContentType="application/xml" />
2464
- ${Df(t)}
2464
+ ${kf(t)}
2465
2465
  </Types>
2466
- `),"[Content_Types].xml")}(t)),t.push(function(){const e=[["Id","rId1"],["Type",Jp.document],["Target","xl/workbook.xml"]];return Of(_f(kf`
2467
- <Relationships xmlns="${Xp.Relationships}">
2468
- <Relationship ${Nf(e)} />
2466
+ `),"[Content_Types].xml")}(t)),t.push(function(){const e=[["Id","rId1"],["Type",em.document],["Target","xl/workbook.xml"]];return Mf(Ff($f`
2467
+ <Relationships xmlns="${Yp.Relationships}">
2468
+ <Relationship ${_f(e)} />
2469
2469
  </Relationships>
2470
- `),"_rels/.rels")}()),{name:"my_spreadsheet.xlsx",files:t}}function MC(e,t,o,i,n){let r=o;if(!e.filterTables.length)return new Gp("");const s=`xl/worksheets/_rels/sheet${t}.xml.rels`,a=[];for(const t of e.filterTables){const o=ef(i.relsFiles,s,{target:`../tables/table${r}.xml`,type:Jp.table});n.push(Of(EC(t,r,e),`xl/tables/table${r}.xml`,"table")),a.push(kf`<tablePart r:id="${o}" />`),r++}return kf`
2470
+ `),"_rels/.rels")}()),{name:"my_spreadsheet.xlsx",files:t}}function NC(e,t,o,i,n){let r=o;if(!e.filterTables.length)return new qp("");const s=`xl/worksheets/_rels/sheet${t}.xml.rels`,a=[];for(const t of e.filterTables){const o=tf(i.relsFiles,s,{target:`../tables/table${r}.xml`,type:em.table});n.push(Mf(wC(t,r,e),`xl/tables/table${r}.xml`,"table")),a.push($f`<tablePart r:id="${o}" />`),r++}return $f`
2471
2471
  <tableParts count="${e.filterTables.length}">
2472
- ${Df(a)}
2472
+ ${kf(a)}
2473
2473
  </tableParts>
2474
- `}var NC;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(NC||(NC={}));const _C={},FC={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:O,HEADER_WIDTH:M,TOPBAR_HEIGHT:63,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:N,DEFAULT_CELL_HEIGHT:_,SCROLLBAR_WIDTH:F},DC={autofillModifiersRegistry:Ag,autofillRulesRegistry:Og,cellMenuRegistry:Nr,colMenuRegistry:_r,linkMenuRegistry:Lg,functionRegistry:Yd,featurePluginRegistry:vb,statefulUIPluginRegistry:bb,coreViewsPluginRegistry:Cb,corePluginRegistry:fb,rowMenuRegistry:Fr,sidePanelRegistry:yp,figureRegistry:Wg,sheetMenuRegistry:jg,chartSidePanelComponentRegistry:pp,chartComponentRegistry:Rn,chartRegistry:In,topbarMenuRegistry:Yg,topbarComponentRegistry:xp,clickableCellRegistry:Sb,otRegistry:Kg,inverseCommandRegistry:Gg,urlRegistry:gg,cellPopoverRegistry:zg},kC={args:zr,toBoolean:Qr,toJsDate:Jr,toNumber:Zr,toString:Xr,toXC:kt,toZone:Oo,toCartesian:Dt,numberToLetters:_t,createFullMenuItem:An,UuidGenerator:To,formatValue:no,computeTextWidth:ke,createEmptyWorkbookData:sv,createEmptySheet:rv,createEmptyExcelSheet:av,getDefaultChartJsRuntime:Qi,chartFontColor:$i,getMenuChildren:Fn,ChartColors:ki,EvaluationError:c,CellErrorLevel:l,getFillingMode:tn,rgbaToHex:vt,colorToRGBA:bt,positionToZone:Yo,isDefined:Qe},$C={isMarkdownLink:We,parseMarkdownLink:Ze,markdownLink:qe,openLink:bg,urlRepresentation:vg},PC={ChartPanel:mp,ChartFigure:Hn,ChartJsComponent:ei,Grid:Wp,GridOverlay:Ap,ScorecardChart:ci,LineConfigPanel:hp,LineBarPieDesignPanel:sp,BarConfigPanel:tp,LineBarPieConfigPanel:ep,GaugeChartConfigPanel:lp,GaugeChartDesignPanel:cp,ScorecardChartConfigPanel:up,ScorecardChartDesignPanel:gp};e.AbstractChart=gi,e.CorePlugin=lv,e.DATETIME_FORMAT=j,e.DispatchResult=wi,e.EvaluationError=c,e.Model=class extends qv{constructor(e={},o={},i=[],n=new To,r=!0){super(),this.corePlugins=[],this.featurePlugins=[],this.statefulUIPlugins=[],this.coreViewsPlugins=[],this.isReplayingCommand=!1,this.renderers=[],this.status=0,this.handlers=[],this.coreHandlers=[],this.dispatch=(e,t)=>{const o={...t,type:e};let i=this.status;if(this.getters.isReadonly()&&(n=o,!Ci.has(n.type)))return new wi(67);var n;if(!this.session.canApplyOptimisticUpdate())return new wi(64);switch(i){case 0:const t=this.checkDispatchAllowed(o);if(!t.isSuccessful)return t;this.status=1;const{changes:i,commands:n}=this.state.recordChanges((()=>{Ei(o)&&this.state.addCommand(o),this.dispatchToHandlers(this.handlers,o),this.finalize()}));this.session.save(n,i),this.status=0,this.trigger("update");break;case 1:if(Ei(o)){const e=this.checkDispatchAllowed(o);if(!e.isSuccessful)return e;this.state.addCommand(o)}this.dispatchToHandlers(this.handlers,o);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(Ei(o))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,o)}return wi.Success},this.dispatchFromCorePlugin=(e,t)=>{const o={...t,type:e},i=this.status;this.status=2;const n=this.isReplayingCommand?[this.range,...this.corePlugins,...this.coreViewsPlugins]:this.handlers;return this.dispatchToHandlers(n,o),this.status=i,wi.Success},i=iv(e,i);const s=tv(e,r);this.state=new qb,this.uuidGenerator=n,this.config=this.setupConfig(o),this.session=this.setupSession(s.revisionId),this.history=new Hb(this.dispatchFromCorePlugin,this.session),this.coreGetters={},this.range=new Iv(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 Gb(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of fb.getAll())this.setupCorePlugin(e,s);Object.assign(this.getters,this.coreGetters);for(let e of bb.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t)}for(let e of Cb.getAll()){const t=this.setupUiPlugin(e);this.coreViewsPlugins.push(t),this.handlers.push(t),this.coreHandlers.push(t)}for(let e of vb.getAll()){const t=this.setupUiPlugin(e);this.featurePlugins.push(t),this.handlers.push(t)}this.uuidGenerator.setIsFastStrategy(!1),this.handlers.push(this.history),this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.setupSessionEvents(),this.session.loadInitialMessages(i),this.joinSession(),o.snapshotRequested&&(this.session.snapshot(this.exportData()),this.garbageCollectExternalResources()),t.markRaw(this)}joinSession(){this.session.join(this.config.client)}leaveSession(){this.session.leave()}setupUiPlugin(e){const t=new e(this.uiPluginConfig);for(let o of e.getters){if(!(o in t))throw new Error(`Invalid getter name: ${o} for plugin ${t.constructor}`);if(o in this.getters)throw new Error(`Getter "${o}" is already defined.`);this.getters[o]=t[o].bind(t)}const o=e.layers.map((e=>[t,e]));return this.renderers.push(...o),this.renderers.sort(((e,t)=>e[1]-t[1])),t}setupCorePlugin(e,t){const o=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in o))throw new Error(`Invalid getter name: ${t} for plugin ${o.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=o[t].bind(o)}o.import(t),this.corePlugins.push(o),this.coreHandlers.push(o),this.handlers.push(o)}onRemoteRevisionReceived({commands:e}){for(let t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new tb(zb(e,this.state.recordChanges.bind(this.state),(e=>{this.checkDispatchAllowed(e).isSuccessful&&(this.isReplayingCommand=!0,this.dispatchToHandlers([this.range,...this.corePlugins,...this.coreViewsPlugins],e),this.isReplayingCommand=!1)})),this.config.transportService,e)}setupSessionEvents(){this.session.on("remote-revision-received",this,this.onRemoteRevisionReceived),this.session.on("revision-redone",this,this.finalize),this.session.on("revision-undone",this,this.finalize),this.session.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.session.on("collaborative-event-received",this,(()=>{this.trigger("update")}))}setupConfig(e){const t=e.client||{id:this.uuidGenerator.uuidv4(),name:r("Anonymous").toString()},o=e.transportService||new _b;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:e.external||{},transportService:o,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e),lazyEvaluation:!("lazyEvaluation"in e)||e.lazyEvaluation}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,uuidGenerator:this.uuidGenerator,custom:this.config.custom,external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,lazyEvaluation:this.config.lazyEvaluation}}checkDispatchAllowed(e){const t=this.handlers.map((t=>t.allowDispatch(e)));return new wi(t.flat())}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0}dispatchToHandlers(e,t){t=Me(t);for(const o of e)o.beforeHandle(t);for(const o of e)o.handle(t)}drawGrid(e){for(let[t,o]of this.renderers)e.ctx.save(),t.drawGrid(e,o),e.ctx.restore()}exportData(){let e=sv();for(let t of this.handlers)t instanceof lv&&t.export(e);return e.revisionId=this.session.getRevisionId()||Y,e=Me(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:[av(ev,"Sheet1")]};for(let t of this.handlers)t instanceof Wu&&t.exportForExcel(e);return e=Me(e),OC(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.Registry=xn,e.Revision=Jv,e.SPREADSHEET_DIMENSIONS=FC,e.Spreadsheet=Nb,e.UIPlugin=Gu,e.__info__=_C,e.addFunction=function(e,t){Yd.add(e,t)},e.astToFormula=Iu,e.compile=Uu,e.components=PC,e.convertAstNodes=xu,e.coreTypes=Si,e.findCellInNewZone=jo,e.functionCache=Lu,e.helpers=kC,e.invalidateEvaluationCommands=vi,e.links=$C,e.load=tv,e.parse=wu,e.readonlyAllowedCommands=Ci,e.registries=DC,e.setTranslationMethod=function(e){o=e},e.tokenize=eu,Object.defineProperty(e,"__esModule",{value:!0}),_C.version="16.1.14",_C.date="2023-06-12T13:50:13.693Z",_C.hash="a51d9fa"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
2474
+ `}var _C;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(_C||(_C={}));const FC={},DC={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:O,HEADER_WIDTH:M,TOPBAR_HEIGHT:63,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:N,DEFAULT_CELL_HEIGHT:_,SCROLLBAR_WIDTH:F},kC={autofillModifiersRegistry:Og,autofillRulesRegistry:Mg,cellMenuRegistry:_r,colMenuRegistry:Fr,linkMenuRegistry:Ug,functionRegistry:Kd,featurePluginRegistry:bb,statefulUIPluginRegistry:Cb,coreViewsPluginRegistry:Sb,corePluginRegistry:vb,rowMenuRegistry:Dr,sidePanelRegistry:xp,figureRegistry:Gg,sheetMenuRegistry:Xg,chartSidePanelComponentRegistry:mp,chartComponentRegistry:Tn,chartRegistry:Rn,topbarMenuRegistry:Kg,topbarComponentRegistry:Ip,clickableCellRegistry:Eb,otRegistry:Qg,inverseCommandRegistry:qg,urlRegistry:pg,cellPopoverRegistry:Bg},$C={args:Br,toBoolean:Jr,toJsDate:es,toNumber:jr,toString:Yr,toXC:$t,toZone:Mo,toCartesian:kt,numberToLetters:Ft,createFullMenuItem:On,UuidGenerator:Ao,formatValue:ro,computeTextWidth:ke,createEmptyWorkbookData:av,createEmptySheet:sv,createEmptyExcelSheet:lv,getDefaultChartJsRuntime:Ji,chartFontColor:Pi,getMenuChildren:Dn,ChartColors:$i,EvaluationError:c,CellErrorLevel:l,getFillingMode:on,rgbaToHex:bt,colorToRGBA:Ct,positionToZone:Ko,isDefined:Je},PC={isMarkdownLink:Ge,parseMarkdownLink:je,markdownLink:Ze,openLink:Cg,urlRepresentation:bg},LC={ChartPanel:fp,ChartFigure:Wn,ChartJsComponent:ti,Grid:Gp,GridOverlay:Op,ScorecardChart:hi,LineConfigPanel:dp,LineBarPieDesignPanel:ap,BarConfigPanel:op,LineBarPieConfigPanel:tp,GaugeChartConfigPanel:cp,GaugeChartDesignPanel:hp,ScorecardChartConfigPanel:gp,ScorecardChartDesignPanel:pp};e.AbstractChart=pi,e.CorePlugin=cv,e.DATETIME_FORMAT=j,e.DispatchResult=yi,e.EvaluationError=c,e.Model=class extends Zv{constructor(e={},o={},i=[],n=new Ao,r=!0){super(),this.corePlugins=[],this.featurePlugins=[],this.statefulUIPlugins=[],this.coreViewsPlugins=[],this.isReplayingCommand=!1,this.renderers=[],this.status=0,this.handlers=[],this.coreHandlers=[],this.dispatch=(e,t)=>{const o={...t,type:e};let i=this.status;if(this.getters.isReadonly()&&(n=o,!Si.has(n.type)))return new yi(67);var n;if(!this.session.canApplyOptimisticUpdate())return new yi(64);switch(i){case 0:const t=this.checkDispatchAllowed(o);if(!t.isSuccessful)return t;this.status=1;const{changes:i,commands:n}=this.state.recordChanges((()=>{wi(o)&&this.state.addCommand(o),this.dispatchToHandlers(this.handlers,o),this.finalize()}));this.session.save(n,i),this.status=0,this.trigger("update");break;case 1:if(wi(o)){const e=this.checkDispatchAllowed(o);if(!e.isSuccessful)return e;this.state.addCommand(o)}this.dispatchToHandlers(this.handlers,o);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(wi(o))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,o)}return yi.Success},this.dispatchFromCorePlugin=(e,t)=>{const o={...t,type:e},i=this.status;this.status=2;const n=this.isReplayingCommand?[this.range,...this.corePlugins,...this.coreViewsPlugins]:this.handlers;return this.dispatchToHandlers(n,o),this.status=i,yi.Success},i=nv(e,i);const s=ov(e,r);this.state=new Zb,this.uuidGenerator=n,this.config=this.setupConfig(o),this.session=this.setupSession(s.revisionId),this.history=new Wb(this.dispatchFromCorePlugin,this.session),this.coreGetters={},this.range=new Rv(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 qb(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of vb.getAll())this.setupCorePlugin(e,s);Object.assign(this.getters,this.coreGetters);for(let e of Cb.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t)}for(let e of Sb.getAll()){const t=this.setupUiPlugin(e);this.coreViewsPlugins.push(t),this.handlers.push(t),this.coreHandlers.push(t)}for(let e of bb.getAll()){const t=this.setupUiPlugin(e);this.featurePlugins.push(t),this.handlers.push(t)}this.uuidGenerator.setIsFastStrategy(!1),this.handlers.push(this.history),this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.setupSessionEvents(),this.session.loadInitialMessages(i),this.joinSession(),o.snapshotRequested&&(this.session.snapshot(this.exportData()),this.garbageCollectExternalResources()),t.markRaw(this)}joinSession(){this.session.join(this.config.client)}leaveSession(){this.session.leave()}setupUiPlugin(e){const t=new e(this.uiPluginConfig);for(let o of e.getters){if(!(o in t))throw new Error(`Invalid getter name: ${o} for plugin ${t.constructor}`);if(o in this.getters)throw new Error(`Getter "${o}" is already defined.`);this.getters[o]=t[o].bind(t)}const o=e.layers.map((e=>[t,e]));return this.renderers.push(...o),this.renderers.sort(((e,t)=>e[1]-t[1])),t}setupCorePlugin(e,t){const o=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in o))throw new Error(`Invalid getter name: ${t} for plugin ${o.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=o[t].bind(o)}o.import(t),this.corePlugins.push(o),this.coreHandlers.push(o),this.handlers.push(o)}onRemoteRevisionReceived({commands:e}){for(let t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new ob(Bb(e,this.state.recordChanges.bind(this.state),(e=>{this.checkDispatchAllowed(e).isSuccessful&&(this.isReplayingCommand=!0,this.dispatchToHandlers([this.range,...this.corePlugins,...this.coreViewsPlugins],e),this.isReplayingCommand=!1)})),this.config.transportService,e)}setupSessionEvents(){this.session.on("remote-revision-received",this,this.onRemoteRevisionReceived),this.session.on("revision-redone",this,this.finalize),this.session.on("revision-undone",this,this.finalize),this.session.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.session.on("collaborative-event-received",this,(()=>{this.trigger("update")}))}setupConfig(e){const t=e.client||{id:this.uuidGenerator.uuidv4(),name:r("Anonymous").toString()},o=e.transportService||new Fb;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:e.external||{},transportService:o,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e),lazyEvaluation:!("lazyEvaluation"in e)||e.lazyEvaluation}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,uuidGenerator:this.uuidGenerator,custom:this.config.custom,external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,lazyEvaluation:this.config.lazyEvaluation}}checkDispatchAllowed(e){const t=this.handlers.map((t=>t.allowDispatch(e)));return new yi(t.flat())}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0}dispatchToHandlers(e,t){t=Me(t);for(const o of e)o.beforeHandle(t);for(const o of e)o.handle(t)}drawGrid(e){for(let[t,o]of this.renderers)e.ctx.save(),t.drawGrid(e,o),e.ctx.restore()}exportData(){let e=av();for(let t of this.handlers)t instanceof cv&&t.export(e);return e.revisionId=this.session.getRevisionId()||Y,e=Me(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={...av(),sheets:[lv(tv,"Sheet1")]};for(let t of this.handlers)t instanceof Gu&&t.exportForExcel(e);return e=Me(e),MC(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.Registry=In,e.Revision=eb,e.SPREADSHEET_DIMENSIONS=DC,e.Spreadsheet=_b,e.UIPlugin=qu,e.__info__=FC,e.addFunction=function(e,t){Kd.add(e,t)},e.astToFormula=Ru,e.compile=Vu,e.components=LC,e.convertAstNodes=Iu,e.coreTypes=Ei,e.findCellInNewZone=Xo,e.functionCache=Uu,e.helpers=$C,e.invalidateEvaluationCommands=bi,e.links=PC,e.load=ov,e.parse=yu,e.readonlyAllowedCommands=Si,e.registries=kC,e.setTranslationMethod=function(e){o=e},e.tokenize=tu,Object.defineProperty(e,"__esModule",{value:!0}),FC.version="16.1.15",FC.date="2023-06-26T14:33:07.859Z",FC.hash="2b264ad"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);