@odoo/o-spreadsheet 16.2.9 → 16.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- !function(e,t){"use strict";let i=e=>e;function o(e,...t){if(1===t.length&&"object"==typeof t[0]){const i=t[0];e=e.replace(/\%\(?([^\)]+)\)s/g,((e,t)=>i[t]))}else t.length>0&&(e=e.replace(/\%s/g,(()=>t.shift())));return e}const n=function(e,...t){return o(i(e),...t)},s=function(e,...t){return new r(e,t)};class r extends String{constructor(e,t){super(e),this.values=t}valueOf(){const e=super.valueOf();return o(i(e),...this.values)}toString(){return this.valueOf()}}var a,l;!function(e){e.NotAvailable="#N/A",e.InvalidReference="#REF",e.BadExpression="#BAD_EXPR",e.CircularDependency="#CYCLE",e.UnknownFunction="#NAME?",e.GenericError="#ERROR"}(a||(a={})),function(e){e[e.silent=0]="silent",e[e.error=1]="error"}(l||(l={}));class c extends Error{constructor(e,t,i=l.error){super(t),this.errorType=e,this.logLevel=i}}class h extends c{constructor(e){super(a.BadExpression,e)}}class d extends c{constructor(){super(a.CircularDependency,s("Circular reference"))}}class u extends c{constructor(){super(a.InvalidReference,s("Invalid reference"))}}class g extends c{constructor(e){super(a.NotAvailable,e||s("Data not available"),e?l.error:l.silent)}}class p extends c{constructor(e){super(a.UnknownFunction,s('Unknown function: "%s"',e))}}const m=.5,f="#f5f5f5",v="#F8F9FA",b="#E8EAED",S="#595959",C="#666666",E="#3266ca",w="#FFFFFF",y=11982760,x="#01666b",I="#188038",R="#E6F4EA",T="#CEEAD6",A="#E0E2E4",M=["#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,N=48,_=96,F=23,D=15,k=18,L=14,P=4,U=4,V=3,z=U,B=17,H=250,$=1,W="400",G=10,q="'Roboto', arial",Z=["thin","#000"],j=["thin",I],X=/[ymdhs:]/,Y=a.InvalidReference,K="START_REVISION",Q=20,J="??",ee="difference",te="#00A04A",ie="#DC6965",oe=.4,ne=["'","*","?","/","\\","[","]"],se=/'|\*|\?|\/|\\|\[|\]/,re="|",ae=s("Invalid expression");var le;!function(e){e[e.Grid=0]="Grid",e[e.Highlight=5]="Highlight",e[e.Figure=10]="Figure",e[e.ScrollBar=15]="ScrollBar",e[e.GridPopover=19]="GridPopover",e[e.GridComposer=20]="GridComposer",e[e.Dropdown=21]="Dropdown",e[e.IconPicker=25]="IconPicker",e[e.TopBarComposer=30]="TopBarComposer",e[e.Popover=35]="Popover",e[e.ChartAnchor=1e3]="ChartAnchor"}(le||(le={}));const ce="\n",he=[6,7,8,9,10,11,12,14,18,24,36],de=new Date(1899,11,30),ue=864e5,ge=2e3,pe=(new Date).getFullYear(),me=new Date(0)-de,fe=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,ve=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,be=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function Se(e){let t;const i=(e=e.trim()).match(be);if(i){if(t=function(e){if(e=e.trim(),be.test(e)){const t=/AM/i.test(e),i=/PM/i.test(e),o=(t||i?e.substring(0,e.length-2).trim():e).split(/:/),n=o.length>=2,s=3===o.length;let r=Number(o[0]),a=n?Number(o[1]):0,l=s?Number(o[2]):0,c=s?"hh:mm:ss":"hh:mm";if(t||i)c+=" a";else if(!n)return null;r>=12&&t?r-=12:r<12&&i&&(r+=12),a+=Math.floor(l/60),l%=60,r+=Math.floor(a/60),a%=60,r>=24&&(c="hhhh:mm:ss");return{value:r/24+a/1440+l/86400,format:c,jsDate:new Date(1899,11,30,r,a,l)}}return null}(i[0]),null===t)return null;e=e.replace(i[0],"").trim()}let o;const n=e.match(fe),s=e.match(ve);if(n||s){let t;if(n?(t=n[0],o=Ce(t,"mdy")):(t=s[0],o=Ce(t,"ymd")),null===o)return null;e=e.replace(t,"").trim()}return""!==e||!o&&!t?null:o&&t?{value:o.value+t.value,format:o.format+" "+("hhhh:mm:ss"===t.format?"hh:mm:ss":t.format),jsDate:new Date(o.jsDate.getFullYear()+t.jsDate.getFullYear()-1899,o.jsDate.getMonth()+t.jsDate.getMonth()-11,o.jsDate.getDate()+t.jsDate.getDate()-30,o.jsDate.getHours()+t.jsDate.getHours(),o.jsDate.getMinutes()+t.jsDate.getMinutes(),o.jsDate.getSeconds()+t.jsDate.getSeconds())}:o||t}function Ce(e,t){const i="mdy"===t;if(i||"ymd"===t){const t=e.split(/\/|-|\s/),o=i?0:1,n=i?1:2,s=i?2:0,r=Number(t[o]),a=Number(t[n]),l=2===t[o].length&&r<10||2===t[n].length&&a<10,c=t[s]?function(e){const t=Number(e);switch(e.length){case 1:return ge+t;case 2:return ge+(ge+t>pe+10?-100:0)+t;case 3:case 4:return t}return 0}(t[s]):pe,h=new Date(c,r-1,a),d=e.match(/\/|-|\s/)[0];if(h.getMonth()!==r-1||h.getDate()!==a)return null;const u=h-de;let g=l?`mm${d}dd`:`m${d}d`;return t[s]&&(g=i?g+d+"yyyy":"yyyy"+d+g),{value:Math.round(u/ue),format:g,jsDate:h}}return null}function Ee(e){const t=Math.trunc(e);let i=new Date(t*ue-me),o=e-t;o=o<0?1+o:o;const n=Math.round(24*o),s=Math.round(24*(o-n/24)*60),r=Math.round(24*(o-n/24-s/24/60)*60*60);return i.setHours(n),i.setMinutes(s),i.setSeconds(r),i}function we(e){const t=e.getTime()-de.getTime();return Math.round(t/ue)}function ye(e){return new Date(e.getFullYear(),e.getMonth()+1,0).getDate()}function xe(e){return ye(e)===e.getDate()}function Ie(e,t,i){const o=e.getFullYear(),n=e.getMonth(),s=e.getDate(),r=new Date(o,n+t);return i&&s===ye(e)||s>ye(r)?r.setDate(ye(r)):r.setDate(s),r}function Re(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function Te(e,t,i){if(e===t)return 0;if(e>t){const i=t;t=e,e=i}const o=Ee(e),n=Ee(t);let s=o.getDate(),r=n.getDate();const a=o.getMonth(),l=n.getMonth(),c=o.getFullYear(),h=n.getFullYear();let d=0,u=0;switch(i){case 0:31===s&&(s=30),30===s&&31===r&&(r=30),1===a&&s===(Re(c)?29:28)&&(s=30,1===l&&r===(Re(h)?29:28)&&(r=30)),d=c+(30*a+s)/360,u=h+(30*l+r)/360;break;case 1:let i=365;const o=c===h;if(!o&&!(c+1===h)||!o&&a<l||!o&&a===l&&s<r){let e=0,t=0;for(let i=c;i<=h;i++)e++,t+=Re(i)?366:365;i=t/e}else o?Re(c)&&(i=366):(Re(c)&&a<2&&(i=366),Re(h)&&(l>1||1===l&&29===r)&&(i=366));d=e/i,u=t/i;break;case 2:d=e/360,u=t/360;break;case 3:d=e/365,u=t/365;break;case 4:31===s&&(s=30),31===r&&(r=30),d=c+(30*a+s)/360,u=h+(30*l+r)/360}return u-d}function Ae(e){return JSON.stringify(e,Object.keys(e).sort())}function Me(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 Ne(e){const t=Array.isArray(e)?[]:{};switch(typeof e){case"object":if(null===e)return e;if(function(e){return"clone"in e&&e.clone instanceof Function}(e))return e.clone();if(!(function(e){return"object"==typeof e&&(null==e?void 0:e.constructor)===Object}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");for(const i in e)t[i]=Ne(e[i]);return t;case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function _e(e){return e.startsWith("'")&&(e=e.slice(1,-1).replace(/''/g,"'")),e}function Fe(e){var t;return(null===(t=e.match(/\w/g))||void 0===t?void 0:t.length)!==e.length&&(e=`'${e}'`),e}function De(e,t,i){return e<t?t:e>i?i:e}function ke(e,t=1){return t*(e+U)-U}function Le(e,t,i){e.save(),e.font=Ue(i);const o=e.measureText(t).width;return e.restore(),o}function Pe(e){return Math.round(96*e/72)}function Ue(e){return`${e.italic?"italic ":""}${e.bold?"bold":W} ${Ve(e)}px ${q}`}function Ve(e){return Pe((null==e?void 0:e.fontSize)||G)}function ze(e,t,i=1){if(t<=e&&i>0)return[];if(0===i)throw new Error("range() step must not be zero");const o=Math.ceil(Math.abs((t-e)/i)),n=Array(o);for(let t=0;t<o;t++)n[t]=e+t*i;return n}function Be(e){return e.reduce(((e,t,i,o)=>{if(1===Math.abs(t-o[i-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*He(e,t){t.next();for(const i of e){const e=t.next();yield{...i,next:e.done?void 0:e.value}}}function $e(e){return null!==Se(e)}const We=/^\[([^\[]+)\]\((.+)\)$/,Ge=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function qe(e){return We.test(e)}function Ze(e){return Ge.test(e)}function je(e,t){return`[${e}](${t})`}function Xe(e){const t=e.match(We)||[],i=t[1],o=t[2];if(!i||!o)throw new Error(`Could not parse markdown link ${e}.`);return{label:i,url:o}}const Ye="o-spreadsheet://";function Ke(e){return e.startsWith(Ye)}function Qe(e){return`${Ye}${e}`}function Je(e){if(e.startsWith(Ye))return e.substr(Ye.length);throw new Error(`${e} is not a valid sheet link`)}function et(e){return void 0!==e}function tt(e){return void 0===e||Object.values(e).every((e=>"object"==typeof e?tt(e):!e))}function it(e,t){for(let[i,o]of Object.entries(t))if(Ae(o)===Ae(e))return parseInt(i,10);const i=Object.keys(t),o=0===i.length?0:Math.max(...i.map((e=>parseInt(e,10))));return t[o+1]=e,o+1}function ot(e){let t="";for(let i=0,o=e.length;i<o;i++)t+=e[i];return t}function nt(e){let t,i=!1;const o=()=>(i||(t=e instanceof Function?e():e,i=!0),t);return o.map=e=>nt((()=>e(o()))),o}function st(e,t){let i=e.slice(t).find((e=>e));return i||(i=e.slice(0,t).reverse().find((e=>e))),i||""}function rt(e,t){return"after"===e?t+1:t}function at(e,t){if(e===t)return!0;if(e&&!t||t&&!e)return!1;const i=new Set;Object.keys(e).forEach((e=>i.add(e))),Object.keys(t).forEach((e=>i.add(e)));for(let o of i){if(typeof e[o]!=typeof e[o])return!1;if("object"==typeof e[o]){if(!at(e[o],t[o]))return!1}else if(e[o]!==t[o])return!1}return!0}function lt(e){const t={...e};return Object.keys(t).forEach((e=>!t[e]&&delete t[e])),t}function ct(e){return e?e.toLowerCase():""}const ht=[" ","\t","\f","\v",String.fromCharCode(parseInt("00a0",16)),String.fromCharCode(parseInt("1680",16)),String.fromCharCode(parseInt("2000",16)),String.fromCharCode(parseInt("200a",16)),String.fromCharCode(parseInt("2028",16)),String.fromCharCode(parseInt("2029",16)),String.fromCharCode(parseInt("202f",16)),String.fromCharCode(parseInt("205f",16)),String.fromCharCode(parseInt("3000",16)),String.fromCharCode(parseInt("feff",16))],dt=new RegExp(ht.join("|"),"g"),ut=/\r\n|\r|\n/g;function gt(e){return e?e=(e=e.replace(dt," ")).replace(ut,ce):""}const pt=/rgba?\(|\s+|\)/gi,mt=/^#([A-F\d]{2}){3,4}$/g,ft=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function vt(e){return bt(e.toString(16).padStart(6,"0"))}function bt(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(pt,"").split(",");let i=255;if(3!==t.length&&4!==t.length)throw new Error("invalid color");if(4===t.length){const e=parseFloat(t.pop()||"1");i=Math.round(255*(e||1))}const o=t.map((e=>parseInt(e,10)));255!==i&&o.push(i);return"#"+ot(o.map((e=>e.toString(16).padStart(2,"0")))).toUpperCase()}(e):(t=e.replace("#","").toUpperCase(),3!==t.length&&4!==t.length||(t=t.split("").reduce(((e,t)=>e+t+t),"")),t=`#${t}`),!t.match(mt))throw new Error(`invalid color input: ${e}`);return t}function St(e){try{return bt(e),!0}catch(e){return!1}}const Ct=e=>e>=0&&e<=255;function Et(e,t,i,o=1){if(!Ct(e)||!Ct(t)||!Ct(i)||o<0||o>1)throw new Error(`Invalid RGBA values ${[e,t,i,o]}`);return{a:o,b:i,g:t,r:e}}function wt(e){let{r:t,g:i,b:o}=xt(e);t/=255,i/=255,o/=255;const n=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return.2126*n(t)+.7152*n(i)+.0722*n(o)}function yt(e){let t=e.r.toString(16),i=e.g.toString(16),o=e.b.toString(16),n=Math.round(255*e.a).toString(16);return 1==t.length&&(t="0"+t),1==i.length&&(i="0"+i),1==o.length&&(o="0"+o),1==n.length&&(n="0"+n),"ff"===n&&(n=""),("#"+t+i+o+n).toUpperCase()}function xt(e){let t,i,o,n;if(7===(e=bt(e)).length)t=parseInt(e[1]+e[2],16),i=parseInt(e[3]+e[4],16),o=parseInt(e[5]+e[6],16),n=255;else{if(9!==e.length)throw new Error("Invalid color");t=parseInt(e[1]+e[2],16),i=parseInt(e[3]+e[4],16),o=parseInt(e[5]+e[6],16),n=parseInt(e[7]+e[8],16)}return n=+(n/255).toFixed(3),{a:n,r:t,g:i,b:o}}function It(e){(e={...e}).s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,i=t*(1-Math.abs(e.h/60%2-1)),o=e.l-t/2,n=0,s=0,r=0;return 0<=e.h&&e.h<60?(n=t,s=i,r=0):60<=e.h&&e.h<120?(n=i,s=t,r=0):120<=e.h&&e.h<180?(n=0,s=t,r=i):180<=e.h&&e.h<240?(n=0,s=i,r=t):240<=e.h&&e.h<300?(n=i,s=0,r=t):300<=e.h&&e.h<360&&(n=t,s=0,r=i),n=Math.round(255*(n+o)),s=Math.round(255*(s+o)),r=Math.round(255*(r+o)),{a:e.a,r:n,g:s,b:r}}function Rt(e){const t=e.r/255,i=e.g/255,o=e.b/255;let n=Math.min(t,i,o),s=Math.max(t,i,o),r=s-n,a=0,l=0,c=0;return a=0==r?0:s==t?(i-o)/r%6:s==i?(o-t)/r+2:(t-i)/r+4,a=Math.round(60*a),a<0&&(a+=360),c=(s+n)/2,l=0==r?0:r/(1-Math.abs(2*c-1)),l=+(100*l).toFixed(1),c=+(100*c).toFixed(1),{a:e.a,h:a,s:l,l:c}}const Tt=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),At=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),Mt=new RegExp(/^([A-Z]{1,3})+$/,"i"),Ot=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),Nt=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),_t=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[Tt.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 Ft(e){return Ot.test(e)}function Dt(e){return Nt.test(e)}function kt(e){return Mt.test(e)}function Lt(e){return At.test(e)}function Pt(e){const t=e.split("!"),i=t.pop();return{sheetName:_e(t.join("!"))||void 0,xc:i}}function Ut(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Ut(Math.floor(e/26)-1)+Ut(e%26)}function Vt(e){let t=0;const i=e.length;for(let o=0;o<i;o++){t+=(e.charCodeAt(o)-65+(o<i-1?1:0))*26**(i-o-1)}return t}function zt(e){const t=(e=e.toUpperCase().trim()).match(Tt);if(null!==t){const[i,o,n]=t;if(i===e){return{col:Vt(o),row:parseInt(n,10)-1}}}throw new Error(`Invalid cell description: ${e}`)}function Bt(e,t,i={colFixed:!1,rowFixed:!1}){return(i.colFixed?"$":"")+Ut(e)+(i.rowFixed?"$":"")+String(t+1)}const Ht=140,$t=20,Wt=.035;function Gt(e){return $t+(Ht-$t)*Math.exp(-Wt*(e-1))}const qt=/(^-?\d+(\.?\d*(e\d+)?)?|^-?\.\d+)(?!\w|!)/,Zt="(\\s*(\\d+(,\\d{3,})*(\\.\\d*)?)|(\\.\\d+))(e(\\+|-)?\\d+)?(\\s*%)?",jt="(\\s*-)?",Xt="(\\s*[\\$€])?",Yt="^(("+[jt+Xt+Zt,jt+Zt+Xt,Xt+jt+Zt].join(")|(")+"))$",Kt=new RegExp(Yt,"i");function Qt(e){return!!e&&Kt.test(e.trim())}const Jt=/[,\$€]+/g;function ei(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 ti(e,t,i){const o=[...e].sort(((e,t)=>e-t));let n=(o.length+(i?-1:1))*t;if(i||n--,Number.isInteger(n))return o[n];const s=Math.ceil(n),r=Math.floor(n);return o[s]*(n-r)+o[r]*(s-n)}const ii=20,oi=11,ni=/(\d+?)(?=(\d{3})+(?!\d)|$)/g,si=/0/g,ri={0:s("January"),1:s("February"),2:s("March"),3:s("April"),4:s("May"),5:s("June"),6:s("July"),7:s("August"),8:s("September"),9:s("October"),10:s("November"),11:s("December")},ai={0:s("Sunday"),1:s("Monday"),2:s("Tuesday"),3:s("Wednesday"),4:s("Thursday"),5:s("Friday"),6:s("Saturday")},li={};function ci(e){let t=li[e];return void 0===t&&(t=function(e){if(""===e)throw new Error("A format cannot be empty");let t=0,i=[];for(;t<e.length;){let o;if("["===e.charAt(t)){if("$"!==e.charAt(t+1))throw new Error(`Currency formats have to be prefixed by a $: ${e}`);if(o=e.substring(t+1).indexOf("]")+t+2,0===o)throw new Error(`Invalid currency brackets format: ${e}`);const n=e.substring(t+2,o-1);if(n.includes("["))throw new Error(`Invalid currency format: ${e}`);i.push({type:"STRING",format:n})}else{const n=e.substring(t).indexOf("[");o=n>-1?n+t:e.length;const s=e.substring(t,o);s.match(X)?i.push({type:"DATE",format:s}):i.push({type:"NUMBER",format:Ri(s)})}t=o}return i}(e),li[e]=t),t}function hi(e,t){switch(typeof e){case"string":return e;case"boolean":return e?"TRUE":"FALSE";case"number":t||(t=Ci(e));return function(e,t){if("DATE"===t[0].type)return vi(e,t[0].format);let i=e<0?"-":"";for(let o of t)switch(o.type){case"NUMBER":i+=di(Math.abs(e),o.format);break;case"STRING":i+=o.format}return i}(e,ci(t));case"object":return"0"}}function di(e,t){t.isPercent&&(e*=100),e/=t.magnitude;let i=0;void 0!==t.decimalPart&&(i=t.decimalPart.length);const{integerDigits:o,decimalDigits:n}=gi(e,i);let s=function(e,t,i){var o;const n="0"===e?"":e;let s=n;const r=t.length-n.length;if(r>0){const e=(t.substring(0,r).match(si)||[]).length;s="0".repeat(e)+s}i&&(s=(null===(o=s.match(ni))||void 0===o?void 0:o.join(","))||s);return s}(o,t.integerPart,t.thousandsSeparator);return void 0!==t.decimalPart&&(s+="."+function(e,t){let i=e;if(t.length-e.length>0){const o=(t.substring(e.length,t.length+1).match(si)||[]).length;i+="0".repeat(o)}return i}(n||"",t.decimalPart)),t.isPercent&&(s+="%"),s}const ui=[];function gi(e,t=ii){const i=e.toString();if(i.includes("e"))return function(e,t=ii){let i=ui[t];i||(i=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),ui[t]=i);const[o,n]=i.format(e).split(".");return{integerDigits:o,decimalDigits:n}}(e,t);if(Number.isInteger(e))return{integerDigits:i,decimalDigits:void 0};const o=i.indexOf(".");let n=i.substring(0,o),s=i.substring(o+1);if(0===t)return Number(s[0])>=5&&(n=(Number(n)+1).toString()),{integerDigits:n,decimalDigits:void 0};if(s.length>t){const{integerDigits:e,decimalDigits:i}=function(e,t){var i;let o="0",n=e,s=e.slice(0,t);const r=t;if(Number(e[r])<5)return{integerDigits:o,decimalDigits:s};const a=(null===(i=s.match(mi))||void 0===i?void 0:i[0])||"",l=(Number(s)+1).toString(),c=s.slice(a.length),h=l.length>c.length;h&&!a?(o="1",n=void 0):n=h?a.slice(0,-1)+l:a+l;return{integerDigits:o,decimalDigits:n}}(s,t);s=i,"0"!==e&&(n=(Number(n)+Number(e)).toString())}return{integerDigits:n,decimalDigits:pi(s||"")}}function pi(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const mi=/^0+/;function fi(e){try{return vi(1,e),!0}catch(e){return!1}}function vi(e,t){const i=Ee(e),o=t.indexOf("h");let n="",s="";return o>0?(n=bi(i,t.substring(0,o-1)),s=Si(i,t.substring(o))):0===o?s=Si(i,t):o<0&&(n=bi(i,t)),n+(n&&s?" ":"")+s}function bi(e,t){var i;const o=null===(i=t.match(/\/|-|\s/))||void 0===i?void 0:i[0];return(o?t.split(o):[t]).map((i=>{switch(i){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return ai[e.getDay()].slice(0,3);case"dddd":return ai[e.getDay()];case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return ri[e.getMonth()].slice(0,3);case"mmmm":return ri[e.getMonth()];case"mmmmm":return ri[e.getMonth()].slice(0,1);case"yy":const i=String(e.getFullYear()).replace("-","").padStart(2,"0");return i.slice(i.length-2);case"yyyy":return e.getFullYear();default:throw new Error(`invalid format: ${t}`)}})).join(o)}function Si(e,t){let i=t.split(/:|\s/);const o=e.getHours(),n="a"===i[i.length-1];let s=o,r="";return n&&(s=0===s?12:s>12?s-12:s,r=o>=12?" PM":" AM",i.pop()),i.map((i=>{switch(i){case"hhhh":return Math.floor((e.getTime()-de)/36e5).toString();case"hh":return s.toString().padStart(2,"0");case"mm":return e.getMinutes().toString().padStart(2,"0");case"ss":return e.getSeconds().toString().padStart(2,"0");default:throw new Error(`invalid format: ${t}`)}})).join(":")+r}function Ci(e){let{integerDigits:t,decimalDigits:i}=gi(e);if(!i)return"0";const o=t.replace("-","").length;if(o+2>oi)return"0";const n=oi-o-1;return({decimalDigits:i}=gi(e,Math.min(n,i.length))),i?"0."+"0".repeat(i.length):"0"}function Ei(e){if($e(e)){return Se(e).format}if(!Qt(e))return;const t=e.includes(".")?"0.00":"0",i=e.match(/[\$€]/);if(i){const o=e.match(/[\d]/),n="[$"+i.values().next().value+"]";return o.index<i.index?"#,##"+t+n:n+"#,##"+t}return e.includes("%")?t+"%":void 0}function wi(e,t,i){return Ai(ci(e||"#,##0").map((e=>"NUMBER"===e.type?[{...e,format:{...e.format,magnitude:t,decimalPart:void 0}},{type:"STRING",format:i}]:e)).flat())}function yi(e,t){const i=ci(e).map((e=>"NUMBER"===e.type?{...e,format:xi(e.format,t)}:e)),o=Ai(i);return li[o]=i,o}function xi(e,t){var i;const o={...e},n=Math.sign(t),s=(null===(i=o.decimalPart)||void 0===i?void 0:i.length)||0,r=Math.min(Math.max(0,s+n),ii);return o.decimalPart="0".repeat(r),""===o.decimalPart&&delete o.decimalPart,o}const Ii=/,*?$/;function Ri(e){var t;if(function(e){return Boolean(e.replace(Ti,""))}(e=e.trim()))throw new Error(`Invalid number format: ${e}`);const i=e.includes("%"),o=(null===(t=e.match(Ii))||void 0===t?void 0:t[0])||"",n=o?1e3**o.length:1;let s=e.slice(0,e.length-(o.length||0));const r=s.includes(",");if(s.match(/\..*,/))throw new Error("A format can't contain ',' symbol in the decimal part");s=s.replace("%","").replace(",","");const a=s.match(/[\%|,]/);if(a)throw new Error(`A format can only contain a single '${a[0]}' symbol`);const[l,c]=s.split(".");if(c&&c.length>20)throw new Error("A format can't contain more than 20 decimal places");return void 0!==c?{integerPart:l,isPercent:i,thousandsSeparator:r,decimalPart:c,magnitude:n}:{integerPart:l,isPercent:i,thousandsSeparator:r,magnitude:n}}const Ti=/[,#0.%]/g;function Ai(e){let t="";for(let i of e){let e;switch(i.type){case"NUMBER":const t=i.format;e=t.integerPart,t.thousandsSeparator&&(e=e.slice(0,-3)+","+e.slice(-3)),void 0!==t.decimalPart&&(e+="."+t.decimalPart),t.isPercent&&(e+="%"),t.magnitude&&(e+=",".repeat(Math.log10(t.magnitude)/3));break;case"STRING":e=`[$${i.format}]`;break;case"DATE":e=i.format}t+=e}return t}class Mi{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 Mi?e:new Mi(e,t.getSheetSize)}get unboundedZone(){return this._zone}get zone(){const{left:e,top:t,bottom:i,right:o}=this._zone;if(void 0!==o&&void 0!==i)return{left:e,top:t,right:o,bottom:i};if(void 0===i&&void 0!==o)return{right:o,top:t,left:e,bottom:this.getSheetSize(this.sheetId).numberOfRows-1};if(void 0===o&&void 0!==i)return{bottom:i,left:e,top:t,right:this.getSheetSize(this.sheetId).numberOfCols-1};throw new Error(s("Bad zone format"))}static getRangeParts(e,t){const i=e.split(":").map((e=>{const t=Dt(e);return{colFixed:!t&&e.startsWith("$"),rowFixed:t?e.startsWith("$"):e.includes("$",1)}})),o=void 0===t.bottom,n=void 0===t.right;return o&&(i[0].rowFixed=i[0].rowFixed||i[1].rowFixed,i[1].rowFixed=i[0].rowFixed||i[1].rowFixed,t.left===t.right&&(i[0].colFixed=i[0].colFixed||i[1].colFixed,i[1].colFixed=i[0].colFixed||i[1].colFixed)),n&&(i[0].colFixed=i[0].colFixed||i[1].colFixed,i[1].colFixed=i[0].colFixed||i[1].colFixed,t.top===t.bottom&&(i[0].rowFixed=i[0].rowFixed||i[1].rowFixed,i[1].rowFixed=i[0].rowFixed||i[1].rowFixed)),i}get isFullCol(){return void 0===this._zone.bottom}get isFullRow(){return void 0===this._zone.right}get rangeData(){return{_zone:this._zone,_sheetId:this.sheetId}}orderZone(){var e,t,i,o,n,s,r,a;const l={...this._zone};let c=this.parts;if(void 0!==l.right&&l.right<l.left){let n=l.right;l.right=l.left,l.left=n,c=[{colFixed:(null===(e=c[1])||void 0===e?void 0:e.colFixed)||!1,rowFixed:(null===(t=c[0])||void 0===t?void 0:t.rowFixed)||!1},{colFixed:(null===(i=c[0])||void 0===i?void 0:i.colFixed)||!1,rowFixed:(null===(o=c[1])||void 0===o?void 0:o.rowFixed)||!1}]}if(void 0!==l.bottom&&l.bottom<l.top){let e=l.bottom;l.bottom=l.top,l.top=e,c=[{colFixed:(null===(n=c[0])||void 0===n?void 0:n.colFixed)||!1,rowFixed:(null===(s=c[1])||void 0===s?void 0:s.rowFixed)||!1},{colFixed:(null===(r=c[1])||void 0===r?void 0:r.colFixed)||!1,rowFixed:(null===(a=c[0])||void 0===a?void 0:a.rowFixed)||!1}]}return this.clone({zone:l,parts:c})}clone(e){return new Mi({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 Oi(e,t,i){const o=i.sheetId===e?t:i.sheetId;return i.clone({sheetId:o})}function Ni(e,t,i){return i?e.getRangeFromSheetXC(t,i):void 0}function _i(e,t,i){const o=[];return t.forEach((t=>{const n=function(e,t){e=e.toLocaleLowerCase();let i=0,o=0,n=(t=t.toLocaleLowerCase()).length,s=0;for(let r=0;r<n;r++)t[r]===e[s]?(s++,o+=100+o-r/200):o=0,i+=o;return s===e.length?i:0}(e,i(t));n>0&&o.push({score:n,elem:t})})),o.sort(((e,t)=>t.score-e.score)),o.map((e=>e.elem))}function Fi(e){const t=[];for(let i=0;i<e;i++){const e={cells:{}};t.push(e)}return t}class Di{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 ki(e){const t=function(e){const t=(e=e.split("!").pop()).replace(/\$/g,"").split(":").map((e=>e.trim()));let i,o,n,s,r=!1,a=!1,l=!1;const c=t[0],h=t[1]&&t[1];if(Ft(c))n=s=Vt(c),i=o=0,r=!0;else if(Dt(c))i=o=parseInt(c,10)-1,n=s=0,a=!0;else{const e=zt(c);n=s=e.col,i=o=e.row,l=!0}if(2===t.length)if(Ft(h))s=Vt(h),r=!0;else if(Dt(h))o=parseInt(h,10)-1,a=!0;else{const e=zt(h);s=e.col,o=e.row,i=r?o:i,n=a?s:n,l=!0}if(r&&a)throw new Error("Wrong zone xc. The zone cannot be at the same time a full column and a full row");const d={top:i,left:n,bottom:r?void 0:o,right:a?void 0:s};return l=l&&(a||r),l&&(d.hasHeader=l),d}(e);if(void 0!==t.right&&t.right<t.left){const e=t.left;t.left=t.right,t.right=e}if(void 0!==t.bottom&&t.bottom<t.top){const e=t.top;t.top=t.bottom,t.bottom=e}return t}function Li(e){const t=ki(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function Pi(e){const{bottom:t,top:i,left:o,right:n}=e;return!(void 0!==t&&isNaN(t)||isNaN(i)||isNaN(o)||void 0!==n&&isNaN(n))&&((void 0===e.bottom||e.bottom>=e.top&&e.bottom>=0)&&(void 0===e.right||e.right>=e.left&&e.right>=0)&&e.top>=0&&e.left>=0)}function Ui(e){const{top:t,bottom:i,left:o,right:n}=e,r="hasHeader"in e&&e.hasHeader,a=t===i&&o===n;if(void 0===i&&void 0!==n)return 0!==t||r?`${Bt(o,t)}:${Ut(n)}`:`${Ut(o)}:${Ut(n)}`;if(void 0===n&&void 0!==i)return 0!==o||r?`${Bt(o,t)}:${i+1}`:`${t+1}:${i+1}`;if(void 0!==i&&void 0!==n)return a?Bt(o,t):`${Bt(o,t)}:${Bt(n,i)}`;throw new Error(s("Bad zone format"))}function Vi(e,t,i,o,n){const s="left"===t?"columns":"rows",r="before"===o?i-1:i,a=e["left"===t?"right":"bottom"];return e[t]<=r&&a&&a>r?eo(e,s,"RESIZE",n):r<e[t]?eo(e,s,"MOVE",n):{...e}}function zi(e,t,i,o,n){const s="left"===t?"columns":"rows",r="before"===o?i-1:i,a="left"===t?"right":"bottom";return e[t]<=r&&e[a]>r?eo(e,s,"RESIZE",n):r<e[t]?eo(e,s,"MOVE",n):{...e}}function Bi(e,t,i){const o="left"===t?"right":"bottom";let n=e[t],s=e[o];for(let r of i.sort(((e,t)=>t-e)))e[t]>r&&(n--,s--),e[t]<r&&e[o]>=r&&s--;return{...e,[t]:n,[o]:s}}function Hi(e,t,i){const o="left"===t?"right":"bottom";let n=e[t],s=e[o];const r=e[o];for(let o of i.sort(((e,t)=>t-e)))e[t]>o&&(n--,void 0!==s&&s--),void 0!==r&&void 0!==s&&e[t]<=o&&r>=o&&s--;if(!(void 0!==s&&n>s))return{...e,[t]:n,[o]:s}}function $i(...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 Wi(e,t){if(qi(e,t))return{top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),bottom:Math.min(e.bottom,t.bottom),right:Math.min(e.right,t.right)}}function Gi(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function qi(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function Zi(e,t,i){const{left:o,right:n,top:s,bottom:r}=i;return e>=o&&e<=n&&t>=s&&t<=r}function ji(e,t){return Gi($i(t,e),t)}function Xi(e,t){const i=e.map(ki),o=t.map(Li),n=Math.max(...i.concat(o).map((e=>e.bottom||0))),s=Math.max(...i.concat(o).map((e=>e.right||0))),r=i.map((e=>({...e,bottom:void 0===e.bottom?n+1:e.bottom,right:void 0===e.right?s+1:e.right}))),a=o.map((e=>({...e,bottom:void 0===e.bottom?n+1:e.bottom,right:void 0===e.right?s+1:e.right}))),l=function(e,t){const i=new Set(t.map((({col:e,row:t})=>`${e}-${t}`)));return e.filter((({col:e,row:t})=>!i.has(`${e}-${t}`)))}(r.map(Ji).flat(),a.map(Ji).flat()),c=function(e){if(0===e.length)return[];const[t,...i]=[...e].sort(((e,t)=>e.row-t.row)).sort(((e,t)=>e.col-t.col)),o=[];let n=oo(t);for(const{col:e,row:t}of i)if(!Zi(e,t,n))if(e===n.left&&t===n.bottom+1){const e=n.bottom+1;n={...n,bottom:e}}else o.push(n),n=oo({col:e,row:t});return[...o,n]}(l);return function(e){if(0===e.length)return[];if(e.some((e=>e.left!==e.right)))throw new Error("only columns can be merged");const t=[],i=Yi(e),o=(e,t)=>e.top===t.top&&e.bottom===t.bottom&&e.right+1===t.left;for(;i.length;){const e=i.reduce(((e,t)=>o(e,t)?$i(e,t):e),i.shift());t.push(e)}return Yi(t)}(c).map((e=>({...e,bottom:e.bottom===n+1?void 0:e.bottom,right:e.right===s+1?void 0:e.right}))).map(Ui)}function Yi(e){const t=[...e].sort(((e,t)=>t.right-e.right)).sort(((e,t)=>t.bottom-e.bottom)).sort(((e,t)=>e.top-t.top)).sort(((e,t)=>e.left-t.left)).reverse(),i=[];for(;0!==t.length;){const e=t.shift();t.some((t=>ji(e,t)))||i.push(e)}return i.reverse()}function Ki(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function Qi(e){const{numberOfCols:t,numberOfRows:i}=Ki(e);return 1===t||1===i}function Ji(e){const t=[],[i,o]=[e.right,e.left].sort(((e,t)=>e-t)),[n,s]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of ze(i,o+1))for(const i of ze(n,s+1))t.push({col:e,row:i});return t}function eo(e,t,i,o){const n="both"===t?o[0]:"columns"===t?o:0,s="both"===t?o[1]:"rows"===t?o:0,r="hasHeader"in e&&e.hasHeader;let a;a=!function(e){return void 0===e.bottom}(e)||r?!(no(e)&&!r)||"columns"!==t:"rows"!==t;const l={...e};return a&&"MOVE"===i&&(l.left+=n,l.top+=s),void 0!==l.right&&(l.right+=n),void 0!==l.bottom&&(l.bottom+=s),l}function to(e,t){let i,o;const{left:n,right:s,top:r,bottom:a}=e,{left:l,right:c,top:h,bottom:d}=t;return i=l!=n?l:c!=s?c:l,o=h!=r?h:d!=a?d:h,{col:i,row:o}}function io(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 oo(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function no(e){return void 0===e.right}function so(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function ro(...e){return e.length<2||1===Xi(e.map(Ui),[]).length}class ao 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;at(e,t)||(this.updateChartJs(t),e=t)}))}createChart(e){const t=this.canvas.el.getContext("2d");this.chart=new window.Chart(t,e)}updateChartJs(e){var t,i,o,n,s;const r=e.chartJsConfig;r.data&&r.data.datasets?(this.chart.data=r.data,(null===(t=r.options)||void 0===t?void 0:t.title)&&(this.chart.config.options.title=r.options.title),r.options&&"valueLabel"in r.options&&(null===(i=r.options)||void 0===i?void 0:i.valueLabel)&&(this.chart.config.options.valueLabel=r.options.valueLabel)):this.chart.data.datasets=void 0,this.chart.config.options.tooltips=null===(o=r.options)||void 0===o?void 0:o.tooltips,this.chart.config.options.legend=null===(n=r.options)||void 0===n?void 0:n.legend,this.chart.config.options.scales=null===(s=r.options)||void 0===s?void 0:s.scales,this.chart.update({duration:0})}}ao.template="o-spreadsheet-ChartJsComponent",ao.props={figure:Object};const lo={};let co=0;function ho(e,...t){const i="__sheet__"+co++;return function(e,t){const i=document.createElement("style");i.textContent=function(e){const t=e.split(/(\{|\}|;)/).map((e=>e.trim())),i=[],o=[];let n=[];function s(e,t){const o=[];for(const n of i[e]){let r=t&&t+" "+n||n;r.includes("&")&&(r=n.replace(/&/g,t||"")),e<i.length-1&&(r=s(e+1,r)),o.push(r)}return o.join(", ")}function r(){n.length&&(o.push(s(0)+" {"),o.push(...n),o.push("}"),n=[])}for(;t.length;){let e=t.shift();"}"===e?(r(),i.pop()):("{"===t[0]&&(r(),i.push(e.split(/\s*,\s*/)),t.shift()),";"===t[0]&&n.push(" "+e+";"))}return o.join("\n")}(t),lo[e]=i}(i,String.raw(e,...t)),function(e){const t=lo[e];t.setAttribute("component",e),document.head.appendChild(t)}(i),i}function uo({strikethrough:e,underline:t}){return e||t?`${e?"line-through":""} ${t?"underline":""}`:"none"}function go(e){const t=po(e);return e?(e.fillColor&&(t.background=e.fillColor),t):t}function po(e){const t={};if(!e)return t;if(e.bold&&(t["font-weight"]="bold"),e.italic&&(t["font-style"]="italic"),e.strikethrough||e.underline){let i=e.strikethrough?"line-through":"";i=e.underline?i+" underline":i,t["text-decoration"]=i}return e.textColor&&(t.color=e.textColor),t}function mo(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>`${e}:${t};`)).join(" ")}const fo=1.2;ho`
1
+ !function(e,t){"use strict";let i=e=>e;function o(e,...t){if(1===t.length&&"object"==typeof t[0]){const i=t[0];e=e.replace(/\%\(?([^\)]+)\)s/g,((e,t)=>i[t]))}else t.length>0&&(e=e.replace(/\%s/g,(()=>t.shift())));return e}const n=function(e,...t){return o(i(e),...t)},s=function(e,...t){return new r(e,t)};class r extends String{constructor(e,t){super(e),this.values=t}valueOf(){const e=super.valueOf();return o(i(e),...this.values)}toString(){return this.valueOf()}}var a,l;!function(e){e.NotAvailable="#N/A",e.InvalidReference="#REF",e.BadExpression="#BAD_EXPR",e.CircularDependency="#CYCLE",e.UnknownFunction="#NAME?",e.GenericError="#ERROR"}(a||(a={})),function(e){e[e.silent=0]="silent",e[e.error=1]="error"}(l||(l={}));class c extends Error{constructor(e,t,i=l.error){super(t),this.errorType=e,this.logLevel=i}}class h extends c{constructor(e){super(a.BadExpression,e)}}class d extends c{constructor(){super(a.CircularDependency,s("Circular reference"))}}class u extends c{constructor(){super(a.InvalidReference,s("Invalid reference"))}}class g extends c{constructor(e){super(a.NotAvailable,e||s("Data not available"),e?l.error:l.silent)}}class p extends c{constructor(e){super(a.UnknownFunction,s('Unknown function: "%s"',e))}}const m=.5,f="#f5f5f5",v="#F8F9FA",b="#E8EAED",S="#595959",C="#666666",E="#3266ca",w="#FFFFFF",y=11982760,x="#01666b",I="#188038",R="#E6F4EA",T="#CEEAD6",A="#E0E2E4",M=["#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,N=48,_=96,F=23,D=15,k=18,L=14,P=4,U=4,V=3,z=U,B=17,H=250,$=1,W="400",G=10,q="'Roboto', arial",Z=["thin","#000"],j=["thin",I],X=/[ymdhs:]/,Y=a.InvalidReference,K="START_REVISION",Q=20,J="??",ee="difference",te="#00A04A",ie="#DC6965",oe=.4,ne=["'","*","?","/","\\","[","]"],se=/'|\*|\?|\/|\\|\[|\]/,re="|",ae=s("Invalid expression");var le;!function(e){e[e.Grid=0]="Grid",e[e.Highlight=5]="Highlight",e[e.Figure=10]="Figure",e[e.ScrollBar=15]="ScrollBar",e[e.GridPopover=19]="GridPopover",e[e.GridComposer=20]="GridComposer",e[e.Dropdown=21]="Dropdown",e[e.IconPicker=25]="IconPicker",e[e.TopBarComposer=30]="TopBarComposer",e[e.Popover=35]="Popover",e[e.ChartAnchor=1e3]="ChartAnchor"}(le||(le={}));const ce="\n",he=[6,7,8,9,10,11,12,14,18,24,36],de=new Date(1899,11,30),ue=864e5,ge=2e3,pe=(new Date).getFullYear(),me=new Date(0)-de,fe=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,ve=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,be=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function Se(e){let t;const i=(e=e.trim()).match(be);if(i){if(t=function(e){if(e=e.trim(),be.test(e)){const t=/AM/i.test(e),i=/PM/i.test(e),o=(t||i?e.substring(0,e.length-2).trim():e).split(/:/),n=o.length>=2,s=3===o.length;let r=Number(o[0]),a=n?Number(o[1]):0,l=s?Number(o[2]):0,c=s?"hh:mm:ss":"hh:mm";if(t||i)c+=" a";else if(!n)return null;r>=12&&t?r-=12:r<12&&i&&(r+=12),a+=Math.floor(l/60),l%=60,r+=Math.floor(a/60),a%=60,r>=24&&(c="hhhh:mm:ss");return{value:r/24+a/1440+l/86400,format:c,jsDate:new Date(1899,11,30,r,a,l)}}return null}(i[0]),null===t)return null;e=e.replace(i[0],"").trim()}let o;const n=e.match(fe),s=e.match(ve);if(n||s){let t;if(n?(t=n[0],o=Ce(t,"mdy")):(t=s[0],o=Ce(t,"ymd")),null===o)return null;e=e.replace(t,"").trim()}return""!==e||!o&&!t?null:o&&t?{value:o.value+t.value,format:o.format+" "+("hhhh:mm:ss"===t.format?"hh:mm:ss":t.format),jsDate:new Date(o.jsDate.getFullYear()+t.jsDate.getFullYear()-1899,o.jsDate.getMonth()+t.jsDate.getMonth()-11,o.jsDate.getDate()+t.jsDate.getDate()-30,o.jsDate.getHours()+t.jsDate.getHours(),o.jsDate.getMinutes()+t.jsDate.getMinutes(),o.jsDate.getSeconds()+t.jsDate.getSeconds())}:o||t}function Ce(e,t){const i="mdy"===t;if(i||"ymd"===t){const t=e.split(/\/|-|\s/),o=i?0:1,n=i?1:2,s=i?2:0,r=Number(t[o]),a=Number(t[n]),l=2===t[o].length&&r<10||2===t[n].length&&a<10,c=t[s]?function(e){const t=Number(e);switch(e.length){case 1:return ge+t;case 2:return ge+(ge+t>pe+10?-100:0)+t;case 3:case 4:return t}return 0}(t[s]):pe,h=new Date(c,r-1,a),d=e.match(/\/|-|\s/)[0];if(h.getMonth()!==r-1||h.getDate()!==a)return null;const u=h-de;let g=l?`mm${d}dd`:`m${d}d`;return t[s]&&(g=i?g+d+"yyyy":"yyyy"+d+g),{value:Math.round(u/ue),format:g,jsDate:h}}return null}function Ee(e){const t=Math.trunc(e);let i=new Date(t*ue-me),o=e-t;o=o<0?1+o:o;const n=Math.round(24*o),s=Math.round(24*(o-n/24)*60),r=Math.round(24*(o-n/24-s/24/60)*60*60);return i.setHours(n),i.setMinutes(s),i.setSeconds(r),i}function we(e){const t=e.getTime()-de.getTime();return Math.round(t/ue)}function ye(e){return new Date(e.getFullYear(),e.getMonth()+1,0).getDate()}function xe(e){return ye(e)===e.getDate()}function Ie(e,t,i){const o=e.getFullYear(),n=e.getMonth(),s=e.getDate(),r=new Date(o,n+t);return i&&s===ye(e)||s>ye(r)?r.setDate(ye(r)):r.setDate(s),r}function Re(e){const t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function Te(e,t,i){if(e===t)return 0;if(e>t){const i=t;t=e,e=i}const o=Ee(e),n=Ee(t);let s=o.getDate(),r=n.getDate();const a=o.getMonth(),l=n.getMonth(),c=o.getFullYear(),h=n.getFullYear();let d=0,u=0;switch(i){case 0:31===s&&(s=30),30===s&&31===r&&(r=30),1===a&&s===(Re(c)?29:28)&&(s=30,1===l&&r===(Re(h)?29:28)&&(r=30)),d=c+(30*a+s)/360,u=h+(30*l+r)/360;break;case 1:let i=365;const o=c===h;if(!o&&!(c+1===h)||!o&&a<l||!o&&a===l&&s<r){let e=0,t=0;for(let i=c;i<=h;i++)e++,t+=Re(i)?366:365;i=t/e}else o?Re(c)&&(i=366):(Re(c)&&a<2&&(i=366),Re(h)&&(l>1||1===l&&29===r)&&(i=366));d=e/i,u=t/i;break;case 2:d=e/360,u=t/360;break;case 3:d=e/365,u=t/365;break;case 4:31===s&&(s=30),31===r&&(r=30),d=c+(30*a+s)/360,u=h+(30*l+r)/360}return u-d}function Ae(e){return JSON.stringify(e,Object.keys(e).sort())}function Me(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 Ne(e){const t=Array.isArray(e)?[]:{};switch(typeof e){case"object":if(null===e)return e;if(function(e){return"clone"in e&&e.clone instanceof Function}(e))return e.clone();if(!(function(e){return"object"==typeof e&&(null==e?void 0:e.constructor)===Object}(e)||e instanceof Array))throw new Error("Unsupported type: only objects and arrays are supported");for(const i in e)t[i]=Ne(e[i]);return t;case"number":case"string":case"boolean":case"function":case"undefined":return e;default:throw new Error("Unsupported type: "+typeof e)}}function _e(e){return e.startsWith("'")&&(e=e.slice(1,-1).replace(/''/g,"'")),e}function Fe(e){var t;return(null===(t=e.match(/\w/g))||void 0===t?void 0:t.length)!==e.length&&(e=`'${e}'`),e}function De(e,t,i){return e<t?t:e>i?i:e}function ke(e,t=1){return t*(e+U)-U}function Le(e,t,i){const o=Ve(i);if(Pe[o]||(Pe[o]={}),void 0===Pe[o][t]){e.save(),e.font=o;const i=e.measureText(t).width;e.restore(),Pe[o][t]=i}return Pe[o][t]}const Pe={};function Ue(e){return Math.round(96*e/72)}function Ve(e){return`${e.italic?"italic ":""}${e.bold?"bold":W} ${ze(e)}px ${q}`}function ze(e){return Ue((null==e?void 0:e.fontSize)||G)}function Be(e,t,i=1){if(t<=e&&i>0)return[];if(0===i)throw new Error("range() step must not be zero");const o=Math.ceil(Math.abs((t-e)/i)),n=Array(o);for(let t=0;t<o;t++)n[t]=e+t*i;return n}function He(e){return e.reduce(((e,t,i,o)=>{if(1===Math.abs(t-o[i-1])){e[e.length-1].push(t)}else e.push([t]);return e}),[])}function*$e(e,t){t.next();for(const i of e){const e=t.next();yield{...i,next:e.done?void 0:e.value}}}function We(e){return null!==Se(e)}const Ge=/^\[([^\[]+)\]\((.+)\)$/,qe=/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/;function Ze(e){return Ge.test(e)}function je(e){return qe.test(e)}function Xe(e,t){return`[${e}](${t})`}function Ye(e){const t=e.match(Ge)||[],i=t[1],o=t[2];if(!i||!o)throw new Error(`Could not parse markdown link ${e}.`);return{label:i,url:o}}const Ke="o-spreadsheet://";function Qe(e){return e.startsWith(Ke)}function Je(e){return`${Ke}${e}`}function et(e){if(e.startsWith(Ke))return e.substr(Ke.length);throw new Error(`${e} is not a valid sheet link`)}function tt(e){return void 0!==e}function it(e){return void 0===e||Object.values(e).every((e=>"object"==typeof e?it(e):!e))}function ot(e,t){for(let[i,o]of Object.entries(t))if(Ae(o)===Ae(e))return parseInt(i,10);const i=Object.keys(t),o=0===i.length?0:Math.max(...i.map((e=>parseInt(e,10))));return t[o+1]=e,o+1}function nt(e){let t="";for(let i=0,o=e.length;i<o;i++)t+=e[i];return t}function st(e){let t,i=!1;const o=()=>(i||(t=e instanceof Function?e():e,i=!0),t);return o.map=e=>st((()=>e(o()))),o}function rt(e,t){let i=e.slice(t).find((e=>e));return i||(i=e.slice(0,t).reverse().find((e=>e))),i||""}function at(e,t){return"after"===e?t+1:t}function lt(e,t){if(e===t)return!0;if(e&&!t||t&&!e)return!1;const i=new Set;Object.keys(e).forEach((e=>i.add(e))),Object.keys(t).forEach((e=>i.add(e)));for(let o of i){if(typeof e[o]!=typeof e[o])return!1;if("object"==typeof e[o]){if(!lt(e[o],t[o]))return!1}else if(e[o]!==t[o])return!1}return!0}function ct(e){const t={...e};return Object.keys(t).forEach((e=>!t[e]&&delete t[e])),t}function ht(e){return e?e.toLowerCase():""}const dt=[" ","\t","\f","\v",String.fromCharCode(parseInt("00a0",16)),String.fromCharCode(parseInt("1680",16)),String.fromCharCode(parseInt("2000",16)),String.fromCharCode(parseInt("200a",16)),String.fromCharCode(parseInt("2028",16)),String.fromCharCode(parseInt("2029",16)),String.fromCharCode(parseInt("202f",16)),String.fromCharCode(parseInt("205f",16)),String.fromCharCode(parseInt("3000",16)),String.fromCharCode(parseInt("feff",16))],ut=new RegExp(dt.join("|"),"g"),gt=/\r\n|\r|\n/g;function pt(e){return e?e=(e=e.replace(ut," ")).replace(gt,ce):""}const mt=/rgba?\(|\s+|\)/gi,ft=/^#([A-F\d]{2}){3,4}$/g,vt=["#eb6d00","#0074d9","#ad8e00","#169ed4","#b10dc9","#00a82d","#00a3a3","#f012be","#3d9970","#111111","#62A300","#ff4136","#949494","#85144b","#001f3f"];function bt(e){return St(e.toString(16).padStart(6,"0"))}function St(e){let t=e;if(e.startsWith("rgb")?t=function(e){const t=e.replace(mt,"").split(",");let i=255;if(3!==t.length&&4!==t.length)throw new Error("invalid color");if(4===t.length){const e=parseFloat(t.pop()||"1");i=Math.round(255*(e||1))}const o=t.map((e=>parseInt(e,10)));255!==i&&o.push(i);return"#"+nt(o.map((e=>e.toString(16).padStart(2,"0")))).toUpperCase()}(e):(t=e.replace("#","").toUpperCase(),3!==t.length&&4!==t.length||(t=t.split("").reduce(((e,t)=>e+t+t),"")),t=`#${t}`),!t.match(ft))throw new Error(`invalid color input: ${e}`);return t}function Ct(e){try{return St(e),!0}catch(e){return!1}}const Et=e=>e>=0&&e<=255;function wt(e,t,i,o=1){if(!Et(e)||!Et(t)||!Et(i)||o<0||o>1)throw new Error(`Invalid RGBA values ${[e,t,i,o]}`);return{a:o,b:i,g:t,r:e}}function yt(e){let{r:t,g:i,b:o}=It(e);t/=255,i/=255,o/=255;const n=e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4;return.2126*n(t)+.7152*n(i)+.0722*n(o)}function xt(e){let t=e.r.toString(16),i=e.g.toString(16),o=e.b.toString(16),n=Math.round(255*e.a).toString(16);return 1==t.length&&(t="0"+t),1==i.length&&(i="0"+i),1==o.length&&(o="0"+o),1==n.length&&(n="0"+n),"ff"===n&&(n=""),("#"+t+i+o+n).toUpperCase()}function It(e){let t,i,o,n;if(7===(e=St(e)).length)t=parseInt(e[1]+e[2],16),i=parseInt(e[3]+e[4],16),o=parseInt(e[5]+e[6],16),n=255;else{if(9!==e.length)throw new Error("Invalid color");t=parseInt(e[1]+e[2],16),i=parseInt(e[3]+e[4],16),o=parseInt(e[5]+e[6],16),n=parseInt(e[7]+e[8],16)}return n=+(n/255).toFixed(3),{a:n,r:t,g:i,b:o}}function Rt(e){(e={...e}).s/=100,e.l/=100;let t=(1-Math.abs(2*e.l-1))*e.s,i=t*(1-Math.abs(e.h/60%2-1)),o=e.l-t/2,n=0,s=0,r=0;return 0<=e.h&&e.h<60?(n=t,s=i,r=0):60<=e.h&&e.h<120?(n=i,s=t,r=0):120<=e.h&&e.h<180?(n=0,s=t,r=i):180<=e.h&&e.h<240?(n=0,s=i,r=t):240<=e.h&&e.h<300?(n=i,s=0,r=t):300<=e.h&&e.h<360&&(n=t,s=0,r=i),n=Math.round(255*(n+o)),s=Math.round(255*(s+o)),r=Math.round(255*(r+o)),{a:e.a,r:n,g:s,b:r}}function Tt(e){const t=e.r/255,i=e.g/255,o=e.b/255;let n=Math.min(t,i,o),s=Math.max(t,i,o),r=s-n,a=0,l=0,c=0;return a=0==r?0:s==t?(i-o)/r%6:s==i?(o-t)/r+2:(t-i)/r+4,a=Math.round(60*a),a<0&&(a+=360),c=(s+n)/2,l=0==r?0:r/(1-Math.abs(2*c-1)),l=+(100*l).toFixed(1),c=+(100*c).toFixed(1),{a:e.a,h:a,s:l,l:c}}const At=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,"i"),Mt=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,"i"),Ot=new RegExp(/^([A-Z]{1,3})+$/,"i"),Nt=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,"i"),_t=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,"i"),Ft=new RegExp(/^\s*('.+'!|[^']+!)?/.source+"("+[At.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 Dt(e){return Nt.test(e)}function kt(e){return _t.test(e)}function Lt(e){return Ot.test(e)}function Pt(e){return Mt.test(e)}function Ut(e){const t=e.split("!"),i=t.pop();return{sheetName:_e(t.join("!"))||void 0,xc:i}}function Vt(e){if(e<0)throw new Error(`number must be positive. Got ${e}`);return e<26?String.fromCharCode(65+e):Vt(Math.floor(e/26)-1)+Vt(e%26)}function zt(e){let t=0;const i=e.length;for(let o=0;o<i;o++){t+=(e.charCodeAt(o)-65+(o<i-1?1:0))*26**(i-o-1)}return t}function Bt(e){const t=(e=e.toUpperCase().trim()).match(At);if(null!==t){const[i,o,n]=t;if(i===e){return{col:zt(o),row:parseInt(n,10)-1}}}throw new Error(`Invalid cell description: ${e}`)}function Ht(e,t,i={colFixed:!1,rowFixed:!1}){return(i.colFixed?"$":"")+Vt(e)+(i.rowFixed?"$":"")+String(t+1)}const $t=140,Wt=20,Gt=.035;function qt(e){return Wt+($t-Wt)*Math.exp(-Gt*(e-1))}const Zt=/(^-?\d+(\.?\d*(e\d+)?)?|^-?\.\d+)(?!\w|!)/,jt="(\\s*(\\d+(,\\d{3,})*(\\.\\d*)?)|(\\.\\d+))(e(\\+|-)?\\d+)?(\\s*%)?",Xt="(\\s*-)?",Yt="(\\s*[\\$€])?",Kt="^(("+[Xt+Yt+jt,Xt+jt+Yt,Yt+Xt+jt].join(")|(")+"))$",Qt=new RegExp(Kt,"i");function Jt(e){return!!e&&Qt.test(e.trim())}const ei=/[,\$€]+/g;function ti(e){e=e.replace(ei,"");let t=Number(e);return isNaN(t)&&e.includes("%")&&(t=Number(e.split("%")[0]),!isNaN(t))?t/100:t}function ii(e,t,i){const o=[...e].sort(((e,t)=>e-t));let n=(o.length+(i?-1:1))*t;if(i||n--,Number.isInteger(n))return o[n];const s=Math.ceil(n),r=Math.floor(n);return o[s]*(n-r)+o[r]*(s-n)}const oi=20,ni=11,si=/(\d+?)(?=(\d{3})+(?!\d)|$)/g,ri=/0/g,ai={0:s("January"),1:s("February"),2:s("March"),3:s("April"),4:s("May"),5:s("June"),6:s("July"),7:s("August"),8:s("September"),9:s("October"),10:s("November"),11:s("December")},li={0:s("Sunday"),1:s("Monday"),2:s("Tuesday"),3:s("Wednesday"),4:s("Thursday"),5:s("Friday"),6:s("Saturday")},ci={};function hi(e){let t=ci[e];return void 0===t&&(t=function(e){if(""===e)throw new Error("A format cannot be empty");let t=0,i=[];for(;t<e.length;){let o;if("["===e.charAt(t)){if("$"!==e.charAt(t+1))throw new Error(`Currency formats have to be prefixed by a $: ${e}`);if(o=e.substring(t+1).indexOf("]")+t+2,0===o)throw new Error(`Invalid currency brackets format: ${e}`);const n=e.substring(t+2,o-1);if(n.includes("["))throw new Error(`Invalid currency format: ${e}`);i.push({type:"STRING",format:n})}else{const n=e.substring(t).indexOf("[");o=n>-1?n+t:e.length;const s=e.substring(t,o);s.match(X)?i.push({type:"DATE",format:s}):i.push({type:"NUMBER",format:Ti(s)})}t=o}return i}(e),ci[e]=t),t}function di(e,t){switch(typeof e){case"string":return e;case"boolean":return e?"TRUE":"FALSE";case"number":t||(t=Ei(e));return function(e,t){if("DATE"===t[0].type)return bi(e,t[0].format);let i=e<0?"-":"";for(let o of t)switch(o.type){case"NUMBER":i+=ui(Math.abs(e),o.format);break;case"STRING":i+=o.format}return i}(e,hi(t));case"object":return"0"}}function ui(e,t){t.isPercent&&(e*=100),e/=t.magnitude;let i=0;void 0!==t.decimalPart&&(i=t.decimalPart.length);const{integerDigits:o,decimalDigits:n}=pi(e,i);let s=function(e,t,i){var o;const n="0"===e?"":e;let s=n;const r=t.length-n.length;if(r>0){const e=(t.substring(0,r).match(ri)||[]).length;s="0".repeat(e)+s}i&&(s=(null===(o=s.match(si))||void 0===o?void 0:o.join(","))||s);return s}(o,t.integerPart,t.thousandsSeparator);return void 0!==t.decimalPart&&(s+="."+function(e,t){let i=e;if(t.length-e.length>0){const o=(t.substring(e.length,t.length+1).match(ri)||[]).length;i+="0".repeat(o)}return i}(n||"",t.decimalPart)),t.isPercent&&(s+="%"),s}const gi=[];function pi(e,t=oi){const i=e.toString();if(i.includes("e"))return function(e,t=oi){let i=gi[t];i||(i=new Intl.NumberFormat("en-US",{maximumFractionDigits:t,useGrouping:!1}),gi[t]=i);const[o,n]=i.format(e).split(".");return{integerDigits:o,decimalDigits:n}}(e,t);if(Number.isInteger(e))return{integerDigits:i,decimalDigits:void 0};const o=i.indexOf(".");let n=i.substring(0,o),s=i.substring(o+1);if(0===t)return Number(s[0])>=5&&(n=(Number(n)+1).toString()),{integerDigits:n,decimalDigits:void 0};if(s.length>t){const{integerDigits:e,decimalDigits:i}=function(e,t){var i;let o="0",n=e,s=e.slice(0,t);const r=t;if(Number(e[r])<5)return{integerDigits:o,decimalDigits:s};const a=(null===(i=s.match(fi))||void 0===i?void 0:i[0])||"",l=(Number(s)+1).toString(),c=s.slice(a.length),h=l.length>c.length;h&&!a?(o="1",n=void 0):n=h?a.slice(0,-1)+l:a+l;return{integerDigits:o,decimalDigits:n}}(s,t);s=i,"0"!==e&&(n=(Number(n)+Number(e)).toString())}return{integerDigits:n,decimalDigits:mi(s||"")}}function mi(e){let t=e.length-1;for(;t>=0&&"0"===e[t];)t--;return e.slice(0,t+1)||void 0}const fi=/^0+/;function vi(e){try{return bi(1,e),!0}catch(e){return!1}}function bi(e,t){const i=Ee(e),o=t.indexOf("h");let n="",s="";return o>0?(n=Si(i,t.substring(0,o-1)),s=Ci(i,t.substring(o))):0===o?s=Ci(i,t):o<0&&(n=Si(i,t)),n+(n&&s?" ":"")+s}function Si(e,t){var i;const o=null===(i=t.match(/\/|-|\s/))||void 0===i?void 0:i[0];return(o?t.split(o):[t]).map((i=>{switch(i){case"d":return e.getDate();case"dd":return e.getDate().toString().padStart(2,"0");case"ddd":return li[e.getDay()].slice(0,3);case"dddd":return li[e.getDay()];case"m":return e.getMonth()+1;case"mm":return String(e.getMonth()+1).padStart(2,"0");case"mmm":return ai[e.getMonth()].slice(0,3);case"mmmm":return ai[e.getMonth()];case"mmmmm":return ai[e.getMonth()].slice(0,1);case"yy":const i=String(e.getFullYear()).replace("-","").padStart(2,"0");return i.slice(i.length-2);case"yyyy":return e.getFullYear();default:throw new Error(`invalid format: ${t}`)}})).join(o)}function Ci(e,t){let i=t.split(/:|\s/);const o=e.getHours(),n="a"===i[i.length-1];let s=o,r="";return n&&(s=0===s?12:s>12?s-12:s,r=o>=12?" PM":" AM",i.pop()),i.map((i=>{switch(i){case"hhhh":return Math.floor((e.getTime()-de)/36e5).toString();case"hh":return s.toString().padStart(2,"0");case"mm":return e.getMinutes().toString().padStart(2,"0");case"ss":return e.getSeconds().toString().padStart(2,"0");default:throw new Error(`invalid format: ${t}`)}})).join(":")+r}function Ei(e){let{integerDigits:t,decimalDigits:i}=pi(e);if(!i)return"0";const o=t.replace("-","").length;if(o+2>ni)return"0";const n=ni-o-1;return({decimalDigits:i}=pi(e,Math.min(n,i.length))),i?"0."+"0".repeat(i.length):"0"}function wi(e){if(We(e)){return Se(e).format}if(!Jt(e))return;const t=e.includes(".")?"0.00":"0",i=e.match(/[\$€]/);if(i){const o=e.match(/[\d]/),n="[$"+i.values().next().value+"]";return o.index<i.index?"#,##"+t+n:n+"#,##"+t}return e.includes("%")?t+"%":void 0}function yi(e,t,i){return Mi(hi(e||"#,##0").map((e=>"NUMBER"===e.type?[{...e,format:{...e.format,magnitude:t,decimalPart:void 0}},{type:"STRING",format:i}]:e)).flat())}function xi(e,t){const i=hi(e).map((e=>"NUMBER"===e.type?{...e,format:Ii(e.format,t)}:e)),o=Mi(i);return ci[o]=i,o}function Ii(e,t){var i;const o={...e},n=Math.sign(t),s=(null===(i=o.decimalPart)||void 0===i?void 0:i.length)||0,r=Math.min(Math.max(0,s+n),oi);return o.decimalPart="0".repeat(r),""===o.decimalPart&&delete o.decimalPart,o}const Ri=/,*?$/;function Ti(e){var t;if(function(e){return Boolean(e.replace(Ai,""))}(e=e.trim()))throw new Error(`Invalid number format: ${e}`);const i=e.includes("%"),o=(null===(t=e.match(Ri))||void 0===t?void 0:t[0])||"",n=o?1e3**o.length:1;let s=e.slice(0,e.length-(o.length||0));const r=s.includes(",");if(s.match(/\..*,/))throw new Error("A format can't contain ',' symbol in the decimal part");s=s.replace("%","").replace(",","");const a=s.match(/[\%|,]/);if(a)throw new Error(`A format can only contain a single '${a[0]}' symbol`);const[l,c]=s.split(".");if(c&&c.length>20)throw new Error("A format can't contain more than 20 decimal places");return void 0!==c?{integerPart:l,isPercent:i,thousandsSeparator:r,decimalPart:c,magnitude:n}:{integerPart:l,isPercent:i,thousandsSeparator:r,magnitude:n}}const Ai=/[,#0.%]/g;function Mi(e){let t="";for(let i of e){let e;switch(i.type){case"NUMBER":const t=i.format;e=t.integerPart,t.thousandsSeparator&&(e=e.slice(0,-3)+","+e.slice(-3)),void 0!==t.decimalPart&&(e+="."+t.decimalPart),t.isPercent&&(e+="%"),t.magnitude&&(e+=",".repeat(Math.log10(t.magnitude)/3));break;case"STRING":e=`[$${i.format}]`;break;case"DATE":e=i.format}t+=e}return t}class Oi{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 Oi?e:new Oi(e,t.getSheetSize)}get unboundedZone(){return this._zone}get zone(){const{left:e,top:t,bottom:i,right:o}=this._zone;if(void 0!==o&&void 0!==i)return{left:e,top:t,right:o,bottom:i};if(void 0===i&&void 0!==o)return{right:o,top:t,left:e,bottom:this.getSheetSize(this.sheetId).numberOfRows-1};if(void 0===o&&void 0!==i)return{bottom:i,left:e,top:t,right:this.getSheetSize(this.sheetId).numberOfCols-1};throw new Error(s("Bad zone format"))}static getRangeParts(e,t){const i=e.split(":").map((e=>{const t=kt(e);return{colFixed:!t&&e.startsWith("$"),rowFixed:t?e.startsWith("$"):e.includes("$",1)}})),o=void 0===t.bottom,n=void 0===t.right;return o&&(i[0].rowFixed=i[0].rowFixed||i[1].rowFixed,i[1].rowFixed=i[0].rowFixed||i[1].rowFixed,t.left===t.right&&(i[0].colFixed=i[0].colFixed||i[1].colFixed,i[1].colFixed=i[0].colFixed||i[1].colFixed)),n&&(i[0].colFixed=i[0].colFixed||i[1].colFixed,i[1].colFixed=i[0].colFixed||i[1].colFixed,t.top===t.bottom&&(i[0].rowFixed=i[0].rowFixed||i[1].rowFixed,i[1].rowFixed=i[0].rowFixed||i[1].rowFixed)),i}get isFullCol(){return void 0===this._zone.bottom}get isFullRow(){return void 0===this._zone.right}get rangeData(){return{_zone:this._zone,_sheetId:this.sheetId}}orderZone(){var e,t,i,o,n,s,r,a;const l={...this._zone};let c=this.parts;if(void 0!==l.right&&l.right<l.left){let n=l.right;l.right=l.left,l.left=n,c=[{colFixed:(null===(e=c[1])||void 0===e?void 0:e.colFixed)||!1,rowFixed:(null===(t=c[0])||void 0===t?void 0:t.rowFixed)||!1},{colFixed:(null===(i=c[0])||void 0===i?void 0:i.colFixed)||!1,rowFixed:(null===(o=c[1])||void 0===o?void 0:o.rowFixed)||!1}]}if(void 0!==l.bottom&&l.bottom<l.top){let e=l.bottom;l.bottom=l.top,l.top=e,c=[{colFixed:(null===(n=c[0])||void 0===n?void 0:n.colFixed)||!1,rowFixed:(null===(s=c[1])||void 0===s?void 0:s.rowFixed)||!1},{colFixed:(null===(r=c[1])||void 0===r?void 0:r.colFixed)||!1,rowFixed:(null===(a=c[0])||void 0===a?void 0:a.rowFixed)||!1}]}return this.clone({zone:l,parts:c})}clone(e){return new Oi({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 Ni(e,t,i){const o=i.sheetId===e?t:i.sheetId;return i.clone({sheetId:o})}function _i(e,t,i){return i?e.getRangeFromSheetXC(t,i):void 0}function Fi(e,t,i){const o=[];return t.forEach((t=>{const n=function(e,t){e=e.toLocaleLowerCase();let i=0,o=0,n=(t=t.toLocaleLowerCase()).length,s=0;for(let r=0;r<n;r++)t[r]===e[s]?(s++,o+=100+o-r/200):o=0,i+=o;return s===e.length?i:0}(e,i(t));n>0&&o.push({score:n,elem:t})})),o.sort(((e,t)=>t.score-e.score)),o.map((e=>e.elem))}function Di(e){const t=[];for(let i=0;i<e;i++){const e={cells:{}};t.push(e)}return t}class ki{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 Li(e){const t=function(e){const t=(e=e.split("!").pop()).replace(/\$/g,"").split(":").map((e=>e.trim()));let i,o,n,s,r=!1,a=!1,l=!1;const c=t[0],h=t[1]&&t[1];if(Dt(c))n=s=zt(c),i=o=0,r=!0;else if(kt(c))i=o=parseInt(c,10)-1,n=s=0,a=!0;else{const e=Bt(c);n=s=e.col,i=o=e.row,l=!0}if(2===t.length)if(Dt(h))s=zt(h),r=!0;else if(kt(h))o=parseInt(h,10)-1,a=!0;else{const e=Bt(h);s=e.col,o=e.row,i=r?o:i,n=a?s:n,l=!0}if(r&&a)throw new Error("Wrong zone xc. The zone cannot be at the same time a full column and a full row");const d={top:i,left:n,bottom:r?void 0:o,right:a?void 0:s};return l=l&&(a||r),l&&(d.hasHeader=l),d}(e);if(void 0!==t.right&&t.right<t.left){const e=t.left;t.left=t.right,t.right=e}if(void 0!==t.bottom&&t.bottom<t.top){const e=t.top;t.top=t.bottom,t.bottom=e}return t}function Pi(e){const t=Li(e);if(void 0===t.bottom||void 0===t.right)throw new Error("This does not support unbounded ranges");return t}function Ui(e){const{bottom:t,top:i,left:o,right:n}=e;return!(void 0!==t&&isNaN(t)||isNaN(i)||isNaN(o)||void 0!==n&&isNaN(n))&&((void 0===e.bottom||e.bottom>=e.top&&e.bottom>=0)&&(void 0===e.right||e.right>=e.left&&e.right>=0)&&e.top>=0&&e.left>=0)}function Vi(e){const{top:t,bottom:i,left:o,right:n}=e,r="hasHeader"in e&&e.hasHeader,a=t===i&&o===n;if(void 0===i&&void 0!==n)return 0!==t||r?`${Ht(o,t)}:${Vt(n)}`:`${Vt(o)}:${Vt(n)}`;if(void 0===n&&void 0!==i)return 0!==o||r?`${Ht(o,t)}:${i+1}`:`${t+1}:${i+1}`;if(void 0!==i&&void 0!==n)return a?Ht(o,t):`${Ht(o,t)}:${Ht(n,i)}`;throw new Error(s("Bad zone format"))}function zi(e,t,i,o,n){const s="left"===t?"columns":"rows",r="before"===o?i-1:i,a=e["left"===t?"right":"bottom"];return e[t]<=r&&a&&a>r?to(e,s,"RESIZE",n):r<e[t]?to(e,s,"MOVE",n):{...e}}function Bi(e,t,i,o,n){const s="left"===t?"columns":"rows",r="before"===o?i-1:i,a="left"===t?"right":"bottom";return e[t]<=r&&e[a]>r?to(e,s,"RESIZE",n):r<e[t]?to(e,s,"MOVE",n):{...e}}function Hi(e,t,i){const o="left"===t?"right":"bottom";let n=e[t],s=e[o];for(let r of i.sort(((e,t)=>t-e)))e[t]>r&&(n--,s--),e[t]<r&&e[o]>=r&&s--;return{...e,[t]:n,[o]:s}}function $i(e,t,i){const o="left"===t?"right":"bottom";let n=e[t],s=e[o];const r=e[o];for(let o of i.sort(((e,t)=>t-e)))e[t]>o&&(n--,void 0!==s&&s--),void 0!==r&&void 0!==s&&e[t]<=o&&r>=o&&s--;if(!(void 0!==s&&n>s))return{...e,[t]:n,[o]:s}}function Wi(...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 Gi(e,t){if(Zi(e,t))return{top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),bottom:Math.min(e.bottom,t.bottom),right:Math.min(e.right,t.right)}}function qi(e,t){return e.left===t.left&&e.right===t.right&&e.top===t.top&&e.bottom===t.bottom}function Zi(e,t){return!(e.bottom<t.top||t.bottom<e.top)&&!(e.right<t.left||t.right<e.left)}function ji(e,t,i){const{left:o,right:n,top:s,bottom:r}=i;return e>=o&&e<=n&&t>=s&&t<=r}function Xi(e,t){return qi(Wi(t,e),t)}function Yi(e,t){const i=e.map(Li),o=t.map(Pi),n=Math.max(...i.concat(o).map((e=>e.bottom||0))),s=Math.max(...i.concat(o).map((e=>e.right||0))),r=i.map((e=>({...e,bottom:void 0===e.bottom?n+1:e.bottom,right:void 0===e.right?s+1:e.right}))),a=o.map((e=>({...e,bottom:void 0===e.bottom?n+1:e.bottom,right:void 0===e.right?s+1:e.right}))),l=function(e,t){const i=new Set(t.map((({col:e,row:t})=>`${e}-${t}`)));return e.filter((({col:e,row:t})=>!i.has(`${e}-${t}`)))}(r.map(eo).flat(),a.map(eo).flat()),c=function(e){if(0===e.length)return[];const[t,...i]=[...e].sort(((e,t)=>e.row-t.row)).sort(((e,t)=>e.col-t.col)),o=[];let n=no(t);for(const{col:e,row:t}of i)if(!ji(e,t,n))if(e===n.left&&t===n.bottom+1){const e=n.bottom+1;n={...n,bottom:e}}else o.push(n),n=no({col:e,row:t});return[...o,n]}(l);return function(e){if(0===e.length)return[];if(e.some((e=>e.left!==e.right)))throw new Error("only columns can be merged");const t=[],i=Ki(e),o=(e,t)=>e.top===t.top&&e.bottom===t.bottom&&e.right+1===t.left;for(;i.length;){const e=i.reduce(((e,t)=>o(e,t)?Wi(e,t):e),i.shift());t.push(e)}return Ki(t)}(c).map((e=>({...e,bottom:e.bottom===n+1?void 0:e.bottom,right:e.right===s+1?void 0:e.right}))).map(Vi)}function Ki(e){const t=[...e].sort(((e,t)=>t.right-e.right)).sort(((e,t)=>t.bottom-e.bottom)).sort(((e,t)=>e.top-t.top)).sort(((e,t)=>e.left-t.left)).reverse(),i=[];for(;0!==t.length;){const e=t.shift();t.some((t=>Xi(e,t)))||i.push(e)}return i.reverse()}function Qi(e){return{numberOfRows:e.bottom-e.top+1,numberOfCols:e.right-e.left+1}}function Ji(e){const{numberOfCols:t,numberOfRows:i}=Qi(e);return 1===t||1===i}function eo(e){const t=[],[i,o]=[e.right,e.left].sort(((e,t)=>e-t)),[n,s]=[e.top,e.bottom].sort(((e,t)=>e-t));for(const e of Be(i,o+1))for(const i of Be(n,s+1))t.push({col:e,row:i});return t}function to(e,t,i,o){const n="both"===t?o[0]:"columns"===t?o:0,s="both"===t?o[1]:"rows"===t?o:0,r="hasHeader"in e&&e.hasHeader;let a;a=!function(e){return void 0===e.bottom}(e)||r?!(so(e)&&!r)||"columns"!==t:"rows"!==t;const l={...e};return a&&"MOVE"===i&&(l.left+=n,l.top+=s),void 0!==l.right&&(l.right+=n),void 0!==l.bottom&&(l.bottom+=s),l}function io(e,t){let i,o;const{left:n,right:s,top:r,bottom:a}=e,{left:l,right:c,top:h,bottom:d}=t;return i=l!=n?l:c!=s?c:l,o=h!=r?h:d!=a?d:h,{col:i,row:o}}function oo(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 no(e){return{left:e.col,right:e.col,top:e.row,bottom:e.row}}function so(e){return void 0===e.right}function ro(e){return(e.bottom-e.top+1)*(e.right-e.left+1)}function ao(...e){return e.length<2||1===Yi(e.map(Vi),[]).length}class lo 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;lt(e,t)||(this.updateChartJs(t),e=t)}))}createChart(e){const t=this.canvas.el.getContext("2d");this.chart=new window.Chart(t,e)}updateChartJs(e){var t,i,o,n,s;const r=e.chartJsConfig;r.data&&r.data.datasets?(this.chart.data=r.data,(null===(t=r.options)||void 0===t?void 0:t.title)&&(this.chart.config.options.title=r.options.title),r.options&&"valueLabel"in r.options&&(null===(i=r.options)||void 0===i?void 0:i.valueLabel)&&(this.chart.config.options.valueLabel=r.options.valueLabel)):this.chart.data.datasets=void 0,this.chart.config.options.tooltips=null===(o=r.options)||void 0===o?void 0:o.tooltips,this.chart.config.options.legend=null===(n=r.options)||void 0===n?void 0:n.legend,this.chart.config.options.scales=null===(s=r.options)||void 0===s?void 0:s.scales,this.chart.update({duration:0})}}lo.template="o-spreadsheet-ChartJsComponent",lo.props={figure:Object};const co={};let ho=0;function uo(e,...t){const i="__sheet__"+ho++;return function(e,t){const i=document.createElement("style");i.textContent=function(e){const t=e.split(/(\{|\}|;)/).map((e=>e.trim())),i=[],o=[];let n=[];function s(e,t){const o=[];for(const n of i[e]){let r=t&&t+" "+n||n;r.includes("&")&&(r=n.replace(/&/g,t||"")),e<i.length-1&&(r=s(e+1,r)),o.push(r)}return o.join(", ")}function r(){n.length&&(o.push(s(0)+" {"),o.push(...n),o.push("}"),n=[])}for(;t.length;){let e=t.shift();"}"===e?(r(),i.pop()):("{"===t[0]&&(r(),i.push(e.split(/\s*,\s*/)),t.shift()),";"===t[0]&&n.push(" "+e+";"))}return o.join("\n")}(t),co[e]=i}(i,String.raw(e,...t)),function(e){const t=co[e];t.setAttribute("component",e),document.head.appendChild(t)}(i),i}function go({strikethrough:e,underline:t}){return e||t?`${e?"line-through":""} ${t?"underline":""}`:"none"}function po(e){const t=mo(e);return e?(e.fillColor&&(t.background=e.fillColor),t):t}function mo(e){const t={};if(!e)return t;if(e.bold&&(t["font-weight"]="bold"),e.italic&&(t["font-style"]="italic"),e.strikethrough||e.underline){let i=e.strikethrough?"line-through":"";i=e.underline?i+" underline":i,t["text-decoration"]=i}return e.textColor&&(t.color=e.textColor),t}function fo(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>`${e}:${t};`)).join(" ")}const vo=1.2;uo`
2
2
  div.o-scorecard {
3
3
  font-family: ${q};
4
4
  user-select: none;
@@ -17,15 +17,15 @@
17
17
 
18
18
  .o-title-text {
19
19
  text-align: left;
20
- height: ${fo+"em"};
21
- line-height: ${fo+"em"};
20
+ height: ${vo+"em"};
21
+ line-height: ${vo+"em"};
22
22
  overflow: hidden;
23
23
  white-space: nowrap;
24
24
  }
25
25
 
26
26
  .o-key-text {
27
- line-height: ${fo+"em"};
28
- height: ${fo+"em"};
27
+ line-height: ${vo+"em"};
28
+ height: ${vo+"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: ${fo+"em"};
44
- height: ${fo+"em"};
43
+ line-height: ${vo+"em"};
44
+ height: ${vo+"em"};
45
45
  overflow: hidden;
46
46
  white-space: nowrap;
47
47
 
@@ -50,7 +50,7 @@
50
50
  }
51
51
  }
52
52
  }
53
- `;class vo 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 wt(this.backgroundColor)>.3?"#525252":"#C8C8C8"}get figure(){return this.props.figure}get chartStyle(){return mo({padding:`${this.chartPadding}px`,background:this.backgroundColor})}get chartContentStyle(){return mo({height:`${this.getDrawableHeight()}px`})}get chartPadding(){return.02*this.props.figure.width}getTextStyles(){const e=.96*this.props.figure.width,t=this.getWidestElement(),i=t.getElementMaxFontSize(this.getDrawableHeight(),this);let o=function(e,t,i,o=.25){let n=1;if(i(n)>e)return n;if(i(t)<e)return t;let s=(n+t)/2,r=i(s),a=0;for(;Math.abs(r-e)>o&&a<20;)r>=e?t=(n+t)/2:n=(n+t)/2,s=(n+t)/2,r=i(s),a++;return s}(e,i,(e=>t.getElementWidth(e,this.ctx,this)))/i;const n=(new So).getElementMaxFontSize(this.getDrawableHeight(),this)*o,s=(new bo).getElementMaxFontSize(this.getDrawableHeight(),this)*o;return{titleStyle:this.getTextStyle({fontSize:18,color:this.secondaryFontColor}),keyStyle:this.getTextStyle({fontSize:n,cellStyle:this.runtime.keyValueStyle,color:this.primaryFontColor}),baselineStyle:this.getTextStyle({fontSize:s}),baselineValueStyle:this.getTextStyle({fontSize:s,cellStyle:this.runtime.baselineStyle,color:this.runtime.baselineColor||this.secondaryFontColor}),baselineDescrStyle:this.getTextStyle({fontSize:.9*s,color:this.secondaryFontColor})}}getTextStyle(e){const t=po(e.cellStyle);return t["font-size"]=`${e.fontSize}px`,t.display="inline-block",!t.color&&e.color&&(t.color=e.color),mo(t)}getDrawableHeight(){const e=2*this.chartPadding;let t=this.props.figure.height-e;return t-=this.title?18*fo:0,t}getWidestElement(){const e=new bo,t=new So;return e.getElementWidth(.35,this.ctx,this)>t.getElementWidth(.65,this.ctx,this)?e:t}}vo.template="o-spreadsheet-ScorecardChart";class bo{getElementWidth(e,t,i){if(!i.runtime)return 0;const o=i.baseline,n="neutral"!==i.baselineArrowDirection?"A "+o:o;t.font=`${e}px ${q}`;let s=t.measureText(n).width;return t.font=`${.9*e}px ${q}`,s+=t.measureText(i.baselineDescr).width,s}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.35*e:0)/fo}}class So{getElementWidth(e,t,i){if(!i.runtime)return 0;const o=i.keyValue||"";return t.font=`${e}px ${q}`,t.measureText(o).width}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.65*e:e)/fo}}vo.props={figure:Object};class Co{constructor(){this.content={}}add(e,t){return this.content[e]=t,this}get(e){const t=this.content[e];if(!t&&!(e in this.content))throw new Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}}function Eo(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const wo=new Co;function yo(e,t){return{url:e=Eo(e),label:t||e,isExternal:!0,isUrlEditable:!0}}wo.add("sheet_URL",{match:e=>Ke(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){const i=Je(e);return t.tryGetSheetName(i)||s("Invalid sheet")},open(e,t){const i=Je(e);t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:i})},sequence:0});const xo={createLink:yo,match:e=>Ze(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function Io(e){return wo.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((t=>t.match(e)))||xo}function Ro(e,t){return Io(e.url).urlRepresentation(e.url,t)}function To(e,t){Io(e.url).open(e.url,t)}function Ao(e){if("string"==typeof e){if(qe(e)){const{label:t,url:i}=Xe(e);return Io(i).createLink(i,t)}return Ze(e)?yo(e):void 0}}const Mo=["number","string","boolean","undefined"];function Oo(e,t){if(!e())throw new Error(t)}const No=e=>s("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function _o(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(Qt(e)||""===e)return ei(e);const t=Se(e);if(t)return t.value;throw new Error(No(e));default:return 0}}function Fo(e){if(""===e)throw new Error(No(e));return _o(e)}function Do(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}function ko(e){return"string"==typeof e?e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):e}const Lo=e=>s("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function Po(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(Lo(e))}return!1;case"number":return!!e;default:return!1}}function Uo(e){return Ee(_o(e))}function Vo(e,t,i){for(let o of e)if(Array.isArray(o)){const e=o.length,i=o[0].length;for(let n=0;n<i;n++)for(let i=0;i<e;i++)t(o[i][n])}else i(o)}function zo(e,t){Vo(e,t,t)}function Bo(e,t){Vo(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(Fo(e))}))}function Ho(e,t,i,o){let n=o;for(let o of e)if(Array.isArray(o)){const e=o.length,i=o[0].length;for(let s=0;s<i;s++)for(let i=0;i<e;i++)n=t(n,o[i][s])}else n=i(n,o);return n}function $o(e,t,i){return Ho(e,t,t,i)}function Wo(e,t,i){return Ho(e,((e,i)=>"number"==typeof i?t(e,i):e),((e,i)=>t(e,Fo(i))),i)}function Go(e,t,i){return Ho(e,((e,i)=>null!=i?t(e,"number"==typeof i?i:"boolean"==typeof i?_o(i):0):e),((e,i)=>t(e,_o(i))),i)}function qo(e,t){return function(e,t,i){for(let o of e)if(Array.isArray(o)){const e=o.length,i=o[0].length;for(let n=0;n<i;n++)for(let i=0;i<e;i++)if(!t(o[i][n]))return}else if(!i(o))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error(Lo(e));return Po(e)}(e))))}function Zo(e,t){let i,o,n=e.substring(0,2);"<="===n||">="===n||"<>"===n?(i=n,o=e.substring(2)):(n=e.substring(0,1),"<"===n||">"===n||"="===n?(i=n,o=e.substring(1)):(i="=",o=e)),Qt(o)?o=_o(o):"TRUE"!==o&&"FALSE"!==o||(o=Po(o));const s={operator:i,operand:o};return"string"==typeof o&&(t&&(o+="*"),s.regexp=function(e){let t="",i="";for(let o of e)"?"===o&&"~"!==i?t+=".":"*"===o&&"~"!==i?t+=".*":("*"!==o&&"?"!==o||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(o)&&(t+="\\"),t+=o),i=o;return new RegExp("^"+t+"$","i")}(o)),s}function jo(e,t){const{operator:i,operand:o}=t;if(void 0===e||void 0===o)return!1;if("number"==typeof o&&"="===i)return Do(e)===Do(o);if("<>"===i||"="===i){let n;return n=typeof e==typeof o&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===o),"="===i?n:!n}if(typeof e==typeof o)switch(i){case"<":return e<o;case">":return e>o;case"<=":return e<=o;case">=":return e>=o}return!1}function Xo(e,t,i=!1){const o=e.length;if(o%2==1)throw new Error(s("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const n=e[0].length,r=e[0][0].length;let a=[];for(let t=0;t<o-1;t+=2){const o=e[t];if(!Array.isArray(o)||o.length!==n||o[0].length!==r)throw new Error(s("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=Do(e[t+1]);a.push(Zo(l,i))}for(let i=0;i<n;i++)for(let n=0;n<r;n++){let s=!0;for(let t=0;t<o-1;t+=2){if(s=jo(e[t][i][n],a[t/2]),!s)break}s&&t(i,n)}}function Yo(e,t){return ko(e[0][t])}function Ko(e,t){return ko(e[t][0])}function Qo(e,t,i,o,n,s){if(null==t)return-1;const r=typeof t;let a,l,c,h,d,u,g=0,p=n-1;for(;p-g>=0;){for(c=Math.floor((g+p)/2),h=c,d=s(e,h),u=typeof d;g<h&&r!==u;)h--,d=s(e,h),u=typeof d;u===r&&void 0!==d?("strict"===i&&d===t?(a=d,l=h):"nextSmaller"===i&&d<=t?(void 0===a||a<d||a===d&&"asc"===o&&l<h||a===d&&"desc"===o&&l>h)&&(a=d,l=h):"nextGreater"===i&&d>=t&&(void 0===a||a>d||a===d&&"asc"===o&&l<h||a===d&&"desc"===o&&l>h)&&(a=d,l=h),"asc"===o&&d>t||"desc"===o&&d<=t?p=h-1:g=c+1):g=c+1}return void 0!==l?l:-1}function Jo(e,t,i,o,n,s=!1){if(null==t)return-1;const r=s?(e,t)=>n(e,o-t-1):n;let a,l=-1;for(let n=0;n<o;n++){const c=r(e,n);if(c===t)return s?o-n-1:n;"nextSmaller"===i?(!a&&en(t,c)>=0||en(t,c)>=0&&en(c,a)>0)&&(a=c,l=n):"nextGreater"===i&&(!a&&en(t,c)<=0||en(t,c)<=0&&en(c,a)<0)&&(a=c,l=n)}return s?o-l-1:l}function en(e,t){let i=Mo.indexOf(typeof e)-Mo.indexOf(typeof t);return 0===i&&("string"==typeof e&&"string"==typeof t?i=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?i=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(i=Number(e)-Number(t))),i}var tn,on;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(tn||(tn={})),function(e){e.PlainText="text/plain",e.Html="text/html"}(on||(on={}));const nn=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),sn=new Set([...nn,"DUPLICATE_SHEET","EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT"]),rn=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"]),an=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 ln(e){return an.has(e.type)}class cn{constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new cn}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var hn,dn,un;function gn(e,t){return mn(pn(e||""),t)}function pn(e){if(e.startsWith("="))throw new Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);return Qt(e)||$e(e)?_o(e):function(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}(e)?"TRUE"===e.toUpperCase():e}function mn(e,t){const i=Ao(e);return i?{...fn(pn(i.label),t||Ei(i.label)),link:i}:fn(e,t)}function fn(e,t){try{for(const i of Cn){const o=i(e,t);if(o)return o}return function(e,t){return{type:tn.text,value:e,format:t,isAutoSummable:!0,defaultAlign:"left",formattedValue:hi(e,t)}}((e||"").toString(),t)}catch(t){return Sn((e||"").toString(),new c(a.GenericError,t.message||ae))}}function vn(e,t){return{type:tn.number,value:e||0,format:t,isAutoSummable:!0,defaultAlign:"right",formattedValue:hi(e,t)}}e.CommandResult=void 0,(hn=e.CommandResult||(e.CommandResult={}))[hn.Success=0]="Success",hn[hn.CancelledForUnknownReason=1]="CancelledForUnknownReason",hn[hn.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",hn[hn.MergeIsDestructive=3]="MergeIsDestructive",hn[hn.CellIsMerged=4]="CellIsMerged",hn[hn.InvalidTarget=5]="InvalidTarget",hn[hn.EmptyUndoStack=6]="EmptyUndoStack",hn[hn.EmptyRedoStack=7]="EmptyRedoStack",hn[hn.NotEnoughElements=8]="NotEnoughElements",hn[hn.NotEnoughSheets=9]="NotEnoughSheets",hn[hn.MissingSheetName=10]="MissingSheetName",hn[hn.DuplicatedSheetName=11]="DuplicatedSheetName",hn[hn.DuplicatedSheetId=12]="DuplicatedSheetId",hn[hn.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",hn[hn.WrongSheetMove=14]="WrongSheetMove",hn[hn.WrongSheetPosition=15]="WrongSheetPosition",hn[hn.InvalidAnchorZone=16]="InvalidAnchorZone",hn[hn.SelectionOutOfBound=17]="SelectionOutOfBound",hn[hn.TargetOutOfSheet=18]="TargetOutOfSheet",hn[hn.WrongCutSelection=19]="WrongCutSelection",hn[hn.WrongPasteSelection=20]="WrongPasteSelection",hn[hn.WrongPasteOption=21]="WrongPasteOption",hn[hn.WrongFigurePasteOption=22]="WrongFigurePasteOption",hn[hn.EmptyClipboard=23]="EmptyClipboard",hn[hn.EmptyRange=24]="EmptyRange",hn[hn.InvalidRange=25]="InvalidRange",hn[hn.InvalidZones=26]="InvalidZones",hn[hn.InvalidSheetId=27]="InvalidSheetId",hn[hn.InvalidFigureId=28]="InvalidFigureId",hn[hn.InputAlreadyFocused=29]="InputAlreadyFocused",hn[hn.MaximumRangesReached=30]="MaximumRangesReached",hn[hn.InvalidChartDefinition=31]="InvalidChartDefinition",hn[hn.InvalidDataSet=32]="InvalidDataSet",hn[hn.InvalidLabelRange=33]="InvalidLabelRange",hn[hn.InvalidScorecardKeyValue=34]="InvalidScorecardKeyValue",hn[hn.InvalidScorecardBaseline=35]="InvalidScorecardBaseline",hn[hn.InvalidGaugeDataRange=36]="InvalidGaugeDataRange",hn[hn.EmptyGaugeRangeMin=37]="EmptyGaugeRangeMin",hn[hn.GaugeRangeMinNaN=38]="GaugeRangeMinNaN",hn[hn.EmptyGaugeRangeMax=39]="EmptyGaugeRangeMax",hn[hn.GaugeRangeMaxNaN=40]="GaugeRangeMaxNaN",hn[hn.GaugeRangeMinBiggerThanRangeMax=41]="GaugeRangeMinBiggerThanRangeMax",hn[hn.GaugeLowerInflectionPointNaN=42]="GaugeLowerInflectionPointNaN",hn[hn.GaugeUpperInflectionPointNaN=43]="GaugeUpperInflectionPointNaN",hn[hn.GaugeLowerBiggerThanUpper=44]="GaugeLowerBiggerThanUpper",hn[hn.InvalidAutofillSelection=45]="InvalidAutofillSelection",hn[hn.WrongComposerSelection=46]="WrongComposerSelection",hn[hn.MinBiggerThanMax=47]="MinBiggerThanMax",hn[hn.LowerBiggerThanUpper=48]="LowerBiggerThanUpper",hn[hn.MidBiggerThanMax=49]="MidBiggerThanMax",hn[hn.MinBiggerThanMid=50]="MinBiggerThanMid",hn[hn.FirstArgMissing=51]="FirstArgMissing",hn[hn.SecondArgMissing=52]="SecondArgMissing",hn[hn.MinNaN=53]="MinNaN",hn[hn.MidNaN=54]="MidNaN",hn[hn.MaxNaN=55]="MaxNaN",hn[hn.ValueUpperInflectionNaN=56]="ValueUpperInflectionNaN",hn[hn.ValueLowerInflectionNaN=57]="ValueLowerInflectionNaN",hn[hn.MinInvalidFormula=58]="MinInvalidFormula",hn[hn.MidInvalidFormula=59]="MidInvalidFormula",hn[hn.MaxInvalidFormula=60]="MaxInvalidFormula",hn[hn.ValueUpperInvalidFormula=61]="ValueUpperInvalidFormula",hn[hn.ValueLowerInvalidFormula=62]="ValueLowerInvalidFormula",hn[hn.InvalidSortZone=63]="InvalidSortZone",hn[hn.WaitingSessionConfirmation=64]="WaitingSessionConfirmation",hn[hn.MergeOverlap=65]="MergeOverlap",hn[hn.TooManyHiddenElements=66]="TooManyHiddenElements",hn[hn.Readonly=67]="Readonly",hn[hn.InvalidViewportSize=68]="InvalidViewportSize",hn[hn.InvalidScrollingDirection=69]="InvalidScrollingDirection",hn[hn.FigureDoesNotExist=70]="FigureDoesNotExist",hn[hn.InvalidConditionalFormatId=71]="InvalidConditionalFormatId",hn[hn.InvalidCellPopover=72]="InvalidCellPopover",hn[hn.EmptyTarget=73]="EmptyTarget",hn[hn.InvalidFreezeQuantity=74]="InvalidFreezeQuantity",hn[hn.FrozenPaneOverlap=75]="FrozenPaneOverlap",hn[hn.ValuesNotChanged=76]="ValuesNotChanged",hn[hn.InvalidFilterZone=77]="InvalidFilterZone",hn[hn.FilterOverlap=78]="FilterOverlap",hn[hn.FilterNotFound=79]="FilterNotFound",hn[hn.MergeInFilter=80]="MergeInFilter",hn[hn.NonContinuousTargets=81]="NonContinuousTargets",hn[hn.DuplicatedFigureId=82]="DuplicatedFigureId",hn[hn.InvalidSelectionStep=83]="InvalidSelectionStep",hn[hn.DuplicatedChartId=84]="DuplicatedChartId",hn[hn.ChartDoesNotExist=85]="ChartDoesNotExist",hn[hn.InvalidHeaderIndex=86]="InvalidHeaderIndex",hn[hn.InvalidQuantity=87]="InvalidQuantity",function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(dn||(dn={})),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"}(un||(un={}));const bn={type:tn.empty,value:"",format:void 0,isAutoSummable:!0,defaultAlign:"left",formattedValue:""};function Sn(e,t){return{type:tn.error,value:t.errorType,error:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:t.errorType}}const Cn=[function(e,t){if(""===e)return function(e){return void 0===e?bn:{type:tn.empty,value:"",format:e,isAutoSummable:!0,defaultAlign:"left",formattedValue:""}}(t)},function(e,t){if(t&&"number"==typeof e&&fi(t))return function(e,t){const i=hi(e,t);return{type:tn.number,value:e,format:t,isAutoSummable:!1,defaultAlign:"right",formattedValue:i}}(e,t)},function(e,t){return"number"==typeof e?vn(e,t):null===e?vn(0,t):void 0},function(e,t){if("boolean"==typeof e)return function(e,t){const i=e?"TRUE":"FALSE";return{type:tn.boolean,value:e,format:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:i}}(e,t)}],En=new Co;En.add("ALPHANUMERIC_INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;const i=`${e.prefix}${e.current.toString().padStart(e.numberPostfixLength||0,"0")}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i},tooltip:{props:{content:i}}}}}).add("INCREMENT_MODIFIER",{apply:(e,t)=>{var i;e.current+=e.increment;const o=e.current.toString(),n=hi(e.current,null===(i=t.cell)||void 0===i?void 0:i.format);return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:n}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,i)=>{var o,n,s;const r=(null===(o=t.cell)||void 0===o?void 0:o.content)||"";return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:gn(null===(n=t.cell)||void 0===n?void 0:n.content,null===(s=t.cell)||void 0===s?void 0:s.format).formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,i,o)=>{e.current+=e.increment;let n=0,s=0;switch(o){case"up":n=0,s=-e.current;break;case"down":n=0,s=e.current;break;case"left":n=-e.current,s=0;break;case"right":n=e.current,s=0}const r=t.cell;if(!r||!r.isFormula)return{cellData:{}};const a=t.sheetId,l=i.createAdaptedRanges(r.dependencies,n,s,a),c=i.buildFormulaContent(a,r,l);return{cellData:{border:t.border,style:r.style,format:r.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});const wn=new Co,yn=/(\d+)$/,xn=/^(.*\D+)/,In=/^(.*\D+)(\d+)$/;function Rn(e,t,i){let o=[],n=!1;for(let s of t){s===e&&(n=!0);const t=gn(null==s?void 0:s.content);if(i(t))o.push(t);else{if(n)return o;o=[]}}return o}function Tn(e){let t=1;return e.length>=2&&(t=function(e){const t=[];let i=e[0];for(let o=1;o<e.length;o++){const n=e[o];t.push(n-i),i=n}return t.reduce(((e,t)=>e+t),0)/t.length}(e)*e.length),t}wn.add("simple_value_copy",{condition:(e,t)=>{var i;return 1===t.length&&!e.isFormula&&!(null===(i=e.format)||void 0===i?void 0:i.match(X))},generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&gn(e.content).type===tn.text&&In.test(e.content),generateRule:(e,t)=>{const i=parseInt(e.content.match(yn)[0]),o=e.content.match(xn)[0],n=e.content.length-o.length,s=Rn(e,t,(e=>e.type===tn.text&&In.test(e.value))).filter((e=>o===e.value.toString().match(xn)[0])).map((e=>parseInt(e.value.toString().match(yn)[0]))),r=Tn(s);return{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:o,current:i,increment:r,numberPostfixLength:n}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&gn(e.content).type===tn.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&&gn(e.content).type===tn.number,generateRule:(e,t)=>{const i=Tn(Rn(e,t,(e=>e.type===tn.number)).map((e=>Number(e.value)))),o=gn(e.content);return{type:"INCREMENT_MODIFIER",increment:i,current:o.type===tn.number?o.value:0}},sequence:40});ho`
53
+ `;class bo 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 yt(this.backgroundColor)>.3?"#525252":"#C8C8C8"}get figure(){return this.props.figure}get chartStyle(){return fo({padding:`${this.chartPadding}px`,background:this.backgroundColor})}get chartContentStyle(){return fo({height:`${this.getDrawableHeight()}px`})}get chartPadding(){return.02*this.props.figure.width}getTextStyles(){const e=.96*this.props.figure.width,t=this.getWidestElement(),i=t.getElementMaxFontSize(this.getDrawableHeight(),this);let o=function(e,t,i,o=.25){let n=1;if(i(n)>e)return n;if(i(t)<e)return t;let s=(n+t)/2,r=i(s),a=0;for(;Math.abs(r-e)>o&&a<20;)r>=e?t=(n+t)/2:n=(n+t)/2,s=(n+t)/2,r=i(s),a++;return s}(e,i,(e=>t.getElementWidth(e,this.ctx,this)))/i;const n=(new Co).getElementMaxFontSize(this.getDrawableHeight(),this)*o,s=(new So).getElementMaxFontSize(this.getDrawableHeight(),this)*o;return{titleStyle:this.getTextStyle({fontSize:18,color:this.secondaryFontColor}),keyStyle:this.getTextStyle({fontSize:n,cellStyle:this.runtime.keyValueStyle,color:this.primaryFontColor}),baselineStyle:this.getTextStyle({fontSize:s}),baselineValueStyle:this.getTextStyle({fontSize:s,cellStyle:this.runtime.baselineStyle,color:this.runtime.baselineColor||this.secondaryFontColor}),baselineDescrStyle:this.getTextStyle({fontSize:.9*s,color:this.secondaryFontColor})}}getTextStyle(e){const t=mo(e.cellStyle);return t["font-size"]=`${e.fontSize}px`,t.display="inline-block",!t.color&&e.color&&(t.color=e.color),fo(t)}getDrawableHeight(){const e=2*this.chartPadding;let t=this.props.figure.height-e;return t-=this.title?18*vo:0,t}getWidestElement(){const e=new So,t=new Co;return e.getElementWidth(.35,this.ctx,this)>t.getElementWidth(.65,this.ctx,this)?e:t}}bo.template="o-spreadsheet-ScorecardChart";class So{getElementWidth(e,t,i){if(!i.runtime)return 0;const o=i.baseline,n="neutral"!==i.baselineArrowDirection?"A "+o:o;t.font=`${e}px ${q}`;let s=t.measureText(n).width;return t.font=`${.9*e}px ${q}`,s+=t.measureText(i.baselineDescr).width,s}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.35*e:0)/vo}}class Co{getElementWidth(e,t,i){if(!i.runtime)return 0;const o=i.keyValue||"";return t.font=`${e}px ${q}`,t.measureText(o).width}getElementMaxFontSize(e,t){if(!t.runtime)return 0;return(""!==t.baseline||t.baselineDescr?.65*e:e)/vo}}bo.props={figure:Object};class Eo{constructor(){this.content={}}add(e,t){return this.content[e]=t,this}get(e){const t=this.content[e];if(!t&&!(e in this.content))throw new Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}}function wo(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}const yo=new Eo;function xo(e,t){return{url:e=wo(e),label:t||e,isExternal:!0,isUrlEditable:!0}}yo.add("sheet_URL",{match:e=>Qe(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){const i=et(e);return t.tryGetSheetName(i)||s("Invalid sheet")},open(e,t){const i=et(e);t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:i})},sequence:0});const Io={createLink:xo,match:e=>je(e),open:e=>window.open(e,"_blank"),urlRepresentation:e=>e,sequence:0};function Ro(e){return yo.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((t=>t.match(e)))||Io}function To(e,t){return Ro(e.url).urlRepresentation(e.url,t)}function Ao(e,t){Ro(e.url).open(e.url,t)}function Mo(e){if("string"==typeof e){if(Ze(e)){const{label:t,url:i}=Ye(e);return Ro(i).createLink(i,t)}return je(e)?xo(e):void 0}}const Oo=["number","string","boolean","undefined"];function No(e,t){if(!e())throw new Error(t)}const _o=e=>s("The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.",e);function Fo(e){switch(typeof e){case"number":return e;case"boolean":return e?1:0;case"string":if(Jt(e)||""===e)return ti(e);const t=Se(e);if(t)return t.value;throw new Error(_o(e));default:return 0}}function Do(e){if(""===e)throw new Error(_o(e));return Fo(e)}function ko(e){switch(typeof e){case"string":return e;case"number":return e.toString();case"boolean":return e?"TRUE":"FALSE";default:return""}}function Lo(e){return"string"==typeof e?e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):e}const Po=e=>s("The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a number.",e);function Uo(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(Po(e))}return!1;case"number":return!!e;default:return!1}}function Vo(e){return Ee(Fo(e))}function zo(e,t,i){for(let o of e)if(Array.isArray(o)){const e=o.length,i=o[0].length;for(let n=0;n<i;n++)for(let i=0;i<e;i++)t(o[i][n])}else i(o)}function Bo(e,t){zo(e,t,t)}function Ho(e,t){zo(e,(e=>{"number"==typeof e&&t(e)}),(e=>{t(Do(e))}))}function $o(e,t,i,o){let n=o;for(let o of e)if(Array.isArray(o)){const e=o.length,i=o[0].length;for(let s=0;s<i;s++)for(let i=0;i<e;i++)n=t(n,o[i][s])}else n=i(n,o);return n}function Wo(e,t,i){return $o(e,t,t,i)}function Go(e,t,i){return $o(e,((e,i)=>"number"==typeof i?t(e,i):e),((e,i)=>t(e,Do(i))),i)}function qo(e,t,i){return $o(e,((e,i)=>null!=i?t(e,"number"==typeof i?i:"boolean"==typeof i?Fo(i):0):e),((e,i)=>t(e,Fo(i))),i)}function Zo(e,t){return function(e,t,i){for(let o of e)if(Array.isArray(o)){const e=o.length,i=o[0].length;for(let n=0;n<i;n++)for(let i=0;i<e;i++)if(!t(o[i][n]))return}else if(!i(o))return}(e,(e=>"boolean"==typeof e?t(e):"number"!=typeof e||t(!!e)),(e=>null==e||t(function(e){if(""===e)throw new Error(Po(e));return Uo(e)}(e))))}function jo(e,t){let i,o,n=e.substring(0,2);"<="===n||">="===n||"<>"===n?(i=n,o=e.substring(2)):(n=e.substring(0,1),"<"===n||">"===n||"="===n?(i=n,o=e.substring(1)):(i="=",o=e)),Jt(o)?o=Fo(o):"TRUE"!==o&&"FALSE"!==o||(o=Uo(o));const s={operator:i,operand:o};return"string"==typeof o&&(t&&(o+="*"),s.regexp=function(e){let t="",i="";for(let o of e)"?"===o&&"~"!==i?t+=".":"*"===o&&"~"!==i?t+=".*":("*"!==o&&"?"!==o||(t=t.slice(0,-1)),["^",".","[","]","$","(",")","*","+","?","|","{","}","\\"].includes(o)&&(t+="\\"),t+=o),i=o;return new RegExp("^"+t+"$","i")}(o)),s}function Xo(e,t){const{operator:i,operand:o}=t;if(void 0===e||void 0===o)return!1;if("number"==typeof o&&"="===i)return ko(e)===ko(o);if("<>"===i||"="===i){let n;return n=typeof e==typeof o&&("string"==typeof e&&t.regexp?t.regexp.test(e):e===o),"="===i?n:!n}if(typeof e==typeof o)switch(i){case"<":return e<o;case">":return e>o;case"<=":return e<=o;case">=":return e>=o}return!1}function Yo(e,t,i=!1){const o=e.length;if(o%2==1)throw new Error(s("Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs."));const n=e[0].length,r=e[0][0].length;let a=[];for(let t=0;t<o-1;t+=2){const o=e[t];if(!Array.isArray(o)||o.length!==n||o[0].length!==r)throw new Error(s("Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension"));const l=ko(e[t+1]);a.push(jo(l,i))}for(let i=0;i<n;i++)for(let n=0;n<r;n++){let s=!0;for(let t=0;t<o-1;t+=2){if(s=Xo(e[t][i][n],a[t/2]),!s)break}s&&t(i,n)}}function Ko(e,t){return Lo(e[0][t])}function Qo(e,t){return Lo(e[t][0])}function Jo(e,t,i,o,n,s){if(null==t)return-1;const r=typeof t;let a,l,c,h,d,u,g=0,p=n-1;for(;p-g>=0;){for(c=Math.floor((g+p)/2),h=c,d=s(e,h),u=typeof d;g<h&&r!==u;)h--,d=s(e,h),u=typeof d;u===r&&void 0!==d?("strict"===i&&d===t?(a=d,l=h):"nextSmaller"===i&&d<=t?(void 0===a||a<d||a===d&&"asc"===o&&l<h||a===d&&"desc"===o&&l>h)&&(a=d,l=h):"nextGreater"===i&&d>=t&&(void 0===a||a>d||a===d&&"asc"===o&&l<h||a===d&&"desc"===o&&l>h)&&(a=d,l=h),"asc"===o&&d>t||"desc"===o&&d<=t?p=h-1:g=c+1):g=c+1}return void 0!==l?l:-1}function en(e,t,i,o,n,s=!1){if(null==t)return-1;const r=s?(e,t)=>n(e,o-t-1):n;let a,l=-1;for(let n=0;n<o;n++){const c=r(e,n);if(c===t)return s?o-n-1:n;"nextSmaller"===i?(!a&&tn(t,c)>=0||tn(t,c)>=0&&tn(c,a)>0)&&(a=c,l=n):"nextGreater"===i&&(!a&&tn(t,c)<=0||tn(t,c)<=0&&tn(c,a)<0)&&(a=c,l=n)}return s?o-l-1:l}function tn(e,t){let i=Oo.indexOf(typeof e)-Oo.indexOf(typeof t);return 0===i&&("string"==typeof e&&"string"==typeof t?i=e.localeCompare(t):"number"==typeof e&&"number"==typeof t?i=e-t:"boolean"==typeof e&&"boolean"==typeof t&&(i=Number(e)-Number(t))),i}var on,nn;!function(e){e.boolean="boolean",e.number="number",e.text="text",e.empty="empty",e.error="error"}(on||(on={})),function(e){e.PlainText="text/plain",e.Html="text/html"}(nn||(nn={}));const sn=new Set(["RENAME_SHEET","DELETE_SHEET","CREATE_SHEET","ADD_COLUMNS_ROWS","REMOVE_COLUMNS_ROWS","DELETE_CELL","INSERT_CELL","UNDO","REDO"]),rn=new Set([...sn,"DUPLICATE_SHEET","EVALUATE_CELLS","ADD_CONDITIONAL_FORMAT","REMOVE_CONDITIONAL_FORMAT","MOVE_CONDITIONAL_FORMAT"]),an=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"]),ln=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 cn(e){return ln.has(e.type)}class hn{constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter((e=>0!==e))}static get Success(){return new hn}get isSuccessful(){return 0===this.reasons.length}isCancelledBecause(e){return this.reasons.includes(e)}}var dn,un,gn;function pn(e,t){return fn(mn(e||""),t)}function mn(e){if(e.startsWith("="))throw new Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);return Jt(e)||We(e)?Fo(e):function(e){const t=e.toUpperCase();return"TRUE"===t||"FALSE"===t}(e)?"TRUE"===e.toUpperCase():e}function fn(e,t){const i=Mo(e);return i?{...vn(mn(i.label),t||wi(i.label)),link:i}:vn(e,t)}function vn(e,t){try{for(const i of En){const o=i(e,t);if(o)return o}return function(e,t){return{type:on.text,value:e,format:t,isAutoSummable:!0,defaultAlign:"left",formattedValue:di(e,t)}}((e||"").toString(),t)}catch(t){return Cn((e||"").toString(),new c(a.GenericError,t.message||ae))}}function bn(e,t){return{type:on.number,value:e||0,format:t,isAutoSummable:!0,defaultAlign:"right",formattedValue:di(e,t)}}e.CommandResult=void 0,(dn=e.CommandResult||(e.CommandResult={}))[dn.Success=0]="Success",dn[dn.CancelledForUnknownReason=1]="CancelledForUnknownReason",dn[dn.WillRemoveExistingMerge=2]="WillRemoveExistingMerge",dn[dn.MergeIsDestructive=3]="MergeIsDestructive",dn[dn.CellIsMerged=4]="CellIsMerged",dn[dn.InvalidTarget=5]="InvalidTarget",dn[dn.EmptyUndoStack=6]="EmptyUndoStack",dn[dn.EmptyRedoStack=7]="EmptyRedoStack",dn[dn.NotEnoughElements=8]="NotEnoughElements",dn[dn.NotEnoughSheets=9]="NotEnoughSheets",dn[dn.MissingSheetName=10]="MissingSheetName",dn[dn.DuplicatedSheetName=11]="DuplicatedSheetName",dn[dn.DuplicatedSheetId=12]="DuplicatedSheetId",dn[dn.ForbiddenCharactersInSheetName=13]="ForbiddenCharactersInSheetName",dn[dn.WrongSheetMove=14]="WrongSheetMove",dn[dn.WrongSheetPosition=15]="WrongSheetPosition",dn[dn.InvalidAnchorZone=16]="InvalidAnchorZone",dn[dn.SelectionOutOfBound=17]="SelectionOutOfBound",dn[dn.TargetOutOfSheet=18]="TargetOutOfSheet",dn[dn.WrongCutSelection=19]="WrongCutSelection",dn[dn.WrongPasteSelection=20]="WrongPasteSelection",dn[dn.WrongPasteOption=21]="WrongPasteOption",dn[dn.WrongFigurePasteOption=22]="WrongFigurePasteOption",dn[dn.EmptyClipboard=23]="EmptyClipboard",dn[dn.EmptyRange=24]="EmptyRange",dn[dn.InvalidRange=25]="InvalidRange",dn[dn.InvalidZones=26]="InvalidZones",dn[dn.InvalidSheetId=27]="InvalidSheetId",dn[dn.InvalidFigureId=28]="InvalidFigureId",dn[dn.InputAlreadyFocused=29]="InputAlreadyFocused",dn[dn.MaximumRangesReached=30]="MaximumRangesReached",dn[dn.InvalidChartDefinition=31]="InvalidChartDefinition",dn[dn.InvalidDataSet=32]="InvalidDataSet",dn[dn.InvalidLabelRange=33]="InvalidLabelRange",dn[dn.InvalidScorecardKeyValue=34]="InvalidScorecardKeyValue",dn[dn.InvalidScorecardBaseline=35]="InvalidScorecardBaseline",dn[dn.InvalidGaugeDataRange=36]="InvalidGaugeDataRange",dn[dn.EmptyGaugeRangeMin=37]="EmptyGaugeRangeMin",dn[dn.GaugeRangeMinNaN=38]="GaugeRangeMinNaN",dn[dn.EmptyGaugeRangeMax=39]="EmptyGaugeRangeMax",dn[dn.GaugeRangeMaxNaN=40]="GaugeRangeMaxNaN",dn[dn.GaugeRangeMinBiggerThanRangeMax=41]="GaugeRangeMinBiggerThanRangeMax",dn[dn.GaugeLowerInflectionPointNaN=42]="GaugeLowerInflectionPointNaN",dn[dn.GaugeUpperInflectionPointNaN=43]="GaugeUpperInflectionPointNaN",dn[dn.GaugeLowerBiggerThanUpper=44]="GaugeLowerBiggerThanUpper",dn[dn.InvalidAutofillSelection=45]="InvalidAutofillSelection",dn[dn.WrongComposerSelection=46]="WrongComposerSelection",dn[dn.MinBiggerThanMax=47]="MinBiggerThanMax",dn[dn.LowerBiggerThanUpper=48]="LowerBiggerThanUpper",dn[dn.MidBiggerThanMax=49]="MidBiggerThanMax",dn[dn.MinBiggerThanMid=50]="MinBiggerThanMid",dn[dn.FirstArgMissing=51]="FirstArgMissing",dn[dn.SecondArgMissing=52]="SecondArgMissing",dn[dn.MinNaN=53]="MinNaN",dn[dn.MidNaN=54]="MidNaN",dn[dn.MaxNaN=55]="MaxNaN",dn[dn.ValueUpperInflectionNaN=56]="ValueUpperInflectionNaN",dn[dn.ValueLowerInflectionNaN=57]="ValueLowerInflectionNaN",dn[dn.MinInvalidFormula=58]="MinInvalidFormula",dn[dn.MidInvalidFormula=59]="MidInvalidFormula",dn[dn.MaxInvalidFormula=60]="MaxInvalidFormula",dn[dn.ValueUpperInvalidFormula=61]="ValueUpperInvalidFormula",dn[dn.ValueLowerInvalidFormula=62]="ValueLowerInvalidFormula",dn[dn.InvalidSortZone=63]="InvalidSortZone",dn[dn.WaitingSessionConfirmation=64]="WaitingSessionConfirmation",dn[dn.MergeOverlap=65]="MergeOverlap",dn[dn.TooManyHiddenElements=66]="TooManyHiddenElements",dn[dn.Readonly=67]="Readonly",dn[dn.InvalidViewportSize=68]="InvalidViewportSize",dn[dn.InvalidScrollingDirection=69]="InvalidScrollingDirection",dn[dn.FigureDoesNotExist=70]="FigureDoesNotExist",dn[dn.InvalidConditionalFormatId=71]="InvalidConditionalFormatId",dn[dn.InvalidCellPopover=72]="InvalidCellPopover",dn[dn.EmptyTarget=73]="EmptyTarget",dn[dn.InvalidFreezeQuantity=74]="InvalidFreezeQuantity",dn[dn.FrozenPaneOverlap=75]="FrozenPaneOverlap",dn[dn.ValuesNotChanged=76]="ValuesNotChanged",dn[dn.InvalidFilterZone=77]="InvalidFilterZone",dn[dn.FilterOverlap=78]="FilterOverlap",dn[dn.FilterNotFound=79]="FilterNotFound",dn[dn.MergeInFilter=80]="MergeInFilter",dn[dn.NonContinuousTargets=81]="NonContinuousTargets",dn[dn.DuplicatedFigureId=82]="DuplicatedFigureId",dn[dn.InvalidSelectionStep=83]="InvalidSelectionStep",dn[dn.DuplicatedChartId=84]="DuplicatedChartId",dn[dn.ChartDoesNotExist=85]="ChartDoesNotExist",dn[dn.InvalidHeaderIndex=86]="InvalidHeaderIndex",dn[dn.InvalidQuantity=87]="InvalidQuantity",function(e){e.UP="up",e.DOWN="down",e.LEFT="left",e.RIGHT="right"}(un||(un={})),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"}(gn||(gn={}));const Sn={type:on.empty,value:"",format:void 0,isAutoSummable:!0,defaultAlign:"left",formattedValue:""};function Cn(e,t){return{type:on.error,value:t.errorType,error:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:t.errorType}}const En=[function(e,t){if(""===e)return function(e){return void 0===e?Sn:{type:on.empty,value:"",format:e,isAutoSummable:!0,defaultAlign:"left",formattedValue:""}}(t)},function(e,t){if(t&&"number"==typeof e&&vi(t))return function(e,t){const i=di(e,t);return{type:on.number,value:e,format:t,isAutoSummable:!1,defaultAlign:"right",formattedValue:i}}(e,t)},function(e,t){return"number"==typeof e?bn(e,t):null===e?bn(0,t):void 0},function(e,t){if("boolean"==typeof e)return function(e,t){const i=e?"TRUE":"FALSE";return{type:on.boolean,value:e,format:t,isAutoSummable:!1,defaultAlign:"center",formattedValue:i}}(e,t)}],wn=new Eo;wn.add("ALPHANUMERIC_INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;const i=`${e.prefix}${e.current.toString().padStart(e.numberPostfixLength||0,"0")}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i},tooltip:{props:{content:i}}}}}).add("INCREMENT_MODIFIER",{apply:(e,t)=>{var i;e.current+=e.increment;const o=e.current.toString(),n=di(e.current,null===(i=t.cell)||void 0===i?void 0:i.format);return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:o},tooltip:o?{props:{content:n}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,i)=>{var o,n,s;const r=(null===(o=t.cell)||void 0===o?void 0:o.content)||"";return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:pn(null===(n=t.cell)||void 0===n?void 0:n.content,null===(s=t.cell)||void 0===s?void 0:s.format).formattedValue}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,i,o)=>{e.current+=e.increment;let n=0,s=0;switch(o){case"up":n=0,s=-e.current;break;case"down":n=0,s=e.current;break;case"left":n=-e.current,s=0;break;case"right":n=e.current,s=0}const r=t.cell;if(!r||!r.isFormula)return{cellData:{}};const a=t.sheetId,l=i.createAdaptedRanges(r.dependencies,n,s,a),c=i.buildFormulaContent(a,r,l);return{cellData:{border:t.border,style:r.style,format:r.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});const yn=new Eo,xn=/(\d+)$/,In=/^(.*\D+)/,Rn=/^(.*\D+)(\d+)$/;function Tn(e,t,i){let o=[],n=!1;for(let s of t){s===e&&(n=!0);const t=pn(null==s?void 0:s.content);if(i(t))o.push(t);else{if(n)return o;o=[]}}return o}function An(e){let t=1;return e.length>=2&&(t=function(e){const t=[];let i=e[0];for(let o=1;o<e.length;o++){const n=e[o];t.push(n-i),i=n}return t.reduce(((e,t)=>e+t),0)/t.length}(e)*e.length),t}yn.add("simple_value_copy",{condition:(e,t)=>{var i;return 1===t.length&&!e.isFormula&&!(null===(i=e.format)||void 0===i?void 0:i.match(X))},generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&pn(e.content).type===on.text&&Rn.test(e.content),generateRule:(e,t)=>{const i=parseInt(e.content.match(xn)[0]),o=e.content.match(In)[0],n=e.content.length-o.length,s=Tn(e,t,(e=>e.type===on.text&&Rn.test(e.value))).filter((e=>o===e.value.toString().match(In)[0])).map((e=>parseInt(e.value.toString().match(xn)[0]))),r=An(s);return{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:o,current:i,increment:r,numberPostfixLength:n}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&pn(e.content).type===on.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&&pn(e.content).type===on.number,generateRule:(e,t)=>{const i=An(Tn(e,t,(e=>e.type===on.number)).map((e=>Number(e.value)))),o=pn(e.content);return{type:"INCREMENT_MODIFIER",increment:i,current:o.type===on.number?o.value:0}},sequence:40});uo`
54
54
  .o-error-tooltip {
55
55
  font-size: 13px;
56
56
  background-color: white;
@@ -59,7 +59,7 @@
59
59
  width: ${180}px;
60
60
  box-sizing: border-box !important;
61
61
  }
62
- `;class An extends t.Component{}An.maxSize={maxHeight:80},An.template="o-spreadsheet-ErrorToolTip",An.components={},An.props={text:String,onClosed:{type:Function,optional:!0}};const Mn={onHover:(e,t)=>{const i=t.getEvaluatedCell(e);return i.type===tn.error&&i.error.logLevel>l.silent?{isOpen:!0,props:{text:i.error.message},Component:An,cellCorner:"TopRight"}:{isOpen:!1}}};ho`
62
+ `;class Mn extends t.Component{}Mn.maxSize={maxHeight:80},Mn.template="o-spreadsheet-ErrorToolTip",Mn.components={},Mn.props={text:String,onClosed:{type:Function,optional:!0}};const On={onHover:(e,t)=>{const i=t.getEvaluatedCell(e);return i.type===on.error&&i.error.logLevel>l.silent?{isOpen:!0,props:{text:i.error.message},Component:Mn,cellCorner:"TopRight"}:{isOpen:!1}}};uo`
63
63
  .o-filter-menu-value {
64
64
  padding: 4px;
65
65
  line-height: 20px;
@@ -68,7 +68,7 @@
68
68
  width: 20px;
69
69
  }
70
70
  }
71
- `;class On 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"}))}}On.template="o-spreadsheet-FilterMenuValueItem",On.props={value:String,isChecked:Boolean,isSelected:Boolean,onMouseMove:Function,onClick:Function,scrolledTo:{type:String,optional:!0}};const Nn=ho`
71
+ `;class Nn extends t.Component{constructor(){super(...arguments),this.itemRef=t.useRef("menuValueItem")}setup(){t.onWillPatch((()=>{this.props.scrolledTo&&this.scrollListToSelectedValue()}))}scrollListToSelectedValue(){var e,t;this.itemRef.el&&(null===(t=(e=this.itemRef.el).scrollIntoView)||void 0===t||t.call(e,{block:"bottom"===this.props.scrolledTo?"end":"start"}))}}Nn.template="o-spreadsheet-FilterMenuValueItem",Nn.props={value:String,isChecked:Boolean,isSelected:Boolean,onMouseMove:Function,onClick:Function,scrolledTo:{type:String,optional:!0}};const _n=uo`
72
72
  .o-filter-menu {
73
73
  box-sizing: border-box;
74
74
  padding: 8px 16px;
@@ -161,7 +161,7 @@
161
161
  }
162
162
  }
163
163
  }
164
- `;class _n extends t.Component{constructor(){super(...arguments),this.state=t.useState({values:[],textFilter:"",selectedValue:void 0}),this.searchBar=t.useRef("filterMenuSearchBar")}setup(){t.onWillUpdateProps((e=>{at(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(),i=this.env.model.getters.getFilter({sheetId:t,...e});if(!i)return[];const o=(i.filteredZone?Ji(i.filteredZone):[]).filter((({row:e})=>!this.env.model.getters.isRowHidden(t,e))).map((({col:e,row:i})=>this.env.model.getters.getEvaluatedCell({sheetId:t,col:e,row:i}).formattedValue)),n=this.env.model.getters.getFilterValues({sheetId:t,...e}),s=[...o,...n],r=n.map(ct);return[...new Set(s.map(ct))].sort(((e,t)=>e.localeCompare(t,void 0,{numeric:!0,sensitivity:"base"}))).map((e=>({checked:-1===r.findIndex((t=>t===e)),string:s.find((t=>ct(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?_i(this.state.textFilter,this.state.values,(e=>e.string)):this.state.values}confirm(){var e,t;const i=this.props.filterPosition;this.env.model.dispatch("UPDATE_FILTER",{...i,sheetId:this.env.model.getters.getActiveSheetId(),values:this.state.values.filter((e=>!e.checked)).map((e=>e.string))}),null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}cancel(){var e,t;null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}onKeyDown(e){const t=this.displayedValues;if(0===t.length)return;let i;if(void 0!==this.state.selectedValue){const e=t.findIndex((e=>e.string===this.state.selectedValue));i=-1===e?void 0:e}switch(e.key){case"ArrowDown":i=void 0===i?0:Math.min(i+1,t.length-1),e.preventDefault(),e.stopPropagation();break;case"ArrowUp":i=void 0===i?t.length-1:Math.max(i-1,0),e.preventDefault(),e.stopPropagation();break;case"Enter":void 0!==i&&this.checkValue(t[i]),e.stopPropagation(),e.preventDefault()}this.state.selectedValue=void 0!==i?t[i].string:void 0,"ArrowUp"!==e.key&&"ArrowDown"!==e.key||this.scrollListToSelectedValue(e.key)}clearScrolledToValue(){this.state.values.forEach((e=>e.scrolledTo=void 0))}scrollListToSelectedValue(e){this.clearScrolledToValue();const t=this.state.values.find((e=>e.string===this.state.selectedValue));t&&(t.scrolledTo="ArrowUp"===e?"top":"bottom")}sortFilterZone(e){var t,i;const o=this.props.filterPosition,n=this.filterTable;if(!o||!n||!n.contentZone)return;const s=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("SORT_CELLS",{sheetId:s,col:o.col,row:n.contentZone.top,zone:n.contentZone,sortDirection:e,sortOptions:{emptyCellAsZero:!0,sortHeaders:!0}}),null===(i=(t=this.props).onClosed)||void 0===i||i.call(t)}}_n.size={width:H,height:295},_n.template="o-spreadsheet-FilterMenu",_n.style=Nn,_n.components={FilterMenuValueItem:On},_n.props={filterPosition:Object,onClosed:{type:Function,optional:!0}};const Fn={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:_n,cellCorner:"BottomLeft"})};function Dn(e,t){return!!t.target&&e.contains(t.target)}function kn(){const e=document.querySelector(".o-grid-overlay");if(e){const{top:t,left:i}=null==e?void 0:e.getBoundingClientRect();return{top:t,left:i}}throw new Error("Can't find spreadsheet position")}function Ln(e){const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function*Pn(e){if(yield e,e.hasChildNodes())for(let t of e.childNodes)yield*Pn(t)}function Un(){const e=t.useState({x:0,y:0,width:0,height:0});let i=document.querySelector(".o-spreadsheet");function o(){if(i||(i=document.querySelector(".o-spreadsheet")),i){const{top:t,left:o,width:n,height:s}=i.getBoundingClientRect();e.x=o,e.y=t,e.width=n,e.height=s}}return o(),t.onMounted(o),t.onPatched(o),e}function Vn(e){const i=t.useState({x:0,y:0,width:0,height:0});function o(){const t=e.el;if(null===t)return;const{top:o,left:n,width:s,height:r}=t.getBoundingClientRect();i.x=n,i.y=o,i.width=s,i.height=r}return t.onMounted(o),t.onPatched(o),i}function zn(e,t){return(i=Wi(Bn(e),Bn(t)))?{x:i.left,y:i.top,width:i.right-i.left,height:i.bottom-i.top}:void 0;var i}function Bn(e){return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}ho`
164
+ `;class Fn extends t.Component{constructor(){super(...arguments),this.state=t.useState({values:[],textFilter:"",selectedValue:void 0}),this.searchBar=t.useRef("filterMenuSearchBar")}setup(){t.onWillUpdateProps((e=>{lt(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(),i=this.env.model.getters.getFilter({sheetId:t,...e});if(!i)return[];const o=(i.filteredZone?eo(i.filteredZone):[]).filter((({row:e})=>!this.env.model.getters.isRowHidden(t,e))).map((({col:e,row:i})=>this.env.model.getters.getEvaluatedCell({sheetId:t,col:e,row:i}).formattedValue)),n=this.env.model.getters.getFilterValues({sheetId:t,...e}),s=[...o,...n],r=n.map(ht);return[...new Set(s.map(ht))].sort(((e,t)=>e.localeCompare(t,void 0,{numeric:!0,sensitivity:"base"}))).map((e=>({checked:-1===r.findIndex((t=>t===e)),string:s.find((t=>ht(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?Fi(this.state.textFilter,this.state.values,(e=>e.string)):this.state.values}confirm(){var e,t;const i=this.props.filterPosition;this.env.model.dispatch("UPDATE_FILTER",{...i,sheetId:this.env.model.getters.getActiveSheetId(),values:this.state.values.filter((e=>!e.checked)).map((e=>e.string))}),null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}cancel(){var e,t;null===(t=(e=this.props).onClosed)||void 0===t||t.call(e)}onKeyDown(e){const t=this.displayedValues;if(0===t.length)return;let i;if(void 0!==this.state.selectedValue){const e=t.findIndex((e=>e.string===this.state.selectedValue));i=-1===e?void 0:e}switch(e.key){case"ArrowDown":i=void 0===i?0:Math.min(i+1,t.length-1),e.preventDefault(),e.stopPropagation();break;case"ArrowUp":i=void 0===i?t.length-1:Math.max(i-1,0),e.preventDefault(),e.stopPropagation();break;case"Enter":void 0!==i&&this.checkValue(t[i]),e.stopPropagation(),e.preventDefault()}this.state.selectedValue=void 0!==i?t[i].string:void 0,"ArrowUp"!==e.key&&"ArrowDown"!==e.key||this.scrollListToSelectedValue(e.key)}clearScrolledToValue(){this.state.values.forEach((e=>e.scrolledTo=void 0))}scrollListToSelectedValue(e){this.clearScrolledToValue();const t=this.state.values.find((e=>e.string===this.state.selectedValue));t&&(t.scrolledTo="ArrowUp"===e?"top":"bottom")}sortFilterZone(e){var t,i;const o=this.props.filterPosition,n=this.filterTable;if(!o||!n||!n.contentZone)return;const s=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("SORT_CELLS",{sheetId:s,col:o.col,row:n.contentZone.top,zone:n.contentZone,sortDirection:e,sortOptions:{emptyCellAsZero:!0,sortHeaders:!0}}),null===(i=(t=this.props).onClosed)||void 0===i||i.call(t)}}Fn.size={width:H,height:295},Fn.template="o-spreadsheet-FilterMenu",Fn.style=_n,Fn.components={FilterMenuValueItem:Nn},Fn.props={filterPosition:Object,onClosed:{type:Function,optional:!0}};const Dn={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:Fn,cellCorner:"BottomLeft"})};function kn(e,t){return!!t.target&&e.contains(t.target)}function Ln(){const e=document.querySelector(".o-grid-overlay");if(e){const{top:t,left:i}=null==e?void 0:e.getBoundingClientRect();return{top:t,left:i}}throw new Error("Can't find spreadsheet position")}function Pn(e){const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function*Un(e){if(yield e,e.hasChildNodes())for(let t of e.childNodes)yield*Un(t)}function Vn(){const e=t.useState({x:0,y:0,width:0,height:0});let i=document.querySelector(".o-spreadsheet");function o(){if(i||(i=document.querySelector(".o-spreadsheet")),i){const{top:t,left:o,width:n,height:s}=i.getBoundingClientRect();e.x=o,e.y=t,e.width=n,e.height=s}}return o(),t.onMounted(o),t.onPatched(o),e}function zn(e){const i=t.useState({x:0,y:0,width:0,height:0});function o(){const t=e.el;if(null===t)return;const{top:o,left:n,width:s,height:r}=t.getBoundingClientRect();i.x=n,i.y=o,i.width=s,i.height=r}return t.onMounted(o),t.onPatched(o),i}function Bn(e,t){return(i=Gi(Hn(e),Hn(t)))?{x:i.left,y:i.top,width:i.right-i.left,height:i.bottom-i.top}:void 0;var i}function Hn(e){return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}uo`
165
165
  .o-popover {
166
166
  position: absolute;
167
167
  z-index: ${le.Popover};
@@ -170,7 +170,7 @@
170
170
  width: fit-content;
171
171
  height: fit-content;
172
172
  }
173
- `;class Hn extends t.Component{constructor(){super(...arguments),this.popoverRef=t.useRef("popover"),this.currentPosition=void 0,this.currentDisplayValue=void 0,this.spreadsheetRect=Un()}setup(){this.containerRect=function(){const e=t.useState({x:0,y:0,width:0,height:0}),i=t.useComponent(),o=Un();function n(){const t=i.env,n="getPopoverContainerRect"in t?t.getPopoverContainerRect():o;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,i,o;if(!this.containerRect)throw new Error("Popover container is not defined");const n=this.popoverRef.el,s=zn(this.props.anchorRect,this.containerRect),r=s?"block":"none";if("none"!==this.currentDisplayValue&&"none"===r&&(null===(t=(e=this.props).onPopoverHidden)||void 0===t||t.call(e)),n.style.display=r,this.currentDisplayValue=r,!s)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 Wn(s,this.containerRect,a,c):new Gn(s,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===(o=(i=this.props).onPopoverMoved)||void 0===o||o.call(i)),this.currentPosition=u}))}get popoverStyle(){return mo({"z-index":`${this.props.zIndex}`})}}Hn.template="o-spreadsheet-Popover",Hn.defaultProps={positioning:"BottomLeft",verticalOffset:0,onMouseWheel:()=>{},onPopoverMoved:()=>{},onPopoverHidden:()=>{},zIndex:le.Popover},Hn.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 $n{constructor(e,t,i,o){this.anchorRect=e,this.containerRect=t,this.propsMaxSize=i,this.spreadsheetOffset=o}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 i=this.getMaxHeight(e.height),o=this.getMaxWidth(e.width),n=Math.min(i,e.height),s=Math.min(o,e.width),r=this.shouldRenderAtBottom(e.height),a=this.shouldRenderAtRight(e.width);t=r?t:-t;return{"max-height":i+"px","max-width":o+"px",top:this.getTopCoordinate(n,r)-this.spreadsheetOffset.y-t+"px",left:this.getLeftCoordinate(s,a)-this.spreadsheetOffset.x+"px"}}getCurrentPosition(e){const t=this.shouldRenderAtBottom(e.height),i=this.shouldRenderAtRight(e.width);return t&&i?"BottomRight":t&&!i?"BottomLeft":!t&&i?"TopRight":"TopLeft"}}class Wn extends $n{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 Gn extends $n{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}}ho`
173
+ `;class $n extends t.Component{constructor(){super(...arguments),this.popoverRef=t.useRef("popover"),this.currentPosition=void 0,this.currentDisplayValue=void 0,this.spreadsheetRect=Vn()}setup(){this.containerRect=function(){const e=t.useState({x:0,y:0,width:0,height:0}),i=t.useComponent(),o=Vn();function n(){const t=i.env,n="getPopoverContainerRect"in t?t.getPopoverContainerRect():o;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,i,o;if(!this.containerRect)throw new Error("Popover container is not defined");const n=this.popoverRef.el,s=Bn(this.props.anchorRect,this.containerRect),r=s?"block":"none";if("none"!==this.currentDisplayValue&&"none"===r&&(null===(t=(e=this.props).onPopoverHidden)||void 0===t||t.call(e)),n.style.display=r,this.currentDisplayValue=r,!s)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 Gn(s,this.containerRect,a,c):new qn(s,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===(o=(i=this.props).onPopoverMoved)||void 0===o||o.call(i)),this.currentPosition=u}))}get popoverStyle(){return fo({"z-index":`${this.props.zIndex}`})}}$n.template="o-spreadsheet-Popover",$n.defaultProps={positioning:"BottomLeft",verticalOffset:0,onMouseWheel:()=>{},onPopoverMoved:()=>{},onPopoverHidden:()=>{},zIndex:le.Popover},$n.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 Wn{constructor(e,t,i,o){this.anchorRect=e,this.containerRect=t,this.propsMaxSize=i,this.spreadsheetOffset=o}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 i=this.getMaxHeight(e.height),o=this.getMaxWidth(e.width),n=Math.min(i,e.height),s=Math.min(o,e.width),r=this.shouldRenderAtBottom(e.height),a=this.shouldRenderAtRight(e.width);t=r?t:-t;return{"max-height":i+"px","max-width":o+"px",top:this.getTopCoordinate(n,r)-this.spreadsheetOffset.y-t+"px",left:this.getLeftCoordinate(s,a)-this.spreadsheetOffset.x+"px"}}getCurrentPosition(e){const t=this.shouldRenderAtBottom(e.height),i=this.shouldRenderAtRight(e.width);return t&&i?"BottomRight":t&&!i?"BottomLeft":!t&&i?"TopRight":"TopLeft"}}class Gn extends Wn{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 qn extends Wn{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}}uo`
174
174
  .o-menu {
175
175
  background-color: white;
176
176
  padding: ${8}px 0px;
@@ -220,7 +220,7 @@
220
220
  }
221
221
  }
222
222
  }
223
- `;class qn extends t.Component{constructor(){super(...arguments),this.subMenu=t.useState({isOpen:!1,position:null,scrollOffset:0,menuItems:[]}),this.menuRef=t.useRef("menu"),this.position=Vn(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);e[e.length-1].separator&&(t-=11);const i=16+t;return this.props.maxHeight?Math.min(i,this.props.maxHeight):i}get popoverProps(){const e=1===this.props.depth;return{anchorRect:{x:this.props.position.x-H*(this.props.depth-1),y:this.props.position.y,width:e?0:H,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,i,o;const n=await(null===(t=e.action)||void 0===t?void 0:t.call(e,this.env));this.close(),null===(o=(i=this.props).onMenuClicked)||void 0===o||o.call(i,{detail:n})}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=>Dn(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 e.name(this.env)}isRoot(e){return!e.action}isEnabled(e){return!!e.isEnabled(this.env)&&(!this.env.model.getters.isReadonly()||e.isReadonlyAllowed)}onScroll(e){this.subMenu.scrollOffset=e.target.scrollTop}openSubMenu(e,t){const i=this.subMenuVerticalPosition(t);this.subMenu.position={x:this.position.x+this.props.depth*H,y:i-(this.subMenu.scrollOffset||0)},this.subMenu.menuItems=e.children(this.env),this.subMenu.isOpen=!0,this.subMenu.parentMenu=e}isParentMenu(e,t){var i;return(null===(i=e.parentMenu)||void 0===i?void 0:i.id)===t.id}closeSubMenu(){this.subMenu.isOpen=!1,this.subMenu.parentMenu=void 0}onClickMenu(e,t){this.isEnabled(e)&&(this.isRoot(e)?this.openSubMenu(e,t):this.activateMenu(e))}onMouseOver(e,t){e.isEnabled(this.env)&&(this.isRoot(e)?this.openSubMenu(e,t):this.closeSubMenu())}}qn.template="o-spreadsheet-Menu",qn.components={Menu:qn,Popover:Hn},qn.defaultProps={depth:1},qn.props={position:Object,menuItems:Array,depth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},onClose:Function,onMenuClicked:{type:Function,optional:!0},menuId:{type:String,optional:!0}};ho`
223
+ `;class Zn extends t.Component{constructor(){super(...arguments),this.subMenu=t.useState({isOpen:!1,position:null,scrollOffset:0,menuItems:[]}),this.menuRef=t.useRef("menu"),this.position=zn(this.menuRef)}setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0}),t.useExternalListener(window,"contextmenu",this.onExternalClick,{capture:!0}),t.onWillUpdateProps((e=>{e.menuItems!==this.props.menuItems&&this.closeSubMenu()}))}get visibleMenuItems(){return this.props.menuItems.filter((e=>e.isVisible(this.env)))}get subMenuPosition(){const e=Object.assign({},this.subMenu.position);return e.y-=this.subMenu.scrollOffset||0,e}get menuHeight(){const e=this.visibleMenuItems;let t=this.getMenuItemsHeight(e);e[e.length-1].separator&&(t-=11);const i=16+t;return this.props.maxHeight?Math.min(i,this.props.maxHeight):i}get popoverProps(){const e=1===this.props.depth;return{anchorRect:{x:this.props.position.x-H*(this.props.depth-1),y:this.props.position.y,width:e?0:H,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,i,o;const n=await(null===(t=e.action)||void 0===t?void 0:t.call(e,this.env));this.close(),null===(o=(i=this.props).onMenuClicked)||void 0===o||o.call(i,{detail:n})}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=>kn(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 e.name(this.env)}isRoot(e){return!e.action}isEnabled(e){return!!e.isEnabled(this.env)&&(!this.env.model.getters.isReadonly()||e.isReadonlyAllowed)}onScroll(e){this.subMenu.scrollOffset=e.target.scrollTop}openSubMenu(e,t){const i=this.subMenuVerticalPosition(t);this.subMenu.position={x:this.position.x+this.props.depth*H,y:i-(this.subMenu.scrollOffset||0)},this.subMenu.menuItems=e.children(this.env),this.subMenu.isOpen=!0,this.subMenu.parentMenu=e}isParentMenu(e,t){var i;return(null===(i=e.parentMenu)||void 0===i?void 0:i.id)===t.id}closeSubMenu(){this.subMenu.isOpen=!1,this.subMenu.parentMenu=void 0}onClickMenu(e,t){this.isEnabled(e)&&(this.isRoot(e)?this.openSubMenu(e,t):this.activateMenu(e))}onMouseOver(e,t){e.isEnabled(this.env)&&(this.isRoot(e)?this.openSubMenu(e,t):this.closeSubMenu())}}Zn.template="o-spreadsheet-Menu",Zn.components={Menu:Zn,Popover:$n},Zn.defaultProps={depth:1},Zn.props={position:Object,menuItems:Array,depth:{type:Number,optional:!0},maxHeight:{type:Number,optional:!0},onClose:Function,onMenuClicked:{type:Function,optional:!0},menuId:{type:String,optional:!0}};uo`
224
224
  .o-link-tool {
225
225
  font-size: 13px;
226
226
  background-color: white;
@@ -267,7 +267,7 @@
267
267
  cursor: pointer;
268
268
  color: #000;
269
269
  }
270
- `;class Zn extends t.Component{get cell(){const{col:e,row:t}=this.props.cellPosition,i=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getEvaluatedCell({sheetId:i,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. ${Bt(e,t)} is not a link.`)}getUrlRepresentation(e){return Ro(e,this.env.model.getters)}openLink(){To(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:i}=this.props.cellPosition,o=this.env.model.getters.getCellComputedStyle({sheetId:e,col:t,row:i}),n=(null==o?void 0:o.textColor)===x||null==o?void 0:o.textColor;this.env.model.dispatch("UPDATE_CELL",{col:t,row:i,sheetId:e,content:this.link.label,style:{...o,textColor:n,underline:void 0}})}}Zn.components={Menu:qn},Zn.template="o-spreadsheet-LinkDisplay";const jn={onHover:(e,t)=>{const i=t.getEvaluatedCell(e);return!t.isDashboard()&&i.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:Zn,props:{cellPosition:e},cellCorner:"BottomLeft"}:{isOpen:!1}}};function Xn(e){return e.map(Kn).sort(((e,t)=>e.sequence-t.sequence))}Zn.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const Yn=new Di;function Kn(e){const t=e.name,i=e.children;return{id:e.id||Yn.uuidv4(),name:"function"==typeof t?t:()=>t,isVisible:e.isVisible?e.isVisible:()=>!0,isEnabled:e.isEnabled?e.isEnabled:()=>!0,action:e.action,children:i?e=>i.map((t=>"function"==typeof t?t(e):t)).flat().map(Kn):()=>[],isReadonlyAllowed:e.isReadonlyAllowed||!1,separator:e.separator||!1,icon:e.icon,description:e.description||"",textColor:e.textColor,sequence:e.sequence||0}}class Qn extends Co{add(e,t){return void 0===t.id&&(t.id=e),this.content[e]=t,this}addChild(e,t,i){"function"!=typeof i&&void 0===i.id&&(i.id=e);const o=t.splice(0,1)[0];let n=this.content[o];if(!n)throw new Error(`Path ${o+":"+t.join(":")} not found`);for(let e of t){const i=n.children;if(!i||"function"==typeof i)throw new Error(`${e} is either not a node or it's dynamically computed`);if(n=i.find((t=>t.id===e)),!n)throw new Error(`Path ${o+":"+t.join(":")} not found`)}return n.children||(n.children=[]),n.children.push(i),this}getMenuItems(){return Xn(this.getAll())}}const Jn=new Qn;Jn.add("sheet",{name:s("Link sheet"),sequence:10}).addChild("sheet_list",["sheet"],(e=>e.model.getters.getSheetIds().map((t=>e.model.getters.getSheet(t))).map((e=>({id:e.id,name:e.name,action:()=>je(e.name,Qe(e.id))})))));ho`
270
+ `;class jn extends t.Component{get cell(){const{col:e,row:t}=this.props.cellPosition,i=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getEvaluatedCell({sheetId:i,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. ${Ht(e,t)} is not a link.`)}getUrlRepresentation(e){return To(e,this.env.model.getters)}openLink(){Ao(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:i}=this.props.cellPosition,o=this.env.model.getters.getCellComputedStyle({sheetId:e,col:t,row:i}),n=(null==o?void 0:o.textColor)===x||null==o?void 0:o.textColor;this.env.model.dispatch("UPDATE_CELL",{col:t,row:i,sheetId:e,content:this.link.label,style:{...o,textColor:n,underline:void 0}})}}jn.components={Menu:Zn},jn.template="o-spreadsheet-LinkDisplay";const Xn={onHover:(e,t)=>{const i=t.getEvaluatedCell(e);return!t.isDashboard()&&i.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:jn,props:{cellPosition:e},cellCorner:"BottomLeft"}:{isOpen:!1}}};function Yn(e){return e.map(Qn).sort(((e,t)=>e.sequence-t.sequence))}jn.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const Kn=new ki;function Qn(e){const t=e.name,i=e.children;return{id:e.id||Kn.uuidv4(),name:"function"==typeof t?t:()=>t,isVisible:e.isVisible?e.isVisible:()=>!0,isEnabled:e.isEnabled?e.isEnabled:()=>!0,action:e.action,children:i?e=>i.map((t=>"function"==typeof t?t(e):t)).flat().map(Qn):()=>[],isReadonlyAllowed:e.isReadonlyAllowed||!1,separator:e.separator||!1,icon:e.icon,description:e.description||"",textColor:e.textColor,sequence:e.sequence||0}}class Jn extends Eo{add(e,t){return void 0===t.id&&(t.id=e),this.content[e]=t,this}addChild(e,t,i){"function"!=typeof i&&void 0===i.id&&(i.id=e);const o=t.splice(0,1)[0];let n=this.content[o];if(!n)throw new Error(`Path ${o+":"+t.join(":")} not found`);for(let e of t){const i=n.children;if(!i||"function"==typeof i)throw new Error(`${e} is either not a node or it's dynamically computed`);if(n=i.find((t=>t.id===e)),!n)throw new Error(`Path ${o+":"+t.join(":")} not found`)}return n.children||(n.children=[]),n.children.push(i),this}getMenuItems(){return Yn(this.getAll())}}const es=new Jn;es.add("sheet",{name:s("Link sheet"),sequence:10}).addChild("sheet_list",["sheet"],(e=>e.model.getters.getSheetIds().map((t=>e.model.getters.getSheet(t))).map((e=>({id:e.id,name:e.name,action:()=>Xe(e.name,Je(e.id))})))));uo`
271
271
  .o-link-editor {
272
272
  font-size: 13px;
273
273
  background-color: white;
@@ -340,13 +340,13 @@
340
340
  }
341
341
  }
342
342
  }
343
- `;class es extends t.Component{constructor(){super(...arguments),this.menuItems=Jn.getMenuItems(),this.link=t.useState(this.defaultState),this.menu=t.useState({isOpen:!1}),this.linkEditorRef=t.useRef("linkEditor"),this.position=Vn(this.linkEditorRef),this.urlInput=t.useRef("urlInput")}setup(){t.onMounted((()=>{var e;return null===(e=this.urlInput.el)||void 0===e?void 0:e.focus()}))}get defaultState(){const{col:e,row:t}=this.props.cellPosition,i=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getEvaluatedCell({sheetId:i,col:e,row:t});return o.link?{url:o.link.url,label:o.formattedValue,isUrlEditable:o.link.isUrlEditable}:{label:o.formattedValue,url:"",isUrlEditable:!0}}get menuPosition(){return{x:this.position.x+320-12-2,y:this.position.y+100}}onSpecialLink(e){const{detail:t}=e,i=Ao(t);i&&(this.link.url=i.url,this.link.label=i.label,this.link.isUrlEditable=i.isUrlEditable)}getUrlRepresentation(e){return Ro(e,this.env.model.getters)}openMenu(){this.menu.isOpen=!0}removeLink(){this.link.url="",this.link.isUrlEditable=!0}save(){var e,t;const{col:i,row:o}=this.props.cellPosition,n=this.link.label||this.link.url;this.env.model.dispatch("UPDATE_CELL",{col:i,row:o,sheetId:this.env.model.getters.getActiveSheetId(),content:je(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()}}}es.template="o-spreadsheet-LinkEditor",es.components={Menu:qn};const ts={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:es,cellCorner:"BottomLeft"})};es.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const is=new Co;function os(e){return 8===(e=bt(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}is.add("ErrorToolTip",Mn).add("LinkCell",jn).add("LinkEditor",ts).add("FilterMenu",Fn);class ns{constructor(e,t,i){this.title=e.title,this.sheetId=t,this.getters=i}static validateChartDefinition(e,t){throw new Error("This method should be implemented by sub class")}static transformDefinition(e,t){throw new Error("This method should be implemented by sub class")}static getDefinitionFromContextCreation(e){throw new Error("This method should be implemented by sub class")}}function ss(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?Hi(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?Vi(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):{...e}}function rs(e,t,i,o){let n=!1;const s=[];for(let o in i){let r=i[o];if(r.labelCell){const e=cs(r.labelCell,t);r.labelCell!==e&&(n=!0,r={...r,labelCell:e})}const a=cs(r.dataRange,t);void 0===a||e.getRangeString(a,a.sheetId)===Y?(n=!0,r=void 0):a!==r.dataRange&&(n=!0,r={...r,dataRange:a}),s[o]=r}let r=o;const a=cs(r,t);a!==r&&(n=!0,r=a);return{isStale:n,dataSets:s.filter(et),labelRange:r}}function as(e,t,i){return i.map((i=>({dataRange:Oi(e,t,i.dataRange),labelCell:i.labelCell?Oi(e,t,i.labelCell):void 0})))}function ls(e,t,i){return i?Oi(e,t,i):void 0}function cs(e,t){if(!e)return;const i=t(e);switch(i.changeType){case"NONE":return e;case"REMOVE":return;default:return i.range}}function hs(e,t,i,o){const n=[];for(const s of t){const t=e.getRangeFromSheetXC(i,s),{unboundedZone:r,sheetId:a,invalidSheetName:l}=t;if(!l)if(r.left!==r.right&&r.top!==r.bottom){if(void 0===r.right)continue;for(let t=r.left;t<=r.right;t++){const i={...r,left:t,right:t};n.push(ds(e,a,i,o?{top:i.top,bottom:i.top,left:i.left,right:i.left}:void 0))}}else r.left===r.right&&r.top===r.bottom?o||n.push(ds(e,a,r,void 0)):n.push(ds(e,a,r,o?{top:r.top,bottom:r.top,left:r.left,right:r.left}:void 0))}return n}function ds(e,t,i,o){if(i.left!==i.right&&i.top!==i.bottom)throw new Error(`Zone should be a single column or row: ${Ui(i)}`);if(o){const n=Ui(i),s=Ui(o);return{labelCell:e.getRangeFromSheetXC(t,s),dataRange:e.getRangeFromSheetXC(t,n)}}return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,Ui(i))}}function us(e,t){var i;const o=null===(i=t.labelCell)||void 0===i?void 0:i.zone;let n=t.dataRange.zone;if(o){const{numberOfRows:e,numberOfCols:t}=Ki(n);1===e?n={...n,left:n.left+1}:1===t&&(n={...n,top:n.top+1})}const s=t.dataRange.clone({zone:n});return{label:t.labelCell?e.getRangeString(t.labelCell,"forceSheetReference"):void 0,range:e.getRangeString(s,"forceSheetReference")}}function gs(e,t){let i;if(e.labelRange){const o=ss(ki(e.labelRange),t);i=o?Ui(o):void 0}const o=e.dataSets.map(ki).map((e=>ss(e,t))).filter(et).map(Ui);return{...e,labelRange:i,dataSets:o}}const ps=["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 ms{constructor(){this.graphColorIndex=0}next(){return ps[this.graphColorIndex++%ps.length]}}function fs(e){return e&&wt(e)<.3?"#FFFFFF":"#000000"}function vs(e){if(e.dataSets){const t=void 0!==e.dataSets.find((e=>!_t.test(e)));if(t)return 32;if(e.dataSets.map(ki).some((e=>e.top!==e.bottom&&no(e))))return 32}return 0}function bs(e){if(e.labelRange){if(!_t.test(e.labelRange||""))return 33}return 0}function Ss(e,t,i){if(e){if("text"===i||(null==t?void 0:t.type)!==tn.number||e.type!==tn.number)return e.formattedValue;{let o=t.value-e.value;if("percentage"===i&&0!==o&&(o=o/e.value*100),"percentage"!==i&&e.format)return hi(o,e.format);const n=Math.abs(parseFloat(o.toFixed(2))).toLocaleString();return"percentage"===i?n+"%":n}}return""}function Cs(e,t,i,o,n){if("text"===t||(null==e?void 0:e.type)!==tn.number||(null==i?void 0:i.type)!==tn.number)return;const s=i.value-e.value;return s>0?o:s<0?n:void 0}function Es(e,t,i){if("text"===i||(null==e?void 0:e.type)!==tn.number||(null==t?void 0:t.type)!==tn.number)return"neutral";const o=t.value-e.value;return o>0?"up":o<0?"down":"neutral"}const ws={Errors:{25:s("The range is invalid"),51:s("The argument is missing. Please provide a value"),52:s("The second argument is missing. Please provide a value"),53:s("The minpoint must be a number"),54:s("The midpoint must be a number"),55:s("The maxpoint must be a number"),56:s("The first value must be a number"),57:s("The second value must be a number"),47:s("Minimum must be smaller then Maximum"),50:s("Minimum must be smaller then Midpoint"),49:s("Midpoint must be smaller then Maximum"),48:s("Lower inflection point must be smaller than upper inflection point"),58:s("Invalid Minpoint formula"),60:s("Invalid Maxpoint formula"),59:s("Invalid Midpoint formula"),61:s("Invalid upper inflection point formula"),62:s("Invalid lower inflection point formula"),24:s("A range needs to be defined"),Unexpected:s("The rule is invalid for an unknown reason")},ColorScale:s("Color scale"),IconSet:s("Icon set")},ys={IsEmpty:s("Is empty"),IsNotEmpty:s("Is not empty"),ContainsText:s("Contains"),NotContains:s("Does not contain"),BeginsWith:s("Starts with"),EndsWith:s("Ends with"),Equal:s("Is equal to"),NotEqual:s("Is not equal to"),GreaterThan:s("Is greater than"),GreaterThanOrEqual:s("Is greater than or equal to"),LessThan:s("Is less than"),LessThanOrEqual:s("Is less than or equal to"),Between:s("Is between"),NotBetween:s("Is not between")},xs={Series:s("Series"),Errors:{Unexpected:s("The chart definition is invalid for an unknown reason"),32:s("The dataset is invalid"),33:s("Labels are invalid"),34:s("The key value is invalid"),35:s("The baseline value is invalid"),36:s("The data range is invalid"),37:s("A minimum range limit value is needed"),38:s("The minimum range limit value must be a number"),39:s("A maximum range limit value is needed"),40:s("The maximum range limit value must be a number"),41:s("Minimum range limit must be smaller than maximum range limit"),42:s("The lower inflection point value must be a number"),43:s("The upper inflection point value must be a number")}},Is={Automatic:s("Automatic"),Number:s("Number"),Percent:s("Percent"),Currency:s("Currency"),CurrencyRounded:s("Currency rounded"),Date:s("Date"),Time:s("Time"),DateTime:s("Date time"),Duration:s("Duration"),CustomCurrency:s("Custom currency")},Rs={Custom:s("Custom")},Ts=s("Merged cells are preventing this operation. Unmerge those cells and try again.");function As(e,t){if(t.dataRange){const i=t.labelCell?[Ui(t.labelCell.zone)]:[],o=Xi([Ui(t.dataRange.zone)],i)[0];if(void 0===o)return[];const n=e.getRangeFromSheetXC(t.dataRange.sheetId,o);return e.getRangeValues(n).map((e=>""===e?void 0:e))}return[]}function Ms(e,t){const i=ze(0,Math.max(e.length,...t.map((e=>{var t;return(null===(t=e.data)||void 0===t?void 0:t.length)||0})))).filter((i=>{const o=e[i],n=t.map((e=>{var t;return null===(t=e.data)||void 0===t?void 0:t[i]}));return o||n.some((e=>0===e||Boolean(e)))}));return{labels:i.map((t=>e[t]||"")),dataSetsValues:t.map((e=>({...e,data:i.map((t=>e.data[t]))})))}}function Os(e,t){const i=new Set(e),o={};i.forEach((e=>{o[e]=new Array(t.length).fill(0)}));for(const i of ze(0,e.length)){const s=e[i];for(const e of ze(0,t.length))o[s][e]+="number"==typeof(n=t[e].data[i])?n:0}var n;return{labels:Object.keys(o),dataSetsValues:t.map(((e,t)=>({...e,data:Object.values(o).map((e=>e[t]))})))}}function Ns(e){return e?e.length>Q?e.substring(0,Q)+"…":e:""}function _s(e,t,i,o){return{type:e.type,options:{responsive:!0,maintainAspectRatio:!1,layout:{padding:{left:20,right:20,top:e.title?10:25,bottom:10}},elements:{line:{fill:!1},point:{hitRadius:15}},animation:{duration:0},hover:{animationDuration:10},responsiveAnimationDuration:0,title:{display:!!e.title,fontSize:22,fontStyle:"normal",text:n(e.title),fontColor:i},legend:{onClick:void 0},tooltips:{callbacks:{label:function(e,t){var i,n,s,r,a;let l=null===(n=null===(i=t.datasets)||void 0===i?void 0:i[e.datasetIndex||0])||void 0===n?void 0:n.label;const c=""!==e.yLabel?e.yLabel:null===(a=null===(r=null===(s=t.datasets)||void 0===s?void 0:s[e.datasetIndex||0])||void 0===r?void 0:r.data)||void 0===a?void 0:a[e.index||0],h=o&&"number"==typeof c?hi(c,o):(null==c?void 0:c.toLocaleString())||"";return l?`${l}: ${h}`:h}}}},data:{labels:t.map(Ns),datasets:[]}}}function Fs(e,t,i){let o={values:[],formattedValues:[]};if(i)i.invalidXc||i.invalidSheetName||(o={formattedValues:e.getRangeFormattedValues(i),values:e.getRangeValues(i).map((e=>String(e)))});else if(1===t.length)for(let i=0;i<As(e,t[0]).length;i++)o.formattedValues.push(""),o.values.push("");else if(t[0]){o={formattedValues:ze(0,As(e,t[0]).length).map((e=>e.toString())),values:o.formattedValues}}return o}function Ds(e,t){for(const i of t){const t=e.getRangeFormats(i.dataRange).find((e=>void 0!==e&&!fi(e)));if(t)return t}}function ks(e,t){const i=[];for(const[o,n]of Object.entries(t)){let t;if(n.labelCell){const i=n.labelCell,s=i?e.getEvaluatedCell({sheetId:i.sheetId,col:i.zone.left,row:i.zone.top}):void 0;t=s&&i?Ns(s.formattedValue):t=`${xs.Series} ${parseInt(o)+1}`}else t=t=`${xs.Series} ${parseInt(o)+1}`;let s=n.dataRange?As(e,n):[];i.push({data:s,label:t})}return i}function Ls(e){return 0===e?"origin":e-1}class Ps extends ns{constructor(e,t,i){super(e,t,i),this.type="bar",this.dataSets=hs(i,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ni(i,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated}static transformDefinition(e,t){return gs(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,vs,bs)}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=as(this.sheetId,e,this.dataSets),i=ls(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,i,e);return new Ps(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Ps(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,i){return{type:"bar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated}}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>us(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:os(this.background||w),fontColor:os(fs(this.background)),dataSets:e}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:o}=rs(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const n=this.getDefinitionWithSpecificDataSets(t,i);return new Ps(n,this.sheetId,this.getters)}}function Us(e){return e.dataRange&&!_t.test(e.dataRange)?36:0}function Vs(e,t){return t((t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):0),(t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):0))}function zs(e){return e.sectionRule&&Number(e.sectionRule.rangeMin)>=Number(e.sectionRule.rangeMax)?41:0}function Bs(e,t){if(""===e)switch(t){case"rangeMin":return 37;case"rangeMax":return 39}return 0}function Hs(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 $s extends ns{constructor(e,t,i){super(e,t,i),this.type="gauge",this.dataRange=Ni(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,Us,e.chainValidations(Vs(Bs,e.batchValidations),Vs(Hs,e.batchValidations),zs),e.chainValidations((i=Hs,(0,e.batchValidations)((e=>e.sectionRule?i(e.sectionRule.lowerInflectionPoint.value,"lowerInflectionPointValue"):0),(e=>e.sectionRule?i(e.sectionRule.upperInflectionPoint.value,"upperInflectionPointValue"):0)))));var i}static transformDefinition(e,t){let i;return e.dataRange&&(i=ss(ki(e.dataRange),t)),{...e,dataRange:i?Ui(i):void 0}}static getDefinitionFromContextCreation(e){return{background:e.background,title:e.title||"",type:"gauge",dataRange:e.range?e.range[0]:void 0,sectionRule:{colors:{lowerColor:"#cc0000",middleColor:"#f1c232",upperColor:"#6aa84f"},rangeMin:"0",rangeMax:"100",lowerInflectionPoint:{type:"percentage",value:"15"},upperInflectionPoint:{type:"percentage",value:"40"}}}}copyForSheetId(e){const t=ls(this.sheetId,e,this.dataRange),i=this.getDefinitionWithSpecificRanges(t,e);return new $s(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.dataRange,e);return new $s(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.dataRange)}getDefinitionWithSpecificRanges(e,t){return{background:this.background,sectionRule:this.sectionRule,title:this.title,type:"gauge",dataRange:e?this.getters.getRangeString(e,t||this.sheetId):void 0}}getDefinitionForExcel(){}getContextCreation(){return{background:this.background,title:this.title,range:this.dataRange?[this.getters.getRangeString(this.dataRange,this.sheetId)]:void 0}}updateRanges(e){const t=cs(this.dataRange,e);if(this.dataRange===t)return this;const i=this.getDefinitionWithSpecificRanges(t);return new $s(i,this.sheetId,this.getters)}}const Ws={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},Gs={inSeconds:function(e){return Math.floor(e/Ws.second)},inMinutes:function(e){return Math.floor(e/Ws.minute)},inHours:function(e){return Math.floor(e/Ws.hour)},inDays:function(e){return Math.floor(e/Ws.day)},inMonths:function(e){return Math.floor(e/Ws.month)},inYears:function(e){return Math.floor(e/Ws.year)}},qs=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function Zs(e,t){const i=function(e){const t=(e=(e=e.replace(/y/g,"Y")).replace(/d/g,"D")).indexOf("h");e=t>=0?e.slice(0,t).replace(/m/g,"M")+e.slice(t):e.replace(/m/g,"M");e.includes("a")||(e=e.replace(/h/g,"H"));return e}(t),o=function(e,t){const i=e.map((e=>{var t;return null===(t=Se(e))||void 0===t?void 0:t.jsDate}));if(i.some((e=>void 0===e))||e.length<2)return;const o=i.map((e=>e.getTime())),n=Math.max(...o)-Math.min(...o),s=function(e){if(e.includes("s"))return"second";if(e.includes("m"))return"minute";if(e.includes("h")||e.includes("H"))return"hour";if(e.includes("D"))return"day";if(e.includes("M"))return"month";return"year"}(t);if(Ws.second>=Ws[s]&&Gs.inSeconds(n)<180)return"second";if(Ws.minute>=Ws[s]&&Gs.inMinutes(n)<180)return"minute";if(Ws.hour>=Ws[s]&&Gs.inHours(n)<96)return"hour";if(Ws.day>=Ws[s]&&Gs.inDays(n)<90)return"day";if(Ws.month>=Ws[s]&&Gs.inMonths(n)<36)return"month";return"year"}(e,i),n={};return o&&(n[o]=i),{parser:i,displayFormats:n,unit:o}}class js extends ns{constructor(e,t,i){super(e,t,i),this.type="line",this.dataSets=hs(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ni(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,vs,bs)}static transformDefinition(e,t){return gs(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,i){return{type:"line",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,stacked:this.stacked,aggregated:this.aggregated}}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:o}=rs(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const n=this.getDefinitionWithSpecificDataSets(t,i);return new js(n,this.sheetId,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>us(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:os(this.background||w),fontColor:os(fs(this.background)),dataSets:e}}copyForSheetId(e){const t=as(this.sheetId,e,this.dataSets),i=ls(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,i,e);return new js(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new js(t,e,this.getters)}}function Xs(e,t){return Ks(e,t)||Qs(e,t)}function Ys(e,t){return function(e,t){return!e.labelsAsText&&Ks(e.labelRange,t)}(e,t)?"time":function(e,t){return!e.labelsAsText&&Qs(e.labelRange,t)}(e,t)?"linear":"category"}function Ks(e,t){if(!e||!Qs(e,t))return!1;const i=t.getEvaluatedCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}).format;return Boolean(i&&qs.test(i))}function Qs(e,t){if(!e)return!1;const i=t.getRangeValues(e);return!i.some((e=>isNaN(Number(e))&&e))&&!i.every((e=>!e))}class Js extends ns{constructor(e,t,i){super(e,t,i),this.type="pie",this.dataSets=hs(i,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ni(i,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated}static transformDefinition(e,t){return gs(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,vs,bs)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:!1,legendPosition:"top",title:e.title||"",type:"pie",labelRange:e.auxiliaryRange||void 0,aggregated:!1}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinitionWithSpecificDataSets(e,t,i){return{type:"pie",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title,aggregated:this.aggregated}}copyForSheetId(e){const t=as(this.sheetId,e,this.dataSets),i=ls(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,i,e);return new Js(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Js(t,e,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>us(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:os(this.background||w),fontColor:os(fs(this.background)),verticalAxisPosition:"left",dataSets:e}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:o}=rs(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const n=this.getDefinitionWithSpecificDataSets(t,i);return new Js(n,this.sheetId,this.getters)}}function er(e,t){const i=[],o=Math.max(...t.map((e=>e.data.length)));for(let t=0;t<=o;t++)i.push(e.next());return i}function tr(e){return e.keyValue&&!_t.test(e.keyValue)?34:0}function ir(e){return e.baseline&&!_t.test(e.baseline)?35:0}class or extends ns{constructor(e,t,i){super(e,t,i),this.type="scorecard",this.keyValue=Ni(i,t,e.keyValue),this.baseline=Ni(i,t,e.baseline),this.baselineMode=e.baselineMode,this.baselineDescr=e.baselineDescr,this.background=e.background,this.baselineColorUp=e.baselineColorUp,this.baselineColorDown=e.baselineColorDown}static validateChartDefinition(e,t){return e.checkValidations(t,tr,ir)}static getDefinitionFromContextCreation(e){return{background:e.background,type:"scorecard",keyValue:e.range?e.range[0]:void 0,title:e.title||"",baselineMode:ee,baselineColorUp:te,baselineColorDown:ie,baseline:e.auxiliaryRange||""}}static transformDefinition(e,t){let i,o;return e.baseline&&(i=ss(ki(e.baseline),t)),e.keyValue&&(o=ss(ki(e.keyValue),t)),{...e,baseline:i?Ui(i):void 0,keyValue:o?Ui(o):void 0}}copyForSheetId(e){const t=ls(this.sheetId,e,this.baseline),i=ls(this.sheetId,e,this.keyValue),o=this.getDefinitionWithSpecificRanges(t,i,e);return new or(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,e);return new or(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue)}getContextCreation(){return{background:this.background,title:this.title,range:this.keyValue?[this.getters.getRangeString(this.keyValue,this.sheetId)]:void 0,auxiliaryRange:this.baseline?this.getters.getRangeString(this.baseline,this.sheetId):void 0}}getDefinitionWithSpecificRanges(e,t,i){return{baselineColorDown:this.baselineColorDown,baselineColorUp:this.baselineColorUp,baselineMode:this.baselineMode,title:this.title,type:"scorecard",background:this.background,baseline:e?this.getters.getRangeString(e,i||this.sheetId):void 0,baselineDescr:this.baselineDescr,keyValue:t?this.getters.getRangeString(t,i||this.sheetId):void 0}}getDefinitionForExcel(){}updateRanges(e){const t=cs(this.baseline,e),i=cs(this.keyValue,e);if(this.baseline===t&&this.keyValue===i)return this;const o=this.getDefinitionWithSpecificRanges(t,i);return new or(o,this.sheetId,this.getters)}}const nr=new Co;nr.add("bar",{match:e=>"bar"===e,createChart:(e,t,i)=>new Ps(e,t,i),getChartRuntime:function(e,t){let i=Fs(t,e.dataSets,e.labelRange).formattedValues,o=ks(t,e.dataSets);({labels:i,dataSetsValues:o}=Ms(i,o)),e.aggregated&&({labels:i,dataSetsValues:o}=Os(i,o));const n=function(e,t,i){var o;const n=fs(e.background),s=_s(e,t,n,i),r={labels:{fontColor:n}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,s.options.legend={...null===(o=s.options)||void 0===o?void 0:o.legend,...r},s.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},s.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:n}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:n,beginAtZero:!0,callback:e=>i?hi(e,i):(null==e?void 0:e.toLocaleString())||e}}]},e.stacked&&(s.options.scales.xAxes[0].stacked=!0,s.options.scales.yAxes[0].stacked=!0),s}(e,i,Ds(t,e.dataSets)),s=new ms;for(let{label:e,data:t}of o){const i=s.next(),o={label:e,data:t,borderColor:i,backgroundColor:i};n.data.datasets.push(o)}return{chartJsConfig:n,background:e.background||w}},validateChartDefinition:(e,t)=>Ps.validateChartDefinition(e,t),transformDefinition:(e,t)=>Ps.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Ps.getDefinitionFromContextCreation(e),name:s("Bar"),sequence:10}),nr.add("line",{match:e=>"line"===e,createChart:(e,t,i)=>new js(e,t,i),getChartRuntime:function(e,t){const i=Ys(e,t),o=Fs(t,e.dataSets,e.labelRange);let n="linear"===i?o.values:o.formattedValues,s=ks(t,e.dataSets);({labels:n,dataSetsValues:s}=Ms(n,s)),"time"===i&&({labels:n,dataSetsValues:s}=function(e,t){if(0===e.length||e.every((e=>!e)))return{labels:e,dataSetsValues:t};const i=[...e],o=Ne(t);for(let e=0;e<i.length;e++)if(!i[e]){i[e]=st(i,e);for(let t of o)t.data[e]=void 0}return{labels:i,dataSetsValues:o}}(n,s)),e.aggregated&&({labels:n,dataSetsValues:s}=Os(n,s));const r=Ds(t,e.dataSets),a=function(e,t,i){var o;const n=fs(e.background),s=_s(e,t,n,i),r={labels:{fontColor:n,generateLabels(e){const{data:t}=e,i=window.Chart.defaults.global.legend.labels.generateLabels(e);for(const[e,o]of i.entries())o.fillStyle=t.datasets[e].borderColor;return i}}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,s.options.legend={...null===(o=s.options)||void 0===o?void 0:o.legend,...r},s.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},s.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:n}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:n,beginAtZero:!0,callback:e=>i?hi(e,i):(null==e?void 0:e.toLocaleString())||e}}]},e.stacked&&(s.options.scales.yAxes[0].stacked=!0),s}(e,n,r),l=function(e,t){if(t)return e.getEvaluatedCell({sheetId:t.sheetId,col:t.zone.left,row:t.zone.top}).format}(t,e.labelRange);"time"===i?(a.options.scales.xAxes[0].type="time",a.options.scales.xAxes[0].time=Zs(n,l),a.options.scales.xAxes[0].ticks.maxTicksLimit=15):"linear"===i&&(a.options.scales.xAxes[0].type="linear",a.options.scales.xAxes[0].ticks.callback=e=>hi(e,l),a.options.tooltips.callbacks.title=e=>{var t;return hi((null===(t=e[0])||void 0===t?void 0:t.xLabel)||"",l)});const c=new ms;for(let[t,{label:o,data:r}]of s.entries()){["linear","time"].includes(i)&&(r=r.map(((e,t)=>({x:n[t]||void 0,y:e}))));const s=c.next();let l=xt(s);e.stacked&&(l.a=oe);const h={label:o,data:r,lineTension:0,borderColor:s,backgroundColor:yt(l),pointBackgroundColor:s,fill:!!e.stacked&&Ls(t)};a.data.datasets.push(h)}return{chartJsConfig:a,background:e.background||w}},validateChartDefinition:(e,t)=>js.validateChartDefinition(e,t),transformDefinition:(e,t)=>js.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>js.getDefinitionFromContextCreation(e),name:s("Line"),sequence:20}),nr.add("pie",{match:e=>"pie"===e,createChart:(e,t,i)=>new Js(e,t,i),getChartRuntime:function(e,t){let i=Fs(t,e.dataSets,e.labelRange).formattedValues,o=ks(t,e.dataSets);({labels:i,dataSetsValues:o}=Ms(i,o)),e.aggregated&&({labels:i,dataSetsValues:o}=Os(i,o));const n=function(e,t,i){var o;const n=fs(e.background),s=_s(e,t,n,i),r={labels:{fontColor:n}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,s.options.legend={...null===(o=s.options)||void 0===o?void 0:o.legend,...r},s.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},s.options.tooltips.callbacks.title=function(e,t){return t.datasets[e[0].datasetIndex].label},s}(e,i,Ds(t,e.dataSets)),s=new ms;for(let{label:e,data:t}of o){const i={label:e,data:t,borderColor:"#FFFFFF",backgroundColor:er(s,o)};n.data.datasets.push(i)}return{chartJsConfig:n,background:e.background||w}},validateChartDefinition:(e,t)=>Js.validateChartDefinition(e,t),transformDefinition:(e,t)=>Js.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Js.getDefinitionFromContextCreation(e),name:s("Pie"),sequence:30}),nr.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,i)=>new or(e,t,i),getChartRuntime:function(e,t){let i,o,s="",r="";if(e.keyValue){const o={sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top};i=t.getEvaluatedCell(o),s=String(i.value),r=i.formattedValue}const a=e.baseline;if(a){const i={sheetId:e.baseline.sheetId,col:e.baseline.zone.left,row:e.baseline.zone.top};o=t.getEvaluatedCell(i)}const l=t.getBackgroundOfSingleCellChart(e.background,e.keyValue);return{title:n(e.title),keyValue:r||s,baselineDisplay:Ss(o,i,e.baselineMode),baselineArrow:Es(o,i,e.baselineMode),baselineColor:Cs(o,e.baselineMode,i,e.baselineColorUp,e.baselineColorDown),baselineDescr:e.baselineDescr?n(e.baselineDescr):"",fontColor:fs(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)=>or.validateChartDefinition(e,t),transformDefinition:(e,t)=>or.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>or.getDefinitionFromContextCreation(e),name:s("Scorecard"),sequence:40}),nr.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,i)=>new $s(e,t,i),getChartRuntime:function(e,t){const i=function(e){const t=_s(e,[],fs(e.background));return t.options.hover=void 0,t.options.events=[],t.options.layout={padding:{left:30,right:30,top:e.title?10:25,bottom:25}},t.options.needle={radiusPercentage:2,widthPercentage:3.2,lengthPercentage:80,color:"#000000"},t.options.valueLabel={display:!1,formatter:null,color:"#FFFFFF",backgroundColor:"#000000",fontSize:30,borderRadius:5,padding:{top:5,right:5,bottom:5,left:5},bottomMarginPercentage:5},t}(e),o=e.sectionRule.colors,n=e.sectionRule.lowerInflectionPoint,s=e.sectionRule.upperInflectionPoint,r=Number(n.value),a=Number(s.value),l=Number(e.sectionRule.rangeMin),c=Number(e.sectionRule.rangeMax),h=c-l,d=[];if(""!==n.value){const e="number"===n.type?r:l+h*r/100;d.push({value:De(e,l,c),color:o.lowerColor})}if(""!==s.value){const e="number"===s.type?a:l+h*a/100;d.push({value:De(e,l,c),color:o.middleColor})}const u=[],g=[];d.sort(((e,t)=>e.value-t.value)).map((e=>{u.push(e.value),g.push(e.color)})),u.push(c),g.push(o.upperColor);const p=e.dataRange,m=h/30;let f=l-m,v=null,b=!1;if(void 0!==p){const e=t.getEvaluatedCell({sheetId:p.sheetId,col:p.zone.left,row:p.zone.top});e.type===tn.number&&(f=De(e.value,l-m,c+m),v=()=>t.getRangeFormattedValues(p)[0],b=!0)}return i.options.valueLabel.display=b,i.options.valueLabel.formatter=v,i.data.datasets.push({data:u,minValue:Number(e.sectionRule.rangeMin),value:f,backgroundColor:g}),{chartJsConfig:i,background:t.getBackgroundOfSingleCellChart(e.background,p)}},validateChartDefinition:(e,t)=>$s.validateChartDefinition(e,t),transformDefinition:(e,t)=>$s.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>$s.getDefinitionFromContextCreation(e),name:s("Gauge"),sequence:50});const sr=new Co;sr.add("line",ao),sr.add("bar",ao),sr.add("pie",ao),sr.add("gauge",ao),sr.add("scorecard",vo);const rr=new Co;ho`
343
+ `;class ts extends t.Component{constructor(){super(...arguments),this.menuItems=es.getMenuItems(),this.link=t.useState(this.defaultState),this.menu=t.useState({isOpen:!1}),this.linkEditorRef=t.useRef("linkEditor"),this.position=zn(this.linkEditorRef),this.urlInput=t.useRef("urlInput")}setup(){t.onMounted((()=>{var e;return null===(e=this.urlInput.el)||void 0===e?void 0:e.focus()}))}get defaultState(){const{col:e,row:t}=this.props.cellPosition,i=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getEvaluatedCell({sheetId:i,col:e,row:t});return o.link?{url:o.link.url,label:o.formattedValue,isUrlEditable:o.link.isUrlEditable}:{label:o.formattedValue,url:"",isUrlEditable:!0}}get menuPosition(){return{x:this.position.x+320-12-2,y:this.position.y+100}}onSpecialLink(e){const{detail:t}=e,i=Mo(t);i&&(this.link.url=i.url,this.link.label=i.label,this.link.isUrlEditable=i.isUrlEditable)}getUrlRepresentation(e){return To(e,this.env.model.getters)}openMenu(){this.menu.isOpen=!0}removeLink(){this.link.url="",this.link.isUrlEditable=!0}save(){var e,t;const{col:i,row:o}=this.props.cellPosition,n=this.link.label||this.link.url;this.env.model.dispatch("UPDATE_CELL",{col:i,row:o,sheetId:this.env.model.getters.getActiveSheetId(),content:Xe(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()}}}ts.template="o-spreadsheet-LinkEditor",ts.components={Menu:Zn};const is={onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:ts,cellCorner:"BottomLeft"})};ts.props={cellPosition:Object,onClosed:{type:Function,optional:!0}};const os=new Eo;function ns(e){return 8===(e=St(e).replace("#","")).length?e.slice(6)+e.slice(0,6):e}os.add("ErrorToolTip",On).add("LinkCell",Xn).add("LinkEditor",is).add("FilterMenu",Dn);class ss{constructor(e,t,i){this.title=e.title,this.sheetId=t,this.getters=i}static validateChartDefinition(e,t){throw new Error("This method should be implemented by sub class")}static transformDefinition(e,t){throw new Error("This method should be implemented by sub class")}static getDefinitionFromContextCreation(e){throw new Error("This method should be implemented by sub class")}}function rs(e,t){return"REMOVE_COLUMNS_ROWS"===t.type?$i(e,"COL"===t.dimension?"left":"top",t.elements):"ADD_COLUMNS_ROWS"===t.type?zi(e,"COL"===t.dimension?"left":"top",t.base,t.position,t.quantity):{...e}}function as(e,t,i,o){let n=!1;const s=[];for(let o in i){let r=i[o];if(r.labelCell){const e=hs(r.labelCell,t);r.labelCell!==e&&(n=!0,r={...r,labelCell:e})}const a=hs(r.dataRange,t);void 0===a||e.getRangeString(a,a.sheetId)===Y?(n=!0,r=void 0):a!==r.dataRange&&(n=!0,r={...r,dataRange:a}),s[o]=r}let r=o;const a=hs(r,t);a!==r&&(n=!0,r=a);return{isStale:n,dataSets:s.filter(tt),labelRange:r}}function ls(e,t,i){return i.map((i=>({dataRange:Ni(e,t,i.dataRange),labelCell:i.labelCell?Ni(e,t,i.labelCell):void 0})))}function cs(e,t,i){return i?Ni(e,t,i):void 0}function hs(e,t){if(!e)return;const i=t(e);switch(i.changeType){case"NONE":return e;case"REMOVE":return;default:return i.range}}function ds(e,t,i,o){const n=[];for(const s of t){const t=e.getRangeFromSheetXC(i,s),{unboundedZone:r,sheetId:a,invalidSheetName:l}=t;if(!l)if(r.left!==r.right&&r.top!==r.bottom){if(void 0===r.right)continue;for(let t=r.left;t<=r.right;t++){const i={...r,left:t,right:t};n.push(us(e,a,i,o?{top:i.top,bottom:i.top,left:i.left,right:i.left}:void 0))}}else r.left===r.right&&r.top===r.bottom?o||n.push(us(e,a,r,void 0)):n.push(us(e,a,r,o?{top:r.top,bottom:r.top,left:r.left,right:r.left}:void 0))}return n}function us(e,t,i,o){if(i.left!==i.right&&i.top!==i.bottom)throw new Error(`Zone should be a single column or row: ${Vi(i)}`);if(o){const n=Vi(i),s=Vi(o);return{labelCell:e.getRangeFromSheetXC(t,s),dataRange:e.getRangeFromSheetXC(t,n)}}return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,Vi(i))}}function gs(e,t){var i;const o=null===(i=t.labelCell)||void 0===i?void 0:i.zone;let n=t.dataRange.zone;if(o){const{numberOfRows:e,numberOfCols:t}=Qi(n);1===e?n={...n,left:n.left+1}:1===t&&(n={...n,top:n.top+1})}const s=t.dataRange.clone({zone:n});return{label:t.labelCell?e.getRangeString(t.labelCell,"forceSheetReference"):void 0,range:e.getRangeString(s,"forceSheetReference")}}function ps(e,t){let i;if(e.labelRange){const o=rs(Li(e.labelRange),t);i=o?Vi(o):void 0}const o=e.dataSets.map(Li).map((e=>rs(e,t))).filter(tt).map(Vi);return{...e,labelRange:i,dataSets:o}}const ms=["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 fs{constructor(){this.graphColorIndex=0}next(){return ms[this.graphColorIndex++%ms.length]}}function vs(e){return e&&yt(e)<.3?"#FFFFFF":"#000000"}function bs(e){if(e.dataSets){const t=void 0!==e.dataSets.find((e=>!Ft.test(e)));if(t)return 32;if(e.dataSets.map(Li).some((e=>e.top!==e.bottom&&so(e))))return 32}return 0}function Ss(e){if(e.labelRange){if(!Ft.test(e.labelRange||""))return 33}return 0}function Cs(e,t,i){if(e){if("text"===i||(null==t?void 0:t.type)!==on.number||e.type!==on.number)return e.formattedValue;{let o=t.value-e.value;if("percentage"===i&&0!==o&&(o=o/e.value*100),"percentage"!==i&&e.format)return di(o,e.format);const n=Math.abs(parseFloat(o.toFixed(2))).toLocaleString();return"percentage"===i?n+"%":n}}return""}function Es(e,t,i,o,n){if("text"===t||(null==e?void 0:e.type)!==on.number||(null==i?void 0:i.type)!==on.number)return;const s=i.value-e.value;return s>0?o:s<0?n:void 0}function ws(e,t,i){if("text"===i||(null==e?void 0:e.type)!==on.number||(null==t?void 0:t.type)!==on.number)return"neutral";const o=t.value-e.value;return o>0?"up":o<0?"down":"neutral"}const ys={Errors:{25:s("The range is invalid"),51:s("The argument is missing. Please provide a value"),52:s("The second argument is missing. Please provide a value"),53:s("The minpoint must be a number"),54:s("The midpoint must be a number"),55:s("The maxpoint must be a number"),56:s("The first value must be a number"),57:s("The second value must be a number"),47:s("Minimum must be smaller then Maximum"),50:s("Minimum must be smaller then Midpoint"),49:s("Midpoint must be smaller then Maximum"),48:s("Lower inflection point must be smaller than upper inflection point"),58:s("Invalid Minpoint formula"),60:s("Invalid Maxpoint formula"),59:s("Invalid Midpoint formula"),61:s("Invalid upper inflection point formula"),62:s("Invalid lower inflection point formula"),24:s("A range needs to be defined"),Unexpected:s("The rule is invalid for an unknown reason")},ColorScale:s("Color scale"),IconSet:s("Icon set")},xs={IsEmpty:s("Is empty"),IsNotEmpty:s("Is not empty"),ContainsText:s("Contains"),NotContains:s("Does not contain"),BeginsWith:s("Starts with"),EndsWith:s("Ends with"),Equal:s("Is equal to"),NotEqual:s("Is not equal to"),GreaterThan:s("Is greater than"),GreaterThanOrEqual:s("Is greater than or equal to"),LessThan:s("Is less than"),LessThanOrEqual:s("Is less than or equal to"),Between:s("Is between"),NotBetween:s("Is not between")},Is={Series:s("Series"),Errors:{Unexpected:s("The chart definition is invalid for an unknown reason"),32:s("The dataset is invalid"),33:s("Labels are invalid"),34:s("The key value is invalid"),35:s("The baseline value is invalid"),36:s("The data range is invalid"),37:s("A minimum range limit value is needed"),38:s("The minimum range limit value must be a number"),39:s("A maximum range limit value is needed"),40:s("The maximum range limit value must be a number"),41:s("Minimum range limit must be smaller than maximum range limit"),42:s("The lower inflection point value must be a number"),43:s("The upper inflection point value must be a number")}},Rs={Automatic:s("Automatic"),Number:s("Number"),Percent:s("Percent"),Currency:s("Currency"),CurrencyRounded:s("Currency rounded"),Date:s("Date"),Time:s("Time"),DateTime:s("Date time"),Duration:s("Duration"),CustomCurrency:s("Custom currency")},Ts={Custom:s("Custom")},As=s("Merged cells are preventing this operation. Unmerge those cells and try again.");function Ms(e,t){if(t.dataRange){const i=t.labelCell?[Vi(t.labelCell.zone)]:[],o=Yi([Vi(t.dataRange.zone)],i)[0];if(void 0===o)return[];const n=e.getRangeFromSheetXC(t.dataRange.sheetId,o);return e.getRangeValues(n).map((e=>""===e?void 0:e))}return[]}function Os(e,t){const i=Be(0,Math.max(e.length,...t.map((e=>{var t;return(null===(t=e.data)||void 0===t?void 0:t.length)||0})))).filter((i=>{const o=e[i],n=t.map((e=>{var t;return null===(t=e.data)||void 0===t?void 0:t[i]}));return o||n.some((e=>0===e||Boolean(e)))}));return{labels:i.map((t=>e[t]||"")),dataSetsValues:t.map((e=>({...e,data:i.map((t=>e.data[t]))})))}}function Ns(e,t){const i=new Set(e),o={};i.forEach((e=>{o[e]=new Array(t.length).fill(0)}));for(const i of Be(0,e.length)){const s=e[i];for(const e of Be(0,t.length))o[s][e]+="number"==typeof(n=t[e].data[i])?n:0}var n;return{labels:Object.keys(o),dataSetsValues:t.map(((e,t)=>({...e,data:Object.values(o).map((e=>e[t]))})))}}function _s(e){return e?e.length>Q?e.substring(0,Q)+"…":e:""}function Fs(e,t,i,o){return{type:e.type,options:{responsive:!0,maintainAspectRatio:!1,layout:{padding:{left:20,right:20,top:e.title?10:25,bottom:10}},elements:{line:{fill:!1},point:{hitRadius:15}},animation:{duration:0},hover:{animationDuration:10},responsiveAnimationDuration:0,title:{display:!!e.title,fontSize:22,fontStyle:"normal",text:n(e.title),fontColor:i},legend:{onClick:void 0},tooltips:{callbacks:{label:function(e,t){var i,n,s,r,a;let l=null===(n=null===(i=t.datasets)||void 0===i?void 0:i[e.datasetIndex||0])||void 0===n?void 0:n.label;const c=""!==e.yLabel?e.yLabel:null===(a=null===(r=null===(s=t.datasets)||void 0===s?void 0:s[e.datasetIndex||0])||void 0===r?void 0:r.data)||void 0===a?void 0:a[e.index||0],h=o&&"number"==typeof c?di(c,o):(null==c?void 0:c.toLocaleString())||"";return l?`${l}: ${h}`:h}}}},data:{labels:t.map(_s),datasets:[]}}}function Ds(e,t,i){let o={values:[],formattedValues:[]};if(i)i.invalidXc||i.invalidSheetName||(o={formattedValues:e.getRangeFormattedValues(i),values:e.getRangeValues(i).map((e=>String(e)))});else if(1===t.length)for(let i=0;i<Ms(e,t[0]).length;i++)o.formattedValues.push(""),o.values.push("");else if(t[0]){o={formattedValues:Be(0,Ms(e,t[0]).length).map((e=>e.toString())),values:o.formattedValues}}return o}function ks(e,t){for(const i of t){const t=e.getRangeFormats(i.dataRange).find((e=>void 0!==e&&!vi(e)));if(t)return t}}function Ls(e,t){const i=[];for(const[o,n]of Object.entries(t)){let t;if(n.labelCell){const i=n.labelCell,s=i?e.getEvaluatedCell({sheetId:i.sheetId,col:i.zone.left,row:i.zone.top}):void 0;t=s&&i?_s(s.formattedValue):t=`${Is.Series} ${parseInt(o)+1}`}else t=t=`${Is.Series} ${parseInt(o)+1}`;let s=n.dataRange?Ms(e,n):[];i.push({data:s,label:t})}return i}function Ps(e){return 0===e?"origin":e-1}class Us extends ss{constructor(e,t,i){super(e,t,i),this.type="bar",this.dataSets=ds(i,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=_i(i,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated}static transformDefinition(e,t){return ps(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,bs,Ss)}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=ls(this.sheetId,e,this.dataSets),i=cs(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,i,e);return new Us(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Us(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,i){return{type:"bar",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated}}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>gs(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:ns(this.background||w),fontColor:ns(vs(this.background)),dataSets:e}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:o}=as(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const n=this.getDefinitionWithSpecificDataSets(t,i);return new Us(n,this.sheetId,this.getters)}}function Vs(e){return e.dataRange&&!Ft.test(e.dataRange)?36:0}function zs(e,t){return t((t=>t.sectionRule?e(t.sectionRule.rangeMin,"rangeMin"):0),(t=>t.sectionRule?e(t.sectionRule.rangeMax,"rangeMax"):0))}function Bs(e){return e.sectionRule&&Number(e.sectionRule.rangeMin)>=Number(e.sectionRule.rangeMax)?41:0}function Hs(e,t){if(""===e)switch(t){case"rangeMin":return 37;case"rangeMax":return 39}return 0}function $s(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 Ws extends ss{constructor(e,t,i){super(e,t,i),this.type="gauge",this.dataRange=_i(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,Vs,e.chainValidations(zs(Hs,e.batchValidations),zs($s,e.batchValidations),Bs),e.chainValidations((i=$s,(0,e.batchValidations)((e=>e.sectionRule?i(e.sectionRule.lowerInflectionPoint.value,"lowerInflectionPointValue"):0),(e=>e.sectionRule?i(e.sectionRule.upperInflectionPoint.value,"upperInflectionPointValue"):0)))));var i}static transformDefinition(e,t){let i;return e.dataRange&&(i=rs(Li(e.dataRange),t)),{...e,dataRange:i?Vi(i):void 0}}static getDefinitionFromContextCreation(e){return{background:e.background,title:e.title||"",type:"gauge",dataRange:e.range?e.range[0]:void 0,sectionRule:{colors:{lowerColor:"#cc0000",middleColor:"#f1c232",upperColor:"#6aa84f"},rangeMin:"0",rangeMax:"100",lowerInflectionPoint:{type:"percentage",value:"15"},upperInflectionPoint:{type:"percentage",value:"40"}}}}copyForSheetId(e){const t=cs(this.sheetId,e,this.dataRange),i=this.getDefinitionWithSpecificRanges(t,e);return new Ws(i,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.dataRange,e);return new Ws(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=hs(this.dataRange,e);if(this.dataRange===t)return this;const i=this.getDefinitionWithSpecificRanges(t);return new Ws(i,this.sheetId,this.getters)}}const Gs={second:1e3,minute:6e4,hour:36e5,day:864e5,month:2592e6,year:31536e6},qs={inSeconds:function(e){return Math.floor(e/Gs.second)},inMinutes:function(e){return Math.floor(e/Gs.minute)},inHours:function(e){return Math.floor(e/Gs.hour)},inDays:function(e){return Math.floor(e/Gs.day)},inMonths:function(e){return Math.floor(e/Gs.month)},inYears:function(e){return Math.floor(e/Gs.year)}},Zs=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function js(e,t){const i=function(e){const t=(e=(e=e.replace(/y/g,"Y")).replace(/d/g,"D")).indexOf("h");e=t>=0?e.slice(0,t).replace(/m/g,"M")+e.slice(t):e.replace(/m/g,"M");e.includes("a")||(e=e.replace(/h/g,"H"));return e}(t),o=function(e,t){const i=e.map((e=>{var t;return null===(t=Se(e))||void 0===t?void 0:t.jsDate}));if(i.some((e=>void 0===e))||e.length<2)return;const o=i.map((e=>e.getTime())),n=Math.max(...o)-Math.min(...o),s=function(e){if(e.includes("s"))return"second";if(e.includes("m"))return"minute";if(e.includes("h")||e.includes("H"))return"hour";if(e.includes("D"))return"day";if(e.includes("M"))return"month";return"year"}(t);if(Gs.second>=Gs[s]&&qs.inSeconds(n)<180)return"second";if(Gs.minute>=Gs[s]&&qs.inMinutes(n)<180)return"minute";if(Gs.hour>=Gs[s]&&qs.inHours(n)<96)return"hour";if(Gs.day>=Gs[s]&&qs.inDays(n)<90)return"day";if(Gs.month>=Gs[s]&&qs.inMonths(n)<36)return"month";return"year"}(e,i),n={};return o&&(n[o]=i),{parser:i,displayFormats:n,unit:o}}class Xs extends ss{constructor(e,t,i){super(e,t,i),this.type="line",this.dataSets=ds(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=_i(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,bs,Ss)}static transformDefinition(e,t){return ps(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,i){return{type:"line",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,stacked:this.stacked,aggregated:this.aggregated}}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:o}=as(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const n=this.getDefinitionWithSpecificDataSets(t,i);return new Xs(n,this.sheetId,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>gs(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:ns(this.background||w),fontColor:ns(vs(this.background)),dataSets:e}}copyForSheetId(e){const t=ls(this.sheetId,e,this.dataSets),i=cs(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,i,e);return new Xs(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new Xs(t,e,this.getters)}}function Ys(e,t){return Qs(e,t)||Js(e,t)}function Ks(e,t){return function(e,t){return!e.labelsAsText&&Qs(e.labelRange,t)}(e,t)?"time":function(e,t){return!e.labelsAsText&&Js(e.labelRange,t)}(e,t)?"linear":"category"}function Qs(e,t){if(!e||!Js(e,t))return!1;const i=t.getEvaluatedCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}).format;return Boolean(i&&Zs.test(i))}function Js(e,t){if(!e)return!1;const i=t.getRangeValues(e);return!i.some((e=>isNaN(Number(e))&&e))&&!i.every((e=>!e))}class er extends ss{constructor(e,t,i){super(e,t,i),this.type="pie",this.dataSets=ds(i,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=_i(i,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated}static transformDefinition(e,t){return ps(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,bs,Ss)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:!1,legendPosition:"top",title:e.title||"",type:"pie",labelRange:e.auxiliaryRange||void 0,aggregated:!1}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){return{background:this.background,title:this.title,range:this.dataSets.map((e=>this.getters.getRangeString(e.dataRange,this.sheetId))),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinitionWithSpecificDataSets(e,t,i){return{type:"pie",dataSetsHaveTitle:!!e.length&&Boolean(e[0].labelCell),background:this.background,dataSets:e.map((e=>this.getters.getRangeString(e.dataRange,i||this.sheetId))),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,i||this.sheetId):void 0,title:this.title,aggregated:this.aggregated}}copyForSheetId(e){const t=ls(this.sheetId,e,this.dataSets),i=cs(this.sheetId,e,this.labelRange),o=this.getDefinitionWithSpecificDataSets(t,i,e);return new er(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,e);return new er(t,e,this.getters)}getDefinitionForExcel(){if(this.aggregated)return;const e=this.dataSets.map((e=>gs(this.getters,e))).filter((e=>""!==e.range));return{...this.getDefinition(),backgroundColor:ns(this.background||w),fontColor:ns(vs(this.background)),verticalAxisPosition:"left",dataSets:e}}updateRanges(e){const{dataSets:t,labelRange:i,isStale:o}=as(this.getters,e,this.dataSets,this.labelRange);if(!o)return this;const n=this.getDefinitionWithSpecificDataSets(t,i);return new er(n,this.sheetId,this.getters)}}function tr(e,t){const i=[],o=Math.max(...t.map((e=>e.data.length)));for(let t=0;t<=o;t++)i.push(e.next());return i}function ir(e){return e.keyValue&&!Ft.test(e.keyValue)?34:0}function or(e){return e.baseline&&!Ft.test(e.baseline)?35:0}class nr extends ss{constructor(e,t,i){super(e,t,i),this.type="scorecard",this.keyValue=_i(i,t,e.keyValue),this.baseline=_i(i,t,e.baseline),this.baselineMode=e.baselineMode,this.baselineDescr=e.baselineDescr,this.background=e.background,this.baselineColorUp=e.baselineColorUp,this.baselineColorDown=e.baselineColorDown}static validateChartDefinition(e,t){return e.checkValidations(t,ir,or)}static getDefinitionFromContextCreation(e){return{background:e.background,type:"scorecard",keyValue:e.range?e.range[0]:void 0,title:e.title||"",baselineMode:ee,baselineColorUp:te,baselineColorDown:ie,baseline:e.auxiliaryRange||""}}static transformDefinition(e,t){let i,o;return e.baseline&&(i=rs(Li(e.baseline),t)),e.keyValue&&(o=rs(Li(e.keyValue),t)),{...e,baseline:i?Vi(i):void 0,keyValue:o?Vi(o):void 0}}copyForSheetId(e){const t=cs(this.sheetId,e,this.baseline),i=cs(this.sheetId,e,this.keyValue),o=this.getDefinitionWithSpecificRanges(t,i,e);return new nr(o,e,this.getters)}copyInSheetId(e){const t=this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,e);return new nr(t,e,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue)}getContextCreation(){return{background:this.background,title:this.title,range:this.keyValue?[this.getters.getRangeString(this.keyValue,this.sheetId)]:void 0,auxiliaryRange:this.baseline?this.getters.getRangeString(this.baseline,this.sheetId):void 0}}getDefinitionWithSpecificRanges(e,t,i){return{baselineColorDown:this.baselineColorDown,baselineColorUp:this.baselineColorUp,baselineMode:this.baselineMode,title:this.title,type:"scorecard",background:this.background,baseline:e?this.getters.getRangeString(e,i||this.sheetId):void 0,baselineDescr:this.baselineDescr,keyValue:t?this.getters.getRangeString(t,i||this.sheetId):void 0}}getDefinitionForExcel(){}updateRanges(e){const t=hs(this.baseline,e),i=hs(this.keyValue,e);if(this.baseline===t&&this.keyValue===i)return this;const o=this.getDefinitionWithSpecificRanges(t,i);return new nr(o,this.sheetId,this.getters)}}const sr=new Eo;sr.add("bar",{match:e=>"bar"===e,createChart:(e,t,i)=>new Us(e,t,i),getChartRuntime:function(e,t){let i=Ds(t,e.dataSets,e.labelRange).formattedValues,o=Ls(t,e.dataSets);({labels:i,dataSetsValues:o}=Os(i,o)),e.aggregated&&({labels:i,dataSetsValues:o}=Ns(i,o));const n=function(e,t,i){var o;const n=vs(e.background),s=Fs(e,t,n,i),r={labels:{fontColor:n}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,s.options.legend={...null===(o=s.options)||void 0===o?void 0:o.legend,...r},s.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},s.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:n}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:n,beginAtZero:!0,callback:e=>i?di(e,i):(null==e?void 0:e.toLocaleString())||e}}]},e.stacked&&(s.options.scales.xAxes[0].stacked=!0,s.options.scales.yAxes[0].stacked=!0),s}(e,i,ks(t,e.dataSets)),s=new fs;for(let{label:e,data:t}of o){const i=s.next(),o={label:e,data:t,borderColor:i,backgroundColor:i};n.data.datasets.push(o)}return{chartJsConfig:n,background:e.background||w}},validateChartDefinition:(e,t)=>Us.validateChartDefinition(e,t),transformDefinition:(e,t)=>Us.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Us.getDefinitionFromContextCreation(e),name:s("Bar"),sequence:10}),sr.add("line",{match:e=>"line"===e,createChart:(e,t,i)=>new Xs(e,t,i),getChartRuntime:function(e,t){const i=Ks(e,t),o=Ds(t,e.dataSets,e.labelRange);let n="linear"===i?o.values:o.formattedValues,s=Ls(t,e.dataSets);({labels:n,dataSetsValues:s}=Os(n,s)),"time"===i&&({labels:n,dataSetsValues:s}=function(e,t){if(0===e.length||e.every((e=>!e)))return{labels:e,dataSetsValues:t};const i=[...e],o=Ne(t);for(let e=0;e<i.length;e++)if(!i[e]){i[e]=rt(i,e);for(let t of o)t.data[e]=void 0}return{labels:i,dataSetsValues:o}}(n,s)),e.aggregated&&({labels:n,dataSetsValues:s}=Ns(n,s));const r=ks(t,e.dataSets),a=function(e,t,i){var o;const n=vs(e.background),s=Fs(e,t,n,i),r={labels:{fontColor:n,generateLabels(e){const{data:t}=e,i=window.Chart.defaults.global.legend.labels.generateLabels(e);for(const[e,o]of i.entries())o.fillStyle=t.datasets[e].borderColor;return i}}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,s.options.legend={...null===(o=s.options)||void 0===o?void 0:o.legend,...r},s.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},s.options.scales={xAxes:[{ticks:{maxRotation:60,minRotation:15,padding:5,labelOffset:2,fontColor:n}}],yAxes:[{position:e.verticalAxisPosition,ticks:{fontColor:n,beginAtZero:!0,callback:e=>i?di(e,i):(null==e?void 0:e.toLocaleString())||e}}]},e.stacked&&(s.options.scales.yAxes[0].stacked=!0),s}(e,n,r),l=function(e,t){if(t)return e.getEvaluatedCell({sheetId:t.sheetId,col:t.zone.left,row:t.zone.top}).format}(t,e.labelRange);"time"===i?(a.options.scales.xAxes[0].type="time",a.options.scales.xAxes[0].time=js(n,l),a.options.scales.xAxes[0].ticks.maxTicksLimit=15):"linear"===i&&(a.options.scales.xAxes[0].type="linear",a.options.scales.xAxes[0].ticks.callback=e=>di(e,l),a.options.tooltips.callbacks.title=e=>{var t;return di((null===(t=e[0])||void 0===t?void 0:t.xLabel)||"",l)});const c=new fs;for(let[t,{label:o,data:r}]of s.entries()){["linear","time"].includes(i)&&(r=r.map(((e,t)=>({x:n[t]||void 0,y:e}))));const s=c.next();let l=It(s);e.stacked&&(l.a=oe);const h={label:o,data:r,lineTension:0,borderColor:s,backgroundColor:xt(l),pointBackgroundColor:s,fill:!!e.stacked&&Ps(t)};a.data.datasets.push(h)}return{chartJsConfig:a,background:e.background||w}},validateChartDefinition:(e,t)=>Xs.validateChartDefinition(e,t),transformDefinition:(e,t)=>Xs.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Xs.getDefinitionFromContextCreation(e),name:s("Line"),sequence:20}),sr.add("pie",{match:e=>"pie"===e,createChart:(e,t,i)=>new er(e,t,i),getChartRuntime:function(e,t){let i=Ds(t,e.dataSets,e.labelRange).formattedValues,o=Ls(t,e.dataSets);({labels:i,dataSetsValues:o}=Os(i,o)),e.aggregated&&({labels:i,dataSetsValues:o}=Ns(i,o));const n=function(e,t,i){var o;const n=vs(e.background),s=Fs(e,t,n,i),r={labels:{fontColor:n}};return!e.labelRange&&1===e.dataSets.length||"none"===e.legendPosition?r.display=!1:r.position=e.legendPosition,s.options.legend={...null===(o=s.options)||void 0===o?void 0:o.legend,...r},s.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},s.options.tooltips.callbacks.title=function(e,t){return t.datasets[e[0].datasetIndex].label},s}(e,i,ks(t,e.dataSets)),s=new fs;for(let{label:e,data:t}of o){const i={label:e,data:t,borderColor:"#FFFFFF",backgroundColor:tr(s,o)};n.data.datasets.push(i)}return{chartJsConfig:n,background:e.background||w}},validateChartDefinition:(e,t)=>er.validateChartDefinition(e,t),transformDefinition:(e,t)=>er.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>er.getDefinitionFromContextCreation(e),name:s("Pie"),sequence:30}),sr.add("scorecard",{match:e=>"scorecard"===e,createChart:(e,t,i)=>new nr(e,t,i),getChartRuntime:function(e,t){let i,o,s="",r="";if(e.keyValue){const o={sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top};i=t.getEvaluatedCell(o),s=String(i.value),r=i.formattedValue}const a=e.baseline;if(a){const i={sheetId:e.baseline.sheetId,col:e.baseline.zone.left,row:e.baseline.zone.top};o=t.getEvaluatedCell(i)}const l=t.getBackgroundOfSingleCellChart(e.background,e.keyValue);return{title:n(e.title),keyValue:r||s,baselineDisplay:Cs(o,i,e.baselineMode),baselineArrow:ws(o,i,e.baselineMode),baselineColor:Es(o,e.baselineMode,i,e.baselineColorUp,e.baselineColorDown),baselineDescr:e.baselineDescr?n(e.baselineDescr):"",fontColor:vs(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)=>nr.validateChartDefinition(e,t),transformDefinition:(e,t)=>nr.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>nr.getDefinitionFromContextCreation(e),name:s("Scorecard"),sequence:40}),sr.add("gauge",{match:e=>"gauge"===e,createChart:(e,t,i)=>new Ws(e,t,i),getChartRuntime:function(e,t){const i=function(e){const t=Fs(e,[],vs(e.background));return t.options.hover=void 0,t.options.events=[],t.options.layout={padding:{left:30,right:30,top:e.title?10:25,bottom:25}},t.options.needle={radiusPercentage:2,widthPercentage:3.2,lengthPercentage:80,color:"#000000"},t.options.valueLabel={display:!1,formatter:null,color:"#FFFFFF",backgroundColor:"#000000",fontSize:30,borderRadius:5,padding:{top:5,right:5,bottom:5,left:5},bottomMarginPercentage:5},t}(e),o=e.sectionRule.colors,n=e.sectionRule.lowerInflectionPoint,s=e.sectionRule.upperInflectionPoint,r=Number(n.value),a=Number(s.value),l=Number(e.sectionRule.rangeMin),c=Number(e.sectionRule.rangeMax),h=c-l,d=[];if(""!==n.value){const e="number"===n.type?r:l+h*r/100;d.push({value:De(e,l,c),color:o.lowerColor})}if(""!==s.value){const e="number"===s.type?a:l+h*a/100;d.push({value:De(e,l,c),color:o.middleColor})}const u=[],g=[];d.sort(((e,t)=>e.value-t.value)).map((e=>{u.push(e.value),g.push(e.color)})),u.push(c),g.push(o.upperColor);const p=e.dataRange,m=h/30;let f=l-m,v=null,b=!1;if(void 0!==p){const e=t.getEvaluatedCell({sheetId:p.sheetId,col:p.zone.left,row:p.zone.top});e.type===on.number&&(f=De(e.value,l-m,c+m),v=()=>t.getRangeFormattedValues(p)[0],b=!0)}return i.options.valueLabel.display=b,i.options.valueLabel.formatter=v,i.data.datasets.push({data:u,minValue:Number(e.sectionRule.rangeMin),value:f,backgroundColor:g}),{chartJsConfig:i,background:t.getBackgroundOfSingleCellChart(e.background,p)}},validateChartDefinition:(e,t)=>Ws.validateChartDefinition(e,t),transformDefinition:(e,t)=>Ws.transformDefinition(e,t),getChartDefinitionFromContextCreation:e=>Ws.getDefinitionFromContextCreation(e),name:s("Gauge"),sequence:50});const rr=new Eo;rr.add("line",lo),rr.add("bar",lo),rr.add("pie",lo),rr.add("gauge",lo),rr.add("scorecard",bo);const ar=new Eo;uo`
344
344
  .o-chart-container {
345
345
  width: 100%;
346
346
  height: 100%;
347
347
  position: relative;
348
348
  }
349
- `;class ar extends t.Component{get chartType(){return this.env.model.getters.getChartType(this.props.figure.id)}get chartComponent(){const e=this.chartType,t=sr.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}ar.template="o-spreadsheet-ChartFigure",ar.components={},ar.props={figure:Object,onFigureDeleted:Function};class lr extends t.Component{get figureId(){return this.props.figure.id}get getImagePath(){return this.env.model.getters.getImagePath(this.figureId)}}function cr(e,t){const i=Ne(t),o=e.getSheetViewDimension(),n=o.width,s=o.height;if(i.width>n){const e=n/i.width;i.width=n,i.height=i.height*e}if(i.height>s){const e=s/i.height;i.height=s,i.width=i.width*e}return i}lr.template="o-spreadsheet-ImageFigure",lr.components={},lr.props={figure:Object,onFigureDeleted:Function};const hr=new Co;function dr(e,t){return{id:"copy",name:s("Copy"),sequence:2,description:"Ctrl+C",action:async()=>{t.model.dispatch("SELECT_FIGURE",{id:e}),t.model.dispatch("COPY"),await t.clipboard.write(t.model.getters.getClipboardContent())}}}function ur(e,t){return{id:"cut",name:s("Cut"),sequence:3,description:"Ctrl+X",action:async()=>{t.model.dispatch("SELECT_FIGURE",{id:e}),t.model.dispatch("CUT"),await t.clipboard.write(t.model.getters.getClipboardContent())}}}function gr(e,t,i){return{id:"delete",name:s("Delete"),sequence:10,action:()=>{i.model.dispatch("DELETE_FIGURE",{sheetId:i.model.getters.getActiveSheetId(),id:e}),t()}}}hr.add("chart",{Component:ar,SidePanelComponent:"ChartPanel",menuBuilder:function(e,t,i){return Xn([{id:"edit",name:s("Edit"),sequence:1,action:()=>{i.model.dispatch("SELECT_FIGURE",{id:e}),i.openSidePanel("ChartPanel")}},dr(e,i),ur(e,i),gr(e,t,i)])}}),hr.add("image",{Component:lr,keepRatio:!0,minFigSize:20,borderWidth:0,menuBuilder:function(e,t,i){return Xn([dr(e,i),ur(e,i),{id:"reset_size",name:s("Reset size"),sequence:4,action:()=>{const t=i.model.getters.getImageSize(e),{height:o,width:n}=cr(i.model.getters,t);i.model.dispatch("UPDATE_FIGURE",{sheetId:i.model.getters.getActiveSheetId(),id:e,height:o,width:n})}},gr(e,t,i)])}});const pr=(new Co).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let i=e.base;"after"===e.position&&i++;for(let o=0;o<e.quantity;o++)t.push(o+i);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],i=[...e.elements].sort(((e,t)=>e-t));for(let o of Be(i)){const i=0===o[0]?0:o[0]-1,n=0===o[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:o.length,base:i,sheetId:e.sheetId,position:n})}return t})).add("ADD_MERGE",(function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]})).add("REMOVE_MERGE",(function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]})).add("CREATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId}]})).add("DELETE_SHEET",(function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1}]})).add("DUPLICATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo}]})).add("CREATE_FIGURE",(function(e){return[{type:"DELETE_FIGURE",id:e.figure.id,sheetId:e.sheetId}]})).add("CREATE_CHART",(function(e){return[{type:"DELETE_FIGURE",id:e.id,sheetId:e.sheetId}]})).add("HIDE_COLUMNS_ROWS",(function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("UNHIDE_COLUMNS_ROWS",(function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}));for(const e of an.values())pr.contains(e)||pr.add(e,mr);function mr(e){return[e]}function fr(e,t){const i=nr.getAll().find((t=>t.match(e.type)));if(!i)throw new Error("Unknown chart type.");return i.transformDefinition(e,t)}function vr(e,t){var i;let o=e;e.left!==e.right&&(o={...e,left:e.left+1});const s=[Ui(o)],r=t.getActiveSheetId(),a=t.getCell({sheetId:r,col:e.left,row:e.top});if(1===so(e)&&(null==a?void 0:a.content))return{type:"scorecard",title:"",background:(null===(i=a.style)||void 0===i?void 0:i.fillColor)||void 0,keyValue:Ui(e),baselineMode:ee,baselineColorUp:te,baselineColorDown:ie};let l="";const c=t.getEvaluatedCellsInZone(r,{...o,bottom:o.top}),h=!!c.find((e=>e.type!==tn.empty&&e.type!==tn.number));if(h){const e=c.filter((e=>e.type!==tn.error&&e.type!==tn.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=Ui({...e,right:e.left,top:h?e.top+1:e.top}));const u=o.right===o.left?"none":"top";return Xs(d?t.getRangeFromSheetXC(r,d):void 0,t)?{title:l,dataSets:s,labelsAsText:!1,stacked:!1,aggregated:!1,labelRange:d,type:"line",dataSetsHaveTitle:h,verticalAxisPosition:"left",legendPosition:u}:{title:l,dataSets:s,labelRange:d,type:"bar",stacked:!1,aggregated:!1,dataSetsHaveTitle:h,verticalAxisPosition:"left",legendPosition:u}}const br=[tn.number,tn.error,tn.text,tn.boolean];function Sr(e,t,i,o,n){let r=cn.Success,a=o.right>o.left;if(e.model.getters.doesIntersectMerge(t,o)){let i;a=!1;for(let n=o.top;n<=o.bottom;n++){i=[];for(let s=o.left;s<=o.right;s++){let o=e.model.getters.getMerge({sheetId:t,col:s,row:n});o&&!i.includes(o.id.toString())&&i.push(o.id.toString())}if(i.length>=2){a=!0;break}}}const{col:l,row:c}=i;if(a)r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:n});else{const i=e.model.getters.getContiguousZone(t,o);Gi(i,o)?r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:n}):e.askConfirmation(s("We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?"),(()=>{o=i,r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:n})}),(()=>{r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:n})}))}if(r.isCancelledBecause(63)){const{col:t,row:n}=i;e.model.selection.selectZone({cell:{col:t,row:n},zone:o}),e.raiseError(s("Cannot sort. To sort, select only cells or only merges that have the same size."))}}function Cr(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause(19)&&e.raiseError(s("This operation is not allowed with multiple selections."))}const Er={filterOverlap:s("You cannot create overlapping filters."),nonContinuousTargets:s("A filter can only be created on a continuous selection."),mergeInFilter:s("You can't create a filter over a range that contains a merge.")};function wr(e,t,i){const o=e.model.dispatch("CREATE_FILTER_TABLE",{target:i,sheetId:t});o.isCancelledBecause(78)?e.raiseError(Er.filterOverlap):o.isCancelledBecause(80)?e.raiseError(Er.mergeInFilter):o.isCancelledBecause(81)&&e.raiseError(Er.nonContinuousTargets)}const yr={wrongPasteSelection:s("This operation is not allowed with multiple selections."),willRemoveExistingMerge:s("This operation is not possible due to a merge. Please remove the merges first than try again."),wrongFigurePasteOption:s("Cannot do a special paste of a figure."),frozenPaneOverlap:s("Cannot paste merged cells over a frozen pane.")};function xr(e,t){t.isSuccessful||(t.reasons.includes(20)?e.raiseError(yr.wrongPasteSelection):t.reasons.includes(2)?e.raiseError(yr.willRemoveExistingMerge):t.reasons.includes(22)?e.raiseError(yr.wrongFigurePasteOption):t.reasons.includes(75)&&e.raiseError(yr.frozenPaneOverlap))}function Ir(e,t,i){const o=e.model.dispatch("PASTE",{target:t,pasteOption:i});xr(e,o)}function Rr(e,t,i){const o=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,text:i});xr(e,o)}function Tr(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 Ar(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 Mr(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function Or(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const Nr=async e=>{e.model.dispatch("COPY"),await e.clipboard.write(e.model.getters.getClipboardContent())},_r=async e=>{Cr(e),await e.clipboard.write(e.model.getters.getClipboardContent())},Fr=async e=>kr(e),Dr=async e=>kr(e,"onlyValue");async function kr(e,t){const i=e.model.getters.getClipboardTextContent(),o=await e.clipboard.readText();switch(o.status){case"ok":const n=e.model.getters.getSelectedZones();o&&o.content!==i?Rr(e,n,o.content):Ir(e,n,t);break;case"notImplemented":e.raiseError(s("Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead."));break;case"permissionDenied":e.raiseError(s("Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings."))}}const Lr=e=>Ir(e,e.model.getters.getSelectedZones(),"onlyFormat"),Pr=e=>!e.model.getters.isCutOperation(),Ur=e=>{if(e.model.getters.getSelectedZones().length>1)return s("Delete rows");let t,i;const o=e.model.getters.getActiveRows();if(0!==o.size)t=Math.min(...o),i=Math.max(...o);else{const o=e.model.getters.getSelectedZones()[0];t=o.top,i=o.bottom}return t===i?s("Delete row %s",(t+1).toString()):s("Delete rows %s - %s",(t+1).toString(),(i+1).toString())},Vr=e=>{let t=[...e.model.getters.getActiveRows()];if(!t.length){const i=e.model.getters.getSelectedZones()[0];for(let e=i.top;e<=i.bottom;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},zr=e=>{if(e.model.getters.getSelectedZones().length>1)return s("Delete columns");let t,i;const o=e.model.getters.getActiveCols();if(0!==o.size)t=Math.min(...o),i=Math.max(...o);else{const o=e.model.getters.getSelectedZones()[0];t=o.left,i=o.right}return t===i?s("Delete column %s",Ut(t)):s("Delete columns %s - %s",Ut(t),Ut(i))},Br=e=>{let t=[...e.model.getters.getActiveCols()];if(!t.length){const i=e.model.getters.getSelectedZones()[0];for(let e=i.left;e<=i.right;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},Hr=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});xr(e,i)},$r=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});xr(e,i)},Wr=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});xr(e,i)},Gr=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});xr(e,i)},qr=e=>{const t=e.model.getters.getActiveRows();let i,o;if(t.size)i=Math.min(...t),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.top,o=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",base:i,quantity:o,dimension:"ROW"})},Zr=e=>{const t=e.model.getters.getActiveRows();let i,o;if(t.size)i=Math.max(...t),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.bottom,o=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",base:i,quantity:o,dimension:"ROW"})},jr=e=>{const t=e.model.getters.getActiveCols();let i,o;if(t.size)i=Math.min(...t),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.left,o=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",dimension:"COL",base:i,quantity:o})},Xr=e=>{const t=e.model.getters.getActiveCols();let i,o;if(t.size)i=Math.max(...t),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.right,o=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",dimension:"COL",base:i,quantity:o})};const Yr=e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},Kr=e=>{let{col:t,row:i}=e.model.getters.getActivePosition();e.model.dispatch("OPEN_CELL_POPOVER",{col:t,row:i,popoverType:"LinkEditor"})},Qr=e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,i)},Jr=e=>{const{anchor:t,zones:i}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();Sr(e,o,t.cell,i[0],"ascending")},ea=e=>{const{anchor:t,zones:i}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();Sr(e,o,t.cell,i[0],"descending")},ta=e=>1===e.model.getters.getSelectedZones().length,ia=new Qn;ia.add("cut",{name:s("Cut"),description:"Ctrl+X",sequence:10,action:_r}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Nr}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:Fr}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Pr}).addChild("paste_value_only",["paste_special"],{name:s("Paste values only"),sequence:10,action:Dr}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:Lr}).add("add_row_before",{name:e=>{const t=Ar(e);return 1===t?s("Insert row"):s("Insert %s rows",t.toString())},sequence:70,action:qr,isVisible:ta}).add("add_column_before",{name:e=>{const t=Tr(e);return 1===t?s("Insert column"):s("Insert %s columns",t.toString())},sequence:90,action:jr,isVisible:ta}).add("insert_cell",{name:s("Insert cells"),sequence:100,isVisible:ta,separator:!0}).addChild("insert_cell_down",["insert_cell"],{name:s("Shift down"),sequence:10,action:Hr}).addChild("insert_cell_right",["insert_cell"],{name:s("Shift right"),sequence:20,action:$r}).add("delete_row",{name:Ur,sequence:110,action:Vr,isVisible:ta}).add("delete_column",{name:zr,sequence:120,action:Br,isVisible:ta}).add("delete_cell",{name:s("Delete cells"),sequence:130,isVisible:ta}).addChild("delete_cell_up",["delete_cell"],{name:s("Shift up"),sequence:10,action:Wr}).addChild("delete_cell_down",["delete_cell"],{name:s("Shift left"),sequence:20,action:Gr}).add("insert_link",{name:s("Insert link"),separator:!0,sequence:150,action:Kr});const oa=new Qn;oa.add("cut",{name:s("Cut"),description:"Ctrl+X",sequence:10,action:_r}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Nr}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:Fr}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Pr}).addChild("paste_value_only",["paste_special"],{name:s("Paste value only"),sequence:10,action:Dr}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:Lr}).add("sort_columns",{name:e=>e.model.getters.getActiveCols().size>1?s("Sort columns"):s("Sort column"),sequence:50,isVisible:ta,separator:!0}).addChild("sort_ascending",["sort_columns"],{name:s("Ascending (A ⟶ Z)"),sequence:10,action:Jr}).addChild("sort_descending",["sort_columns"],{name:s("Descending (Z ⟶ A)"),sequence:20,action:ea}).add("add_column_before",{name:e=>{const t=Tr(e);return 1===t?s("Insert column left"):s("Insert %s columns left",t.toString())},sequence:70,action:jr}).add("add_column_after",{name:e=>{const t=Tr(e);return 1===t?s("Insert column right"):s("Insert %s columns right",t.toString())},sequence:80,action:Xr}).add("delete_column",{name:zr,sequence:90,action:Br,isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getElementsFromSelection("COL");return e.model.getters.canRemoveHeaders(t,"COL",i)}}).add("clear_column",{name:e=>{if(e.model.getters.getSelectedZones().length>1)return s("Clear columns");let t,i;const o=e.model.getters.getActiveCols();if(0!==o.size)t=Math.min(...o),i=Math.max(...o);else{const o=e.model.getters.getSelectedZones()[0];t=o.left,i=o.right}return t===i?s("Clear column %s",Ut(t)):s("Clear columns %s - %s",Ut(t),Ut(i))},sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId(),i=[...e.model.getters.getActiveCols()].map((i=>e.model.getters.getColsZone(t,i,i)));e.model.dispatch("DELETE_CONTENT",{target:i,sheetId:e.model.getters.getActiveSheetId()})}}).add("hide_columns",{name:e=>{const t=e.model.getters.getElementsFromSelection("COL");let i=t[0],o=t[t.length-1];return 1===t.length?s("Hide column %s",Ut(i).toString()):o-i+1===t.length?s("Hide columns %s - %s",Ut(i).toString(),Ut(o).toString()):s("Hide columns")},sequence:85,action:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getElementsFromSelection("COL");return e.model.getters.canRemoveHeaders(t,"COL",i)},separator:!0}).add("unhide_columns",{name:s("Unhide columns"),sequence:86,action:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("COL").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:s("Conditional formatting"),sequence:110,action:Yr});const na=new Qn;na.add("cut",{name:s("Cut"),sequence:10,description:"Ctrl+X",action:_r}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:Nr}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:Fr}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Pr}).addChild("paste_value_only",["paste_special"],{name:s("Paste value only"),sequence:10,action:Dr}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:Lr}).add("add_row_before",{name:e=>{const t=Ar(e);return 1===t?s("Insert row above"):s("Insert %s rows above",t.toString())},sequence:50,action:qr}).add("add_row_after",{name:e=>{const t=Ar(e);return 1===t?s("Insert row below"):s("Insert %s rows below",t.toString())},sequence:60,action:Zr}).add("delete_row",{name:Ur,sequence:70,action:Vr,isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getElementsFromSelection("ROW");return e.model.getters.canRemoveHeaders(t,"ROW",i)}}).add("clear_row",{name:e=>{if(e.model.getters.getSelectedZones().length>1)return s("Clear rows");let t,i;const o=e.model.getters.getActiveRows();if(0!==o.size)t=Math.min(...o),i=Math.max(...o);else{const o=e.model.getters.getSelectedZones()[0];t=o.top,i=o.bottom}return t===i?s("Clear row %s",(t+1).toString()):s("Clear rows %s - %s",(t+1).toString(),(i+1).toString())},sequence:80,action:e=>{const t=e.model.getters.getActiveSheetId(),i=[...e.model.getters.getActiveRows()].map((i=>e.model.getters.getRowsZone(t,i,i)));e.model.dispatch("DELETE_CONTENT",{target:i,sheetId:e.model.getters.getActiveSheetId()})}}).add("hide_rows",{name:e=>{const t=e.model.getters.getElementsFromSelection("ROW");let i=t[0],o=t[t.length-1];return 1===t.length?s("Hide row %s",(i+1).toString()):o-i+1===t.length?s("Hide rows %s - %s",(i+1).toString(),(o+1).toString()):s("Hide rows")},sequence:85,action:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getElementsFromSelection("ROW");return e.model.getters.canRemoveHeaders(t,"ROW",i)},separator:!0}).add("unhide_rows",{name:s("Unhide rows"),sequence:86,action:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("ROW").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:s("Conditional formatting"),sequence:90,action:Yr});const sa=/(.*?)\((.*?)\)(.*)/,ra=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function aa(e,t=""){return function(e){let t,i=e.match(sa),o=i[1].trim(),n=[],s=!1,r=!1,a=!1;for(let e of i[2].split(",")){const i=e.trim().toUpperCase();let o=ra.find((e=>i===e));o?n.push(o):"RANGE<ANY>"===i?n.push("RANGE"):"OPTIONAL"===i?s=!0:"REPEATING"===i?r=!0:"LAZY"===i?a=!0:i.startsWith("DEFAULT=")&&(t=e.trim().slice(8))}let l=i[3].trim();const c={name:o,description:l,type:n};s&&(c.optional=!0);r&&(c.repeating=!0);a&&(c.lazy=!0);void 0!==t&&(c.default=!0,c.defaultValue=t);return c}(`${e} ${t}`)}function la(e){let t=0,i=0,o=0;for(let n of e.args)t++,n.optional||n.repeating||n.default||i++,n.repeating&&o++;const n=e;return n.minArgRequired=i,n.maxArgPossible=o?1/0:t,n.nbrArgRepeating=o,n.getArgToFocus=function(e,t){if(!t)return e=>e;if(1===t)return t=>Math.min(t,e);const i=e-t;return e=>{if(e<=i)return e;return i+((e-i)%t||t)}}(t,o),n.hidden=e.hidden||!1,n}const ca={description:s("Apply a large number format"),args:[aa("value (number)",s("The number.")),aa("unit (string, optional)",s("The formatting unit. Use 'k', 'm', or 'b' to force the unit"))],returns:["NUMBER"],computeFormat:(e,t)=>{const i=Math.abs(_o(e.value)),o=e.format;if(void 0!==t){switch(null==t?void 0:t.value){case"k":return wi(o,1e3,"k");case"m":return wi(o,1e6,"m");case"b":return wi(o,1e9,"b");default:throw new Error(s("The formatting unit should be 'k', 'm' or 'b'."))}}return i<1e5?wi(o,0,""):i<1e8?wi(o,1e3,"k"):i<1e11?wi(o,1e6,"m"):wi(o,1e9,"b")},compute:function(e){return _o(e)}};var ha=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:ca});const da={description:s("Absolute value of a number."),args:[aa("value (number)",s("The number of which to return the absolute value."))],returns:["NUMBER"],compute:function(e){return Math.abs(_o(e))},isExported:!0},ua={description:s("Inverse cosine of a value, in radians."),args:[aa("value (number)",s("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=_o(e);return Oo((()=>Math.abs(t)<=1),s("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},ga={description:s("Inverse hyperbolic cosine of a number."),args:[aa("value (number)",s("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1."))],returns:["NUMBER"],compute:function(e){const t=_o(e);return Oo((()=>t>=1),s("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},pa={description:s("Inverse cotangent of a value."),args:[aa("value (number)",s("The value for which to calculate the inverse cotangent."))],returns:["NUMBER"],compute:function(e){const t=_o(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},ma={description:s("Inverse hyperbolic cotangent of a value."),args:[aa("value (number)",s("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=_o(e);return Oo((()=>Math.abs(t)>1),s("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},fa={description:s("Inverse sine of a value, in radians."),args:[aa("value (number)",s("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=_o(e);return Oo((()=>Math.abs(t)<=1),s("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},va={description:s("Inverse hyperbolic sine of a number."),args:[aa("value (number)",s("The value for which to calculate the inverse hyperbolic sine."))],returns:["NUMBER"],compute:function(e){return Math.asinh(_o(e))},isExported:!0},ba={description:s("Inverse tangent of a value, in radians."),args:[aa("value (number)",s("The value for which to calculate the inverse tangent."))],returns:["NUMBER"],compute:function(e){return Math.atan(_o(e))},isExported:!0},Sa={description:s("Angle from the X axis to a point (x,y), in radians."),args:[aa("x (number)",s("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")),aa("y (number)",s("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis."))],returns:["NUMBER"],compute:function(e,t){const i=_o(e),o=_o(t);return Oo((()=>0!==i||0!==o),s("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(o,i)},isExported:!0},Ca={description:s("Inverse hyperbolic tangent of a number."),args:[aa("value (number)",s("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive."))],returns:["NUMBER"],compute:function(e){const t=_o(e);return Oo((()=>Math.abs(t)<1),s("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},Ea={description:s("Rounds number up to nearest multiple of factor."),args:[aa("value (number)",s("The value to round up to the nearest integer multiple of factor.")),aa("factor (number, default=1)",s("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){const i=_o(e),o=_o(t);return Oo((()=>o>=0||i<=0),s("The factor (%s) must be positive when the value (%s) is positive.",o.toString(),i.toString())),o?Math.ceil(i/o)*o:0},isExported:!0},wa={description:s("Rounds number up to nearest multiple of factor."),args:[aa("number (number)",s("The value to round up to the nearest integer multiple of significance.")),aa("significance (number, default=1)",s("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),aa("mode (number, default=0)",s("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1,i=0){let o=_o(t);if(0===o)return 0;const n=_o(e);if(o=Math.abs(o),n>=0)return Math.ceil(n/o)*o;return 0===_o(i)?-Math.floor(Math.abs(n)/o)*o:-Math.ceil(Math.abs(n)/o)*o},isExported:!0},ya={description:s("Rounds number up to nearest multiple of factor."),args:[aa("number (number)",s("The value to round up to the nearest integer multiple of significance.")),aa("significance (number, default=1)",s("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){return wa.compute(e,t,0)},isExported:!0},xa={description:s("Cosine of an angle provided in radians."),args:[aa("angle (number)",s("The angle to find the cosine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.cos(_o(e))},isExported:!0},Ia={description:s("Hyperbolic cosine of any real number."),args:[aa("value (number)",s("Any real value to calculate the hyperbolic cosine of."))],returns:["NUMBER"],compute:function(e){return Math.cosh(_o(e))},isExported:!0},Ra={description:s("Cotangent of an angle provided in radians."),args:[aa("angle (number)",s("The angle to find the cotangent of, in radians."))],returns:["NUMBER"],compute:function(e){const t=_o(e);return Oo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},Ta={description:s("Hyperbolic cotangent of any real number."),args:[aa("value (number)",s("Any real value to calculate the hyperbolic cotangent of."))],returns:["NUMBER"],compute:function(e){const t=_o(e);return Oo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},Aa={description:s("Number of empty values."),args:[aa("value1 (any, range)",s("The first value or range in which to count the number of blanks.")),aa("value2 (any, range, repeating)",s("Additional values or ranges in which to count the number of blanks."))],returns:["NUMBER"],compute:function(...e){return $o(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},Ma={description:s("A conditional count across a range."),args:[aa("range (range)",s("The range that is tested against criterion.")),aa("criterion (string)",s("The pattern or test to apply to range."))],returns:["NUMBER"],compute:function(...e){let t=0;return Xo(e,((e,i)=>{t+=1})),t},isExported:!0},Oa={description:s("Count values depending on multiple criteria."),args:[aa("criteria_range1 (range)",s("The range to check against criterion1.")),aa("criterion1 (string)",s("The pattern or test to apply to criteria_range1.")),aa("criteria_range2 (any, range, repeating)",s("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),aa("criterion2 (string, repeating)",s("Additional criteria to check."))],returns:["NUMBER"],compute:function(...e){let t=0;return Xo(e,((e,i)=>{t+=1})),t},isExported:!0};function Na(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const _a={description:s("Counts number of unique values in a range."),args:[aa("value1 (any, range)",s("The first value or range to consider for uniqueness.")),aa("value2 (any, range, repeating)",s("Additional values or ranges to consider for uniqueness."))],returns:["NUMBER"],compute:function(...e){return $o(e,((e,t)=>Na(t)?e.add(t):e),new Set).size}},Fa={description:s("Counts number of unique values in a range, filtered by a set of criteria."),args:[aa("range (range)",s("The range of cells from which the number of unique values will be counted.")),aa("criteria_range1 (range)",s("The range of cells over which to evaluate criterion1.")),aa("criterion1 (string)",s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),aa("criteria_range2 (any, range, repeating)",s("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),aa("criterion2 (string, repeating)",s("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let i=new Set;return Xo(t,((t,o)=>{const n=e[t][o];Na(n)&&i.add(n)})),i.size}},Da={description:s("Cosecant of an angle provided in radians."),args:[aa("angle (number)",s("The angle to find the cosecant of, in radians."))],returns:["NUMBER"],compute:function(e){const t=_o(e);return Oo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},ka={description:s("Hyperbolic cosecant of any real number."),args:[aa("value (number)",s("Any real value to calculate the hyperbolic cosecant of."))],returns:["NUMBER"],compute:function(e){const t=_o(e);return Oo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},La={description:s("Converts from another base to decimal."),args:[aa("value (string)",s("The number to convert.")),aa(",base (number)",s("The base to convert the value from."))],returns:["NUMBER"],compute:function(e,t){let i=_o(t);i=Math.floor(i),Oo((()=>2<=i&&i<=36),s("The base (%s) must be between 2 and 36 inclusive.",i.toString()));const o=Do(e);if(""===o)return 0;Oo((()=>!!o.match(/^-?[a-z0-9]+$/i)),s("The value (%s) must be a valid base %s representation.",o,i.toString()));const n=parseInt(o,i);return Oo((()=>!isNaN(n)),s("The value (%s) must be a valid base %s representation.",o,i.toString())),n},isExported:!0},Pa={description:s("Converts an angle value in radians to degrees."),args:[aa("angle (number)",s("The angle to convert from radians to degrees."))],returns:["NUMBER"],compute:function(e){return 180*_o(e)/Math.PI},isExported:!0},Ua={description:s("Euler's number, e (~2.718) raised to a power."),args:[aa("value (number)",s("The exponent to raise e."))],returns:["NUMBER"],compute:function(e){return Math.exp(_o(e))},isExported:!0},Va={description:s("Rounds number down to nearest multiple of factor."),args:[aa("value (number)",s("The value to round down to the nearest integer multiple of factor.")),aa("factor (number, default=1)",s("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){const i=_o(e),o=_o(t);return Oo((()=>o>=0||i<=0),s("The factor (%s) must be positive when the value (%s) is positive.",o.toString(),i.toString())),o?Math.floor(i/o)*o:0},isExported:!0},za={description:s("Rounds number down to nearest multiple of factor."),args:[aa("number (number)",s("The value to round down to the nearest integer multiple of significance.")),aa("significance (number, default=1)",s("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),aa("mode (number, default=0)",s("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1,i=0){let o=_o(t);if(0===o)return 0;const n=_o(e);if(o=Math.abs(o),n>=0)return Math.floor(n/o)*o;return 0===_o(i)?-Math.ceil(Math.abs(n)/o)*o:-Math.floor(Math.abs(n)/o)*o},isExported:!0},Ba={description:s("Rounds number down to nearest multiple of factor."),args:[aa("number (number)",s("The value to round down to the nearest integer multiple of significance.")),aa("significance (number, default=1)",s("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){return za.compute(e,t,0)},isExported:!0},Ha={description:s("Whether the provided value is even."),args:[aa("value (number)",s("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Fo(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},$a={description:s("Rounds number up to nearest multiple of factor."),args:[aa("number (number)",s("The value to round up to the nearest integer multiple of significance.")),aa("significance (number, default=1)",s("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){return wa.compute(e,t,0)},isExported:!0},Wa={description:s("Whether the provided value is even."),args:[aa("value (number)",s("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Fo(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},Ga={description:s("The logarithm of a number, base e (euler's number)."),args:[aa("value (number)",s("The value for which to calculate the logarithm, base e."))],returns:["NUMBER"],compute:function(e){const t=_o(e);return Oo((()=>t>0),s("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},qa={description:s("Modulo (remainder) operator."),args:[aa("dividend (number)",s("The number to be divided to find the remainder.")),aa("divisor (number)",s("The number to divide by."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){const i=_o(t);Oo((()=>0!==i),s("The divisor must be different from 0."));const o=_o(e)%i;return o>0&&i<0||o<0&&i>0?o+i:o},isExported:!0},Za={description:s("Rounds a number up to the nearest odd integer."),args:[aa("value (number)",s("The value to round to the next greatest odd number."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){const t=_o(e);let i=Math.ceil(Math.abs(t));return i=1&i?i:i+1,t<0?-i:i},isExported:!0},ja={description:s("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},Xa={description:s("A number raised to a power."),args:[aa("base (number)",s("The number to raise to the exponent power.")),aa("exponent (number)",s("The exponent to raise base to."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){const i=_o(e),o=_o(t);return Oo((()=>i>=0||Number.isInteger(o)),s("The exponent (%s) must be an integer when the base is negative.",o.toString())),Math.pow(i,o)},isExported:!0},Ya={description:s("Result of multiplying a series of numbers together."),args:[aa("factor1 (number, range<number>)",s("The first number or range to calculate for the product.")),aa("factor2 (number, range<number>, repeating)",s("More numbers or ranges to calculate for the product."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0,i=1;for(let o of e)if(Array.isArray(o))for(let e of o)for(let o of e)"number"==typeof o&&(i*=o,t+=1);else null!=o&&(i*=Fo(o),t+=1);return 0===t?0:i},isExported:!0},Ka={description:s("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},Qa={description:s("Random integer between two values, inclusive."),args:[aa("low (number)",s("The low end of the random range.")),aa("high (number)",s("The high end of the random range."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){let i=_o(e);Number.isInteger(i)||(i=Math.ceil(i));let o=_o(t);return Number.isInteger(o)||(o=Math.floor(o)),Oo((()=>i<=o),s("The high (%s) must be greater than or equal to the low (%s).",o.toString(),i.toString())),i+Math.ceil((o-i+1)*Math.random())-1},isExported:!0},Ja={description:s("Rounds a number according to standard rules."),args:[aa("value (number)",s("The value to round to places number of places.")),aa("places (number, default=0)",s("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=_o(e);let o=_o(t);const n=Math.abs(i);let s;return 0===o?s=Math.round(n):(Number.isInteger(o)||(o=Math.trunc(o)),s=Math.round(n*Math.pow(10,o))/Math.pow(10,o)),i>=0?s:-s},isExported:!0},el={description:s("Rounds down a number."),args:[aa("value (number)",s("The value to round to places number of places, always rounding down.")),aa("places (number, default=0)",s("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=_o(e);let o=_o(t);const n=Math.abs(i);let s;return 0===o?s=Math.floor(n):(Number.isInteger(o)||(o=Math.trunc(o)),s=Math.floor(n*Math.pow(10,o))/Math.pow(10,o)),i>=0?s:-s},isExported:!0},tl={description:s("Rounds up a number."),args:[aa("value (number)",s("The value to round to places number of places, always rounding up.")),aa("places (number, default=0)",s("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=_o(e);let o=_o(t);const n=Math.abs(i);let s;return 0===o?s=Math.ceil(n):(Number.isInteger(o)||(o=Math.trunc(o)),s=Math.ceil(n*Math.pow(10,o))/Math.pow(10,o)),i>=0?s:-s},isExported:!0},il={description:s("Secant of an angle provided in radians."),args:[aa("angle (number)",s("The angle to find the secant of, in radians."))],returns:["NUMBER"],compute:function(e){return 1/Math.cos(_o(e))},isExported:!0},ol={description:s("Hyperbolic secant of any real number."),args:[aa("value (number)",s("Any real value to calculate the hyperbolic secant of."))],returns:["NUMBER"],compute:function(e){return 1/Math.cosh(_o(e))},isExported:!0},nl={description:s("Sine of an angle provided in radians."),args:[aa("angle (number)",s("The angle to find the sine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.sin(_o(e))},isExported:!0},sl={description:s("Hyperbolic sine of any real number."),args:[aa("value (number)",s("Any real value to calculate the hyperbolic sine of."))],returns:["NUMBER"],compute:function(e){return Math.sinh(_o(e))},isExported:!0},rl={description:s("Positive square root of a positive number."),args:[aa("value (number)",s("The number for which to calculate the positive square root."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){const t=_o(e);return Oo((()=>t>=0),s("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},al={description:s("Sum of a series of numbers and/or cells."),args:[aa("value1 (number, range<number>)",s("The first number or range to add together.")),aa("value2 (number, range<number>, repeating)",s("Additional numbers or ranges to add to value1."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){return Wo(e,((e,t)=>e+t),0)},isExported:!0},ll={description:s("A conditional sum across a range."),args:[aa("criteria_range (range)",s("The range which is tested against criterion.")),aa("criterion (string)",s("The pattern or test to apply to range.")),aa("sum_range (range, default=criteria_range)",s("The range to be summed, if different from range."))],returns:["NUMBER"],compute:function(e,t,i){void 0===i&&(i=e);let o=0;return Xo([e,t],((e,t)=>{const n=i[e][t];"number"==typeof n&&(o+=n)})),o},isExported:!0},cl={description:s("Sums a range depending on multiple criteria."),args:[aa("sum_range (range)",s("The range to sum.")),aa("criteria_range1 (range)",s("The range to check against criterion1.")),aa("criterion1 (string)",s("The pattern or test to apply to criteria_range1.")),aa("criteria_range2 (any, range, repeating)",s("Additional ranges to check.")),aa("criterion2 (string, repeating)",s("Additional criteria to check."))],returns:["NUMBER"],compute:function(e,...t){let i=0;return Xo(t,((t,o)=>{const n=e[t][o];"number"==typeof n&&(i+=n)})),i},isExported:!0},hl={description:s("Tangent of an angle provided in radians."),args:[aa("angle (number)",s("The angle to find the tangent of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.tan(_o(e))},isExported:!0},dl={description:s("Hyperbolic tangent of any real number."),args:[aa("value (number)",s("Any real value to calculate the hyperbolic tangent of."))],returns:["NUMBER"],compute:function(e){return Math.tanh(_o(e))},isExported:!0},ul={description:s("Truncates a number."),args:[aa("value (number)",s("The value to be truncated.")),aa("places (number, default=0)",s("The number of significant digits to the right of the decimal point to retain."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=_o(e);let o=_o(t);return 0===o?Math.trunc(i):(Number.isInteger(o)||(o=Math.trunc(o)),Math.trunc(i*Math.pow(10,o))/Math.pow(10,o))},isExported:!0};var gl=Object.freeze({__proto__:null,ABS:da,ACOS:ua,ACOSH:ga,ACOT:pa,ACOTH:ma,ASIN:fa,ASINH:va,ATAN:ba,ATAN2:Sa,ATANH:Ca,CEILING:Ea,CEILING_MATH:wa,CEILING_PRECISE:ya,COS:xa,COSH:Ia,COT:Ra,COTH:Ta,COUNTBLANK:Aa,COUNTIF:Ma,COUNTIFS:Oa,COUNTUNIQUE:_a,COUNTUNIQUEIFS:Fa,CSC:Da,CSCH:ka,DECIMAL:La,DEGREES:Pa,EXP:Ua,FLOOR:Va,FLOOR_MATH:za,FLOOR_PRECISE:Ba,ISEVEN:Ha,ISO_CEILING:$a,ISODD:Wa,LN:Ga,MOD:qa,ODD:Za,PI:ja,POWER:Xa,PRODUCT:Ya,RAND:Ka,RANDBETWEEN:Qa,ROUND:Ja,ROUNDDOWN:el,ROUNDUP:tl,SEC:il,SECH:ol,SIN:nl,SINH:sl,SQRT:rl,SUM:al,SUMIF:ll,SUMIFS:cl,TAN:hl,TANH:dl,TRUNC:ul});function pl(e,t,i){let o=[],n=[],r=0,a=0;zo([e],(e=>{o.push(e),r+=1})),zo([t],(e=>{n.push(e),a+=1})),Oo((()=>r===a),s("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",r.toString(),a.toString()));let l=0,c=0,h=0;for(let e=0;e<r;e++){const t=o[e],i=n[e];"number"==typeof t&&"number"==typeof i&&(l+=1,c+=t,h+=i)}Oo((()=>0!==l&&(!i||1!==l)),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const d=c/l,u=h/l;let g=0;for(let e=0;e<r;e++){const t=o[e],i=n[e];"number"==typeof t&&"number"==typeof i&&(g+=(t-d)*(i-u))}return g/(l-(i?1:0))}function ml(e,t,i){let o=0,n=0;const r=i?Go:Wo;n=r(e,((e,t)=>(o+=1,e+t)),0),Oo((()=>0!==o&&(!t||1!==o)),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const a=n/o;return r(e,((e,t)=>e+Math.pow(t-a,2)),0)/(o-(t?1:0))}function fl(e,t,i){const o=_o(t);Oo((()=>i?0<=o&&o<=1:0<o&&o<1),s("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let n,r=[],a=0;return zo(e,(e=>{"number"==typeof e&&(n=Qo(r,e,"nextSmaller","asc",r.length,((e,t)=>e[t])),r.splice(n+1,0,e),a++)})),Oo((()=>0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),i||Oo((()=>1/(a+1)<=o&&o<=a/(a+1)),s("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),ti(r,o,i)}const vl={description:s("Average magnitude of deviations from mean."),args:[aa("value1 (number, range<number>)",s("The first value or range of the sample.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){let t=0;const i=Wo(e,((e,i)=>(t+=1,e+i)),0);Oo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const o=i/t;return Wo(e,((e,t)=>e+Math.abs(o-t)),0)/t},isExported:!0},bl={description:s("Numerical average value in a dataset, ignoring text."),args:[aa("value1 (number, range<number>)",s("The first value or range to consider when calculating the average value.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the average value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0;const i=Wo(e,((e,i)=>(t+=1,e+i)),0);return Oo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/t},isExported:!0},Sl=s("[[FUNCTION_NAME]] has mismatched range sizes."),Cl=s("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),El={description:s("Weighted average."),args:[aa("values (number, range<number>)",s("Values to average.")),aa("weights (number, range<number>)",s("Weights for each corresponding value.")),aa("additional_values (number, range<number>, repeating)",s("Additional values to average.")),aa("additional_weights (number, range<number>, repeating)",s("Additional weights."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t,i,o=0,n=0;Oo((()=>e.length%2==0),s("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let r=0;r<e.length-1;r+=2)if(t=e[r],i=e[r+1],Array.isArray(t)){Oo((()=>Array.isArray(i)),Sl);let e=t.length,r=t[0].length;Oo((()=>e===i.length&&r===i[0].length),Sl);for(let a=0;a<e;a++)for(let e=0;e<r;e++){let r=t[a][e],l=i[a][e],c="number"==typeof r,h="number"==typeof l;Oo((()=>c===h),s("[[FUNCTION_NAME]] expects number values.")),h&&(Oo((()=>l>=0),Cl),o+=r*l,n+=l)}}else i=_o(i),t=_o(t),Oo((()=>i>=0),Cl),o+=t*i,n+=i;return Oo((()=>0!==n),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/n}},wl={description:s("Numerical average value in a dataset."),args:[aa("value1 (number, range<number>)",s("The first value or range to consider when calculating the average value.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the average value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0;const i=Go(e,((e,i)=>(t+=1,e+i)),0);return Oo((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/t},isExported:!0},yl={description:s("Average of values depending on criteria."),args:[aa("criteria_range (range)",s("The range to check against criterion.")),aa("criterion (string)",s("The pattern or test to apply to criteria_range.")),aa("average_range (range, default=criteria_range)",s("The range to average. If not included, criteria_range is used for the average instead."))],returns:["NUMBER"],compute:function(e,t,i){null==i&&(i=e);let o=0,n=0;return Xo([e,t],((t,s)=>{const r=(i||e)[t][s];"number"==typeof r&&(o+=1,n+=r)})),Oo((()=>0!==o),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),n/o},isExported:!0},xl={description:s("Average of values depending on multiple criteria."),args:[aa("average_range (range)",s("The range to average.")),aa("criteria_range1 (range)",s("The range to check against criterion1.")),aa("criterion1 (string)",s("The pattern or test to apply to criteria_range1.")),aa("criteria_range2 (any, range, repeating)",s("Additional criteria_range and criterion to check.")),aa("criterion2 (string, repeating)",s("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let i=0,o=0;return Xo(t,((t,n)=>{const s=e[t][n];"number"==typeof s&&(i+=1,o+=s)})),Oo((()=>0!==i),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/i},isExported:!0},Il={description:s("The number of numeric values in dataset."),args:[aa("value1 (number, range<number>)",s("The first value or range to consider when counting.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){let t=0;for(let i of e)if(Array.isArray(i))for(let e of i)for(let i of e)"number"==typeof i&&(t+=1);else("string"!=typeof i||Qt(i)||Se(i))&&(t+=1);return t},isExported:!0},Rl={description:s("The number of values in a dataset."),args:[aa("value1 (any, range)",s("The first value or range to consider when counting.")),aa("value2 (any, range, repeating)",s("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){return $o(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},Tl={description:s("The covariance of a dataset."),args:[aa("data_y (any, range)",s("The range representing the array or matrix of dependent data.")),aa("data_x (any, range)",s("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return pl(e,t,!1)},isExported:!0},Al={description:s("The covariance of a dataset."),args:[aa("data_y (any, range)",s("The range representing the array or matrix of dependent data.")),aa("data_x (any, range)",s("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return pl(e,t,!1)},isExported:!0},Ml={description:s("The sample covariance of a dataset."),args:[aa("data_y (any, range)",s("The range representing the array or matrix of dependent data.")),aa("data_x (any, range)",s("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return pl(e,t,!0)},isExported:!0},Ol={description:s("Nth largest element from a data set."),args:[aa("data (any, range)",s("Array or range containing the dataset to consider.")),aa("n (number)",s("The rank from largest to smallest of the element to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){const i=Math.trunc(_o(t));let o,n=[],r=0;zo([e],(e=>{"number"==typeof e&&(o=Qo(n,e,"nextSmaller","asc",n.length,((e,t)=>e[t])),n.splice(o+1,0,e),r++,r>i&&(n.shift(),r--))}));const a=n.shift();return Oo((()=>void 0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),Oo((()=>r>=i),s("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",i.toString())),a},isExported:!0},Nl={description:s("Maximum value in a numeric dataset."),args:[aa("value1 (number, range<number>)",s("The first value or range to consider when calculating the maximum value.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the maximum value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=Wo(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},_l={description:s("Maximum numeric value in a dataset."),args:[aa("value1 (any, range)",s("The first value or range to consider when calculating the maximum value.")),aa("value2 (any, range, repeating)",s("Additional values or ranges to consider when calculating the maximum value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=Go(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},Fl={description:s("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:[aa("range (range)",s("The range of cells from which the maximum will be determined.")),aa("criteria_range1 (range)",s("The range of cells over which to evaluate criterion1.")),aa("criterion1 (string)",s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),aa("criteria_range2 (any, range, repeating)",s("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),aa("criterion2 (string, repeating)",s("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let i=-1/0;return Xo(t,((t,o)=>{const n=e[t][o];"number"==typeof n&&(i=i<n?n:i)})),i===-1/0?0:i},isExported:!0},Dl={description:s("Median value in a numeric dataset."),args:[aa("value1 (any, range)",s("The first value or range to consider when calculating the median value.")),aa("value2 (any, range, repeating)",s("Additional values or ranges to consider when calculating the median value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=[];return Bo(e,(e=>{t.push(e)})),fl(t,.5,!0)},isExported:!0},kl={description:s("Minimum value in a numeric dataset."),args:[aa("value1 (number, range<number>)",s("The first value or range to consider when calculating the minimum value.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the minimum value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=Wo(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},Ll={description:s("Minimum numeric value in a dataset."),args:[aa("value1 (number, range<number>)",s("The first value or range to consider when calculating the minimum value.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the minimum value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=Go(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},Pl={description:s("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:[aa("range (range)",s("The range of cells from which the minimum will be determined.")),aa("criteria_range1 (range)",s("The range of cells over which to evaluate criterion1.")),aa("criterion1 (string)",s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),aa("criteria_range2 (any, range, repeating)",s("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),aa("criterion2 (string, repeating)",s("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let i=1/0;return Xo(t,((t,o)=>{const n=e[t][o];"number"==typeof n&&(i=i>n?n:i)})),i===1/0?0:i},isExported:!0},Ul={description:s("Value at a given percentile of a dataset."),args:[aa("data (any, range)",s("The array or range containing the dataset to consider.")),aa("percentile (number)",s("The percentile whose value within data will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return zl.compute(e,t)},isExported:!0},Vl={description:s("Value at a given percentile of a dataset exclusive of 0 and 1."),args:[aa("data (any, range)",s("The array or range containing the dataset to consider.")),aa("percentile (number)",s("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return fl([e],t,!1)},isExported:!0},zl={description:s("Value at a given percentile of a dataset."),args:[aa("data (any, range)",s("The array or range containing the dataset to consider.")),aa("percentile (number)",s("The percentile whose value within data will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return fl([e],t,!0)},isExported:!0},Bl={description:s("Value nearest to a specific quartile of a dataset."),args:[aa("data (any, range)",s("The array or range containing the dataset to consider.")),aa("quartile_number (number)",s("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return $l.compute(e,t)},isExported:!0},Hl={description:s("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:[aa("data (any, range)",s("The array or range containing the dataset to consider.")),aa("quartile_number (number)",s("Which quartile value, exclusive of 0 and 4, to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return fl([e],.25*Math.trunc(_o(t)),!1)},isExported:!0},$l={description:s("Value nearest to a specific quartile of a dataset."),args:[aa("data (any, range)",s("The array or range containing the dataset to consider.")),aa("quartile_number (number)",s("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return fl([e],.25*Math.trunc(_o(t)),!0)},isExported:!0},Wl={description:s("Nth smallest element in a data set."),args:[aa("data (any, range)",s("The array or range containing the dataset to consider.")),aa("n (number)",s("The rank from smallest to largest of the element to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){const i=Math.trunc(_o(t));let o,n=[],r=0;zo([e],(e=>{"number"==typeof e&&(o=Qo(n,e,"nextSmaller","asc",n.length,((e,t)=>e[t])),n.splice(o+1,0,e),r++,r>i&&(n.pop(),r--))}));const a=n.pop();return Oo((()=>void 0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),Oo((()=>r>=i),s("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",i.toString())),a},isExported:!0},Gl={description:s("Standard deviation."),args:[aa("value1 (number, range<number>)",s("The first value or range of the sample.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Kl.compute(...e))},isExported:!0},ql={description:s("Standard deviation of entire population."),args:[aa("value1 (number, range<number>)",s("The first value or range of the population.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Ql.compute(...e))},isExported:!0},Zl={description:s("Standard deviation."),args:[aa("value1 (number, range<number>)",s("The first value or range of the sample.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Jl.compute(...e))},isExported:!0},jl={description:s("Standard deviation of sample (text as 0)."),args:[aa("value1 (number, range<number>)",s("The first value or range of the sample.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(ec.compute(...e))},isExported:!0},Xl={description:s("Standard deviation of entire population."),args:[aa("value1 (number, range<number>)",s("The first value or range of the population.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(tc.compute(...e))},isExported:!0},Yl={description:s("Standard deviation of entire population (text as 0)."),args:[aa("value1 (number, range<number>)",s("The first value or range of the population.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(ic.compute(...e))},isExported:!0},Kl={description:s("Variance."),args:[aa("value1 (number, range<number>)",s("The first value or range of the sample.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return ml(e,!0,!1)},isExported:!0},Ql={description:s("Variance of entire population."),args:[aa("value1 (number, range<number>)",s("The first value or range of the population.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return ml(e,!1,!1)},isExported:!0},Jl={description:s("Variance."),args:[aa("value1 (number, range<number>)",s("The first value or range of the sample.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return ml(e,!0,!1)},isExported:!0},ec={description:s("Variance of sample (text as 0)."),args:[aa("value1 (number, range<number>)",s("The first value or range of the sample.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return ml(e,!0,!0)},isExported:!0},tc={description:s("Variance of entire population."),args:[aa("value1 (number, range<number>)",s("The first value or range of the population.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return ml(e,!1,!1)},isExported:!0},ic={description:s("Variance of entire population (text as 0)."),args:[aa("value1 (number, range<number>)",s("The first value or range of the population.")),aa("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return ml(e,!1,!0)},isExported:!0};var oc=Object.freeze({__proto__:null,AVEDEV:vl,AVERAGE:bl,AVERAGE_WEIGHTED:El,AVERAGEA:wl,AVERAGEIF:yl,AVERAGEIFS:xl,COUNT:Il,COUNTA:Rl,COVAR:Tl,COVARIANCE_P:Al,COVARIANCE_S:Ml,LARGE:Ol,MAX:Nl,MAXA:_l,MAXIFS:Fl,MEDIAN:Dl,MIN:kl,MINA:Ll,MINIFS:Pl,PERCENTILE:Ul,PERCENTILE_EXC:Vl,PERCENTILE_INC:zl,QUARTILE:Bl,QUARTILE_EXC:Hl,QUARTILE_INC:$l,SMALL:Wl,STDEV:Gl,STDEV_P:ql,STDEV_S:Zl,STDEVA:jl,STDEVP:Xl,STDEVPA:Yl,VAR:Kl,VAR_P:Ql,VAR_S:Jl,VARA:ec,VARP:tc,VARPA:ic});function nc(e,t,i){var o;const n=new Map,r=e.length;for(let t=r-1;t>=0;t--)n.set(Do(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(s("The field must be a number or a string"));let a;if("number"==typeof t){if(a=Math.trunc(t)-1,a<0||r-1<a)throw new Error(s("The field (%s) must be one of %s or must be a number between 1 and %s inclusive.",t.toString(),r.toString()))}else{const e=Do(t).toUpperCase();if(a=null!==(o=n.get(e))&&void 0!==o?o:-1,-1===a)throw new Error(s("The field (%s) must be one of %s.",Do(t),[...n.keys()].toString()))}const l=i[0].length;if(l<2)throw new Error(s("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const h=e[0].length;for(let t=1;t<l;t++){let o=[],s=!0;for(let r=0;r<i.length;r++){const a=Do(i[r][0]).toUpperCase(),l=n.get(a),c=i[r][t];if(void 0!==c){if(void 0===l){s=!1;break}o.push([e[l].slice(1,h)]),o.push(c)}}if(s){if(!(o.length>0)){c=new Set(Array(h-1).keys());break}Xo(o,((e,t)=>{c.add(t)}),!0)}}const d=e[a];return[...c].map((e=>d[e+1]))}const sc=[aa("database (range)",s("The array or range containing the data to consider, structured in such a way that the first row contains the labels for each column's values.")),aa("field (any)",s("Indicates which column in database contains the values to be extracted and operated on.")),aa("criteria (range)",s("An array or range containing zero or more criteria to filter the database values by before operating."))],rc={description:s("Average of a set of values from a table-like range."),args:sc,returns:["NUMBER"],compute:function(e,t,i){const o=nc(e,t,i);return bl.compute([o])},isExported:!0},ac={description:s("Counts values from a table-like range."),args:sc,returns:["NUMBER"],compute:function(e,t,i){const o=nc(e,t,i);return Il.compute([o])},isExported:!0},lc={description:s("Counts values and text from a table-like range."),args:sc,returns:["NUMBER"],compute:function(e,t,i){const o=nc(e,t,i);return Rl.compute([o])},isExported:!0},cc={description:s("Single value from a table-like range."),args:sc,returns:["NUMBER"],compute:function(e,t,i){const o=nc(e,t,i);return Oo((()=>1===o.length),s("More than one match found in DGET evaluation.")),o[0]},isExported:!0},hc={description:s("Maximum of values from a table-like range."),args:sc,returns:["NUMBER"],compute:function(e,t,i){const o=nc(e,t,i);return Nl.compute([o])},isExported:!0},dc={description:s("Minimum of values from a table-like range."),args:sc,returns:["NUMBER"],compute:function(e,t,i){const o=nc(e,t,i);return kl.compute([o])},isExported:!0},uc={description:s("Product of values from a table-like range."),args:sc,returns:["NUMBER"],compute:function(e,t,i){const o=nc(e,t,i);return Ya.compute([o])},isExported:!0},gc={description:s("Standard deviation of population sample from table."),args:sc,returns:["NUMBER"],compute:function(e,t,i){const o=nc(e,t,i);return Gl.compute([o])},isExported:!0},pc={description:s("Standard deviation of entire population from table."),args:sc,returns:["NUMBER"],compute:function(e,t,i){const o=nc(e,t,i);return Xl.compute([o])},isExported:!0},mc={description:s("Sum of values from a table-like range."),args:sc,returns:["NUMBER"],compute:function(e,t,i){const o=nc(e,t,i);return al.compute([o])},isExported:!0},fc={description:s("Variance of population sample from table-like range."),args:sc,returns:["NUMBER"],compute:function(e,t,i){const o=nc(e,t,i);return Kl.compute([o])},isExported:!0},vc={description:s("Variance of a population from a table-like range."),args:sc,returns:["NUMBER"],compute:function(e,t,i){const o=nc(e,t,i);return tc.compute([o])},isExported:!0};var bc=Object.freeze({__proto__:null,DAVERAGE:rc,DCOUNT:ac,DCOUNTA:lc,DGET:cc,DMAX:hc,DMIN:dc,DPRODUCT:uc,DSTDEV:gc,DSTDEVP:pc,DSUM:mc,DVAR:fc,DVARP:vc});const Sc={description:s("Converts year/month/day into a date."),args:[aa("year (number)",s("The year component of the date.")),aa("month (number)",s("The month component of the date.")),aa("day (number)",s("The day component of the date."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i){let o=Math.trunc(_o(e));const n=Math.trunc(_o(t)),r=Math.trunc(_o(i));Oo((()=>0<=o&&o<=9999),s("The year (%s) must be between 0 and 9999 inclusive.",o.toString())),o<1900&&(o+=1900);const a=we(new Date(o,n-1,r));return Oo((()=>a>=0),s("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),a},isExported:!0},Cc={description:s("Converts a date string to a date value."),args:[aa("date_string (string)",s("The string representing the date."))],returns:["NUMBER"],compute:function(e){const t=Do(e),i=Se(t);return Oo((()=>null!==i),s("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(i.value)},isExported:!0},Ec={description:s("Day of the month that a specific date falls on."),args:[aa("date (string)",s("The date from which to extract the day."))],returns:["NUMBER"],compute:function(e){return Uo(e).getDate()},isExported:!0},wc={description:s("Number of days between two dates."),args:[aa("end_date (date)",s("The end of the date range.")),aa("start_date (date)",s("The start of the date range."))],returns:["NUMBER"],compute:function(e,t){const i=Uo(e),o=Uo(t),n=i.getTime()-o.getTime();return Math.round(n/ue)},isExported:!0},yc={description:s("Number of days between two dates on a 360-day year (months of 30 days)."),args:[aa("start_date (date)",s("The start date to consider in the calculation.")),aa("end_date (date)",s("The end date to consider in the calculation.")),aa("method (number, default=0)",s("An indicator of what day count method to use. (0) US NASD method (1) European method"))],returns:["NUMBER"],compute:function(e,t,i=0){const o=_o(e),n=_o(t),s=Po(i)?4:0,r=$c.compute(e,t,s);return Math.sign(n-o)*Math.round(360*r)},isExported:!0},xc={description:s("Date a number of months before/after another date."),args:[aa("start_date (date)",s("The date from which to calculate the result.")),aa("months (number)",s("The number of months before (negative) or after (positive) 'start_date' to calculate."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){return we(Ie(Uo(e),Math.trunc(_o(t)),!1))},isExported:!0},Ic={description:s("Last day of a month before or after a date."),args:[aa("start_date (date)",s("The date from which to calculate the result.")),aa("months (number)",s("The number of months before (negative) or after (positive) 'start_date' to consider."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){const i=Uo(e),o=Math.trunc(_o(t)),n=i.getFullYear(),s=i.getMonth();return we(new Date(n,s+o+1,0))},isExported:!0},Rc={description:s("Hour component of a specific time."),args:[aa("time (date)",s("The time from which to calculate the hour component."))],returns:["NUMBER"],compute:function(e){return Uo(e).getHours()},isExported:!0},Tc={description:s("ISO week number of the year."),args:[aa("date (date)",s("The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number."))],returns:["NUMBER"],compute:function(e){const t=Uo(e),i=t.getFullYear();let o=1;for(;4!==new Date(i,0,o).getDay();)o+=1;const n=new Date(i,0,o-3);let s=31;for(;4!==new Date(i,11,s).getDay();)s-=1;const r=new Date(i,11,s+3);let a,l;switch(a=n.getTime()<=t.getTime()?t.getTime()<=r.getTime()?0:1:-1,a){case 0:l=n;break;case 1:l=new Date(i,11,s+3+1);break;case-1:let e=1;for(;4!==new Date(i-1,0,e).getDay();)e+=1;l=new Date(i-1,0,e-3)}const c=(t.getTime()-l.getTime())/ue;return Math.floor(c/7)+1},isExported:!0},Ac={description:s("Minute component of a specific time."),args:[aa("time (date)",s("The time from which to calculate the minute component."))],returns:["NUMBER"],compute:function(e){return Uo(e).getMinutes()},isExported:!0},Mc={description:s("Month of the year a specific date falls in"),args:[aa("date (date)",s("The date from which to extract the month."))],returns:["NUMBER"],compute:function(e){return Uo(e).getMonth()+1},isExported:!0},Oc={description:s("Net working days between two provided days."),args:[aa("start_date (date)",s("The start date of the period from which to calculate the number of net working days.")),aa("end_date (date)",s("The end date of the period from which to calculate the number of net working days.")),aa("holidays (date, range<date>, optional)",s("A range or array constant containing the date serial numbers to consider holidays."))],returns:["NUMBER"],compute:function(e,t,i){return _c.compute(e,t,1,i)},isExported:!0};function Nc(e){if("string"==typeof e){Oo((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),s('When weekend is a string (%s) it must be composed of "0" or "1".',e));let t=[];for(let i=0;i<7;i++)"1"===e[i]&&t.push((i+1)%7);return t}if("number"==typeof e)return Oo((()=>1<=e&&e<=7||11<=e&&e<=17),s("The weekend (%s) must be a string or a number in the range 1-7 or 11-17.",e.toString())),e<=7?[e-2==-1?6:e-2,e-1]:[e-11];throw Error(s("The weekend must be a number or a string."))}const _c={description:s("Net working days between two dates (specifying weekends)."),args:[aa("start_date (date)",s("The start date of the period from which to calculate the number of net working days.")),aa("end_date (date)",s("The end date of the period from which to calculate the number of net working days.")),aa("weekend (any, default=1)",s("A number or string representing which days of the week are considered weekends.")),aa("holidays (date, range<date>, optional)",s("A range or array constant containing the dates to consider as holidays."))],returns:["NUMBER"],compute:function(e,t,i=1,o){const n=Uo(e),s=Uo(t),r=Nc(i);let a=new Set;void 0!==o&&zo([o],(e=>{const t=Uo(e);a.add(t.getTime())}));const l=n.getTime()>s.getTime(),c=new Date((l?n:s).getTime());let h=new Date((l?s:n).getTime());const d=c.getTime();let u=h.getTime(),g=0;for(;u<=d;)r.includes(h.getDay())||a.has(u)||(g+=1),h.setDate(h.getDate()+1),u=h.getTime();return l?-g:g},isExported:!0},Fc={description:s("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()-de.getTime(),i=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/ue)+i},isExported:!0},Dc={description:s("Minute component of a specific time."),args:[aa("time (date)",s("The time from which to calculate the second component."))],returns:["NUMBER"],compute:function(e){return Uo(e).getSeconds()},isExported:!0},kc={description:s("Converts hour/minute/second into a time."),args:[aa("hour (number)",s("The hour component of the time.")),aa("minute (number)",s("The minute component of the time.")),aa("second (number)",s("The second component of the time."))],returns:["DATE"],computeFormat:()=>"hh:mm:ss a",compute:function(e,t,i){let o=Math.trunc(_o(e)),n=Math.trunc(_o(t)),r=Math.trunc(_o(i));return n+=Math.floor(r/60),r=r%60+(r<0?60:0),o+=Math.floor(n/60),n=n%60+(n<0?60:0),o%=24,Oo((()=>o>=0),s("The function [[FUNCTION_NAME]] result cannot be negative")),o/24+n/1440+r/86400},isExported:!0},Lc={description:s("Converts a time string into its serial number representation."),args:[aa("time_string (string)",s("The string that holds the time representation."))],returns:["NUMBER"],compute:function(e){const t=Do(e),i=Se(t);Oo((()=>null!==i),s("The time_string (%s) cannot be parsed to date/time.",t));const o=i.value-Math.trunc(i.value);return o<0?1+o:o},isExported:!0},Pc={description:s("Current date as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(){const e=new Date;return we(new Date(e.getFullYear(),e.getMonth(),e.getDate()))},isExported:!0},Uc={description:s("Day of the week of the date provided (as number)."),args:[aa("date (date)",s("The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.")),aa("type (number, default=1)",s("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1."))],returns:["NUMBER"],compute:function(e,t=1){const i=Uo(e),o=Math.round(_o(t)),n=i.getDay();return Oo((()=>[1,2,3].includes(o)),s("The type (%s) must be 1, 2 or 3.",o.toString())),1===o?n+1:2===o?0===n?7:n:0===n?6:n-1},isExported:!0},Vc={description:s("Week number of the year."),args:[aa("date (date)",s("The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.")),aa("type (number, default=1)",s("A number representing the day that a week starts on. Sunday = 1."))],returns:["NUMBER"],compute:function(e,t=1){const i=Uo(e),o=Math.round(_o(t));if(Oo((()=>1===o||2===o||11<=o&&o<=17||21===o),s("The type (%s) is out of range.",o.toString())),21===o)return Tc.compute(e);let n;n=1===o||2===o?o-1:o-10==7?0:o-10;const r=i.getFullYear();let a=1,l=new Date(r,0,a);for(;l.getDay()!==n;)a+=1,l=new Date(r,0,a);const c=(i.getTime()-l.getTime())/ue;return c<0?1:Math.floor(c/7)+(1===a?1:2)},isExported:!0},zc={description:s("Date after a number of workdays."),args:[aa("start_date (date)",s("The date from which to begin counting.")),aa("num_days (number)",s("The number of working days to advance from start_date. If negative, counts backwards.")),aa("holidays (date, range<date>, optional)",s("A range or array constant containing the dates to consider holidays."))],returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i){return Bc.compute(e,t,1,i)},isExported:!0},Bc={description:s("Date after a number of workdays (specifying weekends)."),args:[aa("start_date (date)",s("The date from which to begin counting.")),aa("num_days (number)",s("The number of working days to advance from start_date. If negative, counts backwards.")),aa("weekend (any, default=1)",s("A number or string representing which days of the week are considered weekends.")),aa("holidays (date, range<date>, optional)",s("A range or array constant containing the dates to consider holidays."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i=1,o){let n=Uo(e),r=Math.trunc(_o(t));"string"==typeof i&&Oo((()=>"1111111"!==i),s("The weekend (%s) must be different from '1111111'.",i));const a=Nc(i);let l=new Set;void 0!==o&&zo([o],(e=>{const t=Uo(e);l.add(t.getTime())}));let c=new Date(n.getTime()),h=c.getTime();const d=Math.sign(r);let u=Math.abs(r);for(;u>0;)c.setDate(c.getDate()+d),h=c.getTime(),a.includes(c.getDay())||l.has(h)||(u-=1);const g=h-de.getTime();return Math.round(g/ue)},isExported:!0},Hc={description:s("Year specified by a given date."),args:[aa("date (date)",s("The date from which to extract the year."))],returns:["NUMBER"],compute:function(e){return Uo(e).getFullYear()},isExported:!0},$c={description:s("Exact number of years between two dates."),args:[aa("start_date (date)",s("The start date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.")),aa("end_date (date)",s("The end date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.")),aa("day_count_convention (number, default=0)",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i=0){let o=Math.trunc(_o(e)),n=Math.trunc(_o(t));const r=Math.trunc(_o(i));return Oo((()=>o>=0),s("The start_date (%s) must be positive or null.",o.toString())),Oo((()=>n>=0),s("The end_date (%s) must be positive or null.",n.toString())),Oo((()=>0<=r&&r<=4),s("The day_count_convention (%s) must be between 0 and 4 inclusive.",r.toString())),Te(o,n,r)}},Wc={description:s("First day of the month preceding a date."),args:[aa("date (date)",s("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Uo(e),i=t.getFullYear(),o=t.getMonth();return we(new Date(i,o,1))}},Gc={description:s("Last day of the month following a date."),args:[aa("date (date)",s("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){return Ic.compute(e,0)}},qc={description:s("Quarter of the year a specific date falls in"),args:[aa("date (date)",s("The date from which to extract the quarter."))],returns:["NUMBER"],compute:function(e){return Math.ceil((Uo(e).getMonth()+1)/3)}},Zc={description:s("First day of the quarter of the year a specific date falls in."),args:[aa("date (date)",s("The date from which to calculate the start of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=qc.compute(e),i=Hc.compute(e);return we(new Date(i,3*(t-1),1))}},jc={description:s("Last day of the quarter of the year a specific date falls in."),args:[aa("date (date)",s("The date from which to calculate the end of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=qc.compute(e),i=Hc.compute(e);return we(new Date(i,3*t,0))}},Xc={description:s("First day of the year a specific date falls in."),args:[aa("date (date)",s("The date from which to calculate the start of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Hc.compute(e);return we(new Date(t,0,1))}},Yc={description:s("Last day of the year a specific date falls in."),args:[aa("date (date)",s("The date from which to calculate the end of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Hc.compute(e);return we(new Date(t+1,0,0))}};var Kc=Object.freeze({__proto__:null,DATE:Sc,DATEVALUE:Cc,DAY:Ec,DAYS:wc,DAYS360:yc,EDATE:xc,EOMONTH:Ic,HOUR:Rc,ISOWEEKNUM:Tc,MINUTE:Ac,MONTH:Mc,NETWORKDAYS:Oc,NETWORKDAYS_INTL:_c,NOW:Fc,SECOND:Dc,TIME:kc,TIMEVALUE:Lc,TODAY:Pc,WEEKDAY:Uc,WEEKNUM:Vc,WORKDAY:zc,WORKDAY_INTL:Bc,YEAR:Hc,YEARFRAC:$c,MONTH_START:Wc,MONTH_END:Gc,QUARTER:qc,QUARTER_START:Zc,QUARTER_END:jc,YEAR_START:Xc,YEAR_END:Yc});const Qc={description:s("Compare two numeric values, returning 1 if they're equal."),args:[aa(" (number)",s("The first number to compare.")),aa(" (number, default=0)",s("The second number to compare."))],returns:["NUMBER"],compute:function(e,t=0){return _o(e)===_o(t)?1:0},isExported:!0};var Jc=Object.freeze({__proto__:null,DELTA:Qc});function eh(e,t){Oo((()=>e<t),s("The maturity (%s) must be strictly greater than the settlement (%s).",t.toString(),e.toString()))}function th(e,t){Oo((()=>t<e),s("The settlement date (%s) must be strictly greater than the issue date (%s).",e.toString(),t.toString()))}function ih(e){Oo((()=>[1,2,4].includes(e)),s("The frequency (%s) must be one of %s",e.toString(),[1,2,4].toString()))}function oh(e){Oo((()=>0<=e&&e<=4),s("The day_count_convention (%s) must be between 0 and 4 inclusive.",e.toString()))}function nh(e){Oo((()=>e>0),s("The redemption (%s) must be strictly positive.",e.toString()))}function sh(e){Oo((()=>e>0),s("The price (%s) must be strictly positive.",e.toString()))}function rh(e){Oo((()=>e>0),s("The number_of_periods (%s) must be greater than 0.",e.toString()))}function ah(e){Oo((()=>e>0),s("The rate (%s) must be strictly positive.",e.toString()))}function lh(e){Oo((()=>e>0),s("The life (%s) must be strictly positive.",e.toString()))}function ch(e){Oo((()=>e>=0),s("The cost (%s) must be positive or null.",e.toString()))}function hh(e){Oo((()=>e>0),s("The period (%s) must be strictly positive.",e.toString()))}function dh(e){Oo((()=>e>=0),s("The salvage (%s) must be positive or null.",e.toString()))}function uh(e){Oo((()=>e>0),s("The present value (%s) must be strictly positive.",e.toString()))}function gh(e,t){Oo((()=>e<=t),s("The period (%s) must be less than or equal life (%s).",e.toString(),t.toString()))}function ph(e){Oo((()=>e>0),s("The investment (%s) must be strictly positive.",e.toString()))}function mh(e){Oo((()=>e>0),s("The discount (%s) must be strictly positive.",e.toString()))}function fh(e){Oo((()=>e<1),s("The discount (%s) must be smaller than 1.",e.toString()))}function vh(e){Oo((()=>e>0),s("The depreciation factor (%s) must be strictly positive.",e.toString()))}function bh(e,t){const i=Uo(e),o=Uo(t),n=new Date(i);n.setFullYear(i.getFullYear()+1),Oo((()=>o.getTime()<=n.getTime()),s("The settlement date (%s) must at most one year after the maturity date (%s).",e.toString(),t.toString()))}function Sh(e,t,i){rh(i),Oo((()=>e>0),s("The first_period (%s) must be strictly positive.",e.toString())),Oo((()=>t>0),s("The last_period (%s) must be strictly positive.",t.toString())),Oo((()=>e<=t),s("The first_period (%s) must be smaller or equal to the last_period (%s).",e.toString(),t.toString())),Oo((()=>t<=i),s("The last_period (%s) must be smaller or equal to the number_of_periods (%s).",e.toString(),i.toString()))}function Ch(e){Oo((()=>e>-1),s("The rate_guess (%s) must be strictly greater than -1.",e.toString()))}function Eh(e,t){Oo((()=>e.length===t.length&&e[0].length===t[0].length),s("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."))}function wh(e){Oo((()=>e.every((t=>t>=e[0]))),s("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e[0].toString()))}const yh=[aa("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),aa("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),aa("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),aa("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))];function xh(e,t,i,o,n=1e-10,r){let a,l,c,h,d=i,u=!1,g=0;do{c=e(d),isNaN(c)?(Oo((()=>g<o&&void 0!==r),s("Function [[FUNCTION_NAME]] didn't find any result.")),g++,d=r(h),h=d):(a=d-c/t(d),l=Math.abs(a-d),d=a,u=l<n||Math.abs(c)<n,Oo((()=>g<o),s("Function [[FUNCTION_NAME]] didn't find any result.")),g++)}while(!u);return d}const Ih={description:s("Accrued interest of security paying at maturity."),args:[aa("issue (date)",s("The date the security was initially issued.")),aa("maturity (date)",s("The maturity date of the security.")),aa("rate (number)",s("The annualized rate of interest.")),aa("redemption (number)",s("The redemption amount per 100 face value, or par.")),aa("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(_o(e)),r=Math.trunc(_o(t)),a=_o(o),l=_o(i),c=Math.trunc(_o(n));th(r,s),oh(c),nh(a),ah(l);return a*l*$c.compute(s,r,n)},isExported:!0},Rh={description:s("Depreciation for an accounting period."),args:[aa("cost (number)",s("The initial cost of the asset.")),aa("purchase_date (date)",s("The date the asset was purchased.")),aa("first_period_end (date)",s("The date the first period ended.")),aa("salvage (number)",s("The value of the asset at the end of depreciation.")),aa("period (number)",s("The single period within life for which to calculate depreciation.")),aa("rate (number)",s("The deprecation rate.")),aa(" (number, optional)",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r,a=0){a=a||0;const l=_o(e),c=Math.trunc(_o(t)),h=Math.trunc(_o(i)),d=_o(o),u=_o(n),g=_o(r),p=Math.trunc(_o(a));!function(e){Oo((()=>e>0),s("The cost (%s) must be strictly positive.",e.toString()))}(l),dh(d),function(e,t){Oo((()=>e<=t),s("The salvage (%s) must be smaller or equal than the cost (%s).",e.toString(),t.toString()))}(d,l),function(e){Oo((()=>e>=0),s("The period (%s) must be positive or null.",e.toString()))}(u),ah(g),oh(p),Oo((()=>c<=h),s("The purchase_date (%s) must be before the first_period_end (%s).",c.toString(),h.toString()));const m=u<1&&u>0?1:Math.trunc(u),f=l*g,v=$c.compute(c,h,p),b=c===h?f:f*v,S=l-b-f*m;return S>=d?0===m?b:f:d-S<f?f-(d-S):0},isExported:!0},Th={description:s("Days in coupon period containing settlement date."),args:yh,returns:["NUMBER"],compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(_o(e)),s=Math.trunc(_o(t)),r=Math.trunc(_o(i)),a=Math.trunc(_o(o));if(eh(n,s),ih(r),oh(a),1===a){const n=_h.compute(e,t,i,o);return Oh.compute(e,t,i,o)-n}return(3===a?365:360)/r},isExported:!0},Ah={description:s("Days from settlement until next coupon."),args:yh,returns:["NUMBER"],compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(_o(e)),s=Math.trunc(_o(t)),r=Math.trunc(_o(i)),a=Math.trunc(_o(o));eh(n,s),ih(r),oh(a);const l=_h.compute(n,s,i,o);if([1,2,3].includes(a))return n-l;if(4===a){const e=Te(l,n,a);return Math.round(360*e)}const c=Uo(n),h=Uo(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&&xe(h)&&xe(c)&&(f=30),31!==f||30!==m&&31!==m||(f=30),2===g&&xe(h)&&(m=30),31===m&&(m=30),360*(u-d)+30*(p-g)+(f-m)},isExported:!0},Mh={description:s("Days from settlement until next coupon."),args:yh,returns:["NUMBER"],compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(_o(e)),s=Math.trunc(_o(t)),r=Math.trunc(_o(i)),a=Math.trunc(_o(o));eh(n,s),ih(r),oh(a);const l=Oh.compute(n,s,i,o);if([1,2,3].includes(a))return l-n;if(4===a){const e=Te(n,l,a);return Math.round(360*e)}const c=Ah.compute(e,t,i,a);return Th.compute(e,t,i,a)-c},isExported:!0},Oh={description:s("Next coupon date after the settlement date."),args:yh,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(_o(e)),s=Math.trunc(_o(t)),r=Math.trunc(_o(i)),a=Math.trunc(_o(o));eh(n,s),ih(r),oh(a);const l=12/r,c=Nh.compute(e,t,i,o);return we(Ie(Uo(s),-(c-1)*l,!0))},isExported:!0},Nh={description:s("Number of coupons between settlement and maturity."),args:yh,returns:["NUMBER"],compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(_o(e)),s=Math.trunc(_o(t)),r=Math.trunc(_o(i)),a=Math.trunc(_o(o));eh(n,s),ih(r),oh(a);let l=1,c=s;const h=12/r;for(;c>n;)c=we(Ie(Uo(c),-h,!1)),l++;return l-1},isExported:!0},_h={description:s("Last coupon date prior to or on the settlement date."),args:yh,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(_o(e)),s=Math.trunc(_o(t)),r=Math.trunc(_o(i)),a=Math.trunc(_o(o));eh(n,s),ih(r),oh(a);const l=12/r,c=Nh.compute(e,t,i,o);return we(Ie(Uo(s),-c*l,!0))},isExported:!0},Fh={description:s("Cumulative interest paid over a set of periods."),args:[aa("rate (number)",s("The interest rate.")),aa("number_of_periods (number)",s("The number of payments to be made.")),aa("present_value (number)",s("The current value of the annuity.")),aa("first_period (number)",s("The number of the payment period to begin the cumulative calculation.")),aa("last_period (number)",s("The number of the payment period to end the cumulative calculation.")),aa("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,i,o,n,s=0){const r=_o(o),a=_o(n),l=_o(e),c=_o(i),h=_o(t);Sh(r,a,h),ah(l),uh(c);let d=0;for(let t=r;t<=a;t++){d+=Gh.compute(e,t,h,i,0,s)}return d},isExported:!0},Dh={description:s("Cumulative principal paid over a set of periods."),args:[aa("rate (number)",s("The interest rate.")),aa("number_of_periods (number)",s("The number of payments to be made.")),aa("present_value (number)",s("The current value of the annuity.")),aa("first_period (number)",s("The number of the payment period to begin the cumulative calculation.")),aa("last_period (number)",s("The number of the payment period to end the cumulative calculation.")),aa("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,i,o,n,s=0){const r=_o(o),a=_o(n),l=_o(e),c=_o(i),h=_o(t);Sh(r,a,h),ah(l),uh(c);let d=0;for(let t=r;t<=a;t++){d+=td.compute(e,t,h,i,0,s)}return d},isExported:!0},kh={description:s("Depreciation via declining balance method."),args:[aa("cost (number)",s("The initial cost of the asset.")),aa("salvage (number)",s("The value of the asset at the end of depreciation.")),aa("life (number)",s("The number of periods over which the asset is depreciated.")),aa("period (number)",s("The single period within life for which to calculate depreciation.")),aa("month (number, optional)",s("The number of months in the first year of depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o,...n){const r=_o(e),a=_o(t),l=_o(i),c=Math.trunc(_o(o)),h=n.length?Math.trunc(_o(n[0])):12,d=l+(12===h?0:1);ch(r),dh(a),hh(c),lh(l),Oo((()=>1<=h&&h<=12),s("The month (%s) must be between 1 and 12 inclusive.",h.toString())),Oo((()=>c<=d),s("The period (%s) must be less than or equal to %s.",c.toString(),d.toString()));const u=h/12;let g=1-Math.pow(a/r,1/l);g=Math.round(1e3*g)/1e3;let p=r,m=r*(1-g*u);for(let e=1;e<c;e++)p=m,m=p*(1-g),e===l&&(m=p*(1-g*(1-u)));return p-m},isExported:!0},Lh={description:s("Depreciation via double-declining balance method."),args:[aa("cost (number)",s("The initial cost of the asset.")),aa("salvage (number)",s("The value of the asset at the end of depreciation.")),aa("life (number)",s("The number of periods over which the asset is depreciated.")),aa("period (number)",s("The single period within life for which to calculate depreciation.")),aa("factor (number, default=2)",s("The factor by which depreciation decreases."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o,n=2){n=n||0;const s=_o(e),r=_o(t),a=_o(i),l=_o(o),c=_o(n);if(ch(s),dh(r),hh(l),lh(a),gh(l,a),vh(c),0===s||r>=s)return 0;const h=c/a;if(h>1)return 1===o?s-r:0;if(l<=1)return s*h;const d=s*Math.pow(1-h,l-1),u=s*Math.pow(1-h,l),g=u<r?d-r:d-u;return Math.max(g,0)},isExported:!0},Ph={description:s("Discount rate of a security based on price."),args:[aa("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),aa("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),aa("price (number)",s("The price at which the security is bought per 100 face value.")),aa("redemption (number)",s("The redemption amount per 100 face value, or par.")),aa("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(_o(e)),r=Math.trunc(_o(t)),a=_o(i),l=_o(o),c=Math.trunc(_o(n));eh(s,r),oh(c),sh(a),nh(l);return(l-a)/l/$c.compute(s,r,c)},isExported:!0},Uh={description:s("Convert a decimal fraction to decimal value."),args:[aa("fractional_price (number)",s("The price quotation given using fractional decimal conventions.")),aa("unit (number)",s("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const i=_o(e),o=Math.trunc(_o(t));Oo((()=>o>0),s("The unit (%s) must be strictly positive.",o.toString()));const n=Math.trunc(i);return n+(i-n)*(10**Math.ceil(Math.log10(o))/o)},isExported:!0},Vh={description:s("Convert a decimal value to decimal fraction."),args:[aa("decimal_price (number)",s("The price quotation given as a decimal value.")),aa("unit (number)",s("The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const i=_o(e),o=Math.trunc(_o(t));Oo((()=>o>0),s("The unit (%s) must be strictly positive.",o.toString()));const n=Math.trunc(i);return n+(i-n)*(o/10**Math.ceil(Math.log10(o)))},isExported:!0},zh={description:s("Number of periods for an investment to reach a value."),args:[aa("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),aa("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),aa("rate (number)",s("The annualized rate of interest.")),aa("yield (number)",s("The expected annual yield of the security.")),aa("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),aa("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r=0){r=r||0;const a=Math.trunc(_o(e)),l=Math.trunc(_o(t)),c=_o(i),h=_o(o),d=Math.trunc(_o(n)),u=Math.trunc(_o(r));eh(a,l),ih(d),oh(u),Oo((()=>c>=0),s("The rate (%s) must be positive or null.",c.toString())),Oo((()=>h>=0),s("The yield (%s) must be positive or null.",h.toString()));const g=$c.compute(a,l,u),p=g-Math.trunc(g)||1/d,m=Math.ceil(g*d),f=c/d,v=h/d;let b=0,S=0;for(let e=1;e<=m;e++){const t=(f+(e===m?1:0))/(1+v)**e;S+=(p+(e-1)/d)*t,b+=t}return 0===b?0:S/b},isExported:!0},Bh={description:s("Annual effective interest rate."),args:[aa("nominal_rate (number)",s("The nominal interest rate per year.")),aa("periods_per_year (number)",s("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const i=_o(e),o=Math.trunc(_o(t));return Oo((()=>i>0),s("The nominal rate (%s) must be strictly greater than 0.",i.toString())),Oo((()=>o>0),s("The number of periods by year (%s) must strictly greater than 0.",o.toString())),Math.pow(1+i/o,o)-1},isExported:!0},Hh={description:s("Future value of an annuity investment."),args:[aa("rate (number)",s("The interest rate.")),aa("number_of_periods (number)",s("The number of payments to be made.")),aa("payment_amount (number)",s("The amount per period to be paid.")),aa("present_value (number, default=0)",s("The current value of the annuity.")),aa("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o=0,n=0){o=o||0,n=n||0;const s=_o(e),r=_o(t),a=_o(i),l=_o(o),c=Po(n)?1:0;return s?-l*(1+s)**r-a*(1+s*c)*((1+s)**r-1)/s:-(l+a*r)},isExported:!0},$h={description:s("Future value of principal from series of rates."),args:[aa("principal (number)",s("The amount of initial capital or value to compound against.")),aa("rate_schedule (number, range<number>)",s("A series of interest rates to compound against the principal."))],returns:["NUMBER"],compute:function(e,t){return $o([t],((e,t)=>e*(1+_o(t))),_o(e))},isExported:!0},Wh={description:s("Calculates effective interest rate."),args:[aa("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),aa("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),aa("investment (number)",s("The amount invested in the security.")),aa("redemption (number)",s("The amount to be received at maturity.")),aa("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){const s=Math.trunc(_o(e)),r=Math.trunc(_o(t)),a=_o(o),l=_o(i);eh(s,r),ph(l),nh(a);return(a-l)/l/$c.compute(s,r,n)},isExported:!0},Gh={description:s("Payment on the principal of an investment."),args:[aa("rate (number)",s("The annualized rate of interest.")),aa("period (number)",s("The amortization period, in terms of number of periods.")),aa("number_of_periods (number)",s("The number of payments to be made.")),aa("present_value (number)",s("The current value of the annuity.")),aa("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),aa("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o,n=0,s=0){return ed.compute(e,i,o,n,s)-td.compute(e,t,i,o,n,s)},isExported:!0},qh={description:s("Internal rate of return given periodic cashflows."),args:[aa("cashflow_amounts (number, range<number>)",s("An array or range containing the income or payments associated with the investment.")),aa("rate_guess (number, default=0.1)",s("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t=.1){const i=_o(t);Ch(i);let o=!1,n=!1,r=[];Bo([e],(e=>{e>0&&(o=!0),e<0&&(n=!0),r.push(e)})),Oo((()=>o&&n),s("The cashflow_amounts must include negative and positive values."));const a=r.shift();return xh((function(e){return function(e,t,i){const o=i.length;let n=0;return i.reduce(((t,i)=>(n++,t+i*e**(o-n))),t*e**o)}(e,a,r)}),(function(e){return function(e,t,i){const o=i.length;let n=0;return i.reduce(((t,i)=>(n++,t+i*(o-n)*e**(o-n-1))),t*o*e**(o-1))}(e,a,r)}),i+1,20,1e-5)-1},isExported:!0},Zh={description:s("Returns the interest paid at a particular period of an investment."),args:[aa("rate (number)",s("The interest rate.")),aa("period (number)",s("The period for which you want to view the interest payment.")),aa("number_of_periods (number)",s("The number of payments to be made.")),aa("present_value (number)",s("The current value of the annuity."))],returns:["NUMBER"],compute:function(e,t,i,o){const n=_o(e),r=_o(t),a=_o(i),l=_o(o);Oo((()=>0!==a),s("The number of periods must be different than 0.",a.toString()));return-1*(l-l*(r/a))*n},isExported:!0},jh={description:s("Modified Macaulay duration."),args:[aa("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),aa("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),aa("rate (number)",s("The annualized rate of interest.")),aa("yield (number)",s("The expected annual yield of the security.")),aa("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),aa("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,s=0){return zh.compute(e,t,i,o,n,s)/(1+_o(o)/Math.trunc(_o(n)))},isExported:!0},Xh={description:s("Modified internal rate of return."),args:[aa("cashflow_amounts (range<number>)",s("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")),aa("financing_rate (number)",s("The interest rate paid on funds invested.")),aa("reinvestment_return_rate (number)",s("The return (as a percentage) earned on reinvestment of income received from the investment."))],returns:["NUMBER"],compute:function(e,t,i){const o=_o(t),n=_o(i),r=(a=e,a.length?a[0].map(((e,t)=>a.map((e=>e[t])))):a).flat().filter(et).map(_o);var a;const l=r.length;let c=0,h=0;for(const e of ze(0,l)){const t=r[e];t>=0?c+=t*(n+1)**(l-e-1):h+=t/(o+1)**e}Oo((()=>0!==h&&0!==c),s("There must be both positive and negative values in cashflow_amounts."));return(-c/h)**(1/(l-1))-1},isExported:!0},Yh={description:s("Annual nominal interest rate."),args:[aa("effective_rate (number)",s("The effective interest rate per year.")),aa("periods_per_year (number)",s("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const i=_o(e),o=Math.trunc(_o(t));return Oo((()=>i>0),s("The effective rate (%s) must must strictly greater than 0.",i.toString())),Oo((()=>o>0),s("The number of periods by year (%s) must strictly greater than 0.",o.toString())),(Math.pow(i+1,1/o)-1)*o},isExported:!0},Kh={description:s("Number of payment periods for an investment."),args:[aa("rate (number)",s("The interest rate.")),aa("payment_amount (number)",s("The amount of each payment made.")),aa("present_value (number)",s("The current value of the annuity.")),aa("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),aa("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,i,o=0,n=0){o=o||0,n=n||0;const s=_o(e),r=_o(t),a=_o(i),l=_o(o),c=Po(n)?1:0;if(0===s)return-(l+a)/r;const h=r*(1+s*c)/s;return Math.log((h-l)/(a+h))/Math.log(1+s)},isExported:!0};const Qh={description:s("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:[aa("discount (number)",s("The discount rate of the investment over one period.")),aa("cashflow1 (number, range<number>)",s("The first future cash flow.")),aa("cashflow2 (number, range<number>, repeating)",s("Additional future cash flows."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,...t){const i=_o(e);return Oo((()=>-1!==i),s("The discount (%s) must be different from -1.",i.toString())),function(e,t,i){let o=0;return Wo(i,((t,i)=>(o++,t+i/(1+e)**o)),t)}(i,0,t)},isExported:!0},Jh={description:s("Computes the number of periods needed for an investment to reach a value."),args:[aa("rate (number)",s("The rate at which the investment grows each period.")),aa("present_value (number)",s("The investment's current value.")),aa("future_value (number)",s("The investment's desired future value."))],returns:["NUMBER"],compute:function(e,t,i){const o=_o(e),n=_o(t),r=_o(i);return ah(o),Oo((()=>n>0),s("The present_value (%s) must be strictly positive.",n.toString())),Oo((()=>r>0),s("The future_value (%s) must be strictly positive.",r.toString())),(Math.log(r)-Math.log(n))/Math.log(1+o)},isExported:!0},ed={description:s("Periodic payment for an annuity investment."),args:[aa("rate (number)",s("The annualized rate of interest.")),aa("number_of_periods (number)",s("The number of payments to be made.")),aa("present_value (number)",s("The current value of the annuity.")),aa("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),aa("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o=0,n=0){o=o||0,n=n||0;const s=_o(t),r=_o(e),a=Po(n)?1:0;let l=_o(o),c=_o(i);if(rh(s),0===r)return-(l+c)/s;let h=-(c*(1+r)**s+l);return h=h*r/((1+r*a)*((1+r)**s-1)),h},isExported:!0},td={description:s("Payment on the principal of an investment."),args:[aa("rate (number)",s("The annualized rate of interest.")),aa("period (number)",s("The amortization period, in terms of number of periods.")),aa("number_of_periods (number)",s("The number of payments to be made.")),aa("present_value (number)",s("The current value of the annuity.")),aa("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),aa("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o,n=0,r=0){n=n||0,r=r||0;const a=_o(i),l=_o(e),c=_o(t),h=Po(r)?1:0,d=_o(n),u=_o(o);rh(a),Oo((()=>c>0&&c<=a),s("The period must be between 1 and number_of_periods",a.toString()));const g=ed.compute(l,a,u,d,r);if(1===h&&1===c)return g;return g+-Hh.compute(l,0===h?c-1:c-2,g,u+g*h,0)*l},isExported:!0},id={description:s("Present value of an annuity investment."),args:[aa("rate (number)",s("The interest rate.")),aa("number_of_periods (number)",s("The number of payments to be made.")),aa("payment_amount (number)",s("The amount per period to be paid.")),aa("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),aa("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o=0,n=0){o=o||0,n=n||0;const s=_o(e),r=_o(t),a=_o(i),l=_o(o),c=Po(n)?1:0;return s?-(a*(1+s*c)*((1+s)**r-1)/s+l)/(1+s)**r:-(l+a*r)},isExported:!0},od={description:s("Price of a security paying periodic interest."),args:[aa("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),aa("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),aa("rate (number)",s("The annualized rate of interest.")),aa("yield (number)",s("The expected annual yield of the security.")),aa("redemption (number)",s("The redemption amount per 100 face value, or par.")),aa("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),aa("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r,a=0){a=a||0;const l=Math.trunc(_o(e)),c=Math.trunc(_o(t)),h=_o(i),d=_o(o),u=_o(n),g=Math.trunc(_o(r)),p=Math.trunc(_o(a));eh(l,c),ih(g),oh(p),Oo((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),Oo((()=>d>=0),s("The yield (%s) must be positive or null.",d.toString())),nh(u);const m=$c.compute(l,c,p)*g,f=Math.ceil(m),v=m-Math.floor(m)||1,b=1+d/g,S=100*h/g;if(1===f)return(S+u)/(v*d/g+1)-S*(1-v);let C=0;for(let e=1;e<=f;e++)C+=S/b**(e-1+v);return u/b**(f-1+v)+C-S*(1-v)},isExported:!0},nd={description:s("Price of a discount security."),args:[aa("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),aa("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),aa("discount (number)",s("The discount rate of the security at time of purchase.")),aa("redemption (number)",s("The redemption amount per 100 face value, or par.")),aa("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(_o(e)),r=Math.trunc(_o(t)),a=_o(i),l=_o(o),c=Math.trunc(_o(n));eh(s,r),oh(c),mh(a),nh(l);return l-a*l*$c.compute(s,r,c)},isExported:!0},sd={description:s("Calculates the price of a security paying interest at maturity, based on expected yield."),args:[aa("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),aa("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),aa("issue (date)",s("The date the security was initially issued.")),aa("rate (number)",s("The annualized rate of interest.")),aa("yield (number)",s("The expected annual yield of the security.")),aa("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r=0){r=r||0;const a=Math.trunc(_o(e)),l=Math.trunc(_o(t)),c=Math.trunc(_o(i)),h=_o(o),d=_o(n),u=Math.trunc(_o(r));th(a,c),eh(a,l),oh(u),Oo((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),Oo((()=>d>=0),s("The yield (%s) must be positive or null.",d.toString()));const g=$c.compute(a,l,u),p=$c.compute(a,c,u);return(100+$c.compute(c,l,u)*h*100)/(1+g*d)-p*h*100},isExported:!0},rd=.1,ad={description:s("Interest rate of an annuity investment."),args:[aa("number_of_periods (number)",s("The number of payments to be made.")),aa("payment_per_period (number)",s("The amount per period to be paid.")),aa("present_value (number)",s("The current value of the annuity.")),aa("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),aa("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period.")),aa("rate_guess (number, default=0.1)",s("An estimate for what the interest rate will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t,i,o=0,n=0,r=.1){o=o||0,n=n||0,r=r||rd;const a=_o(e),l=_o(t),c=Po(n)?1:0,h=_o(r);let d=_o(o),u=_o(i);rh(a),Oo((()=>[l,u,d].some((e=>e>0))&&[l,u,d].some((e=>e<0))),s("There must be both positive and negative values in [payment_amount, present_value, future_value].",a.toString())),Ch(h),d-=l*c,u+=l*c;return xh((e=>{const t=Math.pow(1+e,a);return d+u*t+l*((t-1)/e)}),(e=>{const t=Math.pow(1+e,a-1),i=Math.pow(1+e,a);return u*a*t+l*(a*t/e-(i-1)/e/e)}),h,40,1e-5)},isExported:!0},ld={description:s("Amount received at maturity for a security."),args:[aa("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),aa("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),aa("investment (number)",s("The amount invested (irrespective of face value of each security).")),aa("discount (number)",s("The discount rate of the security invested in.")),aa("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(_o(e)),r=Math.trunc(_o(t)),a=_o(i),l=_o(o),c=Math.trunc(_o(n));eh(s,r),oh(c),ph(a),mh(l);return a/(1-l*$c.compute(s,r,c))},isExported:!0},cd={description:s("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:[aa("number_of_periods (number)",s("The number of periods.")),aa("present_value (number)",s("The present value of the investment.")),aa("future_value (number)",s("The future value of the investment."))],returns:["NUMBER"],compute:function(e,t,i){const o=_o(e),n=_o(t),s=_o(i);return rh(o),(s/n)**(1/o)-1},isExported:!0},hd={description:s("Depreciation of an asset using the straight-line method."),args:[aa("cost (number)",s("The initial cost of the asset.")),aa("salvage (number)",s("The value of the asset at the end of depreciation.")),aa("life (number)",s("The number of periods over which the asset is depreciated."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i){return(_o(e)-_o(t))/_o(i)},isExported:!0},dd={description:s("Depreciation via sum of years digit method."),args:[aa("cost (number)",s("The initial cost of the asset.")),aa("salvage (number)",s("The value of the asset at the end of depreciation.")),aa("life (number)",s("The number of periods over which the asset is depreciated.")),aa("period (number)",s("The single period within life for which to calculate depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o){const n=_o(e),s=_o(t),r=_o(i),a=_o(o);hh(a),lh(r),gh(a,r);return(r-a+1)/(r*(r+1)/2)*(n-s)},isExported:!0},ud={description:s("Price of a US Treasury bill."),args:[aa("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),aa("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),aa("discount (number)",s("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,i){const o=Math.trunc(_o(e)),n=Math.trunc(_o(t)),s=_o(i);eh(o,n),bh(o,n),mh(s),fh(s);return 100*(1-s*$c.compute(o,n,2))},isExported:!0},gd={description:s("Equivalent rate of return for a US Treasury bill."),args:[aa("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),aa("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),aa("discount (number)",s("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,i){const o=Math.trunc(_o(e)),n=Math.trunc(_o(t)),s=_o(i);eh(o,n),bh(o,n),mh(s),fh(s);const r=wc.compute(n,o);if(r<=182)return 365*s/(360-s*r);const a=ud.compute(o,n,s)/100,l=r/(366===r?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},pd={description:s("The yield of a US Treasury bill based on price."),args:[aa("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),aa("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),aa("price (number)",s("The price at which the security is bought per 100 face value."))],returns:["NUMBER"],compute:function(e,t,i){const o=Math.trunc(_o(e)),n=Math.trunc(_o(t)),s=_o(i);eh(o,n),bh(o,n),sh(s);return(100-s)/s*(1/$c.compute(o,n,2))},isExported:!0},md={description:s("Variable declining balance. WARNING : does not handle decimal periods."),args:[aa("cost (number)",s("The initial cost of the asset.")),aa("salvage (number)",s("The value of the asset at the end of depreciation.")),aa("life (number)",s("The number of periods over which the asset is depreciated.")),aa("start (number)",s("Starting period to calculate depreciation.")),aa("end (number)",s("Ending period to calculate depreciation.")),aa("factor (number, default=2)",s("The number of months in the first year of depreciation.")),aa("no_switch (number, default=false)",s("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r=2,a=false){r=r||0;const l=_o(e),c=_o(t),h=_o(i),d=Math.trunc(_o(o)),u=Math.trunc(_o(n)),g=_o(r),p=Po(a);if(ch(l),dh(c),function(e,t,i){lh(i),Oo((()=>e>=0),s("The start_period (%s) must be greater or equal than 0.",e.toString())),Oo((()=>t>=0),s("The end_period (%s) must be greater or equal than 0.",t.toString())),Oo((()=>e<=t),s("The start_period (%s) must be smaller or equal to the end_period (%s).",e.toString(),t.toString())),Oo((()=>t<=i),s("The end_period (%s) must be smaller or equal to the life (%s).",e.toString(),i.toString()))}(d,u,h),vh(g),0===l)return 0;if(c>=l)return d<1?l-c:0;const m=g/h;if(m>=1)return d<1?l-c:0;let f=l,v=0,b=0,S=!1;for(let e=0;e<u;e++){if(!S||p){const t=f*m,i=(f-c)/(h-e);!p&&i>t?(S=!0,v=i):v=t}const t=Math.max(f-v,c);e>=d&&(b+=f-t),f=t}return b},isExported:!0},fd={description:s("Internal rate of return given non-periodic cash flows."),args:[aa("cashflow_amounts (range<number>)",s("An range containing the income or payments associated with the investment.")),aa("cashflow_dates (range<number>)",s("An range with dates corresponding to the cash flows in cashflow_amounts.")),aa("rate_guess (number, default=0.1)",s("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],compute:function(e,t,i=.1){const o=_o(i=i||0),n=e.flat().map(_o),r=t.flat().map(_o);var a;Eh(e,t),a=n,Oo((()=>a.some((e=>e>0))&&a.some((e=>e<0))),s("There must be both positive and negative values in cashflow_amounts.")),wh(r),Ch(o);const l=new Map;for(const e of ze(0,r.length)){const t=r[e];l.has(t)?l.set(t,l.get(t)+n[e]):l.set(t,n[e])}const c=Array.from(l.keys()),h=c.map((e=>l.get(e)));return xh((e=>{let t=h[0];for(const i of ze(1,h.length)){const o=(c[0]-c[i])/365;t+=h[i]*(1+e)**o}return t}),(e=>{let t=0;for(const i of ze(1,h.length)){const o=(c[0]-c[i])/365;t+=o*h[i]*(1+e)**(o-1)}return t}),o,40,1e-5,(e=>e?e/10-.9:-.9))},isExported:!0},vd={description:s("Net present value given to non-periodic cash flows.."),args:[aa("discount (number)",s("The discount rate of the investment over one period.")),aa("cashflow_amounts (number, range<number>)",s("An range containing the income or payments associated with the investment.")),aa("cashflow_dates (number, range<number>)",s("An range with dates corresponding to the cash flows in cashflow_amounts."))],returns:["NUMBER"],compute:function(e,t,i){const o=_o(e),n=Array.isArray(t)?t.flat().map(Fo):[Fo(t)],r=Array.isArray(i)?i.flat().map(Fo):[Fo(i)];if(Array.isArray(i)&&Array.isArray(t)?Eh(t,i):Oo((()=>n.length===r.length),s("There must be the same number of values in cashflow_amounts and cashflow_dates.")),wh(r),ah(o),1===n.length)return n[0];const a=new Map;for(const e of ze(0,r.length)){const t=r[e];a.has(t)?a.set(t,a.get(t)+n[e]):a.set(t,n[e])}const l=Array.from(a.keys()),c=l.map((e=>a.get(e)));let h=c[0];for(const e of ze(1,c.length)){const t=(l[0]-l[e])/365;h+=c[e]*(1+o)**t}return h},isExported:!0},bd={description:s("Annual yield of a security paying periodic interest."),args:[aa("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),aa("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),aa("rate (number)",s("The annualized rate of interest.")),aa("price (number)",s("The price at which the security is bought per 100 face value.")),aa("redemption (number)",s("The redemption amount per 100 face value, or par.")),aa("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),aa("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r,a=0){a=a||0;const l=Math.trunc(_o(e)),c=Math.trunc(_o(t)),h=_o(i),d=_o(o),u=_o(n),g=Math.trunc(_o(r)),p=Math.trunc(_o(a));eh(l,c),ih(g),oh(p),Oo((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),sh(d),nh(u);const m=$c.compute(l,c,p)*g,f=Math.ceil(m),v=m-Math.floor(m)||1,b=100*h/g;if(1===f){const e=d+b*(1-v);return(u+b-e)*g*(1/v)/e}const S=xh((function(e){return function(e,t,i,o,n,s){let r=s-(e+n*(1-t))*o**(i-1+t);for(let e=1;e<=i;e++)r+=n*o**(e-1);return r}(d,v,f,e,b,u)}),(function(e){return function(e,t,i,o,n){let s=-(e+n*(1-t))*(i-1+t)*o**(i-2+t);for(let e=1;e<=i;e++)s+=n*(e-1)*o**(e-2);return s}(d,v,f,e,b)}),1+(h+1)/g,100,1e-5);return(S-1)*g},isExported:!0},Sd={description:s("Annual yield of a discount security."),args:[aa("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),aa("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),aa("price (number)",s("The price at which the security is bought per 100 face value.")),aa("redemption (number)",s("The redemption amount per 100 face value, or par.")),aa("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(_o(e)),r=Math.trunc(_o(t)),a=_o(i),l=_o(o),c=Math.trunc(_o(n));eh(s,r),oh(c),sh(a),nh(l);return(l/a-1)/$c.compute(e,t,n)},isExported:!0},Cd={description:s("Annual yield of a security paying interest at maturity."),args:[aa("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),aa("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),aa("issue (date)",s("The date the security was initially issued.")),aa("rate (number)",s("The annualized rate of interest.")),aa("price (number)",s("The price at which the security is bought.")),aa("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r=0){r=r||0;const a=Math.trunc(_o(e)),l=Math.trunc(_o(t)),c=Math.trunc(_o(i)),h=_o(o),d=_o(n),u=Math.trunc(_o(r));eh(a,l),oh(u),Oo((()=>a>=c),s("The settlement (%s) must be greater than or equal to the issue (%s).",a.toString(),c.toString())),Oo((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),sh(d);const g=$c.compute(c,l,u),p=$c.compute(c,a,u),m=$c.compute(a,l,u);return(100*(1+h*g)/(d+100*h*p)-1)/m},isExported:!0};var Ed=Object.freeze({__proto__:null,ACCRINTM:Ih,AMORLINC:Rh,COUPDAYS:Th,COUPDAYBS:Ah,COUPDAYSNC:Mh,COUPNCD:Oh,COUPNUM:Nh,COUPPCD:_h,CUMIPMT:Fh,CUMPRINC:Dh,DB:kh,DDB:Lh,DISC:Ph,DOLLARDE:Uh,DOLLARFR:Vh,DURATION:zh,EFFECT:Bh,FV:Hh,FVSCHEDULE:$h,INTRATE:Wh,IPMT:Gh,IRR:qh,ISPMT:Zh,MDURATION:jh,MIRR:Xh,NOMINAL:Yh,NPER:Kh,NPV:Qh,PDURATION:Jh,PMT:ed,PPMT:td,PV:id,PRICE:od,PRICEDISC:nd,PRICEMAT:sd,RATE:ad,RECEIVED:ld,RRI:cd,SLN:hd,SYD:dd,TBILLPRICE:ud,TBILLEQ:gd,TBILLYIELD:pd,VDB:md,XIRR:fd,XNPV:vd,YIELD:bd,YIELDDISC:Sd,YIELDMAT:Cd});const wd={description:s("Whether a value is an error other than #N/A."),args:[aa("value (any, lazy)",s("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return(null==e?void 0:e.errorType)!=a.NotAvailable}},isExported:!0},yd={description:s("Whether a value is an error."),args:[aa("value (any, lazy)",s("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},xd={description:s("Whether a value is `true` or `false`."),args:[aa("value (any, lazy)",s("The value to be verified as a logical TRUE or FALSE."))],returns:["BOOLEAN"],compute:function(e){try{return"boolean"==typeof e()}catch(e){return!1}},isExported:!0},Id={description:s("Whether a value is the error #N/A."),args:[aa("value (any, lazy)",s("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return(null==e?void 0:e.errorType)==a.NotAvailable}},isExported:!0},Rd={description:s("Whether a value is non-textual."),args:[aa("value (any, lazy)",s("The value to be checked."))],returns:["BOOLEAN"],compute:function(e){try{return"string"!=typeof e()}catch(e){return!0}},isExported:!0},Td={description:s("Whether a value is a number."),args:[aa("value (any, lazy)",s("The value to be verified as a number."))],returns:["BOOLEAN"],compute:function(e){try{return"number"==typeof e()}catch(e){return!1}},isExported:!0},Ad={description:s("Whether a value is text."),args:[aa("value (any, lazy)",s("The value to be verified as text."))],returns:["BOOLEAN"],compute:function(e){try{return"string"==typeof e()}catch(e){return!1}},isExported:!0},Md={description:s("Whether the referenced cell is empty"),args:[aa("value (any, lazy)",s("Reference to the cell that will be checked for emptiness."))],returns:["BOOLEAN"],compute:function(e){try{return null===e()}catch(e){return!1}},isExported:!0},Od={description:s("Returns the error value #N/A."),args:[],returns:["BOOLEAN"],compute:function(e){throw new g},isExported:!0};var Nd=Object.freeze({__proto__:null,ISERR:wd,ISERROR:yd,ISLOGICAL:xd,ISNA:Id,ISNONTEXT:Rd,ISNUMBER:Td,ISTEXT:Ad,ISBLANK:Md,NA:Od});const _d={description:s("Logical `and` operator."),args:[aa("logical_expression1 (boolean, range<boolean>)",s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),aa("logical_expression2 (boolean, range<boolean>, repeating)",s("More expressions that represent logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!0;return qo(e,(e=>(t=!0,i=i&&e,i))),Oo((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0},Fd={description:s("Returns value depending on logical expression."),args:[aa("logical_expression (boolean)",s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")),aa("value_if_true (any, lazy)",s("The value the function returns if logical_expression is TRUE.")),aa("value_if_false (any, lazy, default=FALSE)",s("The value the function returns if logical_expression is FALSE."))],returns:["ANY"],compute:function(e,t,i=(()=>!1)){const o=Po(e)?t():i();return null==o?"":o},isExported:!0},Dd={description:s("Value if it is not an error, otherwise 2nd argument."),args:[aa("value (any, lazy)",s("The value to return if value itself is not an error.")),aa('value_if_error (any, lazy, default="empty")',s("The value the function returns if value is an error."))],returns:["ANY"],computeFormat:(e,t=(()=>({value:""})))=>{var i;try{return e().format}catch(e){return null===(i=t())||void 0===i?void 0:i.format}},compute:function(e,t=(()=>"")){let i;try{i=e()}catch(e){i=t()}return null==i?"":i},isExported:!0},kd={description:s("Value if it is not an #N/A error, otherwise 2nd argument."),args:[aa("value (any, lazy)",s("The value to return if value itself is not #N/A an error.")),aa('value_if_error (any, lazy, default="empty")',s("The value the function returns if value is an #N/A error."))],returns:["ANY"],compute:function(e,t=(()=>"")){let i;try{i=e()}catch(o){i=o.errorType===a.NotAvailable?t():e()}return null==i?"":i},isExported:!0},Ld={description:s("Returns a value depending on multiple logical expressions."),args:[aa("condition1 (boolean, lazy)",s("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")),aa("value1 (any, lazy)",s("The returned value if condition1 is TRUE.")),aa("condition2 (boolean, lazy, repeating)",s("Additional conditions to be evaluated if the previous ones are FALSE.")),aa("value2 (any, lazy, repeating)",s("Additional values to be returned if their corresponding conditions are TRUE."))],returns:["ANY"],compute:function(...e){Oo((()=>e.length%2==0),s("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(Po(e[t]())){const i=e[t+1]();return null!==i?i:""}throw new Error(s("No match."))},isExported:!0},Pd={description:s("Returns opposite of provided logical value."),args:[aa("logical_expression (boolean)",s("An expression or reference to a cell holding an expression that represents some logical value."))],returns:["BOOLEAN"],compute:function(e){return!Po(e)},isExported:!0},Ud={description:s("Logical `or` operator."),args:[aa("logical_expression1 (boolean, range<boolean>)",s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),aa("logical_expression2 (boolean, range<boolean>, repeating)",s("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!1;return qo(e,(e=>(t=!0,i=i||e,!i))),Oo((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0},Vd={description:s("Logical `xor` operator."),args:[aa("logical_expression1 (boolean, range<boolean>)",s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),aa("logical_expression2 (boolean, range<boolean>, repeating)",s("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!1;return qo(e,(e=>(t=!0,i=i?!e:e,!0))),Oo((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0};var zd=Object.freeze({__proto__:null,AND:_d,IF:Fd,IFERROR:Dd,IFNA:kd,IFS:Ld,NOT:Pd,OR:Ud,XOR:Vd});function Bd(e,t){if(void 0===e)throw new g(s("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",Do(t)))}const Hd={description:s("Column number of a specified cell."),args:[aa("cell_reference (meta, default='this cell')",s("The cell whose column number will be returned. Column A corresponds to 1. By default, the function use the cell in which the formula is entered."))],returns:["NUMBER"],compute:function(e){var t;const i=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this));Oo((()=>!!i),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Li(i).left+1},isExported:!0},$d={description:s("Number of columns in a specified array or range."),args:[aa("range (meta)",s("The range whose column count will be returned."))],returns:["NUMBER"],compute:function(e){const t=Li(e);return t.right-t.left+1},isExported:!0},Wd={description:s("Horizontal lookup"),args:[aa("search_key (any)",s("The value to search for. For example, 42, 'Cats', or I24.")),aa("range (range)",s("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")),aa("index (number)",s("The row index of the value to be returned, where the first row in range is numbered 1.")),aa("is_sorted (boolean, default=true)",s("Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned."))],returns:["ANY"],compute:function(e,t,i,o=true){const n=Math.trunc(_o(i)),r=ko(e);Oo((()=>1<=n&&n<=t[0].length),s("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=Po(o)?Qo(t,r,"nextSmaller","asc",t.length,Ko):Jo(t,r,"strict",t.length,Ko);const l=t[a];return Bd(l,e),l[n-1]},isExported:!0},Gd={description:s("Look up a value."),args:[aa("search_key (any)",s("The value to search for. For example, 42, 'Cats', or I24.")),aa("search_array (range)",s("One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.")),aa("result_range (range, optional)",s("The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method."))],returns:["ANY"],compute:function(e,t,i){let o=t.length,n=t[0].length;const r=ko(e),a=n>=o,l=Qo(t,r,"nextSmaller","asc",a?n:o,a?Yo:Ko);return-1===l&&Bd(void 0,e),Bd(a?t[0][l]:t[l][n-1],e),void 0===i?a?t[o-1][l]:t[l][n-1]:(o=i.length,n=i[0].length,Oo((()=>1===o||1===n),s("The result_range must be a single row or a single column.")),o>1?(Oo((()=>l<=o-1),s("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(l+1).toString())),i[l][0]):(Oo((()=>l<=n-1),s("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(l+1).toString())),i[0][l]))},isExported:!0},qd={description:s("Position of item in range that matches value."),args:[aa("search_key (any)",s("The value to search for. For example, 42, 'Cats', or I24.")),aa("range (any, range)",s("The one-dimensional array to be searched.")),aa("search_type (number, default=1)",s("The search method. 1 (default) finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order."))],returns:["NUMBER"],compute:function(e,t,i=1){let o=_o(i);const n=ko(e),r=t.length,a=t[0].length;Oo((()=>1===r||1===a),s("The range must be a single row or a single column."));let l=-1;const c=1===r?Yo:Ko,h=1===r?t[0].length:t.length;switch(o=Math.sign(o),o){case 1:l=Qo(t,n,"nextSmaller","asc",h,c);break;case 0:l=Jo(t,n,"strict",h,c);break;case-1:l=Qo(t,n,"nextGreater","desc",h,c)}return Bd(1===r?t[0][l]:t[l],e),l+1},isExported:!0},Zd={description:s("Row number of a specified cell."),args:[aa("cell_reference (meta, default='this cell')",s("The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered."))],returns:["NUMBER"],compute:function(e){var t;e=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this)),Oo((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Li(e).top+1},isExported:!0},jd={description:s("Number of rows in a specified array or range."),args:[aa("range (meta)",s("The range whose row count will be returned."))],returns:["NUMBER"],compute:function(e){const t=Li(e);return t.bottom-t.top+1},isExported:!0},Xd={description:s("Vertical lookup."),args:[aa("search_key (any)",s("The value to search for. For example, 42, 'Cats', or I24.")),aa("range (any, range)",s("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")),aa("index (number)",s("The column index of the value to be returned, where the first column in range is numbered 1.")),aa("is_sorted (boolean, default=true)",s("Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned."))],returns:["ANY"],compute:function(e,t,i,o=true){const n=Math.trunc(_o(i)),r=ko(e);Oo((()=>1<=n&&n<=t.length),s("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=Po(o)?Qo(t,r,"nextSmaller","asc",t[0].length,Yo):Jo(t,r,"strict",t[0].length,Yo);const l=t[n-1][a];return Bd(l,e),l},isExported:!0},Yd={description:s("Search a range for a match and return the corresponding item from a second range."),args:[aa("search_key (any)",s("The value to search for.")),aa("lookup_range (any, range)",s("The range to consider for the search. Should be a single column or a single row.")),aa("return_range (any, range)",s("The range containing the return value. Should have the same dimensions as lookup_range.")),aa("if_not_found (any, lazy, optional)",s("If a valid match is not found, return this value.")),aa("match_mode (any, default=0)",s("(0) Exact match. (-1) Return next smaller item if no match. (1) Return next greater item if no match.")),aa("search_mode (any, default=1)",s("(1) Search starting at first item. (-1) Search starting at last item. (2) Perform a binary search that relies on lookup_array being sorted in ascending order. If not sorted, invalid results will be returned. (-2) Perform a binary search that relies on lookup_array being sorted in descending order. If not sorted, invalid results will be returned. "))],returns:["ANY"],compute:function(e,t,i,o,n=0,r=1){const a=Math.trunc(_o(n)),l=Math.trunc(_o(r)),c=ko(e);Oo((()=>1===t.length||1===t[0].length),s("lookup_range should be either a single row or single column.")),Oo((()=>1===i.length||1===i[0].length),s("return_range should be either a single row or single column.")),Oo((()=>i.length===t.length&&i[0].length===t[0].length),s("return_range should have the same dimensions as lookup_range.")),Oo((()=>[-1,1,-2,2].includes(l)),s("searchMode should be a value in [-1, 1, -2, 2].")),Oo((()=>[-1,0,1].includes(a)),s("matchMode should be a value in [-1, 0, 1]."));const h=1===t.length?Yo:Ko,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=Qo(t,c,u,2===l?"asc":"desc",d,h)}else p=Jo(t,c,u,d,h,g);if(-1!==p)return 1===t.length?i[0][p]:i[p][0];const m=null==o?void 0:o();return Bd(m,e),m},isExported:!0};var Kd=Object.freeze({__proto__:null,COLUMN:Hd,COLUMNS:$d,HLOOKUP:Wd,LOOKUP:Gd,MATCH:qd,ROW:Zd,ROWS:jd,VLOOKUP:Xd,XLOOKUP:Yd});const Qd={description:s("Sum of two numbers."),args:[aa("value1 (number)",s("The first addend.")),aa("value2 (number)",s("The second addend."))],returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return _o(e)+_o(t)}},Jd={description:s("Concatenation of two values."),args:[aa("value1 (string)",s("The value to which value2 will be appended.")),aa("value2 (string)",s("The value to append to value1."))],returns:["STRING"],compute:function(e,t){return Do(e)+Do(t)},isExported:!0},eu={description:s("One number divided by another."),args:[aa("dividend (number)",s("The number to be divided.")),aa("divisor (number)",s("The number to divide by."))],returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){const i=_o(t);return Oo((()=>0!==i),s("The divisor must be different from zero.")),_o(e)/i}};function tu(e){return null==e}const iu={number:0,string:"",boolean:!1},ou={description:s("Equal."),args:[aa("value1 (any)",s("The first value.")),aa("value2 (any)",s("The value to test against value1 for equality."))],returns:["BOOLEAN"],compute:function(e,t){return e=tu(e)?iu[typeof t]:e,t=tu(t)?iu[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function nu(e,t,i){e=tu(e)?iu[typeof t]:e,t=tu(t)?iu[typeof e]:t,"number"!=typeof e&&(e=Do(e).toUpperCase()),"number"!=typeof t&&(t=Do(t).toUpperCase());const o=typeof e,n=typeof t;return"string"===o&&"number"===n||("string"!==n||"number"!==o)&&i(e,t)}const su={description:s("Strictly greater than."),args:[aa("value1 (any)",s("The value to test as being greater than value2.")),aa("value2 (any)",s("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return nu(e,t,((e,t)=>e>t))}},ru={description:s("Greater than or equal to."),args:[aa("value1 (any)",s("The value to test as being greater than or equal to value2.")),aa("value2 (any)",s("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return nu(e,t,((e,t)=>e>=t))}},au={description:s("Less than."),args:[aa("value1 (any)",s("The value to test as being less than value2.")),aa("value2 (any)",s("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!ru.compute(e,t)}},lu={description:s("Less than or equal to."),args:[aa("value1 (any)",s("The value to test as being less than or equal to value2.")),aa("value2 (any)",s("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!su.compute(e,t)}},cu={description:s("Difference of two numbers."),args:[aa("value1 (number)",s("The minuend, or number to be subtracted from.")),aa("value2 (number)",s("The subtrahend, or number to subtract from value1."))],returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return _o(e)-_o(t)}},hu={description:s("Product of two numbers"),args:[aa("factor1 (number)",s("The first multiplicand.")),aa("factor2 (number)",s("The second multiplicand."))],returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return _o(e)*_o(t)}},du={description:s("Not equal."),args:[aa("value1 (any)",s("The first value.")),aa("value2 (any)",s("The value to test against value1 for inequality."))],returns:["BOOLEAN"],compute:function(e,t){return!ou.compute(e,t)}},uu={description:s("A number raised to a power."),args:[aa("base (number)",s("The number to raise to the exponent power.")),aa("exponent (number)",s("The exponent to raise base to."))],returns:["NUMBER"],compute:function(e,t){return Xa.compute(e,t)}},gu={description:s("A number with the sign reversed."),args:[aa("value (number)",s("The number to have its sign reversed. Equivalently, the number to multiply by -1."))],computeFormat:e=>null==e?void 0:e.format,returns:["NUMBER"],compute:function(e){return-_o(e)}},pu={description:s("Value interpreted as a percentage."),args:[aa("percentage (number)",s("The value to interpret as a percentage."))],returns:["NUMBER"],compute:function(e){return _o(e)/100}},mu={description:s("A specified number, unchanged."),args:[aa("value (any)",s("The number to return."))],returns:["ANY"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){return null===e?"":e}};var fu=Object.freeze({__proto__:null,ADD:Qd,CONCAT:Jd,DIVIDE:eu,EQ:ou,GT:su,GTE:ru,LT:au,LTE:lu,MINUS:cu,MULTIPLY:hu,NE:du,POW:uu,UMINUS:gu,UNARY_PERCENT:pu,UPLUS:mu});const vu=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,bu={description:s("Gets character associated with number."),args:[aa("table_number (number)",s("The number of the character to look up from the current Unicode table in decimal format."))],returns:["STRING"],compute:function(e){const t=Math.trunc(_o(e));return Oo((()=>t>=1),s("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},Su={description:s("Remove non-printable characters from a piece of text."),args:[aa("text (string)",s("The text whose non-printable characters are to be removed."))],returns:["STRING"],compute:function(e){const t=Do(e);let i="";for(const e of t)e&&e.charCodeAt(0)>31&&(i+=e);return i},isExported:!0},Cu={description:s("Appends strings to one another."),args:[aa("string1 (string, range<string>)",s("The initial string.")),aa("string2 (string, range<string>, repeating)",s("More strings to append in sequence."))],returns:["STRING"],compute:function(...e){return $o(e,((e,t)=>e+Do(t)),"")},isExported:!0},Eu={description:s("Tests whether two strings are identical."),args:[aa("string1 (string)",s("The first string to compare.")),aa("string2 (string)",s("The second string to compare."))],returns:["BOOLEAN"],compute:function(e,t){return Do(e)===Do(t)},isExported:!0},wu={description:s("First position of string found in text, case-sensitive."),args:[aa("search_for (string)",s("The string to look for within text_to_search.")),aa("text_to_search (string)",s("The text to search for the first occurrence of search_for.")),aa("starting_at (number, default=1)",s("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,i=1){const o=Do(e),n=Do(t),r=_o(i);Oo((()=>""!==n),s("The text_to_search must be non-empty.")),Oo((()=>r>=1),s("The starting_at (%s) must be greater than or equal to 1.",r.toString()));const a=n.indexOf(o,r-1);return Oo((()=>a>=0),s("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o.toString(),n)),a+1},isExported:!0},yu={description:s("Concatenates elements of arrays with delimiter."),args:[aa("delimiter (string)",s("The character or string to place between each concatenated value.")),aa("value_or_array1 (string, range<string>)",s("The value or values to be appended using delimiter.")),aa("value_or_array2 (string, range<string>, repeating)",s("More values to be appended using delimiter."))],returns:["STRING"],compute:function(e,...t){const i=Do(e);return $o(t,((e,t)=>(e?e+i:"")+Do(t)),"")}},xu={description:s("Substring from beginning of specified string."),args:[aa("text (string)",s("The string from which the left portion will be returned.")),aa("number_of_characters (number, optional)",s("The number of characters to return from the left side of string."))],returns:["STRING"],compute:function(e,...t){const i=t.length?_o(t[0]):1;return Oo((()=>i>=0),s("The number_of_characters (%s) must be positive or null.",i.toString())),Do(e).substring(0,i)},isExported:!0},Iu={description:s("Length of a string."),args:[aa("text (string)",s("The string whose length will be returned."))],returns:["NUMBER"],compute:function(e){return Do(e).length},isExported:!0},Ru={description:s("Converts a specified string to lowercase."),args:[aa("text (string)",s("The string to convert to lowercase."))],returns:["STRING"],compute:function(e){return Do(e).toLowerCase()},isExported:!0},Tu={description:s("A segment of a string."),args:[aa("text (string)",s("The string to extract a segment from.")),aa(" (number)",s("The index from the left of string from which to begin extracting. The first character in string has the index 1.")),aa(" (number)",s("The length of the segment to extract."))],returns:["STRING"],compute:function(e,t,i){const o=Do(e),n=_o(t),r=_o(i);return Oo((()=>n>=1),s("The starting_at argument (%s) must be positive greater than one.",n.toString())),Oo((()=>r>=0),s("The extract_length argument (%s) must be positive or null.",r.toString())),o.slice(n-1,n+r-1)},isExported:!0},Au={description:s("Capitalizes each word in a specified string."),args:[aa("text_to_capitalize (string)",s("The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase."))],returns:["STRING"],compute:function(e){return Do(e).replace(vu,(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()))},isExported:!0},Mu={description:s("Replaces part of a text string with different text."),args:[aa("text (string)",s("The text, a part of which will be replaced.")),aa("position (number)",s("The position where the replacement will begin (starting from 1).")),aa("length (number)",s("The number of characters in the text to be replaced.")),aa("new_text (string)",s("The text which will be inserted into the original text."))],returns:["STRING"],compute:function(e,t,i,o){const n=_o(t);Oo((()=>n>=1),s("The position (%s) must be greater than or equal to 1.",n.toString()));const r=Do(e),a=_o(i),l=Do(o);return r.substring(0,n-1)+l+r.substring(n-1+a)},isExported:!0},Ou={description:s("A substring from the end of a specified string."),args:[aa("text (string)",s("The string from which the right portion will be returned.")),aa("number_of_characters (number, optional)",s("The number of characters to return from the right side of string."))],returns:["STRING"],compute:function(e,...t){const i=t.length?_o(t[0]):1;Oo((()=>i>=0),s("The number_of_characters (%s) must be positive or null.",i.toString()));const o=Do(e),n=o.length;return o.substring(n-i,n)},isExported:!0},Nu={description:s("First position of string found in text, ignoring case."),args:[aa("search_for (string)",s("The string to look for within text_to_search.")),aa("text_to_search (string)",s("The text to search for the first occurrence of search_for.")),aa("starting_at (number, default=1)",s("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,i=1){const o=Do(e).toLowerCase(),n=Do(t).toLowerCase(),r=_o(i);Oo((()=>""!==n),s("The text_to_search must be non-empty.")),Oo((()=>r>=1),s("The starting_at (%s) must be greater than or equal to 1.",r.toString()));const a=n.indexOf(o,r-1);return Oo((()=>a>=0),s("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o,n)),a+1},isExported:!0},_u={description:s("Replaces existing text with new text in a string."),args:[aa("text_to_search (string)",s("The text within which to search and replace.")),aa("search_for (string)",s("The string to search for within text_to_search.")),aa("replace_with (string)",s("The string that will replace search_for.")),aa("occurrence_number (number, optional)",s("The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced."))],returns:["NUMBER"],compute:function(e,t,i,o){const n=_o(o);Oo((()=>n>=0),s("The occurrenceNumber (%s) must be positive or null.",n.toString()));const r=Do(e),a=Do(t);if(""===a)return r;const l=Do(i),c=new RegExp(Oe(a),"g");if(0===n)return r.replace(c,l);let h=0;return r.replace(c,(e=>++h===n?l:e))},isExported:!0},Fu={description:s("Combines text from multiple strings and/or arrays."),args:[aa("delimiter (string)",s(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")),aa("ignore_empty (boolean)",s("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")),aa("text1 (string, range<string>)",s("Any text item. This could be a string, or an array of strings in a range.")),aa("text2 (string, range<string>, repeating)",s("Additional text item(s)."))],returns:["STRING"],compute:function(e,t,...i){const o=Do(e),n=Po(t);let s=0;return $o(i,((e,t)=>n&&""===Do(t)?e:(s++?e+o:"")+Do(t)),"")},isExported:!0},Du={description:s("Removes space characters."),args:[aa("text (string)",s("The text or reference to a cell containing text to be trimmed."))],returns:["STRING"],compute:function(e){return Do(e).trim()},isExported:!0},ku={description:s("Converts a specified string to uppercase."),args:[aa("text (string)",s("The string to convert to uppercase."))],returns:["STRING"],compute:function(e){return Do(e).toUpperCase()},isExported:!0},Lu={description:s("Converts a number to text according to a specified format."),args:[aa("number (number)",s("The number, date or time to format.")),aa("format (string)",s("The pattern by which to format the number, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){return hi(_o(e),Do(t))},isExported:!0};var Pu=Object.freeze({__proto__:null,CHAR:bu,CLEAN:Su,CONCATENATE:Cu,EXACT:Eu,FIND:wu,JOIN:yu,LEFT:xu,LEN:Iu,LOWER:Ru,MID:Tu,PROPER:Au,REPLACE:Mu,RIGHT:Ou,SEARCH:Nu,SUBSTITUTE:_u,TEXTJOIN:Fu,TRIM:Du,UPPER:ku,TEXT:Lu});const Uu={description:s("Creates a hyperlink in a cell."),args:[aa("url (string)",s("The full URL of the link enclosed in quotation marks.")),aa("link_label (string, optional)",s("The text to display in the cell, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){const i=Do(e).trim(),o=Do(t)||i;return""===i?o:je(o,i)},isExported:!0};var Vu=Object.freeze({__proto__:null,HYPERLINK:Uu});const zu=[{name:s("Database"),functions:bc},{name:s("Date"),functions:Kc},{name:s("Financial"),functions:Ed},{name:s("Info"),functions:Nd},{name:s("Lookup"),functions:Kd},{name:s("Logical"),functions:zd},{name:s("Math"),functions:gl},{name:s("Misc"),functions:ha},{name:s("Operator"),functions:fu},{name:s("Statistical"),functions:oc},{name:s("Text"),functions:Pu},{name:s("Engineering"),functions:Jc},{name:s("Web"),functions:Vu}],Bu=/^[A-Z0-9\_\.]+$/;function Hu(e){return e.map((e=>{if(void 0!==e)return"function"==typeof e?()=>$u(e()):$u(e)}))}function $u(e){return Array.isArray(e)?e.map((e=>e.map((e=>null==e?void 0:e.value)))):null==e?void 0:e.value}const Wu=new class extends Co{constructor(){super(...arguments),this.mapping={}}add(e,t){if(!(e=e.toUpperCase()).match(Bu))throw new Error(s("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const i=la(t);return function(e){let t=!1,i=!1,o=!1;for(let n of e){if(n.type.includes("META")&&n.type.length>1)throw new Error(s("Function ${name} has an argument that has been declared with more than one type whose type 'META'. The 'META' type can only be declared alone."));if(t&&!n.repeating)throw new Error(s("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=i||t||o,r=!(n.optional||n.repeating||n.default);if(e&&r)throw new Error(s("Function ${name} has at mandatory arguments declared after optional ones. All optional arguments must be after all mandatory arguments."));t=n.repeating,i=n.optional,o=n.default}}(i.args),this.mapping[e]=function(...e){const t=i.compute.bind(this),o=i.computeFormat?i.computeFormat.bind(this):()=>{};return{value:t(...Hu(e)),format:o(...e)}},super.add(e,i),this}};for(let e of zu){const t=e.functions;for(let i in t){const o=t[i];o.category=o.category||e.name,i=i.replace(/_/g,"."),Wu.add(i,{isExported:!1,...o})}}function Gu(e,t,i){const o=e.model.getters.getActiveSheetId(),n="COL"===t?"FREEZE_COLUMNS":"FREEZE_ROWS";e.model.dispatch(n,{sheetId:o,quantity:i}).isCancelledBecause(65)&&e.raiseError(Ts)}const qu=new Qn;qu.add("file",{name:s("File"),sequence:10}).add("edit",{name:s("Edit"),sequence:20}).add("view",{name:s("View"),sequence:30}).add("insert",{name:s("Insert"),sequence:40}).add("format",{name:s("Format"),sequence:50}).add("data",{name:s("Data"),sequence:60}).addChild("save",["file"],{name:s("Save"),description:"Ctrl+S",sequence:10,action:()=>console.log("Not implemented")}).addChild("undo",["edit"],{name:s("Undo"),description:"Ctrl+Z",sequence:10,action:e=>e.model.dispatch("REQUEST_UNDO")}).addChild("redo",["edit"],{name:s("Redo"),description:"Ctrl+Y",sequence:20,action:e=>e.model.dispatch("REQUEST_REDO"),separator:!0}).addChild("copy",["edit"],{name:s("Copy"),description:"Ctrl+C",sequence:30,isReadonlyAllowed:!0,action:Nr}).addChild("cut",["edit"],{name:s("Cut"),description:"Ctrl+X",sequence:40,action:_r}).addChild("paste",["edit"],{name:s("Paste"),description:"Ctrl+V",sequence:50,action:Fr}).addChild("paste_special",["edit"],{name:s("Paste special"),sequence:60,separator:!0,isVisible:Pr}).addChild("paste_special_value",["edit","paste_special"],{name:s("Paste value only"),sequence:10,action:Dr}).addChild("paste_special_format",["edit","paste_special"],{name:s("Paste format only"),sequence:20,action:Lr}).addChild("sort_range",["data"],{name:s("Sort range"),sequence:20,isVisible:ta,separator:!0}).addChild("sort_ascending",["data","sort_range"],{name:s("Ascending (A ⟶ Z)"),sequence:10,action:Jr}).addChild("sort_descending",["data","sort_range"],{name:s("Descending (Z ⟶ A)"),sequence:20,action:ea}).addChild("find_and_replace",["edit"],{name:s("Find and replace"),description:"Ctrl+H",sequence:65,isReadonlyAllowed:!0,action:e=>{e.openSidePanel("FindAndReplace",{})},separator:!0}).addChild("edit_delete_cell_values",["edit"],{name:s("Delete values"),sequence:70,action:e=>e.model.dispatch("DELETE_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})}).addChild("edit_delete_row",["edit"],{name:Ur,sequence:80,action:Vr}).addChild("edit_delete_column",["edit"],{name:zr,sequence:90,action:Br}).addChild("edit_delete_cell_shift_up",["edit"],{name:s("Delete cell and shift up"),sequence:93,action:Wr}).addChild("edit_delete_cell_shift_left",["edit"],{name:s("Delete cell and shift left"),sequence:97,action:Gr}).addChild("edit_unhide_columns",["edit"],{name:s("Unhide all columns"),sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"COL",elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0}).addChild("edit_unhide_rows",["edit"],{name:s("Unhide all rows"),sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"ROW",elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0}).addChild("insert_row_before",["insert"],{name:e=>{const t=Ar(e);return 1===t?s("Row above"):s("%s Rows above",t.toString())},sequence:10,action:qr,isVisible:e=>0===e.model.getters.getActiveCols().size}).addChild("insert_row_after",["insert"],{name:e=>{const t=Ar(e);return 1===t?s("Row below"):s("%s Rows below",t.toString())},sequence:20,action:Zr,isVisible:e=>0===e.model.getters.getActiveCols().size,separator:!0}).addChild("insert_column_before",["insert"],{name:e=>{const t=Tr(e);return 1===t?s("Column left"):s("%s Columns left",t.toString())},sequence:30,action:jr,isVisible:e=>0===e.model.getters.getActiveRows().size}).addChild("insert_column_after",["insert"],{name:e=>{const t=Tr(e);return 1===t?s("Column right"):s("%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:s("Insert cells and shift down"),sequence:43,action:Hr}).addChild("insert_insert_cell_shift_right",["insert"],{name:s("Insert cells and shift right"),sequence:47,action:$r,separator:!0}).addChild("insert_chart",["insert"],{name:s("Chart"),sequence:50,action:e=>{const t=e.model.getters,i=e.model.uuidGenerator.uuidv4(),o=t.getActiveSheetId();1===so(e.model.getters.getSelectedZone())&&e.model.selection.selectTableAroundSelection();const n={width:536,height:335},s=function(e,t){const{x:i,y:o}=e.getMainViewportCoordinates(),{scrollX:n,scrollY:s}=e.getActiveSheetScrollInfo(),{width:r,height:a}=e.getVisibleRect(e.getActiveMainViewport());return{x:i+n+Math.max(0,(r-t.width)/2),y:o+s+Math.max(0,(a-t.height)/2)}}(t,n);e.model.dispatch("CREATE_CHART",{sheetId:o,id:i,position:s,size:n,definition:vr(e.model.getters.getSelectedZone(),e.model.getters)}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{id:i}),e.openSidePanel("ChartPanel"))}}).addChild("insert_image",["insert"],{name:s("Image"),sequence:55,action:async e=>{if(e.imageProvider){const t=e.model.getters.getActiveSheetId(),i=e.model.uuidGenerator.uuidv4(),o=await async function(e){try{return await e.imageProvider.requestImage()}catch{return void e.raiseError(s("An unexpected error occurred during the image transfer"))}}(e);if(!o)throw new Error("No image provider was given to the environment");const n=cr(e.model.getters,o.size),r=function(e,t){const{x:i,y:o}=e.getMainViewportCoordinates(),{scrollX:n,scrollY:s}=e.getActiveSheetScrollInfo(),r=e.getSheetViewDimension(),a=e.getVisibleRect(e.getActiveMainViewport()),l=Math.min(a.width,r.width-i),c=Math.min(a.height,r.height-o);return{x:i+n+Math.max(0,(l-t.width)/2),y:o+s+Math.max(0,(c-t.height)/2)}}(e.model.getters,n);e.model.dispatch("CREATE_IMAGE",{sheetId:t,figureId:i,position:r,size:n,definition:o})}},isVisible:e=>void 0!==e.imageProvider}).addChild("insert_function",["insert"],{name:s("Function"),sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{name:s("SUM"),action:e=>e.startCellEdition("=SUM("),sequence:0}).addChild("insert_function_average",["insert","insert_function"],{name:s("AVERAGE"),action:e=>e.startCellEdition("=AVERAGE("),sequence:10}).addChild("insert_function_count",["insert","insert_function"],{name:s("COUNT"),action:e=>e.startCellEdition("=COUNT("),sequence:20}).addChild("insert_function_max",["insert","insert_function"],{name:s("MAX"),action:e=>e.startCellEdition("=MAX("),sequence:30}).addChild("insert_function_min",["insert","insert_function"],{name:s("MIN"),action:e=>e.startCellEdition("=MIN("),sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{name:s("All"),sequence:50}).addChild("all_function_list",["insert","insert_function","categorie_function_all"],(()=>Zu(Wu.getKeys()))).addChild("categories_function_list",["insert","insert_function"],(()=>{const e=Wu.content;return[...new Set(Wu.getAll().map((e=>e.category)))].filter(et).sort().map(((t,i)=>{const o=Object.keys(e).filter((i=>e[i].category===t));return{name:t,sequence:60+10*i,children:Zu(o)}}))})).addChild("insert_link",["insert"],{name:s("Link"),separator:!0,sequence:70,action:Kr}).addChild("insert_sheet",["insert"],{name:s("New sheet"),sequence:80,action:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSheetIds().indexOf(t)+1,o=e.model.uuidGenerator.uuidv4();e.model.dispatch("CREATE_SHEET",{sheetId:o,position:i}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})},separator:!0}).addChild("unfreeze_panes",["view"],{name:s("Unfreeze"),sequence:4,isVisible:e=>{const{xSplit:t,ySplit:i}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+i>0},action:e=>e.model.dispatch("UNFREEZE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId()})}).addChild("freeze_panes",["view"],{name:s("Freeze"),sequence:5,separator:!0}).addChild("unfreeze_rows",["view","freeze_panes"],{name:s("No rows"),action:e=>e.model.dispatch("UNFREEZE_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,sequence:5,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit}).addChild("freeze_first_row",["view","freeze_panes"],{name:s("1 row"),action:e=>Gu(e,"ROW",1),isReadonlyAllowed:!0,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{name:s("2 rows"),action:e=>Gu(e,"ROW",2),isReadonlyAllowed:!0,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{name:s("Up to current row"),action:e=>{const{bottom:t}=e.model.getters.getSelectedZone();Gu(e,"ROW",t+1)},isReadonlyAllowed:!0,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{name:s("No columns"),action:e=>e.model.dispatch("UNFREEZE_COLUMNS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,sequence:25,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit}).addChild("freeze_first_col",["view","freeze_panes"],{name:s("1 column"),action:e=>Gu(e,"COL",1),isReadonlyAllowed:!0,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{name:s("2 columns"),action:e=>Gu(e,"COL",2),isReadonlyAllowed:!0,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{name:s("Up to current column"),action:e=>{const{right:t}=e.model.getters.getSelectedZone();Gu(e,"COL",t+1)},isReadonlyAllowed:!0,sequence:40}).addChild("view_gridlines",["view"],{name:e=>e.model.getters.getGridLinesVisibility(e.model.getters.getActiveSheetId())?s("Hide gridlines"):s("Show gridlines"),action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},sequence:10}).addChild("view_formulas",["view"],{name:e=>e.model.getters.shouldShowFormulas()?s("Hide formulas"):s("Show formulas"),action:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,sequence:15}).addChild("format_number",["format"],{name:s("Numbers"),sequence:10,separator:!0}).addChild("format_number_automatic",["format","format_number"],{name:Is.Automatic,sequence:10,separator:!0,action:e=>Mr(e,"")}).addChild("format_number_number",["format","format_number"],{name:Is.Number,description:"1,000.12",sequence:20,action:e=>Mr(e,"#,##0.00")}).addChild("format_number_percent",["format","format_number"],{name:Is.Percent,description:"10.12%",sequence:30,separator:!0,action:e=>Mr(e,"0.00%")}).addChild("format_number_currency",["format","format_number"],{name:Is.Currency,description:"$1,000.12",sequence:37,action:e=>Mr(e,"[$$]#,##0.00")}).addChild("format_number_currency_rounded",["format","format_number"],{name:Is.CurrencyRounded,description:"$1,000",sequence:38,action:e=>Mr(e,"[$$]#,##0")}).addChild("format_custom_currency",["format","format_number"],{name:Is.CustomCurrency,sequence:39,separator:!0,isVisible:e=>void 0!==e.loadCurrencies,action:e=>{e.openSidePanel("CustomCurrency",{})}}).addChild("format_number_date",["format","format_number"],{name:Is.Date,description:"9/26/2008",sequence:40,action:e=>Mr(e,"m/d/yyyy")}).addChild("format_number_time",["format","format_number"],{name:Is.Time,description:"10:43:00 PM",sequence:50,action:e=>Mr(e,"hh:mm:ss a")}).addChild("format_number_date_time",["format","format_number"],{name:Is.DateTime,description:"9/26/2008 22:43:00",sequence:60,action:e=>Mr(e,"m/d/yyyy hh:mm:ss")}).addChild("format_number_duration",["format","format_number"],{name:Is.Duration,description:"27:51:38",sequence:70,separator:!0,action:e=>Mr(e,"hhhh:mm:ss")}).addChild("format_bold",["format"],{name:s("Bold"),sequence:20,description:"Ctrl+B",action:e=>Or(e,{bold:!e.model.getters.getCurrentStyle().bold})}).addChild("format_italic",["format"],{name:s("Italic"),sequence:30,description:"Ctrl+I",action:e=>Or(e,{italic:!e.model.getters.getCurrentStyle().italic})}).addChild("format_underline",["format"],{name:s("Underline"),description:"Ctrl+U",sequence:40,action:e=>Or(e,{underline:!e.model.getters.getCurrentStyle().underline})}).addChild("format_strikethrough",["format"],{name:s("Strikethrough"),sequence:50,action:e=>Or(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),separator:!0}).addChild("format_font_size",["format"],{name:s("Font size"),sequence:60,separator:!0}).addChild("format_alignment",["format"],{name:s("Alignment"),sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{name:"Left",sequence:10,action:e=>Or(e,{align:"left"})}).addChild("format_alignment_center",["format","format_alignment"],{name:"Center",sequence:20,action:e=>Or(e,{align:"center"})}).addChild("format_alignment_right",["format","format_alignment"],{name:"Right",sequence:30,action:e=>Or(e,{align:"right"}),separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{name:"Top",sequence:40,action:e=>Or(e,{verticalAlign:"top"})}).addChild("format_alignment_middle",["format","format_alignment"],{name:"Middle",sequence:50,action:e=>Or(e,{verticalAlign:"middle"})}).addChild("format_alignment_bottom",["format","format_alignment"],{name:"Bottom",sequence:60,action:e=>Or(e,{verticalAlign:"bottom"}),separator:!0}).addChild("format_wrapping",["format"],{name:s("Wrapping"),sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{name:s("Overflow"),sequence:10,action:e=>Or(e,{wrapping:"overflow"})}).addChild("format_wrapping_wrap",["format","format_wrapping"],{name:s("Wrap"),sequence:20,action:e=>Or(e,{wrapping:"wrap"})}).addChild("format_wrapping_clip",["format","format_wrapping"],{name:s("Clip"),sequence:30,action:e=>Or(e,{wrapping:"clip"})}).addChild("format_cf",["format"],{name:s("Conditional formatting"),sequence:90,action:Yr,separator:!0}).addChild("format_clearFormat",["format"],{name:s("Clear formatting"),sequence:100,action:e=>{e.model.dispatch("CLEAR_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},separator:!0}).addChild("add_data_filter",["data"],{name:s("Create filter"),sequence:10,action:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSelection().zones;wr(e,t,i)},isVisible:e=>!Qr(e),isEnabled:e=>(e=>ro(...e.model.getters.getSelectedZones()))(e)}).addChild("remove_data_filter",["data"],{name:s("Remove filter"),sequence:10,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:t,target:e.model.getters.getSelectedZones()})},isVisible:Qr});for(let e of he)qu.addChild(`format_font_size_${e}`,["format","format_font_size"],{name:e.toString(),sequence:e,action:t=>Or(t,{fontSize:e})});function Zu(e){return e.sort().map(((e,t)=>({name:e,sequence:10*t,action:t=>t.startCellEdition(`=${e}(`)})))}const ju=new class extends Co{addTransformation(e,t,i){for(let o of t)this.content[o]||(this.content[o]=new Map),this.content[o].set(e,i);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},Xu={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function Yu(e,t){const i=Xu[e.key];e.shiftKey?t.resizeAnchorZone(i,e.ctrlKey?"end":1):t.moveAnchorCell(i,e.ctrlKey?"end":1)}const Ku=new Di;ho`
349
+ `;class lr extends t.Component{get chartType(){return this.env.model.getters.getChartType(this.props.figure.id)}get chartComponent(){const e=this.chartType,t=rr.get(e);if(!t)throw new Error(`Component is not defined for type ${e}`);return t}}lr.template="o-spreadsheet-ChartFigure",lr.components={},lr.props={figure:Object,onFigureDeleted:Function};class cr extends t.Component{get figureId(){return this.props.figure.id}get getImagePath(){return this.env.model.getters.getImagePath(this.figureId)}}function hr(e,t){const i=Ne(t),o=e.getSheetViewDimension(),n=o.width,s=o.height;if(i.width>n){const e=n/i.width;i.width=n,i.height=i.height*e}if(i.height>s){const e=s/i.height;i.height=s,i.width=i.width*e}return i}cr.template="o-spreadsheet-ImageFigure",cr.components={},cr.props={figure:Object,onFigureDeleted:Function};const dr=new Eo;function ur(e,t){return{id:"copy",name:s("Copy"),sequence:2,description:"Ctrl+C",action:async()=>{t.model.dispatch("SELECT_FIGURE",{id:e}),t.model.dispatch("COPY"),await t.clipboard.write(t.model.getters.getClipboardContent())}}}function gr(e,t){return{id:"cut",name:s("Cut"),sequence:3,description:"Ctrl+X",action:async()=>{t.model.dispatch("SELECT_FIGURE",{id:e}),t.model.dispatch("CUT"),await t.clipboard.write(t.model.getters.getClipboardContent())}}}function pr(e,t,i){return{id:"delete",name:s("Delete"),sequence:10,action:()=>{i.model.dispatch("DELETE_FIGURE",{sheetId:i.model.getters.getActiveSheetId(),id:e}),t()}}}dr.add("chart",{Component:lr,SidePanelComponent:"ChartPanel",menuBuilder:function(e,t,i){return Yn([{id:"edit",name:s("Edit"),sequence:1,action:()=>{i.model.dispatch("SELECT_FIGURE",{id:e}),i.openSidePanel("ChartPanel")}},ur(e,i),gr(e,i),pr(e,t,i)])}}),dr.add("image",{Component:cr,keepRatio:!0,minFigSize:20,borderWidth:0,menuBuilder:function(e,t,i){return Yn([ur(e,i),gr(e,i),{id:"reset_size",name:s("Reset size"),sequence:4,action:()=>{const t=i.model.getters.getImageSize(e),{height:o,width:n}=hr(i.model.getters,t);i.model.dispatch("UPDATE_FIGURE",{sheetId:i.model.getters.getActiveSheetId(),id:e,height:o,width:n})}},pr(e,t,i)])}});const mr=(new Eo).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let i=e.base;"after"===e.position&&i++;for(let o=0;o<e.quantity;o++)t.push(o+i);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],i=[...e.elements].sort(((e,t)=>e-t));for(let o of He(i)){const i=0===o[0]?0:o[0]-1,n=0===o[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:o.length,base:i,sheetId:e.sheetId,position:n})}return t})).add("ADD_MERGE",(function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]})).add("REMOVE_MERGE",(function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]})).add("CREATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId}]})).add("DELETE_SHEET",(function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1}]})).add("DUPLICATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo}]})).add("CREATE_FIGURE",(function(e){return[{type:"DELETE_FIGURE",id:e.figure.id,sheetId:e.sheetId}]})).add("CREATE_CHART",(function(e){return[{type:"DELETE_FIGURE",id:e.id,sheetId:e.sheetId}]})).add("HIDE_COLUMNS_ROWS",(function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("UNHIDE_COLUMNS_ROWS",(function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}));for(const e of ln.values())mr.contains(e)||mr.add(e,fr);function fr(e){return[e]}function vr(e,t){const i=sr.getAll().find((t=>t.match(e.type)));if(!i)throw new Error("Unknown chart type.");return i.transformDefinition(e,t)}function br(e,t){var i;let o=e;e.left!==e.right&&(o={...e,left:e.left+1});const s=[Vi(o)],r=t.getActiveSheetId(),a=t.getCell({sheetId:r,col:e.left,row:e.top});if(1===ro(e)&&(null==a?void 0:a.content))return{type:"scorecard",title:"",background:(null===(i=a.style)||void 0===i?void 0:i.fillColor)||void 0,keyValue:Vi(e),baselineMode:ee,baselineColorUp:te,baselineColorDown:ie};let l="";const c=t.getEvaluatedCellsInZone(r,{...o,bottom:o.top}),h=!!c.find((e=>e.type!==on.empty&&e.type!==on.number));if(h){const e=c.filter((e=>e.type!==on.error&&e.type!==on.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=Vi({...e,right:e.left,top:h?e.top+1:e.top}));const u=o.right===o.left?"none":"top";return Ys(d?t.getRangeFromSheetXC(r,d):void 0,t)?{title:l,dataSets:s,labelsAsText:!1,stacked:!1,aggregated:!1,labelRange:d,type:"line",dataSetsHaveTitle:h,verticalAxisPosition:"left",legendPosition:u}:{title:l,dataSets:s,labelRange:d,type:"bar",stacked:!1,aggregated:!1,dataSetsHaveTitle:h,verticalAxisPosition:"left",legendPosition:u}}const Sr=[on.number,on.error,on.text,on.boolean];function Cr(e,t,i,o,n){let r=hn.Success,a=o.right>o.left;if(e.model.getters.doesIntersectMerge(t,o)){let i;a=!1;for(let n=o.top;n<=o.bottom;n++){i=[];for(let s=o.left;s<=o.right;s++){let o=e.model.getters.getMerge({sheetId:t,col:s,row:n});o&&!i.includes(o.id.toString())&&i.push(o.id.toString())}if(i.length>=2){a=!0;break}}}const{col:l,row:c}=i;if(a)r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:n});else{const i=e.model.getters.getContiguousZone(t,o);qi(i,o)?r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:n}):e.askConfirmation(s("We found data next to your selection. Since this data was not selected, it will not be sorted. Do you want to extend your selection?"),(()=>{o=i,r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:n})}),(()=>{r=e.model.dispatch("SORT_CELLS",{sheetId:t,col:l,row:c,zone:o,sortDirection:n})}))}if(r.isCancelledBecause(63)){const{col:t,row:n}=i;e.model.selection.selectZone({cell:{col:t,row:n},zone:o}),e.raiseError(s("Cannot sort. To sort, select only cells or only merges that have the same size."))}}function Er(e){const t=e.model.dispatch("CUT");t.isSuccessful||t.isCancelledBecause(19)&&e.raiseError(s("This operation is not allowed with multiple selections."))}const wr={filterOverlap:s("You cannot create overlapping filters."),nonContinuousTargets:s("A filter can only be created on a continuous selection."),mergeInFilter:s("You can't create a filter over a range that contains a merge.")};function yr(e,t,i){const o=e.model.dispatch("CREATE_FILTER_TABLE",{target:i,sheetId:t});o.isCancelledBecause(78)?e.raiseError(wr.filterOverlap):o.isCancelledBecause(80)?e.raiseError(wr.mergeInFilter):o.isCancelledBecause(81)&&e.raiseError(wr.nonContinuousTargets)}const xr={wrongPasteSelection:s("This operation is not allowed with multiple selections."),willRemoveExistingMerge:s("This operation is not possible due to a merge. Please remove the merges first than try again."),wrongFigurePasteOption:s("Cannot do a special paste of a figure."),frozenPaneOverlap:s("Cannot paste merged cells over a frozen pane.")};function Ir(e,t){t.isSuccessful||(t.reasons.includes(20)?e.raiseError(xr.wrongPasteSelection):t.reasons.includes(2)?e.raiseError(xr.willRemoveExistingMerge):t.reasons.includes(22)?e.raiseError(xr.wrongFigurePasteOption):t.reasons.includes(75)&&e.raiseError(xr.frozenPaneOverlap))}function Rr(e,t,i){const o=e.model.dispatch("PASTE",{target:t,pasteOption:i});Ir(e,o)}function Tr(e,t,i){const o=e.model.dispatch("PASTE_FROM_OS_CLIPBOARD",{target:t,text:i});Ir(e,o)}function Ar(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 Mr(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 Or(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function Nr(e,t){e.model.dispatch("SET_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}const _r=async e=>{e.model.dispatch("COPY"),await e.clipboard.write(e.model.getters.getClipboardContent())},Fr=async e=>{Er(e),await e.clipboard.write(e.model.getters.getClipboardContent())},Dr=async e=>Lr(e),kr=async e=>Lr(e,"onlyValue");async function Lr(e,t){const i=e.model.getters.getClipboardTextContent(),o=await e.clipboard.readText();switch(o.status){case"ok":const n=e.model.getters.getSelectedZones();o&&o.content!==i?Tr(e,n,o.content):Rr(e,n,t);break;case"notImplemented":e.raiseError(s("Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead."));break;case"permissionDenied":e.raiseError(s("Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings."))}}const Pr=e=>Rr(e,e.model.getters.getSelectedZones(),"onlyFormat"),Ur=e=>!e.model.getters.isCutOperation(),Vr=e=>{if(e.model.getters.getSelectedZones().length>1)return s("Delete rows");let t,i;const o=e.model.getters.getActiveRows();if(0!==o.size)t=Math.min(...o),i=Math.max(...o);else{const o=e.model.getters.getSelectedZones()[0];t=o.top,i=o.bottom}return t===i?s("Delete row %s",(t+1).toString()):s("Delete rows %s - %s",(t+1).toString(),(i+1).toString())},zr=e=>{let t=[...e.model.getters.getActiveRows()];if(!t.length){const i=e.model.getters.getSelectedZones()[0];for(let e=i.top;e<=i.bottom;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},Br=e=>{if(e.model.getters.getSelectedZones().length>1)return s("Delete columns");let t,i;const o=e.model.getters.getActiveCols();if(0!==o.size)t=Math.min(...o),i=Math.max(...o);else{const o=e.model.getters.getSelectedZones()[0];t=o.left,i=o.right}return t===i?s("Delete column %s",Vt(t)):s("Delete columns %s - %s",Vt(t),Vt(i))},Hr=e=>{let t=[...e.model.getters.getActiveCols()];if(!t.length){const i=e.model.getters.getSelectedZones()[0];for(let e=i.left;e<=i.right;e++)t.push(e)}e.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},$r=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"ROW"});Ir(e,i)},Wr=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("INSERT_CELL",{zone:t,shiftDimension:"COL"});Ir(e,i)},Gr=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"ROW"});Ir(e,i)},qr=e=>{const t=e.model.getters.getSelectedZone(),i=e.model.dispatch("DELETE_CELL",{zone:t,shiftDimension:"COL"});Ir(e,i)},Zr=e=>{const t=e.model.getters.getActiveRows();let i,o;if(t.size)i=Math.min(...t),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.top,o=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",base:i,quantity:o,dimension:"ROW"})},jr=e=>{const t=e.model.getters.getActiveRows();let i,o;if(t.size)i=Math.max(...t),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.bottom,o=t.bottom-t.top+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",base:i,quantity:o,dimension:"ROW"})},Xr=e=>{const t=e.model.getters.getActiveCols();let i,o;if(t.size)i=Math.min(...t),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.left,o=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"before",dimension:"COL",base:i,quantity:o})},Yr=e=>{const t=e.model.getters.getActiveCols();let i,o;if(t.size)i=Math.max(...t),o=t.size;else{const t=e.model.getters.getSelectedZones()[0];i=t.right,o=t.right-t.left+1}e.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),position:"after",dimension:"COL",base:i,quantity:o})};const Kr=e=>{e.openSidePanel("ConditionalFormatting",{selection:e.model.getters.getSelectedZones()})},Qr=e=>{let{col:t,row:i}=e.model.getters.getActivePosition();e.model.dispatch("OPEN_CELL_POPOVER",{col:t,row:i,popoverType:"LinkEditor"})},Jr=e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSelectedZones();return e.model.getters.doesZonesContainFilter(t,i)},ea=e=>{const{anchor:t,zones:i}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();Cr(e,o,t.cell,i[0],"ascending")},ta=e=>{const{anchor:t,zones:i}=e.model.getters.getSelection(),o=e.model.getters.getActiveSheetId();Cr(e,o,t.cell,i[0],"descending")},ia=e=>1===e.model.getters.getSelectedZones().length,oa=new Jn;oa.add("cut",{name:s("Cut"),description:"Ctrl+X",sequence:10,action:Fr}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:_r}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:Dr}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Ur}).addChild("paste_value_only",["paste_special"],{name:s("Paste values only"),sequence:10,action:kr}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:Pr}).add("add_row_before",{name:e=>{const t=Mr(e);return 1===t?s("Insert row"):s("Insert %s rows",t.toString())},sequence:70,action:Zr,isVisible:ia}).add("add_column_before",{name:e=>{const t=Ar(e);return 1===t?s("Insert column"):s("Insert %s columns",t.toString())},sequence:90,action:Xr,isVisible:ia}).add("insert_cell",{name:s("Insert cells"),sequence:100,isVisible:ia,separator:!0}).addChild("insert_cell_down",["insert_cell"],{name:s("Shift down"),sequence:10,action:$r}).addChild("insert_cell_right",["insert_cell"],{name:s("Shift right"),sequence:20,action:Wr}).add("delete_row",{name:Vr,sequence:110,action:zr,isVisible:ia}).add("delete_column",{name:Br,sequence:120,action:Hr,isVisible:ia}).add("delete_cell",{name:s("Delete cells"),sequence:130,isVisible:ia}).addChild("delete_cell_up",["delete_cell"],{name:s("Shift up"),sequence:10,action:Gr}).addChild("delete_cell_down",["delete_cell"],{name:s("Shift left"),sequence:20,action:qr}).add("insert_link",{name:s("Insert link"),separator:!0,sequence:150,action:Qr});const na=new Jn;na.add("cut",{name:s("Cut"),description:"Ctrl+X",sequence:10,action:Fr}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:_r}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:Dr}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Ur}).addChild("paste_value_only",["paste_special"],{name:s("Paste value only"),sequence:10,action:kr}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:Pr}).add("sort_columns",{name:e=>e.model.getters.getActiveCols().size>1?s("Sort columns"):s("Sort column"),sequence:50,isVisible:ia,separator:!0}).addChild("sort_ascending",["sort_columns"],{name:s("Ascending (A ⟶ Z)"),sequence:10,action:ea}).addChild("sort_descending",["sort_columns"],{name:s("Descending (Z ⟶ A)"),sequence:20,action:ta}).add("add_column_before",{name:e=>{const t=Ar(e);return 1===t?s("Insert column left"):s("Insert %s columns left",t.toString())},sequence:70,action:Xr}).add("add_column_after",{name:e=>{const t=Ar(e);return 1===t?s("Insert column right"):s("Insert %s columns right",t.toString())},sequence:80,action:Yr}).add("delete_column",{name:Br,sequence:90,action:Hr,isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getElementsFromSelection("COL");return e.model.getters.canRemoveHeaders(t,"COL",i)}}).add("clear_column",{name:e=>{if(e.model.getters.getSelectedZones().length>1)return s("Clear columns");let t,i;const o=e.model.getters.getActiveCols();if(0!==o.size)t=Math.min(...o),i=Math.max(...o);else{const o=e.model.getters.getSelectedZones()[0];t=o.left,i=o.right}return t===i?s("Clear column %s",Vt(t)):s("Clear columns %s - %s",Vt(t),Vt(i))},sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId(),i=[...e.model.getters.getActiveCols()].map((i=>e.model.getters.getColsZone(t,i,i)));e.model.dispatch("DELETE_CONTENT",{target:i,sheetId:e.model.getters.getActiveSheetId()})}}).add("hide_columns",{name:e=>{const t=e.model.getters.getElementsFromSelection("COL");let i=t[0],o=t[t.length-1];return 1===t.length?s("Hide column %s",Vt(i).toString()):o-i+1===t.length?s("Hide columns %s - %s",Vt(i).toString(),Vt(o).toString()):s("Hide columns")},sequence:85,action:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getElementsFromSelection("COL");return e.model.getters.canRemoveHeaders(t,"COL",i)},separator:!0}).add("unhide_columns",{name:s("Unhide columns"),sequence:86,action:e=>{const t=e.model.getters.getElementsFromSelection("COL");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"COL",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("COL").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:s("Conditional formatting"),sequence:110,action:Kr});const sa=new Jn;sa.add("cut",{name:s("Cut"),sequence:10,description:"Ctrl+X",action:Fr}).add("copy",{name:s("Copy"),description:"Ctrl+C",sequence:20,isReadonlyAllowed:!0,action:_r}).add("paste",{name:s("Paste"),description:"Ctrl+V",sequence:30,action:Dr}).add("paste_special",{name:s("Paste special"),sequence:40,separator:!0,isVisible:Ur}).addChild("paste_value_only",["paste_special"],{name:s("Paste value only"),sequence:10,action:kr}).addChild("paste_format_only",["paste_special"],{name:s("Paste format only"),sequence:20,action:Pr}).add("add_row_before",{name:e=>{const t=Mr(e);return 1===t?s("Insert row above"):s("Insert %s rows above",t.toString())},sequence:50,action:Zr}).add("add_row_after",{name:e=>{const t=Mr(e);return 1===t?s("Insert row below"):s("Insert %s rows below",t.toString())},sequence:60,action:jr}).add("delete_row",{name:Vr,sequence:70,action:zr,isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getElementsFromSelection("ROW");return e.model.getters.canRemoveHeaders(t,"ROW",i)}}).add("clear_row",{name:e=>{if(e.model.getters.getSelectedZones().length>1)return s("Clear rows");let t,i;const o=e.model.getters.getActiveRows();if(0!==o.size)t=Math.min(...o),i=Math.max(...o);else{const o=e.model.getters.getSelectedZones()[0];t=o.top,i=o.bottom}return t===i?s("Clear row %s",(t+1).toString()):s("Clear rows %s - %s",(t+1).toString(),(i+1).toString())},sequence:80,action:e=>{const t=e.model.getters.getActiveSheetId(),i=[...e.model.getters.getActiveRows()].map((i=>e.model.getters.getRowsZone(t,i,i)));e.model.dispatch("DELETE_CONTENT",{target:i,sheetId:e.model.getters.getActiveSheetId()})}}).add("hide_rows",{name:e=>{const t=e.model.getters.getElementsFromSelection("ROW");let i=t[0],o=t[t.length-1];return 1===t.length?s("Hide row %s",(i+1).toString()):o-i+1===t.length?s("Hide rows %s - %s",(i+1).toString(),(o+1).toString()):s("Hide rows")},sequence:85,action:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("HIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getElementsFromSelection("ROW");return e.model.getters.canRemoveHeaders(t,"ROW",i)},separator:!0}).add("unhide_rows",{name:s("Unhide rows"),sequence:86,action:e=>{const t=e.model.getters.getElementsFromSelection("ROW");e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},isVisible:e=>{const t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection("ROW").some((e=>t.includes(e)))},separator:!0}).add("conditional_formatting",{name:s("Conditional formatting"),sequence:90,action:Kr});const ra=/(.*?)\((.*?)\)(.*)/,aa=["ANY","BOOLEAN","DATE","NUMBER","STRING","RANGE","RANGE<BOOLEAN>","RANGE<DATE>","RANGE<NUMBER>","RANGE<STRING>","META"];function la(e,t=""){return function(e){let t,i=e.match(ra),o=i[1].trim(),n=[],s=!1,r=!1,a=!1;for(let e of i[2].split(",")){const i=e.trim().toUpperCase();let o=aa.find((e=>i===e));o?n.push(o):"RANGE<ANY>"===i?n.push("RANGE"):"OPTIONAL"===i?s=!0:"REPEATING"===i?r=!0:"LAZY"===i?a=!0:i.startsWith("DEFAULT=")&&(t=e.trim().slice(8))}let l=i[3].trim();const c={name:o,description:l,type:n};s&&(c.optional=!0);r&&(c.repeating=!0);a&&(c.lazy=!0);void 0!==t&&(c.default=!0,c.defaultValue=t);return c}(`${e} ${t}`)}function ca(e){let t=0,i=0,o=0;for(let n of e.args)t++,n.optional||n.repeating||n.default||i++,n.repeating&&o++;const n=e;return n.minArgRequired=i,n.maxArgPossible=o?1/0:t,n.nbrArgRepeating=o,n.getArgToFocus=function(e,t){if(!t)return e=>e;if(1===t)return t=>Math.min(t,e);const i=e-t;return e=>{if(e<=i)return e;return i+((e-i)%t||t)}}(t,o),n.hidden=e.hidden||!1,n}const ha={description:s("Apply a large number format"),args:[la("value (number)",s("The number.")),la("unit (string, optional)",s("The formatting unit. Use 'k', 'm', or 'b' to force the unit"))],returns:["NUMBER"],computeFormat:(e,t)=>{const i=Math.abs(Fo(e.value)),o=e.format;if(void 0!==t){switch(null==t?void 0:t.value){case"k":return yi(o,1e3,"k");case"m":return yi(o,1e6,"m");case"b":return yi(o,1e9,"b");default:throw new Error(s("The formatting unit should be 'k', 'm' or 'b'."))}}return i<1e5?yi(o,0,""):i<1e8?yi(o,1e3,"k"):i<1e11?yi(o,1e6,"m"):yi(o,1e9,"b")},compute:function(e){return Fo(e)}};var da=Object.freeze({__proto__:null,FORMAT_LARGE_NUMBER:ha});const ua={description:s("Absolute value of a number."),args:[la("value (number)",s("The number of which to return the absolute value."))],returns:["NUMBER"],compute:function(e){return Math.abs(Fo(e))},isExported:!0},ga={description:s("Inverse cosine of a value, in radians."),args:[la("value (number)",s("The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Fo(e);return No((()=>Math.abs(t)<=1),s("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.acos(t)},isExported:!0},pa={description:s("Inverse hyperbolic cosine of a number."),args:[la("value (number)",s("The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1."))],returns:["NUMBER"],compute:function(e){const t=Fo(e);return No((()=>t>=1),s("The value (%s) must be greater than or equal to 1.",t.toString())),Math.acosh(t)},isExported:!0},ma={description:s("Inverse cotangent of a value."),args:[la("value (number)",s("The value for which to calculate the inverse cotangent."))],returns:["NUMBER"],compute:function(e){const t=Fo(e);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},fa={description:s("Inverse hyperbolic cotangent of a value."),args:[la("value (number)",s("The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Fo(e);return No((()=>Math.abs(t)>1),s("The value (%s) cannot be between -1 and 1 inclusive.",t.toString())),Math.log((t+1)/(t-1))/2},isExported:!0},va={description:s("Inverse sine of a value, in radians."),args:[la("value (number)",s("The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive."))],returns:["NUMBER"],compute:function(e){const t=Fo(e);return No((()=>Math.abs(t)<=1),s("The value (%s) must be between -1 and 1 inclusive.",t.toString())),Math.asin(t)},isExported:!0},ba={description:s("Inverse hyperbolic sine of a number."),args:[la("value (number)",s("The value for which to calculate the inverse hyperbolic sine."))],returns:["NUMBER"],compute:function(e){return Math.asinh(Fo(e))},isExported:!0},Sa={description:s("Inverse tangent of a value, in radians."),args:[la("value (number)",s("The value for which to calculate the inverse tangent."))],returns:["NUMBER"],compute:function(e){return Math.atan(Fo(e))},isExported:!0},Ca={description:s("Angle from the X axis to a point (x,y), in radians."),args:[la("x (number)",s("The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.")),la("y (number)",s("The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis."))],returns:["NUMBER"],compute:function(e,t){const i=Fo(e),o=Fo(t);return No((()=>0!==i||0!==o),s("Function [[FUNCTION_NAME]] caused a divide by zero error.")),Math.atan2(o,i)},isExported:!0},Ea={description:s("Inverse hyperbolic tangent of a number."),args:[la("value (number)",s("The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive."))],returns:["NUMBER"],compute:function(e){const t=Fo(e);return No((()=>Math.abs(t)<1),s("The value (%s) must be between -1 and 1 exclusive.",t.toString())),Math.atanh(t)},isExported:!0},wa={description:s("Rounds number up to nearest multiple of factor."),args:[la("value (number)",s("The value to round up to the nearest integer multiple of factor.")),la("factor (number, default=1)",s("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){const i=Fo(e),o=Fo(t);return No((()=>o>=0||i<=0),s("The factor (%s) must be positive when the value (%s) is positive.",o.toString(),i.toString())),o?Math.ceil(i/o)*o:0},isExported:!0},ya={description:s("Rounds number up to nearest multiple of factor."),args:[la("number (number)",s("The value to round up to the nearest integer multiple of significance.")),la("significance (number, default=1)",s("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),la("mode (number, default=0)",s("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1,i=0){let o=Fo(t);if(0===o)return 0;const n=Fo(e);if(o=Math.abs(o),n>=0)return Math.ceil(n/o)*o;return 0===Fo(i)?-Math.floor(Math.abs(n)/o)*o:-Math.ceil(Math.abs(n)/o)*o},isExported:!0},xa={description:s("Rounds number up to nearest multiple of factor."),args:[la("number (number)",s("The value to round up to the nearest integer multiple of significance.")),la("significance (number, default=1)",s("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){return ya.compute(e,t,0)},isExported:!0},Ia={description:s("Cosine of an angle provided in radians."),args:[la("angle (number)",s("The angle to find the cosine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.cos(Fo(e))},isExported:!0},Ra={description:s("Hyperbolic cosine of any real number."),args:[la("value (number)",s("Any real value to calculate the hyperbolic cosine of."))],returns:["NUMBER"],compute:function(e){return Math.cosh(Fo(e))},isExported:!0},Ta={description:s("Cotangent of an angle provided in radians."),args:[la("angle (number)",s("The angle to find the cotangent of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Fo(e);return No((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tan(t)},isExported:!0},Aa={description:s("Hyperbolic cotangent of any real number."),args:[la("value (number)",s("Any real value to calculate the hyperbolic cotangent of."))],returns:["NUMBER"],compute:function(e){const t=Fo(e);return No((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.tanh(t)},isExported:!0},Ma={description:s("Number of empty values."),args:[la("value1 (any, range)",s("The first value or range in which to count the number of blanks.")),la("value2 (any, range, repeating)",s("Additional values or ranges in which to count the number of blanks."))],returns:["NUMBER"],compute:function(...e){return Wo(e,((e,t)=>null==t||""===t?e+1:e),0)},isExported:!0},Oa={description:s("A conditional count across a range."),args:[la("range (range)",s("The range that is tested against criterion.")),la("criterion (string)",s("The pattern or test to apply to range."))],returns:["NUMBER"],compute:function(...e){let t=0;return Yo(e,((e,i)=>{t+=1})),t},isExported:!0},Na={description:s("Count values depending on multiple criteria."),args:[la("criteria_range1 (range)",s("The range to check against criterion1.")),la("criterion1 (string)",s("The pattern or test to apply to criteria_range1.")),la("criteria_range2 (any, range, repeating)",s("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),la("criterion2 (string, repeating)",s("Additional criteria to check."))],returns:["NUMBER"],compute:function(...e){let t=0;return Yo(e,((e,i)=>{t+=1})),t},isExported:!0};function _a(e){switch(e){case void 0:case"":case null:return!1;default:return!0}}const Fa={description:s("Counts number of unique values in a range."),args:[la("value1 (any, range)",s("The first value or range to consider for uniqueness.")),la("value2 (any, range, repeating)",s("Additional values or ranges to consider for uniqueness."))],returns:["NUMBER"],compute:function(...e){return Wo(e,((e,t)=>_a(t)?e.add(t):e),new Set).size}},Da={description:s("Counts number of unique values in a range, filtered by a set of criteria."),args:[la("range (range)",s("The range of cells from which the number of unique values will be counted.")),la("criteria_range1 (range)",s("The range of cells over which to evaluate criterion1.")),la("criterion1 (string)",s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),la("criteria_range2 (any, range, repeating)",s("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),la("criterion2 (string, repeating)",s("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let i=new Set;return Yo(t,((t,o)=>{const n=e[t][o];_a(n)&&i.add(n)})),i.size}},ka={description:s("Cosecant of an angle provided in radians."),args:[la("angle (number)",s("The angle to find the cosecant of, in radians."))],returns:["NUMBER"],compute:function(e){const t=Fo(e);return No((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sin(t)},isExported:!0},La={description:s("Hyperbolic cosecant of any real number."),args:[la("value (number)",s("Any real value to calculate the hyperbolic cosecant of."))],returns:["NUMBER"],compute:function(e){const t=Fo(e);return No((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),1/Math.sinh(t)},isExported:!0},Pa={description:s("Converts from another base to decimal."),args:[la("value (string)",s("The number to convert.")),la(",base (number)",s("The base to convert the value from."))],returns:["NUMBER"],compute:function(e,t){let i=Fo(t);i=Math.floor(i),No((()=>2<=i&&i<=36),s("The base (%s) must be between 2 and 36 inclusive.",i.toString()));const o=ko(e);if(""===o)return 0;No((()=>!!o.match(/^-?[a-z0-9]+$/i)),s("The value (%s) must be a valid base %s representation.",o,i.toString()));const n=parseInt(o,i);return No((()=>!isNaN(n)),s("The value (%s) must be a valid base %s representation.",o,i.toString())),n},isExported:!0},Ua={description:s("Converts an angle value in radians to degrees."),args:[la("angle (number)",s("The angle to convert from radians to degrees."))],returns:["NUMBER"],compute:function(e){return 180*Fo(e)/Math.PI},isExported:!0},Va={description:s("Euler's number, e (~2.718) raised to a power."),args:[la("value (number)",s("The exponent to raise e."))],returns:["NUMBER"],compute:function(e){return Math.exp(Fo(e))},isExported:!0},za={description:s("Rounds number down to nearest multiple of factor."),args:[la("value (number)",s("The value to round down to the nearest integer multiple of factor.")),la("factor (number, default=1)",s("The number to whose multiples value will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){const i=Fo(e),o=Fo(t);return No((()=>o>=0||i<=0),s("The factor (%s) must be positive when the value (%s) is positive.",o.toString(),i.toString())),o?Math.floor(i/o)*o:0},isExported:!0},Ba={description:s("Rounds number down to nearest multiple of factor."),args:[la("number (number)",s("The value to round down to the nearest integer multiple of significance.")),la("significance (number, default=1)",s("The number to whose multiples number will be rounded. The sign of significance will be ignored.")),la("mode (number, default=0)",s("If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1,i=0){let o=Fo(t);if(0===o)return 0;const n=Fo(e);if(o=Math.abs(o),n>=0)return Math.floor(n/o)*o;return 0===Fo(i)?-Math.ceil(Math.abs(n)/o)*o:-Math.floor(Math.abs(n)/o)*o},isExported:!0},Ha={description:s("Rounds number down to nearest multiple of factor."),args:[la("number (number)",s("The value to round down to the nearest integer multiple of significance.")),la("significance (number, default=1)",s("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){return Ba.compute(e,t,0)},isExported:!0},$a={description:s("Whether the provided value is even."),args:[la("value (number)",s("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Do(e);return!(1&Math.floor(Math.abs(t)))},isExported:!0},Wa={description:s("Rounds number up to nearest multiple of factor."),args:[la("number (number)",s("The value to round up to the nearest integer multiple of significance.")),la("significance (number, default=1)",s("The number to whose multiples number will be rounded."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=1){return ya.compute(e,t,0)},isExported:!0},Ga={description:s("Whether the provided value is even."),args:[la("value (number)",s("The value to be verified as even."))],returns:["BOOLEAN"],compute:function(e){const t=Do(e);return!!(1&Math.floor(Math.abs(t)))},isExported:!0},qa={description:s("The logarithm of a number, base e (euler's number)."),args:[la("value (number)",s("The value for which to calculate the logarithm, base e."))],returns:["NUMBER"],compute:function(e){const t=Fo(e);return No((()=>t>0),s("The value (%s) must be strictly positive.",t.toString())),Math.log(t)},isExported:!0},Za={description:s("Modulo (remainder) operator."),args:[la("dividend (number)",s("The number to be divided to find the remainder.")),la("divisor (number)",s("The number to divide by."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){const i=Fo(t);No((()=>0!==i),s("The divisor must be different from 0."));const o=Fo(e)%i;return o>0&&i<0||o<0&&i>0?o+i:o},isExported:!0},ja={description:s("Rounds a number up to the nearest odd integer."),args:[la("value (number)",s("The value to round to the next greatest odd number."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){const t=Fo(e);let i=Math.ceil(Math.abs(t));return i=1&i?i:i+1,t<0?-i:i},isExported:!0},Xa={description:s("The number pi."),args:[],returns:["NUMBER"],compute:function(){return Math.PI},isExported:!0},Ya={description:s("A number raised to a power."),args:[la("base (number)",s("The number to raise to the exponent power.")),la("exponent (number)",s("The exponent to raise base to."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){const i=Fo(e),o=Fo(t);return No((()=>i>=0||Number.isInteger(o)),s("The exponent (%s) must be an integer when the base is negative.",o.toString())),Math.pow(i,o)},isExported:!0},Ka={description:s("Result of multiplying a series of numbers together."),args:[la("factor1 (number, range<number>)",s("The first number or range to calculate for the product.")),la("factor2 (number, range<number>, repeating)",s("More numbers or ranges to calculate for the product."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0,i=1;for(let o of e)if(Array.isArray(o))for(let e of o)for(let o of e)"number"==typeof o&&(i*=o,t+=1);else null!=o&&(i*=Do(o),t+=1);return 0===t?0:i},isExported:!0},Qa={description:s("A random number between 0 inclusive and 1 exclusive."),args:[],returns:["NUMBER"],compute:function(){return Math.random()},isExported:!0},Ja={description:s("Random integer between two values, inclusive."),args:[la("low (number)",s("The low end of the random range.")),la("high (number)",s("The high end of the random range."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t){let i=Fo(e);Number.isInteger(i)||(i=Math.ceil(i));let o=Fo(t);return Number.isInteger(o)||(o=Math.floor(o)),No((()=>i<=o),s("The high (%s) must be greater than or equal to the low (%s).",o.toString(),i.toString())),i+Math.ceil((o-i+1)*Math.random())-1},isExported:!0},el={description:s("Rounds a number according to standard rules."),args:[la("value (number)",s("The value to round to places number of places.")),la("places (number, default=0)",s("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Fo(e);let o=Fo(t);const n=Math.abs(i);let s;return 0===o?s=Math.round(n):(Number.isInteger(o)||(o=Math.trunc(o)),s=Math.round(n*Math.pow(10,o))/Math.pow(10,o)),i>=0?s:-s},isExported:!0},tl={description:s("Rounds down a number."),args:[la("value (number)",s("The value to round to places number of places, always rounding down.")),la("places (number, default=0)",s("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Fo(e);let o=Fo(t);const n=Math.abs(i);let s;return 0===o?s=Math.floor(n):(Number.isInteger(o)||(o=Math.trunc(o)),s=Math.floor(n*Math.pow(10,o))/Math.pow(10,o)),i>=0?s:-s},isExported:!0},il={description:s("Rounds up a number."),args:[la("value (number)",s("The value to round to places number of places, always rounding up.")),la("places (number, default=0)",s("The number of decimal places to which to round."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Fo(e);let o=Fo(t);const n=Math.abs(i);let s;return 0===o?s=Math.ceil(n):(Number.isInteger(o)||(o=Math.trunc(o)),s=Math.ceil(n*Math.pow(10,o))/Math.pow(10,o)),i>=0?s:-s},isExported:!0},ol={description:s("Secant of an angle provided in radians."),args:[la("angle (number)",s("The angle to find the secant of, in radians."))],returns:["NUMBER"],compute:function(e){return 1/Math.cos(Fo(e))},isExported:!0},nl={description:s("Hyperbolic secant of any real number."),args:[la("value (number)",s("Any real value to calculate the hyperbolic secant of."))],returns:["NUMBER"],compute:function(e){return 1/Math.cosh(Fo(e))},isExported:!0},sl={description:s("Sine of an angle provided in radians."),args:[la("angle (number)",s("The angle to find the sine of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.sin(Fo(e))},isExported:!0},rl={description:s("Hyperbolic sine of any real number."),args:[la("value (number)",s("Any real value to calculate the hyperbolic sine of."))],returns:["NUMBER"],compute:function(e){return Math.sinh(Fo(e))},isExported:!0},al={description:s("Positive square root of a positive number."),args:[la("value (number)",s("The number for which to calculate the positive square root."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){const t=Fo(e);return No((()=>t>=0),s("The value (%s) must be positive or null.",t.toString())),Math.sqrt(t)},isExported:!0},ll={description:s("Sum of a series of numbers and/or cells."),args:[la("value1 (number, range<number>)",s("The first number or range to add together.")),la("value2 (number, range<number>, repeating)",s("Additional numbers or ranges to add to value1."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){return Go(e,((e,t)=>e+t),0)},isExported:!0},cl={description:s("A conditional sum across a range."),args:[la("criteria_range (range)",s("The range which is tested against criterion.")),la("criterion (string)",s("The pattern or test to apply to range.")),la("sum_range (range, default=criteria_range)",s("The range to be summed, if different from range."))],returns:["NUMBER"],compute:function(e,t,i){void 0===i&&(i=e);let o=0;return Yo([e,t],((e,t)=>{const n=i[e][t];"number"==typeof n&&(o+=n)})),o},isExported:!0},hl={description:s("Sums a range depending on multiple criteria."),args:[la("sum_range (range)",s("The range to sum.")),la("criteria_range1 (range)",s("The range to check against criterion1.")),la("criterion1 (string)",s("The pattern or test to apply to criteria_range1.")),la("criteria_range2 (any, range, repeating)",s("Additional ranges to check.")),la("criterion2 (string, repeating)",s("Additional criteria to check."))],returns:["NUMBER"],compute:function(e,...t){let i=0;return Yo(t,((t,o)=>{const n=e[t][o];"number"==typeof n&&(i+=n)})),i},isExported:!0},dl={description:s("Tangent of an angle provided in radians."),args:[la("angle (number)",s("The angle to find the tangent of, in radians."))],returns:["NUMBER"],compute:function(e){return Math.tan(Fo(e))},isExported:!0},ul={description:s("Hyperbolic tangent of any real number."),args:[la("value (number)",s("Any real value to calculate the hyperbolic tangent of."))],returns:["NUMBER"],compute:function(e){return Math.tanh(Fo(e))},isExported:!0},gl={description:s("Truncates a number."),args:[la("value (number)",s("The value to be truncated.")),la("places (number, default=0)",s("The number of significant digits to the right of the decimal point to retain."))],returns:["NUMBER"],computeFormat:e=>null==e?void 0:e.format,compute:function(e,t=0){const i=Fo(e);let o=Fo(t);return 0===o?Math.trunc(i):(Number.isInteger(o)||(o=Math.trunc(o)),Math.trunc(i*Math.pow(10,o))/Math.pow(10,o))},isExported:!0};var pl=Object.freeze({__proto__:null,ABS:ua,ACOS:ga,ACOSH:pa,ACOT:ma,ACOTH:fa,ASIN:va,ASINH:ba,ATAN:Sa,ATAN2:Ca,ATANH:Ea,CEILING:wa,CEILING_MATH:ya,CEILING_PRECISE:xa,COS:Ia,COSH:Ra,COT:Ta,COTH:Aa,COUNTBLANK:Ma,COUNTIF:Oa,COUNTIFS:Na,COUNTUNIQUE:Fa,COUNTUNIQUEIFS:Da,CSC:ka,CSCH:La,DECIMAL:Pa,DEGREES:Ua,EXP:Va,FLOOR:za,FLOOR_MATH:Ba,FLOOR_PRECISE:Ha,ISEVEN:$a,ISO_CEILING:Wa,ISODD:Ga,LN:qa,MOD:Za,ODD:ja,PI:Xa,POWER:Ya,PRODUCT:Ka,RAND:Qa,RANDBETWEEN:Ja,ROUND:el,ROUNDDOWN:tl,ROUNDUP:il,SEC:ol,SECH:nl,SIN:sl,SINH:rl,SQRT:al,SUM:ll,SUMIF:cl,SUMIFS:hl,TAN:dl,TANH:ul,TRUNC:gl});function ml(e,t,i){let o=[],n=[],r=0,a=0;Bo([e],(e=>{o.push(e),r+=1})),Bo([t],(e=>{n.push(e),a+=1})),No((()=>r===a),s("[[FUNCTION_NAME]] has mismatched argument count %s vs %s.",r.toString(),a.toString()));let l=0,c=0,h=0;for(let e=0;e<r;e++){const t=o[e],i=n[e];"number"==typeof t&&"number"==typeof i&&(l+=1,c+=t,h+=i)}No((()=>0!==l&&(!i||1!==l)),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const d=c/l,u=h/l;let g=0;for(let e=0;e<r;e++){const t=o[e],i=n[e];"number"==typeof t&&"number"==typeof i&&(g+=(t-d)*(i-u))}return g/(l-(i?1:0))}function fl(e,t,i){let o=0,n=0;const r=i?qo:Go;n=r(e,((e,t)=>(o+=1,e+t)),0),No((()=>0!==o&&(!t||1!==o)),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const a=n/o;return r(e,((e,t)=>e+Math.pow(t-a,2)),0)/(o-(t?1:0))}function vl(e,t,i){const o=Fo(t);No((()=>i?0<=o&&o<=1:0<o&&o<1),s("Function [[FUNCTION_NAME]] parameter 2 value is out of range."));let n,r=[],a=0;return Bo(e,(e=>{"number"==typeof e&&(n=Jo(r,e,"nextSmaller","asc",r.length,((e,t)=>e[t])),r.splice(n+1,0,e),a++)})),No((()=>0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),i||No((()=>1/(a+1)<=o&&o<=a/(a+1)),s("Function [[FUNCTION_NAME]] parameter 2 value is out of range.")),ii(r,o,i)}const bl={description:s("Average magnitude of deviations from mean."),args:[la("value1 (number, range<number>)",s("The first value or range of the sample.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){let t=0;const i=Go(e,((e,i)=>(t+=1,e+i)),0);No((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error."));const o=i/t;return Go(e,((e,t)=>e+Math.abs(o-t)),0)/t},isExported:!0},Sl={description:s("Numerical average value in a dataset, ignoring text."),args:[la("value1 (number, range<number>)",s("The first value or range to consider when calculating the average value.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the average value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0;const i=Go(e,((e,i)=>(t+=1,e+i)),0);return No((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/t},isExported:!0},Cl=s("[[FUNCTION_NAME]] has mismatched range sizes."),El=s("[[FUNCTION_NAME]] expects the weight to be positive or equal to 0."),wl={description:s("Weighted average."),args:[la("values (number, range<number>)",s("Values to average.")),la("weights (number, range<number>)",s("Weights for each corresponding value.")),la("additional_values (number, range<number>, repeating)",s("Additional values to average.")),la("additional_weights (number, range<number>, repeating)",s("Additional weights."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t,i,o=0,n=0;No((()=>e.length%2==0),s("Wrong number of Argument[]. Expected an even number of Argument[]."));for(let r=0;r<e.length-1;r+=2)if(t=e[r],i=e[r+1],Array.isArray(t)){No((()=>Array.isArray(i)),Cl);let e=t.length,r=t[0].length;No((()=>e===i.length&&r===i[0].length),Cl);for(let a=0;a<e;a++)for(let e=0;e<r;e++){let r=t[a][e],l=i[a][e],c="number"==typeof r,h="number"==typeof l;No((()=>c===h),s("[[FUNCTION_NAME]] expects number values.")),h&&(No((()=>l>=0),El),o+=r*l,n+=l)}}else i=Fo(i),t=Fo(t),No((()=>i>=0),El),o+=t*i,n+=i;return No((()=>0!==n),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/n}},yl={description:s("Numerical average value in a dataset."),args:[la("value1 (number, range<number>)",s("The first value or range to consider when calculating the average value.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the average value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=0;const i=qo(e,((e,i)=>(t+=1,e+i)),0);return No((()=>0!==t),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),i/t},isExported:!0},xl={description:s("Average of values depending on criteria."),args:[la("criteria_range (range)",s("The range to check against criterion.")),la("criterion (string)",s("The pattern or test to apply to criteria_range.")),la("average_range (range, default=criteria_range)",s("The range to average. If not included, criteria_range is used for the average instead."))],returns:["NUMBER"],compute:function(e,t,i){null==i&&(i=e);let o=0,n=0;return Yo([e,t],((t,s)=>{const r=(i||e)[t][s];"number"==typeof r&&(o+=1,n+=r)})),No((()=>0!==o),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),n/o},isExported:!0},Il={description:s("Average of values depending on multiple criteria."),args:[la("average_range (range)",s("The range to average.")),la("criteria_range1 (range)",s("The range to check against criterion1.")),la("criterion1 (string)",s("The pattern or test to apply to criteria_range1.")),la("criteria_range2 (any, range, repeating)",s("Additional criteria_range and criterion to check.")),la("criterion2 (string, repeating)",s("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let i=0,o=0;return Yo(t,((t,n)=>{const s=e[t][n];"number"==typeof s&&(i+=1,o+=s)})),No((()=>0!==i),s("Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.")),o/i},isExported:!0},Rl={description:s("The number of numeric values in dataset."),args:[la("value1 (number, range<number>)",s("The first value or range to consider when counting.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){let t=0;for(let i of e)if(Array.isArray(i))for(let e of i)for(let i of e)"number"==typeof i&&(t+=1);else("string"!=typeof i||Jt(i)||Se(i))&&(t+=1);return t},isExported:!0},Tl={description:s("The number of values in a dataset."),args:[la("value1 (any, range)",s("The first value or range to consider when counting.")),la("value2 (any, range, repeating)",s("Additional values or ranges to consider when counting."))],returns:["NUMBER"],compute:function(...e){return Wo(e,((e,t)=>null!=t?e+1:e),0)},isExported:!0},Al={description:s("The covariance of a dataset."),args:[la("data_y (any, range)",s("The range representing the array or matrix of dependent data.")),la("data_x (any, range)",s("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return ml(e,t,!1)},isExported:!0},Ml={description:s("The covariance of a dataset."),args:[la("data_y (any, range)",s("The range representing the array or matrix of dependent data.")),la("data_x (any, range)",s("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return ml(e,t,!1)},isExported:!0},Ol={description:s("The sample covariance of a dataset."),args:[la("data_y (any, range)",s("The range representing the array or matrix of dependent data.")),la("data_x (any, range)",s("The range representing the array or matrix of independent data."))],returns:["NUMBER"],compute:function(e,t){return ml(e,t,!0)},isExported:!0},Nl={description:s("Nth largest element from a data set."),args:[la("data (any, range)",s("Array or range containing the dataset to consider.")),la("n (number)",s("The rank from largest to smallest of the element to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){const i=Math.trunc(Fo(t));let o,n=[],r=0;Bo([e],(e=>{"number"==typeof e&&(o=Jo(n,e,"nextSmaller","asc",n.length,((e,t)=>e[t])),n.splice(o+1,0,e),r++,r>i&&(n.shift(),r--))}));const a=n.shift();return No((()=>void 0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),No((()=>r>=i),s("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",i.toString())),a},isExported:!0},_l={description:s("Maximum value in a numeric dataset."),args:[la("value1 (number, range<number>)",s("The first value or range to consider when calculating the maximum value.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the maximum value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=Go(e,((e,t)=>e<t?t:e),-1/0);return t===-1/0?0:t},isExported:!0},Fl={description:s("Maximum numeric value in a dataset."),args:[la("value1 (any, range)",s("The first value or range to consider when calculating the maximum value.")),la("value2 (any, range, repeating)",s("Additional values or ranges to consider when calculating the maximum value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=qo(e,((e,t)=>Math.max(t,e)),-1/0);return t===-1/0?0:t},isExported:!0},Dl={description:s("Returns the maximum value in a range of cells, filtered by a set of criteria."),args:[la("range (range)",s("The range of cells from which the maximum will be determined.")),la("criteria_range1 (range)",s("The range of cells over which to evaluate criterion1.")),la("criterion1 (string)",s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),la("criteria_range2 (any, range, repeating)",s("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),la("criterion2 (string, repeating)",s("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let i=-1/0;return Yo(t,((t,o)=>{const n=e[t][o];"number"==typeof n&&(i=i<n?n:i)})),i===-1/0?0:i},isExported:!0},kl={description:s("Median value in a numeric dataset."),args:[la("value1 (any, range)",s("The first value or range to consider when calculating the median value.")),la("value2 (any, range, repeating)",s("Additional values or ranges to consider when calculating the median value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){let t=[];return Ho(e,(e=>{t.push(e)})),vl(t,.5,!0)},isExported:!0},Ll={description:s("Minimum value in a numeric dataset."),args:[la("value1 (number, range<number>)",s("The first value or range to consider when calculating the minimum value.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the minimum value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=Go(e,((e,t)=>t<e?t:e),1/0);return t===1/0?0:t},isExported:!0},Pl={description:s("Minimum numeric value in a dataset."),args:[la("value1 (number, range<number>)",s("The first value or range to consider when calculating the minimum value.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to consider when calculating the minimum value."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(...e){const t=qo(e,((e,t)=>Math.min(t,e)),1/0);return t===1/0?0:t},isExported:!0},Ul={description:s("Returns the minimum value in a range of cells, filtered by a set of criteria."),args:[la("range (range)",s("The range of cells from which the minimum will be determined.")),la("criteria_range1 (range)",s("The range of cells over which to evaluate criterion1.")),la("criterion1 (string)",s("The pattern or test to apply to criteria_range1, such that each cell that evaluates to TRUE will be included in the filtered set.")),la("criteria_range2 (any, range, repeating)",s("Additional ranges over which to evaluate the additional criteria. The filtered set will be the intersection of the sets produced by each criterion-range pair.")),la("criterion2 (string, repeating)",s("The pattern or test to apply to criteria_range2."))],returns:["NUMBER"],compute:function(e,...t){let i=1/0;return Yo(t,((t,o)=>{const n=e[t][o];"number"==typeof n&&(i=i>n?n:i)})),i===1/0?0:i},isExported:!0},Vl={description:s("Value at a given percentile of a dataset."),args:[la("data (any, range)",s("The array or range containing the dataset to consider.")),la("percentile (number)",s("The percentile whose value within data will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return Bl.compute(e,t)},isExported:!0},zl={description:s("Value at a given percentile of a dataset exclusive of 0 and 1."),args:[la("data (any, range)",s("The array or range containing the dataset to consider.")),la("percentile (number)",s("The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return vl([e],t,!1)},isExported:!0},Bl={description:s("Value at a given percentile of a dataset."),args:[la("data (any, range)",s("The array or range containing the dataset to consider.")),la("percentile (number)",s("The percentile whose value within data will be calculated and returned."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return vl([e],t,!0)},isExported:!0},Hl={description:s("Value nearest to a specific quartile of a dataset."),args:[la("data (any, range)",s("The array or range containing the dataset to consider.")),la("quartile_number (number)",s("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return Wl.compute(e,t)},isExported:!0},$l={description:s("Value nearest to a specific quartile of a dataset exclusive of 0 and 4."),args:[la("data (any, range)",s("The array or range containing the dataset to consider.")),la("quartile_number (number)",s("Which quartile value, exclusive of 0 and 4, to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return vl([e],.25*Math.trunc(Fo(t)),!1)},isExported:!0},Wl={description:s("Value nearest to a specific quartile of a dataset."),args:[la("data (any, range)",s("The array or range containing the dataset to consider.")),la("quartile_number (number)",s("Which quartile value to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){return vl([e],.25*Math.trunc(Fo(t)),!0)},isExported:!0},Gl={description:s("Nth smallest element in a data set."),args:[la("data (any, range)",s("The array or range containing the dataset to consider.")),la("n (number)",s("The rank from smallest to largest of the element to return."))],returns:["NUMBER"],computeFormat:e=>{var t;return Array.isArray(e)?null===(t=e[0][0])||void 0===t?void 0:t.format:null==e?void 0:e.format},compute:function(e,t){const i=Math.trunc(Fo(t));let o,n=[],r=0;Bo([e],(e=>{"number"==typeof e&&(o=Jo(n,e,"nextSmaller","asc",n.length,((e,t)=>e[t])),n.splice(o+1,0,e),r++,r>i&&(n.pop(),r--))}));const a=n.pop();return No((()=>void 0!==a),s("[[FUNCTION_NAME]] has no valid input data.")),No((()=>r>=i),s("Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.",i.toString())),a},isExported:!0},ql={description:s("Standard deviation."),args:[la("value1 (number, range<number>)",s("The first value or range of the sample.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Ql.compute(...e))},isExported:!0},Zl={description:s("Standard deviation of entire population."),args:[la("value1 (number, range<number>)",s("The first value or range of the population.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(Jl.compute(...e))},isExported:!0},jl={description:s("Standard deviation."),args:[la("value1 (number, range<number>)",s("The first value or range of the sample.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(ec.compute(...e))},isExported:!0},Xl={description:s("Standard deviation of sample (text as 0)."),args:[la("value1 (number, range<number>)",s("The first value or range of the sample.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(tc.compute(...e))},isExported:!0},Yl={description:s("Standard deviation of entire population."),args:[la("value1 (number, range<number>)",s("The first value or range of the population.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(ic.compute(...e))},isExported:!0},Kl={description:s("Standard deviation of entire population (text as 0)."),args:[la("value1 (number, range<number>)",s("The first value or range of the population.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return Math.sqrt(oc.compute(...e))},isExported:!0},Ql={description:s("Variance."),args:[la("value1 (number, range<number>)",s("The first value or range of the sample.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return fl(e,!0,!1)},isExported:!0},Jl={description:s("Variance of entire population."),args:[la("value1 (number, range<number>)",s("The first value or range of the population.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return fl(e,!1,!1)},isExported:!0},ec={description:s("Variance."),args:[la("value1 (number, range<number>)",s("The first value or range of the sample.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return fl(e,!0,!1)},isExported:!0},tc={description:s("Variance of sample (text as 0)."),args:[la("value1 (number, range<number>)",s("The first value or range of the sample.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the sample."))],returns:["NUMBER"],compute:function(...e){return fl(e,!0,!0)},isExported:!0},ic={description:s("Variance of entire population."),args:[la("value1 (number, range<number>)",s("The first value or range of the population.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return fl(e,!1,!1)},isExported:!0},oc={description:s("Variance of entire population (text as 0)."),args:[la("value1 (number, range<number>)",s("The first value or range of the population.")),la("value2 (number, range<number>, repeating)",s("Additional values or ranges to include in the population."))],returns:["NUMBER"],compute:function(...e){return fl(e,!1,!0)},isExported:!0};var nc=Object.freeze({__proto__:null,AVEDEV:bl,AVERAGE:Sl,AVERAGE_WEIGHTED:wl,AVERAGEA:yl,AVERAGEIF:xl,AVERAGEIFS:Il,COUNT:Rl,COUNTA:Tl,COVAR:Al,COVARIANCE_P:Ml,COVARIANCE_S:Ol,LARGE:Nl,MAX:_l,MAXA:Fl,MAXIFS:Dl,MEDIAN:kl,MIN:Ll,MINA:Pl,MINIFS:Ul,PERCENTILE:Vl,PERCENTILE_EXC:zl,PERCENTILE_INC:Bl,QUARTILE:Hl,QUARTILE_EXC:$l,QUARTILE_INC:Wl,SMALL:Gl,STDEV:ql,STDEV_P:Zl,STDEV_S:jl,STDEVA:Xl,STDEVP:Yl,STDEVPA:Kl,VAR:Ql,VAR_P:Jl,VAR_S:ec,VARA:tc,VARP:ic,VARPA:oc});function sc(e,t,i){var o;const n=new Map,r=e.length;for(let t=r-1;t>=0;t--)n.set(ko(e[t][0]).toUpperCase(),t);if("number"!=typeof t&&"string"!=typeof t)throw new Error(s("The field must be a number or a string"));let a;if("number"==typeof t){if(a=Math.trunc(t)-1,a<0||r-1<a)throw new Error(s("The field (%s) must be one of %s or must be a number between 1 and %s inclusive.",t.toString(),r.toString()))}else{const e=ko(t).toUpperCase();if(a=null!==(o=n.get(e))&&void 0!==o?o:-1,-1===a)throw new Error(s("The field (%s) must be one of %s.",ko(t),[...n.keys()].toString()))}const l=i[0].length;if(l<2)throw new Error(s("The criteria range contains %s row, it must be at least 2 rows.",l.toString()));let c=new Set;const h=e[0].length;for(let t=1;t<l;t++){let o=[],s=!0;for(let r=0;r<i.length;r++){const a=ko(i[r][0]).toUpperCase(),l=n.get(a),c=i[r][t];if(void 0!==c){if(void 0===l){s=!1;break}o.push([e[l].slice(1,h)]),o.push(c)}}if(s){if(!(o.length>0)){c=new Set(Array(h-1).keys());break}Yo(o,((e,t)=>{c.add(t)}),!0)}}const d=e[a];return[...c].map((e=>d[e+1]))}const rc=[la("database (range)",s("The array or range containing the data to consider, structured in such a way that the first row contains the labels for each column's values.")),la("field (any)",s("Indicates which column in database contains the values to be extracted and operated on.")),la("criteria (range)",s("An array or range containing zero or more criteria to filter the database values by before operating."))],ac={description:s("Average of a set of values from a table-like range."),args:rc,returns:["NUMBER"],compute:function(e,t,i){const o=sc(e,t,i);return Sl.compute([o])},isExported:!0},lc={description:s("Counts values from a table-like range."),args:rc,returns:["NUMBER"],compute:function(e,t,i){const o=sc(e,t,i);return Rl.compute([o])},isExported:!0},cc={description:s("Counts values and text from a table-like range."),args:rc,returns:["NUMBER"],compute:function(e,t,i){const o=sc(e,t,i);return Tl.compute([o])},isExported:!0},hc={description:s("Single value from a table-like range."),args:rc,returns:["NUMBER"],compute:function(e,t,i){const o=sc(e,t,i);return No((()=>1===o.length),s("More than one match found in DGET evaluation.")),o[0]},isExported:!0},dc={description:s("Maximum of values from a table-like range."),args:rc,returns:["NUMBER"],compute:function(e,t,i){const o=sc(e,t,i);return _l.compute([o])},isExported:!0},uc={description:s("Minimum of values from a table-like range."),args:rc,returns:["NUMBER"],compute:function(e,t,i){const o=sc(e,t,i);return Ll.compute([o])},isExported:!0},gc={description:s("Product of values from a table-like range."),args:rc,returns:["NUMBER"],compute:function(e,t,i){const o=sc(e,t,i);return Ka.compute([o])},isExported:!0},pc={description:s("Standard deviation of population sample from table."),args:rc,returns:["NUMBER"],compute:function(e,t,i){const o=sc(e,t,i);return ql.compute([o])},isExported:!0},mc={description:s("Standard deviation of entire population from table."),args:rc,returns:["NUMBER"],compute:function(e,t,i){const o=sc(e,t,i);return Yl.compute([o])},isExported:!0},fc={description:s("Sum of values from a table-like range."),args:rc,returns:["NUMBER"],compute:function(e,t,i){const o=sc(e,t,i);return ll.compute([o])},isExported:!0},vc={description:s("Variance of population sample from table-like range."),args:rc,returns:["NUMBER"],compute:function(e,t,i){const o=sc(e,t,i);return Ql.compute([o])},isExported:!0},bc={description:s("Variance of a population from a table-like range."),args:rc,returns:["NUMBER"],compute:function(e,t,i){const o=sc(e,t,i);return ic.compute([o])},isExported:!0};var Sc=Object.freeze({__proto__:null,DAVERAGE:ac,DCOUNT:lc,DCOUNTA:cc,DGET:hc,DMAX:dc,DMIN:uc,DPRODUCT:gc,DSTDEV:pc,DSTDEVP:mc,DSUM:fc,DVAR:vc,DVARP:bc});const Cc={description:s("Converts year/month/day into a date."),args:[la("year (number)",s("The year component of the date.")),la("month (number)",s("The month component of the date.")),la("day (number)",s("The day component of the date."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i){let o=Math.trunc(Fo(e));const n=Math.trunc(Fo(t)),r=Math.trunc(Fo(i));No((()=>0<=o&&o<=9999),s("The year (%s) must be between 0 and 9999 inclusive.",o.toString())),o<1900&&(o+=1900);const a=we(new Date(o,n-1,r));return No((()=>a>=0),s("The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.")),a},isExported:!0},Ec={description:s("Converts a date string to a date value."),args:[la("date_string (string)",s("The string representing the date."))],returns:["NUMBER"],compute:function(e){const t=ko(e),i=Se(t);return No((()=>null!==i),s("The date_string (%s) cannot be parsed to date/time.",t.toString())),Math.trunc(i.value)},isExported:!0},wc={description:s("Day of the month that a specific date falls on."),args:[la("date (string)",s("The date from which to extract the day."))],returns:["NUMBER"],compute:function(e){return Vo(e).getDate()},isExported:!0},yc={description:s("Number of days between two dates."),args:[la("end_date (date)",s("The end of the date range.")),la("start_date (date)",s("The start of the date range."))],returns:["NUMBER"],compute:function(e,t){const i=Vo(e),o=Vo(t),n=i.getTime()-o.getTime();return Math.round(n/ue)},isExported:!0},xc={description:s("Number of days between two dates on a 360-day year (months of 30 days)."),args:[la("start_date (date)",s("The start date to consider in the calculation.")),la("end_date (date)",s("The end date to consider in the calculation.")),la("method (number, default=0)",s("An indicator of what day count method to use. (0) US NASD method (1) European method"))],returns:["NUMBER"],compute:function(e,t,i=0){const o=Fo(e),n=Fo(t),s=Uo(i)?4:0,r=Wc.compute(e,t,s);return Math.sign(n-o)*Math.round(360*r)},isExported:!0},Ic={description:s("Date a number of months before/after another date."),args:[la("start_date (date)",s("The date from which to calculate the result.")),la("months (number)",s("The number of months before (negative) or after (positive) 'start_date' to calculate."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){return we(Ie(Vo(e),Math.trunc(Fo(t)),!1))},isExported:!0},Rc={description:s("Last day of a month before or after a date."),args:[la("start_date (date)",s("The date from which to calculate the result.")),la("months (number)",s("The number of months before (negative) or after (positive) 'start_date' to consider."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t){const i=Vo(e),o=Math.trunc(Fo(t)),n=i.getFullYear(),s=i.getMonth();return we(new Date(n,s+o+1,0))},isExported:!0},Tc={description:s("Hour component of a specific time."),args:[la("time (date)",s("The time from which to calculate the hour component."))],returns:["NUMBER"],compute:function(e){return Vo(e).getHours()},isExported:!0},Ac={description:s("ISO week number of the year."),args:[la("date (date)",s("The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number."))],returns:["NUMBER"],compute:function(e){const t=Vo(e),i=t.getFullYear();let o=1;for(;4!==new Date(i,0,o).getDay();)o+=1;const n=new Date(i,0,o-3);let s=31;for(;4!==new Date(i,11,s).getDay();)s-=1;const r=new Date(i,11,s+3);let a,l;switch(a=n.getTime()<=t.getTime()?t.getTime()<=r.getTime()?0:1:-1,a){case 0:l=n;break;case 1:l=new Date(i,11,s+3+1);break;case-1:let e=1;for(;4!==new Date(i-1,0,e).getDay();)e+=1;l=new Date(i-1,0,e-3)}const c=(t.getTime()-l.getTime())/ue;return Math.floor(c/7)+1},isExported:!0},Mc={description:s("Minute component of a specific time."),args:[la("time (date)",s("The time from which to calculate the minute component."))],returns:["NUMBER"],compute:function(e){return Vo(e).getMinutes()},isExported:!0},Oc={description:s("Month of the year a specific date falls in"),args:[la("date (date)",s("The date from which to extract the month."))],returns:["NUMBER"],compute:function(e){return Vo(e).getMonth()+1},isExported:!0},Nc={description:s("Net working days between two provided days."),args:[la("start_date (date)",s("The start date of the period from which to calculate the number of net working days.")),la("end_date (date)",s("The end date of the period from which to calculate the number of net working days.")),la("holidays (date, range<date>, optional)",s("A range or array constant containing the date serial numbers to consider holidays."))],returns:["NUMBER"],compute:function(e,t,i){return Fc.compute(e,t,1,i)},isExported:!0};function _c(e){if("string"==typeof e){No((()=>{if(7!==e.length)return!1;for(let t of e)if("0"!==t&&"1"!==t)return!1;return!0}),s('When weekend is a string (%s) it must be composed of "0" or "1".',e));let t=[];for(let i=0;i<7;i++)"1"===e[i]&&t.push((i+1)%7);return t}if("number"==typeof e)return No((()=>1<=e&&e<=7||11<=e&&e<=17),s("The weekend (%s) must be a string or a number in the range 1-7 or 11-17.",e.toString())),e<=7?[e-2==-1?6:e-2,e-1]:[e-11];throw Error(s("The weekend must be a number or a string."))}const Fc={description:s("Net working days between two dates (specifying weekends)."),args:[la("start_date (date)",s("The start date of the period from which to calculate the number of net working days.")),la("end_date (date)",s("The end date of the period from which to calculate the number of net working days.")),la("weekend (any, default=1)",s("A number or string representing which days of the week are considered weekends.")),la("holidays (date, range<date>, optional)",s("A range or array constant containing the dates to consider as holidays."))],returns:["NUMBER"],compute:function(e,t,i=1,o){const n=Vo(e),s=Vo(t),r=_c(i);let a=new Set;void 0!==o&&Bo([o],(e=>{const t=Vo(e);a.add(t.getTime())}));const l=n.getTime()>s.getTime(),c=new Date((l?n:s).getTime());let h=new Date((l?s:n).getTime());const d=c.getTime();let u=h.getTime(),g=0;for(;u<=d;)r.includes(h.getDay())||a.has(u)||(g+=1),h.setDate(h.getDate()+1),u=h.getTime();return l?-g:g},isExported:!0},Dc={description:s("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()-de.getTime(),i=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return Math.floor(t/ue)+i},isExported:!0},kc={description:s("Minute component of a specific time."),args:[la("time (date)",s("The time from which to calculate the second component."))],returns:["NUMBER"],compute:function(e){return Vo(e).getSeconds()},isExported:!0},Lc={description:s("Converts hour/minute/second into a time."),args:[la("hour (number)",s("The hour component of the time.")),la("minute (number)",s("The minute component of the time.")),la("second (number)",s("The second component of the time."))],returns:["DATE"],computeFormat:()=>"hh:mm:ss a",compute:function(e,t,i){let o=Math.trunc(Fo(e)),n=Math.trunc(Fo(t)),r=Math.trunc(Fo(i));return n+=Math.floor(r/60),r=r%60+(r<0?60:0),o+=Math.floor(n/60),n=n%60+(n<0?60:0),o%=24,No((()=>o>=0),s("The function [[FUNCTION_NAME]] result cannot be negative")),o/24+n/1440+r/86400},isExported:!0},Pc={description:s("Converts a time string into its serial number representation."),args:[la("time_string (string)",s("The string that holds the time representation."))],returns:["NUMBER"],compute:function(e){const t=ko(e),i=Se(t);No((()=>null!==i),s("The time_string (%s) cannot be parsed to date/time.",t));const o=i.value-Math.trunc(i.value);return o<0?1+o:o},isExported:!0},Uc={description:s("Current date as a date value."),args:[],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(){const e=new Date;return we(new Date(e.getFullYear(),e.getMonth(),e.getDate()))},isExported:!0},Vc={description:s("Day of the week of the date provided (as number)."),args:[la("date (date)",s("The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.")),la("type (number, default=1)",s("A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1."))],returns:["NUMBER"],compute:function(e,t=1){const i=Vo(e),o=Math.round(Fo(t)),n=i.getDay();return No((()=>[1,2,3].includes(o)),s("The type (%s) must be 1, 2 or 3.",o.toString())),1===o?n+1:2===o?0===n?7:n:0===n?6:n-1},isExported:!0},zc={description:s("Week number of the year."),args:[la("date (date)",s("The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.")),la("type (number, default=1)",s("A number representing the day that a week starts on. Sunday = 1."))],returns:["NUMBER"],compute:function(e,t=1){const i=Vo(e),o=Math.round(Fo(t));if(No((()=>1===o||2===o||11<=o&&o<=17||21===o),s("The type (%s) is out of range.",o.toString())),21===o)return Ac.compute(e);let n;n=1===o||2===o?o-1:o-10==7?0:o-10;const r=i.getFullYear();let a=1,l=new Date(r,0,a);for(;l.getDay()!==n;)a+=1,l=new Date(r,0,a);const c=(i.getTime()-l.getTime())/ue;return c<0?1:Math.floor(c/7)+(1===a?1:2)},isExported:!0},Bc={description:s("Date after a number of workdays."),args:[la("start_date (date)",s("The date from which to begin counting.")),la("num_days (number)",s("The number of working days to advance from start_date. If negative, counts backwards.")),la("holidays (date, range<date>, optional)",s("A range or array constant containing the dates to consider holidays."))],returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i){return Hc.compute(e,t,1,i)},isExported:!0},Hc={description:s("Date after a number of workdays (specifying weekends)."),args:[la("start_date (date)",s("The date from which to begin counting.")),la("num_days (number)",s("The number of working days to advance from start_date. If negative, counts backwards.")),la("weekend (any, default=1)",s("A number or string representing which days of the week are considered weekends.")),la("holidays (date, range<date>, optional)",s("A range or array constant containing the dates to consider holidays."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i=1,o){let n=Vo(e),r=Math.trunc(Fo(t));"string"==typeof i&&No((()=>"1111111"!==i),s("The weekend (%s) must be different from '1111111'.",i));const a=_c(i);let l=new Set;void 0!==o&&Bo([o],(e=>{const t=Vo(e);l.add(t.getTime())}));let c=new Date(n.getTime()),h=c.getTime();const d=Math.sign(r);let u=Math.abs(r);for(;u>0;)c.setDate(c.getDate()+d),h=c.getTime(),a.includes(c.getDay())||l.has(h)||(u-=1);const g=h-de.getTime();return Math.round(g/ue)},isExported:!0},$c={description:s("Year specified by a given date."),args:[la("date (date)",s("The date from which to extract the year."))],returns:["NUMBER"],compute:function(e){return Vo(e).getFullYear()},isExported:!0},Wc={description:s("Exact number of years between two dates."),args:[la("start_date (date)",s("The start date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.")),la("end_date (date)",s("The end date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.")),la("day_count_convention (number, default=0)",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i=0){let o=Math.trunc(Fo(e)),n=Math.trunc(Fo(t));const r=Math.trunc(Fo(i));return No((()=>o>=0),s("The start_date (%s) must be positive or null.",o.toString())),No((()=>n>=0),s("The end_date (%s) must be positive or null.",n.toString())),No((()=>0<=r&&r<=4),s("The day_count_convention (%s) must be between 0 and 4 inclusive.",r.toString())),Te(o,n,r)}},Gc={description:s("First day of the month preceding a date."),args:[la("date (date)",s("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Vo(e),i=t.getFullYear(),o=t.getMonth();return we(new Date(i,o,1))}},qc={description:s("Last day of the month following a date."),args:[la("date (date)",s("The date from which to calculate the result."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){return Rc.compute(e,0)}},Zc={description:s("Quarter of the year a specific date falls in"),args:[la("date (date)",s("The date from which to extract the quarter."))],returns:["NUMBER"],compute:function(e){return Math.ceil((Vo(e).getMonth()+1)/3)}},jc={description:s("First day of the quarter of the year a specific date falls in."),args:[la("date (date)",s("The date from which to calculate the start of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Zc.compute(e),i=$c.compute(e);return we(new Date(i,3*(t-1),1))}},Xc={description:s("Last day of the quarter of the year a specific date falls in."),args:[la("date (date)",s("The date from which to calculate the end of quarter."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=Zc.compute(e),i=$c.compute(e);return we(new Date(i,3*t,0))}},Yc={description:s("First day of the year a specific date falls in."),args:[la("date (date)",s("The date from which to calculate the start of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=$c.compute(e);return we(new Date(t,0,1))}},Kc={description:s("Last day of the year a specific date falls in."),args:[la("date (date)",s("The date from which to calculate the end of the year."))],returns:["DATE"],computeFormat:()=>"m/d/yyyy",compute:function(e){const t=$c.compute(e);return we(new Date(t+1,0,0))}};var Qc=Object.freeze({__proto__:null,DATE:Cc,DATEVALUE:Ec,DAY:wc,DAYS:yc,DAYS360:xc,EDATE:Ic,EOMONTH:Rc,HOUR:Tc,ISOWEEKNUM:Ac,MINUTE:Mc,MONTH:Oc,NETWORKDAYS:Nc,NETWORKDAYS_INTL:Fc,NOW:Dc,SECOND:kc,TIME:Lc,TIMEVALUE:Pc,TODAY:Uc,WEEKDAY:Vc,WEEKNUM:zc,WORKDAY:Bc,WORKDAY_INTL:Hc,YEAR:$c,YEARFRAC:Wc,MONTH_START:Gc,MONTH_END:qc,QUARTER:Zc,QUARTER_START:jc,QUARTER_END:Xc,YEAR_START:Yc,YEAR_END:Kc});const Jc={description:s("Compare two numeric values, returning 1 if they're equal."),args:[la(" (number)",s("The first number to compare.")),la(" (number, default=0)",s("The second number to compare."))],returns:["NUMBER"],compute:function(e,t=0){return Fo(e)===Fo(t)?1:0},isExported:!0};var eh=Object.freeze({__proto__:null,DELTA:Jc});function th(e,t){No((()=>e<t),s("The maturity (%s) must be strictly greater than the settlement (%s).",t.toString(),e.toString()))}function ih(e,t){No((()=>t<e),s("The settlement date (%s) must be strictly greater than the issue date (%s).",e.toString(),t.toString()))}function oh(e){No((()=>[1,2,4].includes(e)),s("The frequency (%s) must be one of %s",e.toString(),[1,2,4].toString()))}function nh(e){No((()=>0<=e&&e<=4),s("The day_count_convention (%s) must be between 0 and 4 inclusive.",e.toString()))}function sh(e){No((()=>e>0),s("The redemption (%s) must be strictly positive.",e.toString()))}function rh(e){No((()=>e>0),s("The price (%s) must be strictly positive.",e.toString()))}function ah(e){No((()=>e>0),s("The number_of_periods (%s) must be greater than 0.",e.toString()))}function lh(e){No((()=>e>0),s("The rate (%s) must be strictly positive.",e.toString()))}function ch(e){No((()=>e>0),s("The life (%s) must be strictly positive.",e.toString()))}function hh(e){No((()=>e>=0),s("The cost (%s) must be positive or null.",e.toString()))}function dh(e){No((()=>e>0),s("The period (%s) must be strictly positive.",e.toString()))}function uh(e){No((()=>e>=0),s("The salvage (%s) must be positive or null.",e.toString()))}function gh(e){No((()=>e>0),s("The present value (%s) must be strictly positive.",e.toString()))}function ph(e,t){No((()=>e<=t),s("The period (%s) must be less than or equal life (%s).",e.toString(),t.toString()))}function mh(e){No((()=>e>0),s("The investment (%s) must be strictly positive.",e.toString()))}function fh(e){No((()=>e>0),s("The discount (%s) must be strictly positive.",e.toString()))}function vh(e){No((()=>e<1),s("The discount (%s) must be smaller than 1.",e.toString()))}function bh(e){No((()=>e>0),s("The depreciation factor (%s) must be strictly positive.",e.toString()))}function Sh(e,t){const i=Vo(e),o=Vo(t),n=new Date(i);n.setFullYear(i.getFullYear()+1),No((()=>o.getTime()<=n.getTime()),s("The settlement date (%s) must at most one year after the maturity date (%s).",e.toString(),t.toString()))}function Ch(e,t,i){ah(i),No((()=>e>0),s("The first_period (%s) must be strictly positive.",e.toString())),No((()=>t>0),s("The last_period (%s) must be strictly positive.",t.toString())),No((()=>e<=t),s("The first_period (%s) must be smaller or equal to the last_period (%s).",e.toString(),t.toString())),No((()=>t<=i),s("The last_period (%s) must be smaller or equal to the number_of_periods (%s).",e.toString(),i.toString()))}function Eh(e){No((()=>e>-1),s("The rate_guess (%s) must be strictly greater than -1.",e.toString()))}function wh(e,t){No((()=>e.length===t.length&&e[0].length===t[0].length),s("The cashflow_amounts and cashflow_dates ranges must have the same dimensions."))}function yh(e){No((()=>e.every((t=>t>=e[0]))),s("All the dates should be greater or equal to the first date in cashflow_dates (%s).",e[0].toString()))}const xh=[la("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),la("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),la("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),la("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))];function Ih(e,t,i,o,n=1e-10,r){let a,l,c,h,d=i,u=!1,g=0;do{c=e(d),isNaN(c)?(No((()=>g<o&&void 0!==r),s("Function [[FUNCTION_NAME]] didn't find any result.")),g++,d=r(h),h=d):(a=d-c/t(d),l=Math.abs(a-d),d=a,u=l<n||Math.abs(c)<n,No((()=>g<o),s("Function [[FUNCTION_NAME]] didn't find any result.")),g++)}while(!u);return d}const Rh={description:s("Accrued interest of security paying at maturity."),args:[la("issue (date)",s("The date the security was initially issued.")),la("maturity (date)",s("The maturity date of the security.")),la("rate (number)",s("The annualized rate of interest.")),la("redemption (number)",s("The redemption amount per 100 face value, or par.")),la("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(Fo(e)),r=Math.trunc(Fo(t)),a=Fo(o),l=Fo(i),c=Math.trunc(Fo(n));ih(r,s),nh(c),sh(a),lh(l);return a*l*Wc.compute(s,r,n)},isExported:!0},Th={description:s("Depreciation for an accounting period."),args:[la("cost (number)",s("The initial cost of the asset.")),la("purchase_date (date)",s("The date the asset was purchased.")),la("first_period_end (date)",s("The date the first period ended.")),la("salvage (number)",s("The value of the asset at the end of depreciation.")),la("period (number)",s("The single period within life for which to calculate depreciation.")),la("rate (number)",s("The deprecation rate.")),la(" (number, optional)",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r,a=0){a=a||0;const l=Fo(e),c=Math.trunc(Fo(t)),h=Math.trunc(Fo(i)),d=Fo(o),u=Fo(n),g=Fo(r),p=Math.trunc(Fo(a));!function(e){No((()=>e>0),s("The cost (%s) must be strictly positive.",e.toString()))}(l),uh(d),function(e,t){No((()=>e<=t),s("The salvage (%s) must be smaller or equal than the cost (%s).",e.toString(),t.toString()))}(d,l),function(e){No((()=>e>=0),s("The period (%s) must be positive or null.",e.toString()))}(u),lh(g),nh(p),No((()=>c<=h),s("The purchase_date (%s) must be before the first_period_end (%s).",c.toString(),h.toString()));const m=u<1&&u>0?1:Math.trunc(u),f=l*g,v=Wc.compute(c,h,p),b=c===h?f:f*v,S=l-b-f*m;return S>=d?0===m?b:f:d-S<f?f-(d-S):0},isExported:!0},Ah={description:s("Days in coupon period containing settlement date."),args:xh,returns:["NUMBER"],compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Fo(e)),s=Math.trunc(Fo(t)),r=Math.trunc(Fo(i)),a=Math.trunc(Fo(o));if(th(n,s),oh(r),nh(a),1===a){const n=Fh.compute(e,t,i,o);return Nh.compute(e,t,i,o)-n}return(3===a?365:360)/r},isExported:!0},Mh={description:s("Days from settlement until next coupon."),args:xh,returns:["NUMBER"],compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Fo(e)),s=Math.trunc(Fo(t)),r=Math.trunc(Fo(i)),a=Math.trunc(Fo(o));th(n,s),oh(r),nh(a);const l=Fh.compute(n,s,i,o);if([1,2,3].includes(a))return n-l;if(4===a){const e=Te(l,n,a);return Math.round(360*e)}const c=Vo(n),h=Vo(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&&xe(h)&&xe(c)&&(f=30),31!==f||30!==m&&31!==m||(f=30),2===g&&xe(h)&&(m=30),31===m&&(m=30),360*(u-d)+30*(p-g)+(f-m)},isExported:!0},Oh={description:s("Days from settlement until next coupon."),args:xh,returns:["NUMBER"],compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Fo(e)),s=Math.trunc(Fo(t)),r=Math.trunc(Fo(i)),a=Math.trunc(Fo(o));th(n,s),oh(r),nh(a);const l=Nh.compute(n,s,i,o);if([1,2,3].includes(a))return l-n;if(4===a){const e=Te(n,l,a);return Math.round(360*e)}const c=Mh.compute(e,t,i,a);return Ah.compute(e,t,i,a)-c},isExported:!0},Nh={description:s("Next coupon date after the settlement date."),args:xh,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Fo(e)),s=Math.trunc(Fo(t)),r=Math.trunc(Fo(i)),a=Math.trunc(Fo(o));th(n,s),oh(r),nh(a);const l=12/r,c=_h.compute(e,t,i,o);return we(Ie(Vo(s),-(c-1)*l,!0))},isExported:!0},_h={description:s("Number of coupons between settlement and maturity."),args:xh,returns:["NUMBER"],compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Fo(e)),s=Math.trunc(Fo(t)),r=Math.trunc(Fo(i)),a=Math.trunc(Fo(o));th(n,s),oh(r),nh(a);let l=1,c=s;const h=12/r;for(;c>n;)c=we(Ie(Vo(c),-h,!1)),l++;return l-1},isExported:!0},Fh={description:s("Last coupon date prior to or on the settlement date."),args:xh,returns:["NUMBER"],computeFormat:()=>"m/d/yyyy",compute:function(e,t,i,o=0){o=o||0;const n=Math.trunc(Fo(e)),s=Math.trunc(Fo(t)),r=Math.trunc(Fo(i)),a=Math.trunc(Fo(o));th(n,s),oh(r),nh(a);const l=12/r,c=_h.compute(e,t,i,o);return we(Ie(Vo(s),-c*l,!0))},isExported:!0},Dh={description:s("Cumulative interest paid over a set of periods."),args:[la("rate (number)",s("The interest rate.")),la("number_of_periods (number)",s("The number of payments to be made.")),la("present_value (number)",s("The current value of the annuity.")),la("first_period (number)",s("The number of the payment period to begin the cumulative calculation.")),la("last_period (number)",s("The number of the payment period to end the cumulative calculation.")),la("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,i,o,n,s=0){const r=Fo(o),a=Fo(n),l=Fo(e),c=Fo(i),h=Fo(t);Ch(r,a,h),lh(l),gh(c);let d=0;for(let t=r;t<=a;t++){d+=qh.compute(e,t,h,i,0,s)}return d},isExported:!0},kh={description:s("Cumulative principal paid over a set of periods."),args:[la("rate (number)",s("The interest rate.")),la("number_of_periods (number)",s("The number of payments to be made.")),la("present_value (number)",s("The current value of the annuity.")),la("first_period (number)",s("The number of the payment period to begin the cumulative calculation.")),la("last_period (number)",s("The number of the payment period to end the cumulative calculation.")),la("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,i,o,n,s=0){const r=Fo(o),a=Fo(n),l=Fo(e),c=Fo(i),h=Fo(t);Ch(r,a,h),lh(l),gh(c);let d=0;for(let t=r;t<=a;t++){d+=id.compute(e,t,h,i,0,s)}return d},isExported:!0},Lh={description:s("Depreciation via declining balance method."),args:[la("cost (number)",s("The initial cost of the asset.")),la("salvage (number)",s("The value of the asset at the end of depreciation.")),la("life (number)",s("The number of periods over which the asset is depreciated.")),la("period (number)",s("The single period within life for which to calculate depreciation.")),la("month (number, optional)",s("The number of months in the first year of depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o,...n){const r=Fo(e),a=Fo(t),l=Fo(i),c=Math.trunc(Fo(o)),h=n.length?Math.trunc(Fo(n[0])):12,d=l+(12===h?0:1);hh(r),uh(a),dh(c),ch(l),No((()=>1<=h&&h<=12),s("The month (%s) must be between 1 and 12 inclusive.",h.toString())),No((()=>c<=d),s("The period (%s) must be less than or equal to %s.",c.toString(),d.toString()));const u=h/12;let g=1-Math.pow(a/r,1/l);g=Math.round(1e3*g)/1e3;let p=r,m=r*(1-g*u);for(let e=1;e<c;e++)p=m,m=p*(1-g),e===l&&(m=p*(1-g*(1-u)));return p-m},isExported:!0},Ph={description:s("Depreciation via double-declining balance method."),args:[la("cost (number)",s("The initial cost of the asset.")),la("salvage (number)",s("The value of the asset at the end of depreciation.")),la("life (number)",s("The number of periods over which the asset is depreciated.")),la("period (number)",s("The single period within life for which to calculate depreciation.")),la("factor (number, default=2)",s("The factor by which depreciation decreases."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o,n=2){n=n||0;const s=Fo(e),r=Fo(t),a=Fo(i),l=Fo(o),c=Fo(n);if(hh(s),uh(r),dh(l),ch(a),ph(l,a),bh(c),0===s||r>=s)return 0;const h=c/a;if(h>1)return 1===o?s-r:0;if(l<=1)return s*h;const d=s*Math.pow(1-h,l-1),u=s*Math.pow(1-h,l),g=u<r?d-r:d-u;return Math.max(g,0)},isExported:!0},Uh={description:s("Discount rate of a security based on price."),args:[la("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),la("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),la("price (number)",s("The price at which the security is bought per 100 face value.")),la("redemption (number)",s("The redemption amount per 100 face value, or par.")),la("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(Fo(e)),r=Math.trunc(Fo(t)),a=Fo(i),l=Fo(o),c=Math.trunc(Fo(n));th(s,r),nh(c),rh(a),sh(l);return(l-a)/l/Wc.compute(s,r,c)},isExported:!0},Vh={description:s("Convert a decimal fraction to decimal value."),args:[la("fractional_price (number)",s("The price quotation given using fractional decimal conventions.")),la("unit (number)",s("The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const i=Fo(e),o=Math.trunc(Fo(t));No((()=>o>0),s("The unit (%s) must be strictly positive.",o.toString()));const n=Math.trunc(i);return n+(i-n)*(10**Math.ceil(Math.log10(o))/o)},isExported:!0},zh={description:s("Convert a decimal value to decimal fraction."),args:[la("decimal_price (number)",s("The price quotation given as a decimal value.")),la("unit (number)",s("The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds."))],returns:["NUMBER"],compute:function(e,t){const i=Fo(e),o=Math.trunc(Fo(t));No((()=>o>0),s("The unit (%s) must be strictly positive.",o.toString()));const n=Math.trunc(i);return n+(i-n)*(o/10**Math.ceil(Math.log10(o)))},isExported:!0},Bh={description:s("Number of periods for an investment to reach a value."),args:[la("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),la("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),la("rate (number)",s("The annualized rate of interest.")),la("yield (number)",s("The expected annual yield of the security.")),la("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),la("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r=0){r=r||0;const a=Math.trunc(Fo(e)),l=Math.trunc(Fo(t)),c=Fo(i),h=Fo(o),d=Math.trunc(Fo(n)),u=Math.trunc(Fo(r));th(a,l),oh(d),nh(u),No((()=>c>=0),s("The rate (%s) must be positive or null.",c.toString())),No((()=>h>=0),s("The yield (%s) must be positive or null.",h.toString()));const g=Wc.compute(a,l,u),p=g-Math.trunc(g)||1/d,m=Math.ceil(g*d),f=c/d,v=h/d;let b=0,S=0;for(let e=1;e<=m;e++){const t=(f+(e===m?1:0))/(1+v)**e;S+=(p+(e-1)/d)*t,b+=t}return 0===b?0:S/b},isExported:!0},Hh={description:s("Annual effective interest rate."),args:[la("nominal_rate (number)",s("The nominal interest rate per year.")),la("periods_per_year (number)",s("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const i=Fo(e),o=Math.trunc(Fo(t));return No((()=>i>0),s("The nominal rate (%s) must be strictly greater than 0.",i.toString())),No((()=>o>0),s("The number of periods by year (%s) must strictly greater than 0.",o.toString())),Math.pow(1+i/o,o)-1},isExported:!0},$h={description:s("Future value of an annuity investment."),args:[la("rate (number)",s("The interest rate.")),la("number_of_periods (number)",s("The number of payments to be made.")),la("payment_amount (number)",s("The amount per period to be paid.")),la("present_value (number, default=0)",s("The current value of the annuity.")),la("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o=0,n=0){o=o||0,n=n||0;const s=Fo(e),r=Fo(t),a=Fo(i),l=Fo(o),c=Uo(n)?1:0;return s?-l*(1+s)**r-a*(1+s*c)*((1+s)**r-1)/s:-(l+a*r)},isExported:!0},Wh={description:s("Future value of principal from series of rates."),args:[la("principal (number)",s("The amount of initial capital or value to compound against.")),la("rate_schedule (number, range<number>)",s("A series of interest rates to compound against the principal."))],returns:["NUMBER"],compute:function(e,t){return Wo([t],((e,t)=>e*(1+Fo(t))),Fo(e))},isExported:!0},Gh={description:s("Calculates effective interest rate."),args:[la("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),la("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),la("investment (number)",s("The amount invested in the security.")),la("redemption (number)",s("The amount to be received at maturity.")),la("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){const s=Math.trunc(Fo(e)),r=Math.trunc(Fo(t)),a=Fo(o),l=Fo(i);th(s,r),mh(l),sh(a);return(a-l)/l/Wc.compute(s,r,n)},isExported:!0},qh={description:s("Payment on the principal of an investment."),args:[la("rate (number)",s("The annualized rate of interest.")),la("period (number)",s("The amortization period, in terms of number of periods.")),la("number_of_periods (number)",s("The number of payments to be made.")),la("present_value (number)",s("The current value of the annuity.")),la("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),la("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o,n=0,s=0){return td.compute(e,i,o,n,s)-id.compute(e,t,i,o,n,s)},isExported:!0},Zh={description:s("Internal rate of return given periodic cashflows."),args:[la("cashflow_amounts (number, range<number>)",s("An array or range containing the income or payments associated with the investment.")),la("rate_guess (number, default=0.1)",s("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t=.1){const i=Fo(t);Eh(i);let o=!1,n=!1,r=[];Ho([e],(e=>{e>0&&(o=!0),e<0&&(n=!0),r.push(e)})),No((()=>o&&n),s("The cashflow_amounts must include negative and positive values."));const a=r.shift();return Ih((function(e){return function(e,t,i){const o=i.length;let n=0;return i.reduce(((t,i)=>(n++,t+i*e**(o-n))),t*e**o)}(e,a,r)}),(function(e){return function(e,t,i){const o=i.length;let n=0;return i.reduce(((t,i)=>(n++,t+i*(o-n)*e**(o-n-1))),t*o*e**(o-1))}(e,a,r)}),i+1,20,1e-5)-1},isExported:!0},jh={description:s("Returns the interest paid at a particular period of an investment."),args:[la("rate (number)",s("The interest rate.")),la("period (number)",s("The period for which you want to view the interest payment.")),la("number_of_periods (number)",s("The number of payments to be made.")),la("present_value (number)",s("The current value of the annuity."))],returns:["NUMBER"],compute:function(e,t,i,o){const n=Fo(e),r=Fo(t),a=Fo(i),l=Fo(o);No((()=>0!==a),s("The number of periods must be different than 0.",a.toString()));return-1*(l-l*(r/a))*n},isExported:!0},Xh={description:s("Modified Macaulay duration."),args:[la("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),la("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),la("rate (number)",s("The annualized rate of interest.")),la("yield (number)",s("The expected annual yield of the security.")),la("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),la("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,s=0){return Bh.compute(e,t,i,o,n,s)/(1+Fo(o)/Math.trunc(Fo(n)))},isExported:!0},Yh={description:s("Modified internal rate of return."),args:[la("cashflow_amounts (range<number>)",s("A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.")),la("financing_rate (number)",s("The interest rate paid on funds invested.")),la("reinvestment_return_rate (number)",s("The return (as a percentage) earned on reinvestment of income received from the investment."))],returns:["NUMBER"],compute:function(e,t,i){const o=Fo(t),n=Fo(i),r=(a=e,a.length?a[0].map(((e,t)=>a.map((e=>e[t])))):a).flat().filter(tt).map(Fo);var a;const l=r.length;let c=0,h=0;for(const e of Be(0,l)){const t=r[e];t>=0?c+=t*(n+1)**(l-e-1):h+=t/(o+1)**e}No((()=>0!==h&&0!==c),s("There must be both positive and negative values in cashflow_amounts."));return(-c/h)**(1/(l-1))-1},isExported:!0},Kh={description:s("Annual nominal interest rate."),args:[la("effective_rate (number)",s("The effective interest rate per year.")),la("periods_per_year (number)",s("The number of compounding periods per year."))],returns:["NUMBER"],compute:function(e,t){const i=Fo(e),o=Math.trunc(Fo(t));return No((()=>i>0),s("The effective rate (%s) must must strictly greater than 0.",i.toString())),No((()=>o>0),s("The number of periods by year (%s) must strictly greater than 0.",o.toString())),(Math.pow(i+1,1/o)-1)*o},isExported:!0},Qh={description:s("Number of payment periods for an investment."),args:[la("rate (number)",s("The interest rate.")),la("payment_amount (number)",s("The amount of each payment made.")),la("present_value (number)",s("The current value of the annuity.")),la("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),la("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],compute:function(e,t,i,o=0,n=0){o=o||0,n=n||0;const s=Fo(e),r=Fo(t),a=Fo(i),l=Fo(o),c=Uo(n)?1:0;if(0===s)return-(l+a)/r;const h=r*(1+s*c)/s;return Math.log((h-l)/(a+h))/Math.log(1+s)},isExported:!0};const Jh={description:s("The net present value of an investment based on a series of periodic cash flows and a discount rate."),args:[la("discount (number)",s("The discount rate of the investment over one period.")),la("cashflow1 (number, range<number>)",s("The first future cash flow.")),la("cashflow2 (number, range<number>, repeating)",s("Additional future cash flows."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,...t){const i=Fo(e);return No((()=>-1!==i),s("The discount (%s) must be different from -1.",i.toString())),function(e,t,i){let o=0;return Go(i,((t,i)=>(o++,t+i/(1+e)**o)),t)}(i,0,t)},isExported:!0},ed={description:s("Computes the number of periods needed for an investment to reach a value."),args:[la("rate (number)",s("The rate at which the investment grows each period.")),la("present_value (number)",s("The investment's current value.")),la("future_value (number)",s("The investment's desired future value."))],returns:["NUMBER"],compute:function(e,t,i){const o=Fo(e),n=Fo(t),r=Fo(i);return lh(o),No((()=>n>0),s("The present_value (%s) must be strictly positive.",n.toString())),No((()=>r>0),s("The future_value (%s) must be strictly positive.",r.toString())),(Math.log(r)-Math.log(n))/Math.log(1+o)},isExported:!0},td={description:s("Periodic payment for an annuity investment."),args:[la("rate (number)",s("The annualized rate of interest.")),la("number_of_periods (number)",s("The number of payments to be made.")),la("present_value (number)",s("The current value of the annuity.")),la("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),la("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o=0,n=0){o=o||0,n=n||0;const s=Fo(t),r=Fo(e),a=Uo(n)?1:0;let l=Fo(o),c=Fo(i);if(ah(s),0===r)return-(l+c)/s;let h=-(c*(1+r)**s+l);return h=h*r/((1+r*a)*((1+r)**s-1)),h},isExported:!0},id={description:s("Payment on the principal of an investment."),args:[la("rate (number)",s("The annualized rate of interest.")),la("period (number)",s("The amortization period, in terms of number of periods.")),la("number_of_periods (number)",s("The number of payments to be made.")),la("present_value (number)",s("The current value of the annuity.")),la("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),la("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o,n=0,r=0){n=n||0,r=r||0;const a=Fo(i),l=Fo(e),c=Fo(t),h=Uo(r)?1:0,d=Fo(n),u=Fo(o);ah(a),No((()=>c>0&&c<=a),s("The period must be between 1 and number_of_periods",a.toString()));const g=td.compute(l,a,u,d,r);if(1===h&&1===c)return g;return g+-$h.compute(l,0===h?c-1:c-2,g,u+g*h,0)*l},isExported:!0},od={description:s("Present value of an annuity investment."),args:[la("rate (number)",s("The interest rate.")),la("number_of_periods (number)",s("The number of payments to be made.")),la("payment_amount (number)",s("The amount per period to be paid.")),la("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),la("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o=0,n=0){o=o||0,n=n||0;const s=Fo(e),r=Fo(t),a=Fo(i),l=Fo(o),c=Uo(n)?1:0;return s?-(a*(1+s*c)*((1+s)**r-1)/s+l)/(1+s)**r:-(l+a*r)},isExported:!0},nd={description:s("Price of a security paying periodic interest."),args:[la("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),la("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),la("rate (number)",s("The annualized rate of interest.")),la("yield (number)",s("The expected annual yield of the security.")),la("redemption (number)",s("The redemption amount per 100 face value, or par.")),la("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),la("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r,a=0){a=a||0;const l=Math.trunc(Fo(e)),c=Math.trunc(Fo(t)),h=Fo(i),d=Fo(o),u=Fo(n),g=Math.trunc(Fo(r)),p=Math.trunc(Fo(a));th(l,c),oh(g),nh(p),No((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),No((()=>d>=0),s("The yield (%s) must be positive or null.",d.toString())),sh(u);const m=Wc.compute(l,c,p)*g,f=Math.ceil(m),v=m-Math.floor(m)||1,b=1+d/g,S=100*h/g;if(1===f)return(S+u)/(v*d/g+1)-S*(1-v);let C=0;for(let e=1;e<=f;e++)C+=S/b**(e-1+v);return u/b**(f-1+v)+C-S*(1-v)},isExported:!0},sd={description:s("Price of a discount security."),args:[la("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),la("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),la("discount (number)",s("The discount rate of the security at time of purchase.")),la("redemption (number)",s("The redemption amount per 100 face value, or par.")),la("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(Fo(e)),r=Math.trunc(Fo(t)),a=Fo(i),l=Fo(o),c=Math.trunc(Fo(n));th(s,r),nh(c),fh(a),sh(l);return l-a*l*Wc.compute(s,r,c)},isExported:!0},rd={description:s("Calculates the price of a security paying interest at maturity, based on expected yield."),args:[la("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),la("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),la("issue (date)",s("The date the security was initially issued.")),la("rate (number)",s("The annualized rate of interest.")),la("yield (number)",s("The expected annual yield of the security.")),la("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r=0){r=r||0;const a=Math.trunc(Fo(e)),l=Math.trunc(Fo(t)),c=Math.trunc(Fo(i)),h=Fo(o),d=Fo(n),u=Math.trunc(Fo(r));ih(a,c),th(a,l),nh(u),No((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),No((()=>d>=0),s("The yield (%s) must be positive or null.",d.toString()));const g=Wc.compute(a,l,u),p=Wc.compute(a,c,u);return(100+Wc.compute(c,l,u)*h*100)/(1+g*d)-p*h*100},isExported:!0},ad=.1,ld={description:s("Interest rate of an annuity investment."),args:[la("number_of_periods (number)",s("The number of payments to be made.")),la("payment_per_period (number)",s("The amount per period to be paid.")),la("present_value (number)",s("The current value of the annuity.")),la("future_value (number, default=0)",s("The future value remaining after the final payment has been made.")),la("end_or_beginning (number, default=0)",s("Whether payments are due at the end (0) or beginning (1) of each period.")),la("rate_guess (number, default=0.1)",s("An estimate for what the interest rate will be."))],returns:["NUMBER"],computeFormat:()=>"0%",compute:function(e,t,i,o=0,n=0,r=.1){o=o||0,n=n||0,r=r||ad;const a=Fo(e),l=Fo(t),c=Uo(n)?1:0,h=Fo(r);let d=Fo(o),u=Fo(i);ah(a),No((()=>[l,u,d].some((e=>e>0))&&[l,u,d].some((e=>e<0))),s("There must be both positive and negative values in [payment_amount, present_value, future_value].",a.toString())),Eh(h),d-=l*c,u+=l*c;return Ih((e=>{const t=Math.pow(1+e,a);return d+u*t+l*((t-1)/e)}),(e=>{const t=Math.pow(1+e,a-1),i=Math.pow(1+e,a);return u*a*t+l*(a*t/e-(i-1)/e/e)}),h,40,1e-5)},isExported:!0},cd={description:s("Amount received at maturity for a security."),args:[la("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),la("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),la("investment (number)",s("The amount invested (irrespective of face value of each security).")),la("discount (number)",s("The discount rate of the security invested in.")),la("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(Fo(e)),r=Math.trunc(Fo(t)),a=Fo(i),l=Fo(o),c=Math.trunc(Fo(n));th(s,r),nh(c),mh(a),fh(l);return a/(1-l*Wc.compute(s,r,c))},isExported:!0},hd={description:s("Computes the rate needed for an investment to reach a specific value within a specific number of periods."),args:[la("number_of_periods (number)",s("The number of periods.")),la("present_value (number)",s("The present value of the investment.")),la("future_value (number)",s("The future value of the investment."))],returns:["NUMBER"],compute:function(e,t,i){const o=Fo(e),n=Fo(t),s=Fo(i);return ah(o),(s/n)**(1/o)-1},isExported:!0},dd={description:s("Depreciation of an asset using the straight-line method."),args:[la("cost (number)",s("The initial cost of the asset.")),la("salvage (number)",s("The value of the asset at the end of depreciation.")),la("life (number)",s("The number of periods over which the asset is depreciated."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i){return(Fo(e)-Fo(t))/Fo(i)},isExported:!0},ud={description:s("Depreciation via sum of years digit method."),args:[la("cost (number)",s("The initial cost of the asset.")),la("salvage (number)",s("The value of the asset at the end of depreciation.")),la("life (number)",s("The number of periods over which the asset is depreciated.")),la("period (number)",s("The single period within life for which to calculate depreciation."))],returns:["NUMBER"],computeFormat:()=>"#,##0.00",compute:function(e,t,i,o){const n=Fo(e),s=Fo(t),r=Fo(i),a=Fo(o);dh(a),ch(r),ph(a,r);return(r-a+1)/(r*(r+1)/2)*(n-s)},isExported:!0},gd={description:s("Price of a US Treasury bill."),args:[la("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),la("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),la("discount (number)",s("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,i){const o=Math.trunc(Fo(e)),n=Math.trunc(Fo(t)),s=Fo(i);th(o,n),Sh(o,n),fh(s),vh(s);return 100*(1-s*Wc.compute(o,n,2))},isExported:!0},pd={description:s("Equivalent rate of return for a US Treasury bill."),args:[la("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),la("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),la("discount (number)",s("The discount rate of the bill at time of purchase."))],returns:["NUMBER"],compute:function(e,t,i){const o=Math.trunc(Fo(e)),n=Math.trunc(Fo(t)),s=Fo(i);th(o,n),Sh(o,n),fh(s),vh(s);const r=yc.compute(n,o);if(r<=182)return 365*s/(360-s*r);const a=gd.compute(o,n,s)/100,l=r/(366===r?366:365);return(-2*l+2*Math.sqrt(l**2-(2*l-1)*(1-1/a)))/(2*l-1)},isExported:!0},md={description:s("The yield of a US Treasury bill based on price."),args:[la("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),la("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),la("price (number)",s("The price at which the security is bought per 100 face value."))],returns:["NUMBER"],compute:function(e,t,i){const o=Math.trunc(Fo(e)),n=Math.trunc(Fo(t)),s=Fo(i);th(o,n),Sh(o,n),rh(s);return(100-s)/s*(1/Wc.compute(o,n,2))},isExported:!0},fd={description:s("Variable declining balance. WARNING : does not handle decimal periods."),args:[la("cost (number)",s("The initial cost of the asset.")),la("salvage (number)",s("The value of the asset at the end of depreciation.")),la("life (number)",s("The number of periods over which the asset is depreciated.")),la("start (number)",s("Starting period to calculate depreciation.")),la("end (number)",s("Ending period to calculate depreciation.")),la("factor (number, default=2)",s("The number of months in the first year of depreciation.")),la("no_switch (number, default=false)",s("Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r=2,a=false){r=r||0;const l=Fo(e),c=Fo(t),h=Fo(i),d=Math.trunc(Fo(o)),u=Math.trunc(Fo(n)),g=Fo(r),p=Uo(a);if(hh(l),uh(c),function(e,t,i){ch(i),No((()=>e>=0),s("The start_period (%s) must be greater or equal than 0.",e.toString())),No((()=>t>=0),s("The end_period (%s) must be greater or equal than 0.",t.toString())),No((()=>e<=t),s("The start_period (%s) must be smaller or equal to the end_period (%s).",e.toString(),t.toString())),No((()=>t<=i),s("The end_period (%s) must be smaller or equal to the life (%s).",e.toString(),i.toString()))}(d,u,h),bh(g),0===l)return 0;if(c>=l)return d<1?l-c:0;const m=g/h;if(m>=1)return d<1?l-c:0;let f=l,v=0,b=0,S=!1;for(let e=0;e<u;e++){if(!S||p){const t=f*m,i=(f-c)/(h-e);!p&&i>t?(S=!0,v=i):v=t}const t=Math.max(f-v,c);e>=d&&(b+=f-t),f=t}return b},isExported:!0},vd={description:s("Internal rate of return given non-periodic cash flows."),args:[la("cashflow_amounts (range<number>)",s("An range containing the income or payments associated with the investment.")),la("cashflow_dates (range<number>)",s("An range with dates corresponding to the cash flows in cashflow_amounts.")),la("rate_guess (number, default=0.1)",s("An estimate for what the internal rate of return will be."))],returns:["NUMBER"],compute:function(e,t,i=.1){const o=Fo(i=i||0),n=e.flat().map(Fo),r=t.flat().map(Fo);var a;wh(e,t),a=n,No((()=>a.some((e=>e>0))&&a.some((e=>e<0))),s("There must be both positive and negative values in cashflow_amounts.")),yh(r),Eh(o);const l=new Map;for(const e of Be(0,r.length)){const t=r[e];l.has(t)?l.set(t,l.get(t)+n[e]):l.set(t,n[e])}const c=Array.from(l.keys()),h=c.map((e=>l.get(e)));return Ih((e=>{let t=h[0];for(const i of Be(1,h.length)){const o=(c[0]-c[i])/365;t+=h[i]*(1+e)**o}return t}),(e=>{let t=0;for(const i of Be(1,h.length)){const o=(c[0]-c[i])/365;t+=o*h[i]*(1+e)**(o-1)}return t}),o,40,1e-5,(e=>e?e/10-.9:-.9))},isExported:!0},bd={description:s("Net present value given to non-periodic cash flows.."),args:[la("discount (number)",s("The discount rate of the investment over one period.")),la("cashflow_amounts (number, range<number>)",s("An range containing the income or payments associated with the investment.")),la("cashflow_dates (number, range<number>)",s("An range with dates corresponding to the cash flows in cashflow_amounts."))],returns:["NUMBER"],compute:function(e,t,i){const o=Fo(e),n=Array.isArray(t)?t.flat().map(Do):[Do(t)],r=Array.isArray(i)?i.flat().map(Do):[Do(i)];if(Array.isArray(i)&&Array.isArray(t)?wh(t,i):No((()=>n.length===r.length),s("There must be the same number of values in cashflow_amounts and cashflow_dates.")),yh(r),lh(o),1===n.length)return n[0];const a=new Map;for(const e of Be(0,r.length)){const t=r[e];a.has(t)?a.set(t,a.get(t)+n[e]):a.set(t,n[e])}const l=Array.from(a.keys()),c=l.map((e=>a.get(e)));let h=c[0];for(const e of Be(1,c.length)){const t=(l[0]-l[e])/365;h+=c[e]*(1+o)**t}return h},isExported:!0},Sd={description:s("Annual yield of a security paying periodic interest."),args:[la("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),la("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),la("rate (number)",s("The annualized rate of interest.")),la("price (number)",s("The price at which the security is bought per 100 face value.")),la("redemption (number)",s("The redemption amount per 100 face value, or par.")),la("frequency (number)",s("The number of interest or coupon payments per year (1, 2, or 4).")),la("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r,a=0){a=a||0;const l=Math.trunc(Fo(e)),c=Math.trunc(Fo(t)),h=Fo(i),d=Fo(o),u=Fo(n),g=Math.trunc(Fo(r)),p=Math.trunc(Fo(a));th(l,c),oh(g),nh(p),No((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),rh(d),sh(u);const m=Wc.compute(l,c,p)*g,f=Math.ceil(m),v=m-Math.floor(m)||1,b=100*h/g;if(1===f){const e=d+b*(1-v);return(u+b-e)*g*(1/v)/e}const S=Ih((function(e){return function(e,t,i,o,n,s){let r=s-(e+n*(1-t))*o**(i-1+t);for(let e=1;e<=i;e++)r+=n*o**(e-1);return r}(d,v,f,e,b,u)}),(function(e){return function(e,t,i,o,n){let s=-(e+n*(1-t))*(i-1+t)*o**(i-2+t);for(let e=1;e<=i;e++)s+=n*(e-1)*o**(e-2);return s}(d,v,f,e,b)}),1+(h+1)/g,100,1e-5);return(S-1)*g},isExported:!0},Cd={description:s("Annual yield of a discount security."),args:[la("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),la("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),la("price (number)",s("The price at which the security is bought per 100 face value.")),la("redemption (number)",s("The redemption amount per 100 face value, or par.")),la("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n=0){n=n||0;const s=Math.trunc(Fo(e)),r=Math.trunc(Fo(t)),a=Fo(i),l=Fo(o),c=Math.trunc(Fo(n));th(s,r),nh(c),rh(a),sh(l);return(l/a-1)/Wc.compute(e,t,n)},isExported:!0},Ed={description:s("Annual yield of a security paying interest at maturity."),args:[la("settlement (date)",s("The settlement date of the security, the date after issuance when the security is delivered to the buyer.")),la("maturity (date)",s("The maturity or end date of the security, when it can be redeemed at face, or par value.")),la("issue (date)",s("The date the security was initially issued.")),la("rate (number)",s("The annualized rate of interest.")),la("price (number)",s("The price at which the security is bought.")),la("day_count_convention (number, default=0 )",s("An indicator of what day count method to use."))],returns:["NUMBER"],compute:function(e,t,i,o,n,r=0){r=r||0;const a=Math.trunc(Fo(e)),l=Math.trunc(Fo(t)),c=Math.trunc(Fo(i)),h=Fo(o),d=Fo(n),u=Math.trunc(Fo(r));th(a,l),nh(u),No((()=>a>=c),s("The settlement (%s) must be greater than or equal to the issue (%s).",a.toString(),c.toString())),No((()=>h>=0),s("The rate (%s) must be positive or null.",h.toString())),rh(d);const g=Wc.compute(c,l,u),p=Wc.compute(c,a,u),m=Wc.compute(a,l,u);return(100*(1+h*g)/(d+100*h*p)-1)/m},isExported:!0};var wd=Object.freeze({__proto__:null,ACCRINTM:Rh,AMORLINC:Th,COUPDAYS:Ah,COUPDAYBS:Mh,COUPDAYSNC:Oh,COUPNCD:Nh,COUPNUM:_h,COUPPCD:Fh,CUMIPMT:Dh,CUMPRINC:kh,DB:Lh,DDB:Ph,DISC:Uh,DOLLARDE:Vh,DOLLARFR:zh,DURATION:Bh,EFFECT:Hh,FV:$h,FVSCHEDULE:Wh,INTRATE:Gh,IPMT:qh,IRR:Zh,ISPMT:jh,MDURATION:Xh,MIRR:Yh,NOMINAL:Kh,NPER:Qh,NPV:Jh,PDURATION:ed,PMT:td,PPMT:id,PV:od,PRICE:nd,PRICEDISC:sd,PRICEMAT:rd,RATE:ld,RECEIVED:cd,RRI:hd,SLN:dd,SYD:ud,TBILLPRICE:gd,TBILLEQ:pd,TBILLYIELD:md,VDB:fd,XIRR:vd,XNPV:bd,YIELD:Sd,YIELDDISC:Cd,YIELDMAT:Ed});const yd={description:s("Whether a value is an error other than #N/A."),args:[la("value (any, lazy)",s("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return(null==e?void 0:e.errorType)!=a.NotAvailable}},isExported:!0},xd={description:s("Whether a value is an error."),args:[la("value (any, lazy)",s("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return!0}},isExported:!0},Id={description:s("Whether a value is `true` or `false`."),args:[la("value (any, lazy)",s("The value to be verified as a logical TRUE or FALSE."))],returns:["BOOLEAN"],compute:function(e){try{return"boolean"==typeof e()}catch(e){return!1}},isExported:!0},Rd={description:s("Whether a value is the error #N/A."),args:[la("value (any, lazy)",s("The value to be verified as an error type."))],returns:["BOOLEAN"],compute:function(e){try{return e(),!1}catch(e){return(null==e?void 0:e.errorType)==a.NotAvailable}},isExported:!0},Td={description:s("Whether a value is non-textual."),args:[la("value (any, lazy)",s("The value to be checked."))],returns:["BOOLEAN"],compute:function(e){try{return"string"!=typeof e()}catch(e){return!0}},isExported:!0},Ad={description:s("Whether a value is a number."),args:[la("value (any, lazy)",s("The value to be verified as a number."))],returns:["BOOLEAN"],compute:function(e){try{return"number"==typeof e()}catch(e){return!1}},isExported:!0},Md={description:s("Whether a value is text."),args:[la("value (any, lazy)",s("The value to be verified as text."))],returns:["BOOLEAN"],compute:function(e){try{return"string"==typeof e()}catch(e){return!1}},isExported:!0},Od={description:s("Whether the referenced cell is empty"),args:[la("value (any, lazy)",s("Reference to the cell that will be checked for emptiness."))],returns:["BOOLEAN"],compute:function(e){try{return null===e()}catch(e){return!1}},isExported:!0},Nd={description:s("Returns the error value #N/A."),args:[],returns:["BOOLEAN"],compute:function(e){throw new g},isExported:!0};var _d=Object.freeze({__proto__:null,ISERR:yd,ISERROR:xd,ISLOGICAL:Id,ISNA:Rd,ISNONTEXT:Td,ISNUMBER:Ad,ISTEXT:Md,ISBLANK:Od,NA:Nd});const Fd={description:s("Logical `and` operator."),args:[la("logical_expression1 (boolean, range<boolean>)",s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),la("logical_expression2 (boolean, range<boolean>, repeating)",s("More expressions that represent logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!0;return Zo(e,(e=>(t=!0,i=i&&e,i))),No((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0},Dd={description:s("Returns value depending on logical expression."),args:[la("logical_expression (boolean)",s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.")),la("value_if_true (any, lazy)",s("The value the function returns if logical_expression is TRUE.")),la("value_if_false (any, lazy, default=FALSE)",s("The value the function returns if logical_expression is FALSE."))],returns:["ANY"],compute:function(e,t,i=(()=>!1)){const o=Uo(e)?t():i();return null==o?"":o},isExported:!0},kd={description:s("Value if it is not an error, otherwise 2nd argument."),args:[la("value (any, lazy)",s("The value to return if value itself is not an error.")),la('value_if_error (any, lazy, default="empty")',s("The value the function returns if value is an error."))],returns:["ANY"],computeFormat:(e,t=(()=>({value:""})))=>{var i;try{return e().format}catch(e){return null===(i=t())||void 0===i?void 0:i.format}},compute:function(e,t=(()=>"")){let i;try{i=e()}catch(e){i=t()}return null==i?"":i},isExported:!0},Ld={description:s("Value if it is not an #N/A error, otherwise 2nd argument."),args:[la("value (any, lazy)",s("The value to return if value itself is not #N/A an error.")),la('value_if_error (any, lazy, default="empty")',s("The value the function returns if value is an #N/A error."))],returns:["ANY"],compute:function(e,t=(()=>"")){let i;try{i=e()}catch(o){i=o.errorType===a.NotAvailable?t():e()}return null==i?"":i},isExported:!0},Pd={description:s("Returns a value depending on multiple logical expressions."),args:[la("condition1 (boolean, lazy)",s("The first condition to be evaluated. This can be a boolean, a number, an array, or a reference to any of those.")),la("value1 (any, lazy)",s("The returned value if condition1 is TRUE.")),la("condition2 (boolean, lazy, repeating)",s("Additional conditions to be evaluated if the previous ones are FALSE.")),la("value2 (any, lazy, repeating)",s("Additional values to be returned if their corresponding conditions are TRUE."))],returns:["ANY"],compute:function(...e){No((()=>e.length%2==0),s("Wrong number of arguments. Expected an even number of arguments."));for(let t=0;t<e.length-1;t+=2)if(Uo(e[t]())){const i=e[t+1]();return null!==i?i:""}throw new Error(s("No match."))},isExported:!0},Ud={description:s("Returns opposite of provided logical value."),args:[la("logical_expression (boolean)",s("An expression or reference to a cell holding an expression that represents some logical value."))],returns:["BOOLEAN"],compute:function(e){return!Uo(e)},isExported:!0},Vd={description:s("Logical `or` operator."),args:[la("logical_expression1 (boolean, range<boolean>)",s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),la("logical_expression2 (boolean, range<boolean>, repeating)",s("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!1;return Zo(e,(e=>(t=!0,i=i||e,!i))),No((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0},zd={description:s("Logical `xor` operator."),args:[la("logical_expression1 (boolean, range<boolean>)",s("An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE, or an expression that can be coerced to a logical value.")),la("logical_expression2 (boolean, range<boolean>, repeating)",s("More expressions that evaluate to logical values."))],returns:["BOOLEAN"],compute:function(...e){let t=!1,i=!1;return Zo(e,(e=>(t=!0,i=i?!e:e,!0))),No((()=>t),s("[[FUNCTION_NAME]] has no valid input data.")),i},isExported:!0};var Bd=Object.freeze({__proto__:null,AND:Fd,IF:Dd,IFERROR:kd,IFNA:Ld,IFS:Pd,NOT:Ud,OR:Vd,XOR:zd});function Hd(e,t){if(void 0===e)throw new g(s("Did not find value '%s' in [[FUNCTION_NAME]] evaluation.",ko(t)))}const $d={description:s("Column number of a specified cell."),args:[la("cell_reference (meta, default='this cell')",s("The cell whose column number will be returned. Column A corresponds to 1. By default, the function use the cell in which the formula is entered."))],returns:["NUMBER"],compute:function(e){var t;const i=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this));No((()=>!!i),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Pi(i).left+1},isExported:!0},Wd={description:s("Number of columns in a specified array or range."),args:[la("range (meta)",s("The range whose column count will be returned."))],returns:["NUMBER"],compute:function(e){const t=Pi(e);return t.right-t.left+1},isExported:!0},Gd={description:s("Horizontal lookup"),args:[la("search_key (any)",s("The value to search for. For example, 42, 'Cats', or I24.")),la("range (range)",s("The range to consider for the search. The first row in the range is searched for the key specified in search_key.")),la("index (number)",s("The row index of the value to be returned, where the first row in range is numbered 1.")),la("is_sorted (boolean, default=true)",s("Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned."))],returns:["ANY"],compute:function(e,t,i,o=true){const n=Math.trunc(Fo(i)),r=Lo(e);No((()=>1<=n&&n<=t[0].length),s("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=Uo(o)?Jo(t,r,"nextSmaller","asc",t.length,Qo):en(t,r,"strict",t.length,Qo);const l=t[a];return Hd(l,e),l[n-1]},isExported:!0},qd={description:s("Look up a value."),args:[la("search_key (any)",s("The value to search for. For example, 42, 'Cats', or I24.")),la("search_array (range)",s("One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.")),la("result_range (range, optional)",s("The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method."))],returns:["ANY"],compute:function(e,t,i){let o=t.length,n=t[0].length;const r=Lo(e),a=n>=o,l=Jo(t,r,"nextSmaller","asc",a?n:o,a?Ko:Qo);return-1===l&&Hd(void 0,e),Hd(a?t[0][l]:t[l][n-1],e),void 0===i?a?t[o-1][l]:t[l][n-1]:(o=i.length,n=i[0].length,No((()=>1===o||1===n),s("The result_range must be a single row or a single column.")),o>1?(No((()=>l<=o-1),s("[[FUNCTION_NAME]] evaluates to an out of range row value %s.",(l+1).toString())),i[l][0]):(No((()=>l<=n-1),s("[[FUNCTION_NAME]] evaluates to an out of range column value %s.",(l+1).toString())),i[0][l]))},isExported:!0},Zd={description:s("Position of item in range that matches value."),args:[la("search_key (any)",s("The value to search for. For example, 42, 'Cats', or I24.")),la("range (any, range)",s("The one-dimensional array to be searched.")),la("search_type (number, default=1)",s("The search method. 1 (default) finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order."))],returns:["NUMBER"],compute:function(e,t,i=1){let o=Fo(i);const n=Lo(e),r=t.length,a=t[0].length;No((()=>1===r||1===a),s("The range must be a single row or a single column."));let l=-1;const c=1===r?Ko:Qo,h=1===r?t[0].length:t.length;switch(o=Math.sign(o),o){case 1:l=Jo(t,n,"nextSmaller","asc",h,c);break;case 0:l=en(t,n,"strict",h,c);break;case-1:l=Jo(t,n,"nextGreater","desc",h,c)}return Hd(1===r?t[0][l]:t[l],e),l+1},isExported:!0},jd={description:s("Row number of a specified cell."),args:[la("cell_reference (meta, default='this cell')",s("The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered."))],returns:["NUMBER"],compute:function(e){var t;e=e||(null===(t=this.__originCellXC)||void 0===t?void 0:t.call(this)),No((()=>!!e),"In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.");return Pi(e).top+1},isExported:!0},Xd={description:s("Number of rows in a specified array or range."),args:[la("range (meta)",s("The range whose row count will be returned."))],returns:["NUMBER"],compute:function(e){const t=Pi(e);return t.bottom-t.top+1},isExported:!0},Yd={description:s("Vertical lookup."),args:[la("search_key (any)",s("The value to search for. For example, 42, 'Cats', or I24.")),la("range (any, range)",s("The range to consider for the search. The first column in the range is searched for the key specified in search_key.")),la("index (number)",s("The column index of the value to be returned, where the first column in range is numbered 1.")),la("is_sorted (boolean, default=true)",s("Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned."))],returns:["ANY"],compute:function(e,t,i,o=true){const n=Math.trunc(Fo(i)),r=Lo(e);No((()=>1<=n&&n<=t.length),s("[[FUNCTION_NAME]] evaluates to an out of bounds range."));let a;a=Uo(o)?Jo(t,r,"nextSmaller","asc",t[0].length,Ko):en(t,r,"strict",t[0].length,Ko);const l=t[n-1][a];return Hd(l,e),l},isExported:!0},Kd={description:s("Search a range for a match and return the corresponding item from a second range."),args:[la("search_key (any)",s("The value to search for.")),la("lookup_range (any, range)",s("The range to consider for the search. Should be a single column or a single row.")),la("return_range (any, range)",s("The range containing the return value. Should have the same dimensions as lookup_range.")),la("if_not_found (any, lazy, optional)",s("If a valid match is not found, return this value.")),la("match_mode (any, default=0)",s("(0) Exact match. (-1) Return next smaller item if no match. (1) Return next greater item if no match.")),la("search_mode (any, default=1)",s("(1) Search starting at first item. (-1) Search starting at last item. (2) Perform a binary search that relies on lookup_array being sorted in ascending order. If not sorted, invalid results will be returned. (-2) Perform a binary search that relies on lookup_array being sorted in descending order. If not sorted, invalid results will be returned. "))],returns:["ANY"],compute:function(e,t,i,o,n=0,r=1){const a=Math.trunc(Fo(n)),l=Math.trunc(Fo(r)),c=Lo(e);No((()=>1===t.length||1===t[0].length),s("lookup_range should be either a single row or single column.")),No((()=>1===i.length||1===i[0].length),s("return_range should be either a single row or single column.")),No((()=>i.length===t.length&&i[0].length===t[0].length),s("return_range should have the same dimensions as lookup_range.")),No((()=>[-1,1,-2,2].includes(l)),s("searchMode should be a value in [-1, 1, -2, 2].")),No((()=>[-1,0,1].includes(a)),s("matchMode should be a value in [-1, 0, 1]."));const h=1===t.length?Ko:Qo,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=Jo(t,c,u,2===l?"asc":"desc",d,h)}else p=en(t,c,u,d,h,g);if(-1!==p)return 1===t.length?i[0][p]:i[p][0];const m=null==o?void 0:o();return Hd(m,e),m},isExported:!0};var Qd=Object.freeze({__proto__:null,COLUMN:$d,COLUMNS:Wd,HLOOKUP:Gd,LOOKUP:qd,MATCH:Zd,ROW:jd,ROWS:Xd,VLOOKUP:Yd,XLOOKUP:Kd});const Jd={description:s("Sum of two numbers."),args:[la("value1 (number)",s("The first addend.")),la("value2 (number)",s("The second addend."))],returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return Fo(e)+Fo(t)}},eu={description:s("Concatenation of two values."),args:[la("value1 (string)",s("The value to which value2 will be appended.")),la("value2 (string)",s("The value to append to value1."))],returns:["STRING"],compute:function(e,t){return ko(e)+ko(t)},isExported:!0},tu={description:s("One number divided by another."),args:[la("dividend (number)",s("The number to be divided.")),la("divisor (number)",s("The number to divide by."))],returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){const i=Fo(t);return No((()=>0!==i),s("The divisor must be different from zero.")),Fo(e)/i}};function iu(e){return null==e}const ou={number:0,string:"",boolean:!1},nu={description:s("Equal."),args:[la("value1 (any)",s("The first value.")),la("value2 (any)",s("The value to test against value1 for equality."))],returns:["BOOLEAN"],compute:function(e,t){return e=iu(e)?ou[typeof t]:e,t=iu(t)?ou[typeof e]:t,"string"==typeof e&&(e=e.toUpperCase()),"string"==typeof t&&(t=t.toUpperCase()),e===t}};function su(e,t,i){e=iu(e)?ou[typeof t]:e,t=iu(t)?ou[typeof e]:t,"number"!=typeof e&&(e=ko(e).toUpperCase()),"number"!=typeof t&&(t=ko(t).toUpperCase());const o=typeof e,n=typeof t;return"string"===o&&"number"===n||("string"!==n||"number"!==o)&&i(e,t)}const ru={description:s("Strictly greater than."),args:[la("value1 (any)",s("The value to test as being greater than value2.")),la("value2 (any)",s("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return su(e,t,((e,t)=>e>t))}},au={description:s("Greater than or equal to."),args:[la("value1 (any)",s("The value to test as being greater than or equal to value2.")),la("value2 (any)",s("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return su(e,t,((e,t)=>e>=t))}},lu={description:s("Less than."),args:[la("value1 (any)",s("The value to test as being less than value2.")),la("value2 (any)",s("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!au.compute(e,t)}},cu={description:s("Less than or equal to."),args:[la("value1 (any)",s("The value to test as being less than or equal to value2.")),la("value2 (any)",s("The second value."))],returns:["BOOLEAN"],compute:function(e,t){return!ru.compute(e,t)}},hu={description:s("Difference of two numbers."),args:[la("value1 (number)",s("The minuend, or number to be subtracted from.")),la("value2 (number)",s("The subtrahend, or number to subtract from value1."))],returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return Fo(e)-Fo(t)}},du={description:s("Product of two numbers"),args:[la("factor1 (number)",s("The first multiplicand.")),la("factor2 (number)",s("The second multiplicand."))],returns:["NUMBER"],computeFormat:(e,t)=>(null==e?void 0:e.format)||(null==t?void 0:t.format),compute:function(e,t){return Fo(e)*Fo(t)}},uu={description:s("Not equal."),args:[la("value1 (any)",s("The first value.")),la("value2 (any)",s("The value to test against value1 for inequality."))],returns:["BOOLEAN"],compute:function(e,t){return!nu.compute(e,t)}},gu={description:s("A number raised to a power."),args:[la("base (number)",s("The number to raise to the exponent power.")),la("exponent (number)",s("The exponent to raise base to."))],returns:["NUMBER"],compute:function(e,t){return Ya.compute(e,t)}},pu={description:s("A number with the sign reversed."),args:[la("value (number)",s("The number to have its sign reversed. Equivalently, the number to multiply by -1."))],computeFormat:e=>null==e?void 0:e.format,returns:["NUMBER"],compute:function(e){return-Fo(e)}},mu={description:s("Value interpreted as a percentage."),args:[la("percentage (number)",s("The value to interpret as a percentage."))],returns:["NUMBER"],compute:function(e){return Fo(e)/100}},fu={description:s("A specified number, unchanged."),args:[la("value (any)",s("The number to return."))],returns:["ANY"],computeFormat:e=>null==e?void 0:e.format,compute:function(e){return null===e?"":e}};var vu=Object.freeze({__proto__:null,ADD:Jd,CONCAT:eu,DIVIDE:tu,EQ:nu,GT:ru,GTE:au,LT:lu,LTE:cu,MINUS:hu,MULTIPLY:du,NE:uu,POW:gu,UMINUS:pu,UNARY_PERCENT:mu,UPLUS:fu});const bu=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,Su={description:s("Gets character associated with number."),args:[la("table_number (number)",s("The number of the character to look up from the current Unicode table in decimal format."))],returns:["STRING"],compute:function(e){const t=Math.trunc(Fo(e));return No((()=>t>=1),s("The table_number (%s) is out of range.",t.toString())),String.fromCharCode(t)},isExported:!0},Cu={description:s("Remove non-printable characters from a piece of text."),args:[la("text (string)",s("The text whose non-printable characters are to be removed."))],returns:["STRING"],compute:function(e){const t=ko(e);let i="";for(const e of t)e&&e.charCodeAt(0)>31&&(i+=e);return i},isExported:!0},Eu={description:s("Appends strings to one another."),args:[la("string1 (string, range<string>)",s("The initial string.")),la("string2 (string, range<string>, repeating)",s("More strings to append in sequence."))],returns:["STRING"],compute:function(...e){return Wo(e,((e,t)=>e+ko(t)),"")},isExported:!0},wu={description:s("Tests whether two strings are identical."),args:[la("string1 (string)",s("The first string to compare.")),la("string2 (string)",s("The second string to compare."))],returns:["BOOLEAN"],compute:function(e,t){return ko(e)===ko(t)},isExported:!0},yu={description:s("First position of string found in text, case-sensitive."),args:[la("search_for (string)",s("The string to look for within text_to_search.")),la("text_to_search (string)",s("The text to search for the first occurrence of search_for.")),la("starting_at (number, default=1)",s("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,i=1){const o=ko(e),n=ko(t),r=Fo(i);No((()=>""!==n),s("The text_to_search must be non-empty.")),No((()=>r>=1),s("The starting_at (%s) must be greater than or equal to 1.",r.toString()));const a=n.indexOf(o,r-1);return No((()=>a>=0),s("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o.toString(),n)),a+1},isExported:!0},xu={description:s("Concatenates elements of arrays with delimiter."),args:[la("delimiter (string)",s("The character or string to place between each concatenated value.")),la("value_or_array1 (string, range<string>)",s("The value or values to be appended using delimiter.")),la("value_or_array2 (string, range<string>, repeating)",s("More values to be appended using delimiter."))],returns:["STRING"],compute:function(e,...t){const i=ko(e);return Wo(t,((e,t)=>(e?e+i:"")+ko(t)),"")}},Iu={description:s("Substring from beginning of specified string."),args:[la("text (string)",s("The string from which the left portion will be returned.")),la("number_of_characters (number, optional)",s("The number of characters to return from the left side of string."))],returns:["STRING"],compute:function(e,...t){const i=t.length?Fo(t[0]):1;return No((()=>i>=0),s("The number_of_characters (%s) must be positive or null.",i.toString())),ko(e).substring(0,i)},isExported:!0},Ru={description:s("Length of a string."),args:[la("text (string)",s("The string whose length will be returned."))],returns:["NUMBER"],compute:function(e){return ko(e).length},isExported:!0},Tu={description:s("Converts a specified string to lowercase."),args:[la("text (string)",s("The string to convert to lowercase."))],returns:["STRING"],compute:function(e){return ko(e).toLowerCase()},isExported:!0},Au={description:s("A segment of a string."),args:[la("text (string)",s("The string to extract a segment from.")),la(" (number)",s("The index from the left of string from which to begin extracting. The first character in string has the index 1.")),la(" (number)",s("The length of the segment to extract."))],returns:["STRING"],compute:function(e,t,i){const o=ko(e),n=Fo(t),r=Fo(i);return No((()=>n>=1),s("The starting_at argument (%s) must be positive greater than one.",n.toString())),No((()=>r>=0),s("The extract_length argument (%s) must be positive or null.",r.toString())),o.slice(n-1,n+r-1)},isExported:!0},Mu={description:s("Capitalizes each word in a specified string."),args:[la("text_to_capitalize (string)",s("The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase."))],returns:["STRING"],compute:function(e){return ko(e).replace(bu,(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()))},isExported:!0},Ou={description:s("Replaces part of a text string with different text."),args:[la("text (string)",s("The text, a part of which will be replaced.")),la("position (number)",s("The position where the replacement will begin (starting from 1).")),la("length (number)",s("The number of characters in the text to be replaced.")),la("new_text (string)",s("The text which will be inserted into the original text."))],returns:["STRING"],compute:function(e,t,i,o){const n=Fo(t);No((()=>n>=1),s("The position (%s) must be greater than or equal to 1.",n.toString()));const r=ko(e),a=Fo(i),l=ko(o);return r.substring(0,n-1)+l+r.substring(n-1+a)},isExported:!0},Nu={description:s("A substring from the end of a specified string."),args:[la("text (string)",s("The string from which the right portion will be returned.")),la("number_of_characters (number, optional)",s("The number of characters to return from the right side of string."))],returns:["STRING"],compute:function(e,...t){const i=t.length?Fo(t[0]):1;No((()=>i>=0),s("The number_of_characters (%s) must be positive or null.",i.toString()));const o=ko(e),n=o.length;return o.substring(n-i,n)},isExported:!0},_u={description:s("First position of string found in text, ignoring case."),args:[la("search_for (string)",s("The string to look for within text_to_search.")),la("text_to_search (string)",s("The text to search for the first occurrence of search_for.")),la("starting_at (number, default=1)",s("The character within text_to_search at which to start the search."))],returns:["NUMBER"],compute:function(e,t,i=1){const o=ko(e).toLowerCase(),n=ko(t).toLowerCase(),r=Fo(i);No((()=>""!==n),s("The text_to_search must be non-empty.")),No((()=>r>=1),s("The starting_at (%s) must be greater than or equal to 1.",r.toString()));const a=n.indexOf(o,r-1);return No((()=>a>=0),s("In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.",o,n)),a+1},isExported:!0},Fu={description:s("Replaces existing text with new text in a string."),args:[la("text_to_search (string)",s("The text within which to search and replace.")),la("search_for (string)",s("The string to search for within text_to_search.")),la("replace_with (string)",s("The string that will replace search_for.")),la("occurrence_number (number, optional)",s("The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced."))],returns:["NUMBER"],compute:function(e,t,i,o){const n=Fo(o);No((()=>n>=0),s("The occurrenceNumber (%s) must be positive or null.",n.toString()));const r=ko(e),a=ko(t);if(""===a)return r;const l=ko(i),c=new RegExp(Oe(a),"g");if(0===n)return r.replace(c,l);let h=0;return r.replace(c,(e=>++h===n?l:e))},isExported:!0},Du={description:s("Combines text from multiple strings and/or arrays."),args:[la("delimiter (string)",s(" A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.")),la("ignore_empty (boolean)",s("A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.")),la("text1 (string, range<string>)",s("Any text item. This could be a string, or an array of strings in a range.")),la("text2 (string, range<string>, repeating)",s("Additional text item(s)."))],returns:["STRING"],compute:function(e,t,...i){const o=ko(e),n=Uo(t);let s=0;return Wo(i,((e,t)=>n&&""===ko(t)?e:(s++?e+o:"")+ko(t)),"")},isExported:!0},ku={description:s("Removes space characters."),args:[la("text (string)",s("The text or reference to a cell containing text to be trimmed."))],returns:["STRING"],compute:function(e){return ko(e).trim()},isExported:!0},Lu={description:s("Converts a specified string to uppercase."),args:[la("text (string)",s("The string to convert to uppercase."))],returns:["STRING"],compute:function(e){return ko(e).toUpperCase()},isExported:!0},Pu={description:s("Converts a number to text according to a specified format."),args:[la("number (number)",s("The number, date or time to format.")),la("format (string)",s("The pattern by which to format the number, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){return di(Fo(e),ko(t))},isExported:!0};var Uu=Object.freeze({__proto__:null,CHAR:Su,CLEAN:Cu,CONCATENATE:Eu,EXACT:wu,FIND:yu,JOIN:xu,LEFT:Iu,LEN:Ru,LOWER:Tu,MID:Au,PROPER:Mu,REPLACE:Ou,RIGHT:Nu,SEARCH:_u,SUBSTITUTE:Fu,TEXTJOIN:Du,TRIM:ku,UPPER:Lu,TEXT:Pu});const Vu={description:s("Creates a hyperlink in a cell."),args:[la("url (string)",s("The full URL of the link enclosed in quotation marks.")),la("link_label (string, optional)",s("The text to display in the cell, enclosed in quotation marks."))],returns:["STRING"],compute:function(e,t){const i=ko(e).trim(),o=ko(t)||i;return""===i?o:Xe(o,i)},isExported:!0};var zu=Object.freeze({__proto__:null,HYPERLINK:Vu});const Bu=[{name:s("Database"),functions:Sc},{name:s("Date"),functions:Qc},{name:s("Financial"),functions:wd},{name:s("Info"),functions:_d},{name:s("Lookup"),functions:Qd},{name:s("Logical"),functions:Bd},{name:s("Math"),functions:pl},{name:s("Misc"),functions:da},{name:s("Operator"),functions:vu},{name:s("Statistical"),functions:nc},{name:s("Text"),functions:Uu},{name:s("Engineering"),functions:eh},{name:s("Web"),functions:zu}],Hu=/^[A-Z0-9\_\.]+$/;function $u(e){return e.map((e=>{if(void 0!==e)return"function"==typeof e?()=>Wu(e()):Wu(e)}))}function Wu(e){return Array.isArray(e)?e.map((e=>e.map((e=>null==e?void 0:e.value)))):null==e?void 0:e.value}const Gu=new class extends Eo{constructor(){super(...arguments),this.mapping={}}add(e,t){if(!(e=e.toUpperCase()).match(Hu))throw new Error(s("Invalid function name %s. Function names can exclusively contain alphanumerical values separated by dots (.) or underscore (_)",e));const i=ca(t);return function(e){let t=!1,i=!1,o=!1;for(let n of e){if(n.type.includes("META")&&n.type.length>1)throw new Error(s("Function ${name} has an argument that has been declared with more than one type whose type 'META'. The 'META' type can only be declared alone."));if(t&&!n.repeating)throw new Error(s("Function ${name} has no-repeatable arguments declared after repeatable ones. All repeatable arguments must be declared last."));const e=i||t||o,r=!(n.optional||n.repeating||n.default);if(e&&r)throw new Error(s("Function ${name} has at mandatory arguments declared after optional ones. All optional arguments must be after all mandatory arguments."));t=n.repeating,i=n.optional,o=n.default}}(i.args),this.mapping[e]=function(...e){const t=i.compute.bind(this),o=i.computeFormat?i.computeFormat.bind(this):()=>{};return{value:t(...$u(e)),format:o(...e)}},super.add(e,i),this}};for(let e of Bu){const t=e.functions;for(let i in t){const o=t[i];o.category=o.category||e.name,i=i.replace(/_/g,"."),Gu.add(i,{isExported:!1,...o})}}function qu(e,t,i){const o=e.model.getters.getActiveSheetId(),n="COL"===t?"FREEZE_COLUMNS":"FREEZE_ROWS";e.model.dispatch(n,{sheetId:o,quantity:i}).isCancelledBecause(65)&&e.raiseError(As)}const Zu=new Jn;Zu.add("file",{name:s("File"),sequence:10}).add("edit",{name:s("Edit"),sequence:20}).add("view",{name:s("View"),sequence:30}).add("insert",{name:s("Insert"),sequence:40}).add("format",{name:s("Format"),sequence:50}).add("data",{name:s("Data"),sequence:60}).addChild("save",["file"],{name:s("Save"),description:"Ctrl+S",sequence:10,action:()=>console.log("Not implemented")}).addChild("undo",["edit"],{name:s("Undo"),description:"Ctrl+Z",sequence:10,action:e=>e.model.dispatch("REQUEST_UNDO")}).addChild("redo",["edit"],{name:s("Redo"),description:"Ctrl+Y",sequence:20,action:e=>e.model.dispatch("REQUEST_REDO"),separator:!0}).addChild("copy",["edit"],{name:s("Copy"),description:"Ctrl+C",sequence:30,isReadonlyAllowed:!0,action:_r}).addChild("cut",["edit"],{name:s("Cut"),description:"Ctrl+X",sequence:40,action:Fr}).addChild("paste",["edit"],{name:s("Paste"),description:"Ctrl+V",sequence:50,action:Dr}).addChild("paste_special",["edit"],{name:s("Paste special"),sequence:60,separator:!0,isVisible:Ur}).addChild("paste_special_value",["edit","paste_special"],{name:s("Paste value only"),sequence:10,action:kr}).addChild("paste_special_format",["edit","paste_special"],{name:s("Paste format only"),sequence:20,action:Pr}).addChild("sort_range",["data"],{name:s("Sort range"),sequence:20,isVisible:ia,separator:!0}).addChild("sort_ascending",["data","sort_range"],{name:s("Ascending (A ⟶ Z)"),sequence:10,action:ea}).addChild("sort_descending",["data","sort_range"],{name:s("Descending (Z ⟶ A)"),sequence:20,action:ta}).addChild("find_and_replace",["edit"],{name:s("Find and replace"),description:"Ctrl+H",sequence:65,isReadonlyAllowed:!0,action:e=>{e.openSidePanel("FindAndReplace",{})},separator:!0}).addChild("edit_delete_cell_values",["edit"],{name:s("Delete values"),sequence:70,action:e=>e.model.dispatch("DELETE_CONTENT",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})}).addChild("edit_delete_row",["edit"],{name:Vr,sequence:80,action:zr}).addChild("edit_delete_column",["edit"],{name:Br,sequence:90,action:Hr}).addChild("edit_delete_cell_shift_up",["edit"],{name:s("Delete cell and shift up"),sequence:93,action:Gr}).addChild("edit_delete_cell_shift_left",["edit"],{name:s("Delete cell and shift left"),sequence:97,action:qr}).addChild("edit_unhide_columns",["edit"],{name:s("Unhide all columns"),sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"COL",elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0}).addChild("edit_unhide_rows",["edit"],{name:s("Unhide all rows"),sequence:100,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:t,dimension:"ROW",elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0}).addChild("insert_row_before",["insert"],{name:e=>{const t=Mr(e);return 1===t?s("Row above"):s("%s Rows above",t.toString())},sequence:10,action:Zr,isVisible:e=>0===e.model.getters.getActiveCols().size}).addChild("insert_row_after",["insert"],{name:e=>{const t=Mr(e);return 1===t?s("Row below"):s("%s Rows below",t.toString())},sequence:20,action:jr,isVisible:e=>0===e.model.getters.getActiveCols().size,separator:!0}).addChild("insert_column_before",["insert"],{name:e=>{const t=Ar(e);return 1===t?s("Column left"):s("%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=Ar(e);return 1===t?s("Column right"):s("%s Columns right",t.toString())},sequence:40,action:Yr,isVisible:e=>0===e.model.getters.getActiveRows().size,separator:!0}).addChild("insert_insert_cell_shift_down",["insert"],{name:s("Insert cells and shift down"),sequence:43,action:$r}).addChild("insert_insert_cell_shift_right",["insert"],{name:s("Insert cells and shift right"),sequence:47,action:Wr,separator:!0}).addChild("insert_chart",["insert"],{name:s("Chart"),sequence:50,action:e=>{const t=e.model.getters,i=e.model.uuidGenerator.uuidv4(),o=t.getActiveSheetId();1===ro(e.model.getters.getSelectedZone())&&e.model.selection.selectTableAroundSelection();const n={width:536,height:335},s=function(e,t){const{x:i,y:o}=e.getMainViewportCoordinates(),{scrollX:n,scrollY:s}=e.getActiveSheetScrollInfo(),{width:r,height:a}=e.getVisibleRect(e.getActiveMainViewport());return{x:i+n+Math.max(0,(r-t.width)/2),y:o+s+Math.max(0,(a-t.height)/2)}}(t,n);e.model.dispatch("CREATE_CHART",{sheetId:o,id:i,position:s,size:n,definition:br(e.model.getters.getSelectedZone(),e.model.getters)}).isSuccessful&&(e.model.dispatch("SELECT_FIGURE",{id:i}),e.openSidePanel("ChartPanel"))}}).addChild("insert_image",["insert"],{name:s("Image"),sequence:55,action:async e=>{if(e.imageProvider){const t=e.model.getters.getActiveSheetId(),i=e.model.uuidGenerator.uuidv4(),o=await async function(e){try{return await e.imageProvider.requestImage()}catch{return void e.raiseError(s("An unexpected error occurred during the image transfer"))}}(e);if(!o)throw new Error("No image provider was given to the environment");const n=hr(e.model.getters,o.size),r=function(e,t){const{x:i,y:o}=e.getMainViewportCoordinates(),{scrollX:n,scrollY:s}=e.getActiveSheetScrollInfo(),r=e.getSheetViewDimension(),a=e.getVisibleRect(e.getActiveMainViewport()),l=Math.min(a.width,r.width-i),c=Math.min(a.height,r.height-o);return{x:i+n+Math.max(0,(l-t.width)/2),y:o+s+Math.max(0,(c-t.height)/2)}}(e.model.getters,n);e.model.dispatch("CREATE_IMAGE",{sheetId:t,figureId:i,position:r,size:n,definition:o})}},isVisible:e=>void 0!==e.imageProvider}).addChild("insert_function",["insert"],{name:s("Function"),sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{name:s("SUM"),action:e=>e.startCellEdition("=SUM("),sequence:0}).addChild("insert_function_average",["insert","insert_function"],{name:s("AVERAGE"),action:e=>e.startCellEdition("=AVERAGE("),sequence:10}).addChild("insert_function_count",["insert","insert_function"],{name:s("COUNT"),action:e=>e.startCellEdition("=COUNT("),sequence:20}).addChild("insert_function_max",["insert","insert_function"],{name:s("MAX"),action:e=>e.startCellEdition("=MAX("),sequence:30}).addChild("insert_function_min",["insert","insert_function"],{name:s("MIN"),action:e=>e.startCellEdition("=MIN("),sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{name:s("All"),sequence:50}).addChild("all_function_list",["insert","insert_function","categorie_function_all"],(()=>ju(Gu.getKeys()))).addChild("categories_function_list",["insert","insert_function"],(()=>{const e=Gu.content;return[...new Set(Gu.getAll().map((e=>e.category)))].filter(tt).sort().map(((t,i)=>{const o=Object.keys(e).filter((i=>e[i].category===t));return{name:t,sequence:60+10*i,children:ju(o)}}))})).addChild("insert_link",["insert"],{name:s("Link"),separator:!0,sequence:70,action:Qr}).addChild("insert_sheet",["insert"],{name:s("New sheet"),sequence:80,action:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSheetIds().indexOf(t)+1,o=e.model.uuidGenerator.uuidv4();e.model.dispatch("CREATE_SHEET",{sheetId:o,position:i}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})},separator:!0}).addChild("unfreeze_panes",["view"],{name:s("Unfreeze"),sequence:4,isVisible:e=>{const{xSplit:t,ySplit:i}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+i>0},action:e=>e.model.dispatch("UNFREEZE_COLUMNS_ROWS",{sheetId:e.model.getters.getActiveSheetId()})}).addChild("freeze_panes",["view"],{name:s("Freeze"),sequence:5,separator:!0}).addChild("unfreeze_rows",["view","freeze_panes"],{name:s("No rows"),action:e=>e.model.dispatch("UNFREEZE_ROWS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,sequence:5,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit}).addChild("freeze_first_row",["view","freeze_panes"],{name:s("1 row"),action:e=>qu(e,"ROW",1),isReadonlyAllowed:!0,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{name:s("2 rows"),action:e=>qu(e,"ROW",2),isReadonlyAllowed:!0,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{name:s("Up to current row"),action:e=>{const{bottom:t}=e.model.getters.getSelectedZone();qu(e,"ROW",t+1)},isReadonlyAllowed:!0,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{name:s("No columns"),action:e=>e.model.dispatch("UNFREEZE_COLUMNS",{sheetId:e.model.getters.getActiveSheetId()}),isReadonlyAllowed:!0,sequence:25,isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit}).addChild("freeze_first_col",["view","freeze_panes"],{name:s("1 column"),action:e=>qu(e,"COL",1),isReadonlyAllowed:!0,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{name:s("2 columns"),action:e=>qu(e,"COL",2),isReadonlyAllowed:!0,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{name:s("Up to current column"),action:e=>{const{right:t}=e.model.getters.getSelectedZone();qu(e,"COL",t+1)},isReadonlyAllowed:!0,sequence:40}).addChild("view_gridlines",["view"],{name:e=>e.model.getters.getGridLinesVisibility(e.model.getters.getActiveSheetId())?s("Hide gridlines"):s("Show gridlines"),action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("SET_GRID_LINES_VISIBILITY",{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},sequence:10}).addChild("view_formulas",["view"],{name:e=>e.model.getters.shouldShowFormulas()?s("Hide formulas"):s("Show formulas"),action:e=>e.model.dispatch("SET_FORMULA_VISIBILITY",{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,sequence:15}).addChild("format_number",["format"],{name:s("Numbers"),sequence:10,separator:!0}).addChild("format_number_automatic",["format","format_number"],{name:Rs.Automatic,sequence:10,separator:!0,action:e=>Or(e,"")}).addChild("format_number_number",["format","format_number"],{name:Rs.Number,description:"1,000.12",sequence:20,action:e=>Or(e,"#,##0.00")}).addChild("format_number_percent",["format","format_number"],{name:Rs.Percent,description:"10.12%",sequence:30,separator:!0,action:e=>Or(e,"0.00%")}).addChild("format_number_currency",["format","format_number"],{name:Rs.Currency,description:"$1,000.12",sequence:37,action:e=>Or(e,"[$$]#,##0.00")}).addChild("format_number_currency_rounded",["format","format_number"],{name:Rs.CurrencyRounded,description:"$1,000",sequence:38,action:e=>Or(e,"[$$]#,##0")}).addChild("format_custom_currency",["format","format_number"],{name:Rs.CustomCurrency,sequence:39,separator:!0,isVisible:e=>void 0!==e.loadCurrencies,action:e=>{e.openSidePanel("CustomCurrency",{})}}).addChild("format_number_date",["format","format_number"],{name:Rs.Date,description:"9/26/2008",sequence:40,action:e=>Or(e,"m/d/yyyy")}).addChild("format_number_time",["format","format_number"],{name:Rs.Time,description:"10:43:00 PM",sequence:50,action:e=>Or(e,"hh:mm:ss a")}).addChild("format_number_date_time",["format","format_number"],{name:Rs.DateTime,description:"9/26/2008 22:43:00",sequence:60,action:e=>Or(e,"m/d/yyyy hh:mm:ss")}).addChild("format_number_duration",["format","format_number"],{name:Rs.Duration,description:"27:51:38",sequence:70,separator:!0,action:e=>Or(e,"hhhh:mm:ss")}).addChild("format_bold",["format"],{name:s("Bold"),sequence:20,description:"Ctrl+B",action:e=>Nr(e,{bold:!e.model.getters.getCurrentStyle().bold})}).addChild("format_italic",["format"],{name:s("Italic"),sequence:30,description:"Ctrl+I",action:e=>Nr(e,{italic:!e.model.getters.getCurrentStyle().italic})}).addChild("format_underline",["format"],{name:s("Underline"),description:"Ctrl+U",sequence:40,action:e=>Nr(e,{underline:!e.model.getters.getCurrentStyle().underline})}).addChild("format_strikethrough",["format"],{name:s("Strikethrough"),sequence:50,action:e=>Nr(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),separator:!0}).addChild("format_font_size",["format"],{name:s("Font size"),sequence:60,separator:!0}).addChild("format_alignment",["format"],{name:s("Alignment"),sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{name:"Left",sequence:10,action:e=>Nr(e,{align:"left"})}).addChild("format_alignment_center",["format","format_alignment"],{name:"Center",sequence:20,action:e=>Nr(e,{align:"center"})}).addChild("format_alignment_right",["format","format_alignment"],{name:"Right",sequence:30,action:e=>Nr(e,{align:"right"}),separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{name:"Top",sequence:40,action:e=>Nr(e,{verticalAlign:"top"})}).addChild("format_alignment_middle",["format","format_alignment"],{name:"Middle",sequence:50,action:e=>Nr(e,{verticalAlign:"middle"})}).addChild("format_alignment_bottom",["format","format_alignment"],{name:"Bottom",sequence:60,action:e=>Nr(e,{verticalAlign:"bottom"}),separator:!0}).addChild("format_wrapping",["format"],{name:s("Wrapping"),sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{name:s("Overflow"),sequence:10,action:e=>Nr(e,{wrapping:"overflow"})}).addChild("format_wrapping_wrap",["format","format_wrapping"],{name:s("Wrap"),sequence:20,action:e=>Nr(e,{wrapping:"wrap"})}).addChild("format_wrapping_clip",["format","format_wrapping"],{name:s("Clip"),sequence:30,action:e=>Nr(e,{wrapping:"clip"})}).addChild("format_cf",["format"],{name:s("Conditional formatting"),sequence:90,action:Kr,separator:!0}).addChild("format_clearFormat",["format"],{name:s("Clear formatting"),sequence:100,action:e=>{e.model.dispatch("CLEAR_FORMATTING",{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},separator:!0}).addChild("add_data_filter",["data"],{name:s("Create filter"),sequence:10,action:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getSelection().zones;yr(e,t,i)},isVisible:e=>!Jr(e),isEnabled:e=>(e=>ao(...e.model.getters.getSelectedZones()))(e)}).addChild("remove_data_filter",["data"],{name:s("Remove filter"),sequence:10,action:e=>{const t=e.model.getters.getActiveSheetId();e.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:t,target:e.model.getters.getSelectedZones()})},isVisible:Jr});for(let e of he)Zu.addChild(`format_font_size_${e}`,["format","format_font_size"],{name:e.toString(),sequence:e,action:t=>Nr(t,{fontSize:e})});function ju(e){return e.sort().map(((e,t)=>({name:e,sequence:10*t,action:t=>t.startCellEdition(`=${e}(`)})))}const Xu=new class extends Eo{addTransformation(e,t,i){for(let o of t)this.content[o]||(this.content[o]=new Map),this.content[o].set(e,i);return this}getTransformation(e,t){return this.content[e]&&this.content[e].get(t)}},Yu={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up"};function Ku(e,t){const i=Yu[e.key];e.shiftKey?t.resizeAnchorZone(i,e.ctrlKey?"end":1):t.moveAnchorCell(i,e.ctrlKey?"end":1)}const Qu=new ki;uo`
350
350
  .o-selection {
351
351
  .o-selection-input {
352
352
  display: flex;
@@ -396,7 +396,7 @@
396
396
  font-size: calc(100% + 4px);
397
397
  }
398
398
  }
399
- `;class Qu extends t.Component{constructor(){super(...arguments),this.id=Ku.uuidv4(),this.previousRanges=this.props.ranges||[],this.originSheet=this.env.model.getters.getActiveSheetId(),this.state=t.useState({isMissing:!1,mode:"select-range"}),this.focusedInput=t.useRef("focusedInput")}get ranges(){const e=this.env.model.getters.getSelectionInput(this.id);return(e.length?e:this.props.ranges?this.props.ranges.map(((e,t)=>({xc:e,id:t,isFocused:!1}))):[]).map((e=>({...e,isValidRange:""===e.xc||this.env.model.getters.isRangeValid(e.xc)})))}get hasFocus(){return this.ranges.filter((e=>e.isFocused)).length>0}get canAddRange(){return!this.props.hasSingleRange}get isInvalid(){return this.props.isInvalid||this.state.isMissing}setup(){t.useEffect((()=>{var e;return null===(e=this.focusedInput.el)||void 0===e?void 0:e.focus()}),(()=>[this.focusedInput.el])),t.onMounted((()=>this.enableNewSelectionInput())),t.onWillUnmount((async()=>this.disableNewSelectionInput())),t.onPatched((()=>this.checkChange()))}enableNewSelectionInput(){this.env.model.dispatch("ENABLE_NEW_SELECTION_INPUT",{id:this.id,initialRanges:this.props.ranges,hasSingleRange:this.props.hasSingleRange})}disableNewSelectionInput(){this.env.model.dispatch("DISABLE_SELECTION_INPUT",{id:this.id})}checkChange(){const e=this.env.model.getters.getSelectionInputValue(this.id);this.previousRanges.join()!==e.join()&&this.triggerChange()}getColor(e){return"color: "+(e.color||"#000")+";"}triggerChange(){var e,t;const i=this.env.model.getters.getSelectionInputValue(this.id);null===(t=(e=this.props).onSelectionChanged)||void 0===t||t.call(e,i),this.previousRanges=i}onKeydown(e){if("F2"===e.key)e.preventDefault(),e.stopPropagation(),this.state.mode="select-range"===this.state.mode?"text-edit":"select-range";else if(e.key.startsWith("Arrow"))e.stopPropagation(),"select-range"===this.state.mode&&(e.preventDefault(),Yu(e,this.env.model.selection));else if("Enter"===e.key){e.target.blur(),this.confirm()}}extractRanges(e){return this.props.hasSingleRange?e.split(",")[0]:e}focus(e){this.state.isMissing=!1,this.state.mode="select-range",this.env.model.dispatch("FOCUS_RANGE",{id:this.id,rangeId:e})}addEmptyInput(){this.env.model.dispatch("ADD_EMPTY_RANGE",{id:this.id})}removeInput(e){var t,i;this.env.model.dispatch("REMOVE_RANGE",{id:this.id,rangeId:e}),this.triggerChange(),null===(i=(t=this.props).onSelectionConfirmed)||void 0===i||i.call(t)}onInputChanged(e,t){const i=t.target,o=this.extractRanges(i.value);this.env.model.dispatch("CHANGE_RANGE",{id:this.id,rangeId:e,value:o}),this.triggerChange()}confirm(){var e,t;this.env.model.dispatch("UNFOCUS_SELECTION_INPUT");const i=this.env.model.getters.getSelectionInputValue(this.id);this.props.required&&0===i.length&&(this.state.isMissing=!0);const o=this.env.model.getters.getActiveSheetId();this.originSheet!==o&&this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:o,sheetIdTo:this.originSheet}),null===(t=(e=this.props).onSelectionConfirmed)||void 0===t||t.call(e)}}Qu.template="o-spreadsheet-SelectionInput",Qu.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 Ju 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=>xs.Errors[e]||xs.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})}}Ju.template="o-spreadsheet-LineBarPieConfigPanel",Ju.components={SelectionInput:Qu},Ju.props={figureId:String,definition:Object,updateChart:Function};class eg extends Ju{onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e.target.checked})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}}eg.template="o-spreadsheet-BarConfigPanel";const tg=218,ig=182;function og(e){return yt(It({h:360*e.offsetX/tg,s:100,l:100*e.offsetY/ig,a:1}))}ho`
399
+ `;class Ju extends t.Component{constructor(){super(...arguments),this.id=Qu.uuidv4(),this.previousRanges=this.props.ranges||[],this.originSheet=this.env.model.getters.getActiveSheetId(),this.state=t.useState({isMissing:!1,mode:"select-range"}),this.focusedInput=t.useRef("focusedInput")}get ranges(){const e=this.env.model.getters.getSelectionInput(this.id);return(e.length?e:this.props.ranges?this.props.ranges.map(((e,t)=>({xc:e,id:t,isFocused:!1}))):[]).map((e=>({...e,isValidRange:""===e.xc||this.env.model.getters.isRangeValid(e.xc)})))}get hasFocus(){return this.ranges.filter((e=>e.isFocused)).length>0}get canAddRange(){return!this.props.hasSingleRange}get isInvalid(){return this.props.isInvalid||this.state.isMissing}setup(){t.useEffect((()=>{var e;return null===(e=this.focusedInput.el)||void 0===e?void 0:e.focus()}),(()=>[this.focusedInput.el])),t.onMounted((()=>this.enableNewSelectionInput())),t.onWillUnmount((async()=>this.disableNewSelectionInput())),t.onPatched((()=>this.checkChange()))}enableNewSelectionInput(){this.env.model.dispatch("ENABLE_NEW_SELECTION_INPUT",{id:this.id,initialRanges:this.props.ranges,hasSingleRange:this.props.hasSingleRange})}disableNewSelectionInput(){this.env.model.dispatch("DISABLE_SELECTION_INPUT",{id:this.id})}checkChange(){const e=this.env.model.getters.getSelectionInputValue(this.id);this.previousRanges.join()!==e.join()&&this.triggerChange()}getColor(e){return"color: "+(e.color||"#000")+";"}triggerChange(){var e,t;const i=this.env.model.getters.getSelectionInputValue(this.id);null===(t=(e=this.props).onSelectionChanged)||void 0===t||t.call(e,i),this.previousRanges=i}onKeydown(e){if("F2"===e.key)e.preventDefault(),e.stopPropagation(),this.state.mode="select-range"===this.state.mode?"text-edit":"select-range";else if(e.key.startsWith("Arrow"))e.stopPropagation(),"select-range"===this.state.mode&&(e.preventDefault(),Ku(e,this.env.model.selection));else if("Enter"===e.key){e.target.blur(),this.confirm()}}extractRanges(e){return this.props.hasSingleRange?e.split(",")[0]:e}focus(e){this.state.isMissing=!1,this.state.mode="select-range",this.env.model.dispatch("FOCUS_RANGE",{id:this.id,rangeId:e})}addEmptyInput(){this.env.model.dispatch("ADD_EMPTY_RANGE",{id:this.id})}removeInput(e){var t,i;this.env.model.dispatch("REMOVE_RANGE",{id:this.id,rangeId:e}),this.triggerChange(),null===(i=(t=this.props).onSelectionConfirmed)||void 0===i||i.call(t)}onInputChanged(e,t){const i=t.target,o=this.extractRanges(i.value);this.env.model.dispatch("CHANGE_RANGE",{id:this.id,rangeId:e,value:o}),this.triggerChange()}confirm(){var e,t;this.env.model.dispatch("UNFOCUS_SELECTION_INPUT");const i=this.env.model.getters.getSelectionInputValue(this.id);this.props.required&&0===i.length&&(this.state.isMissing=!0);const o=this.env.model.getters.getActiveSheetId();this.originSheet!==o&&this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:o,sheetIdTo:this.originSheet}),null===(t=(e=this.props).onSelectionConfirmed)||void 0===t||t.call(e)}}Ju.template="o-spreadsheet-SelectionInput",Ju.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 eg 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=>Is.Errors[e]||Is.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})}}eg.template="o-spreadsheet-LineBarPieConfigPanel",eg.components={SelectionInput:Ju},eg.props={figureId:String,definition:Object,updateChart:Function};class tg extends eg{onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e.target.checked})}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e.target.checked})}}tg.template="o-spreadsheet-BarConfigPanel";const ig=218,og=182;function ng(e){return xt(Rt({h:360*e.offsetX/ig,s:100,l:100*e.offsetY/og,a:1}))}uo`
400
400
  .o-color-picker {
401
401
  padding: ${6}px 0px;
402
402
  box-shadow: 1px 2px 5px 2px rgba(51, 51, 51, 0.15);
@@ -404,7 +404,7 @@
404
404
  line-height: 1.2;
405
405
  overflow-y: auto;
406
406
  overflow-x: hidden;
407
- width: ${tg+12}px;
407
+ width: ${ig+12}px;
408
408
 
409
409
  .o-color-picker-section-name {
410
410
  margin: 0px ${1}px;
@@ -505,8 +505,8 @@
505
505
  hsl(1turn 100% 50%) 100%
506
506
  );
507
507
  border: ${1}px solid #c0c0c0;
508
- width: ${tg}px;
509
- height: ${ig}px;
508
+ width: ${ig}px;
509
+ height: ${og}px;
510
510
  &:hover {
511
511
  cursor: crosshair;
512
512
  }
@@ -533,7 +533,7 @@
533
533
  width: 30px;
534
534
  height: 30px;
535
535
  }
536
- `;class ng extends t.Component{constructor(){super(...arguments),this.COLORS=M,this.state=t.useState({showGradient:!1,currentColor:St(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?mo({display:"none"}):""}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"BottomLeft",verticalOffset:0}}onColorClick(e){e&&this.props.onColorPicked(bt(e))}getCheckMarkColor(){return fs(this.props.currentColor)}resetColor(){this.props.onColorPicked("")}setCustomColor(e){if(!St(this.state.currentColor))return e.stopPropagation(),void(this.state.isCurrentColorInvalid=!0);const t=bt(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=og(e)}hideMagnifier(e){this.state.style.display="none"}showMagnifier(e){this.state.style.display="block"}moveMagnifier(e){this.state.style.background=og(e);this.state.style.left=`${e.offsetX+10}px`,this.state.style.top=`${e.offsetY+10}px`}get magnifyingGlassStyle(){const{display:e,background:t,left:i,top:o}=this.state.style;return mo({display:e,"background-color":"block"===e?t:void 0,left:i,top:o})}isSameColor(e,t){return function(e,t){return St(e)&&St(t)&&bt(e)===bt(t)}(e,t)}}ng.template="o-spreadsheet-ColorPicker",ng.defaultProps={currentColor:""},ng.components={Popover:Hn},ng.props={onColorPicked:Function,currentColor:{type:String,optional:!0},maxHeight:{type:Number,optional:!0},anchorRect:Object},ho`
536
+ `;class sg extends t.Component{constructor(){super(...arguments),this.COLORS=M,this.state=t.useState({showGradient:!1,currentColor:Ct(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?fo({display:"none"}):""}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"BottomLeft",verticalOffset:0}}onColorClick(e){e&&this.props.onColorPicked(St(e))}getCheckMarkColor(){return vs(this.props.currentColor)}resetColor(){this.props.onColorPicked("")}setCustomColor(e){if(!Ct(this.state.currentColor))return e.stopPropagation(),void(this.state.isCurrentColorInvalid=!0);const t=St(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=ng(e)}hideMagnifier(e){this.state.style.display="none"}showMagnifier(e){this.state.style.display="block"}moveMagnifier(e){this.state.style.background=ng(e);this.state.style.left=`${e.offsetX+10}px`,this.state.style.top=`${e.offsetY+10}px`}get magnifyingGlassStyle(){const{display:e,background:t,left:i,top:o}=this.state.style;return fo({display:e,"background-color":"block"===e?t:void 0,left:i,top:o})}isSameColor(e,t){return function(e,t){return Ct(e)&&Ct(t)&&St(e)===St(t)}(e,t)}}sg.template="o-spreadsheet-ColorPicker",sg.defaultProps={currentColor:""},sg.components={Popover:$n},sg.props={onColorPicked:Function,currentColor:{type:String,optional:!0},maxHeight:{type:Number,optional:!0},anchorRect:Object},uo`
537
537
  .o-color-picker-widget {
538
538
  display: inline-block;
539
539
  position: relative;
@@ -564,7 +564,7 @@
564
564
  }
565
565
  }
566
566
  }
567
- `;class sg extends t.Component{constructor(){super(...arguments),this.colorPickerButtonRef=t.useRef("colorPickerButton")}get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:"border-bottom-style: hidden"}get colorPickerAnchorRect(){const e=this.colorPickerButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}}sg.template="o-spreadsheet-ColorPickerWidget",sg.components={ColorPicker:ng},sg.props={currentColor:{type:String,optional:!0},toggleColorPicker:Function,showColorPicker:Boolean,onColorPicked:Function,icon:String,title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};class rg 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})}}rg.template="o-spreadsheet-LineBarPieDesignPanel",rg.components={ColorPickerWidget:sg},rg.props={figureId:String,definition:Object,updateChart:Function};class ag extends rg{}ag.template="o-spreadsheet-BarChartDesignPanel";class lg 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=>xs.Errors[e]||xs.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})}}lg.template="o-spreadsheet-GaugeChartConfigPanel",lg.components={SelectionInput:Qu},lg.props={figureId:String,definition:Object,updateChart:Function},ho`
567
+ `;class rg extends t.Component{constructor(){super(...arguments),this.colorPickerButtonRef=t.useRef("colorPickerButton")}get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:"border-bottom-style: hidden"}get colorPickerAnchorRect(){const e=this.colorPickerButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}}rg.template="o-spreadsheet-ColorPickerWidget",rg.components={ColorPicker:sg},rg.props={currentColor:{type:String,optional:!0},toggleColorPicker:Function,showColorPicker:Boolean,onColorPicked:Function,icon:String,title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};class ag 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})}}ag.template="o-spreadsheet-LineBarPieDesignPanel",ag.components={ColorPickerWidget:rg},ag.props={figureId:String,definition:Object,updateChart:Function};class lg extends ag{}lg.template="o-spreadsheet-BarChartDesignPanel";class cg 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=>Is.Errors[e]||Is.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})}}cg.template="o-spreadsheet-GaugeChartConfigPanel",cg.components={SelectionInput:Ju},cg.props={figureId:String,definition:Object,updateChart:Function},uo`
568
568
  .o-gauge-color-set {
569
569
  table {
570
570
  table-layout: fixed;
@@ -594,7 +594,7 @@
594
594
  box-sizing: border-box;
595
595
  }
596
596
  }
597
- `;class cg extends t.Component{constructor(){super(...arguments),this.state=t.useState({openedMenu:void 0,sectionRuleDispatchResult:void 0})}setup(){t.useExternalListener(window,"click",this.closeMenus)}get designErrorMessages(){var e;return[...(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.reasons)||[]].map((e=>xs.Errors[e]||xs.Errors.Unexpected))}updateBackgroundColor(e){this.state.openedMenu=void 0,this.props.updateChart(this.props.figureId,{background:e})}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}isRangeMinInvalid(){var e,t,i;return!!((null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(37))||(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(38))||(null===(i=this.state.sectionRuleDispatchResult)||void 0===i?void 0:i.isCancelledBecause(41)))}isRangeMaxInvalid(){var e,t,i;return!!((null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(39))||(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(40))||(null===(i=this.state.sectionRuleDispatchResult)||void 0===i?void 0:i.isCancelledBecause(41)))}get isLowerInflectionPointInvalid(){var e,t;return!(!(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(42))&&!(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(44)))}get isUpperInflectionPointInvalid(){var e,t;return!(!(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(43))&&!(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(44)))}updateInflectionPointValue(e,t){const i=Ne(this.props.definition.sectionRule);i[e].value=t.target.value,this.updateSectionRule(i)}updateInflectionPointType(e,t){const i=Ne(this.props.definition.sectionRule);i[e].type=t.target.value,this.updateSectionRule(i)}updateSectionColor(e,t){const i=Ne(this.props.definition.sectionRule);i.colors[e]=t,this.updateSectionRule(i),this.closeMenus()}updateRangeMin(e){let t=Ne(this.props.definition.sectionRule);t={...t,rangeMin:e.target.value},this.updateSectionRule(t)}updateRangeMax(e){let t=Ne(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}}cg.template="o-spreadsheet-GaugeChartDesignPanel",cg.components={ColorPickerWidget:sg},cg.props={figureId:String,definition:Object,updateChart:Function};class hg extends Ju{get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.figureId);return!!(e&&e instanceof js)&&Xs(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})}}hg.template="o-spreadsheet-LineConfigPanel";class dg extends rg{}dg.template="o-spreadsheet-LineChartDesignPanel";class ug 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=>xs.Errors[e]||xs.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})}}ug.template="o-spreadsheet-ScorecardChartConfigPanel",ug.components={SelectionInput:Qu},ug.props={figureId:String,definition:Object,updateChart:Function};class gg extends t.Component{constructor(){super(...arguments),this.state=t.useState({openedColorPicker:void 0})}setup(){t.useExternalListener(window,"click",this.closeMenus)}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}updateBaselineDescr(e){this.props.updateChart(this.props.figureId,{baselineDescr:e.target.value})}toggleColorPicker(e){this.state.openedColorPicker===e?this.state.openedColorPicker=void 0:this.state.openedColorPicker=e}setColor(e,t){switch(t){case"backgroundColor":this.props.updateChart(this.props.figureId,{background:e});break;case"baselineColorDown":this.props.updateChart(this.props.figureId,{baselineColorDown:e});break;case"baselineColorUp":this.props.updateChart(this.props.figureId,{baselineColorUp:e})}this.closeMenus()}closeMenus(){this.state.openedColorPicker=void 0}}gg.template="o-spreadsheet-ScorecardChartDesignPanel",gg.components={ColorPickerWidget:sg},gg.props={figureId:String,definition:Object,updateChart:Function};const pg=new Co;pg.add("line",{configuration:hg,design:dg}).add("bar",{configuration:eg,design:ag}).add("pie",{configuration:Ju,design:rg}).add("gauge",{configuration:lg,design:cg}).add("scorecard",{configuration:ug,design:gg}),ho`
597
+ `;class hg extends t.Component{constructor(){super(...arguments),this.state=t.useState({openedMenu:void 0,sectionRuleDispatchResult:void 0})}setup(){t.useExternalListener(window,"click",this.closeMenus)}get designErrorMessages(){var e;return[...(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.reasons)||[]].map((e=>Is.Errors[e]||Is.Errors.Unexpected))}updateBackgroundColor(e){this.state.openedMenu=void 0,this.props.updateChart(this.props.figureId,{background:e})}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}isRangeMinInvalid(){var e,t,i;return!!((null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(37))||(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(38))||(null===(i=this.state.sectionRuleDispatchResult)||void 0===i?void 0:i.isCancelledBecause(41)))}isRangeMaxInvalid(){var e,t,i;return!!((null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(39))||(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(40))||(null===(i=this.state.sectionRuleDispatchResult)||void 0===i?void 0:i.isCancelledBecause(41)))}get isLowerInflectionPointInvalid(){var e,t;return!(!(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(42))&&!(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(44)))}get isUpperInflectionPointInvalid(){var e,t;return!(!(null===(e=this.state.sectionRuleDispatchResult)||void 0===e?void 0:e.isCancelledBecause(43))&&!(null===(t=this.state.sectionRuleDispatchResult)||void 0===t?void 0:t.isCancelledBecause(44)))}updateInflectionPointValue(e,t){const i=Ne(this.props.definition.sectionRule);i[e].value=t.target.value,this.updateSectionRule(i)}updateInflectionPointType(e,t){const i=Ne(this.props.definition.sectionRule);i[e].type=t.target.value,this.updateSectionRule(i)}updateSectionColor(e,t){const i=Ne(this.props.definition.sectionRule);i.colors[e]=t,this.updateSectionRule(i),this.closeMenus()}updateRangeMin(e){let t=Ne(this.props.definition.sectionRule);t={...t,rangeMin:e.target.value},this.updateSectionRule(t)}updateRangeMax(e){let t=Ne(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}}hg.template="o-spreadsheet-GaugeChartDesignPanel",hg.components={ColorPickerWidget:rg},hg.props={figureId:String,definition:Object,updateChart:Function};class dg extends eg{get canTreatLabelsAsText(){const e=this.env.model.getters.getChart(this.props.figureId);return!!(e&&e instanceof Xs)&&Ys(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})}}dg.template="o-spreadsheet-LineConfigPanel";class ug extends ag{}ug.template="o-spreadsheet-LineChartDesignPanel";class gg 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=>Is.Errors[e]||Is.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})}}gg.template="o-spreadsheet-ScorecardChartConfigPanel",gg.components={SelectionInput:Ju},gg.props={figureId:String,definition:Object,updateChart:Function};class pg extends t.Component{constructor(){super(...arguments),this.state=t.useState({openedColorPicker:void 0})}setup(){t.useExternalListener(window,"click",this.closeMenus)}updateTitle(e){this.props.updateChart(this.props.figureId,{title:e.target.value})}updateBaselineDescr(e){this.props.updateChart(this.props.figureId,{baselineDescr:e.target.value})}toggleColorPicker(e){this.state.openedColorPicker===e?this.state.openedColorPicker=void 0:this.state.openedColorPicker=e}setColor(e,t){switch(t){case"backgroundColor":this.props.updateChart(this.props.figureId,{background:e});break;case"baselineColorDown":this.props.updateChart(this.props.figureId,{baselineColorDown:e});break;case"baselineColorUp":this.props.updateChart(this.props.figureId,{baselineColorUp:e})}this.closeMenus()}closeMenus(){this.state.openedColorPicker=void 0}}pg.template="o-spreadsheet-ScorecardChartDesignPanel",pg.components={ColorPickerWidget:rg},pg.props={figureId:String,definition:Object,updateChart:Function};const mg=new Eo;mg.add("line",{configuration:dg,design:ug}).add("bar",{configuration:tg,design:lg}).add("pie",{configuration:eg,design:ag}).add("gauge",{configuration:cg,design:hg}).add("scorecard",{configuration:gg,design:pg}),uo`
598
598
  .o-chart {
599
599
  .o-panel {
600
600
  display: flex;
@@ -617,7 +617,7 @@
617
617
  }
618
618
  }
619
619
  }
620
- `;class mg extends t.Component{get figureId(){return this.state.figureId}setup(){const e=this.env.model.getters.getSelectedFigureId();if(!e)throw new Error(s("Cannot open the chart side panel while no chart are selected"));this.state=t.useState({panel:"configuration",figureId:e}),t.onWillUpdateProps((()=>{const e=this.env.model.getters.getSelectedFigureId();e&&e!==this.state.figureId&&(this.state.figureId=e),this.env.model.getters.isChartDefined(this.figureId)||this.props.onCloseSidePanel()}))}updateChart(e,t){if(e!==this.figureId)return;const i={...this.getChartDefinition(),...t};return this.env.model.dispatch("UPDATE_CHART",{definition:i,id:e,sheetId:this.env.model.getters.getFigureSheetId(e)})}onTypeChange(e){const t=this.env.model.getters.getContextCreationChart(this.figureId);if(!t)throw new Error("Chart not defined.");const i=function(e,t){return nr.get(t).getChartDefinitionFromContextCreation(e)}(t,e);this.env.model.dispatch("UPDATE_CHART",{definition:i,id:this.figureId,sheetId:this.env.model.getters.getFigureSheetId(this.figureId)})}get chartPanel(){const e=this.env.model.getters.getChartType(this.figureId);if(!e)throw new Error("Chart not defined.");const t=pg.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 nr.getKeys())e[t]=nr.get(t).name;return e}()}activatePanel(e){this.state.panel=e}}mg.template="o-spreadsheet-ChartPanel",mg.props={onCloseSidePanel:Function};function fg(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 vg={arrowGood:{template:"ARROW_UP",img:fg('<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:fg('<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:fg('<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:fg('<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:fg('<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:fg('<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:fg('<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:fg('<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:fg('<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>')}},bg={arrows:{good:"arrowGood",neutral:"arrowNeutral",bad:"arrowBad"},smiley:{good:"smileyGood",neutral:"smileyNeutral",bad:"smileyBad"},dots:{good:"dotGood",neutral:"dotNeutral",bad:"dotBad"}};ho`
620
+ `;class fg extends t.Component{get figureId(){return this.state.figureId}setup(){const e=this.env.model.getters.getSelectedFigureId();if(!e)throw new Error(s("Cannot open the chart side panel while no chart are selected"));this.state=t.useState({panel:"configuration",figureId:e}),t.onWillUpdateProps((()=>{const e=this.env.model.getters.getSelectedFigureId();e&&e!==this.state.figureId&&(this.state.figureId=e),this.env.model.getters.isChartDefined(this.figureId)||this.props.onCloseSidePanel()}))}updateChart(e,t){if(e!==this.figureId)return;const i={...this.getChartDefinition(),...t};return this.env.model.dispatch("UPDATE_CHART",{definition:i,id:e,sheetId:this.env.model.getters.getFigureSheetId(e)})}onTypeChange(e){const t=this.env.model.getters.getContextCreationChart(this.figureId);if(!t)throw new Error("Chart not defined.");const i=function(e,t){return sr.get(t).getChartDefinitionFromContextCreation(e)}(t,e);this.env.model.dispatch("UPDATE_CHART",{definition:i,id:this.figureId,sheetId:this.env.model.getters.getFigureSheetId(this.figureId)})}get chartPanel(){const e=this.env.model.getters.getChartType(this.figureId);if(!e)throw new Error("Chart not defined.");const t=mg.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 sr.getKeys())e[t]=sr.get(t).name;return e}()}activatePanel(e){this.state.panel=e}}fg.template="o-spreadsheet-ChartPanel",fg.props={onCloseSidePanel:Function};function vg(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 bg={arrowGood:{template:"ARROW_UP",img:vg('<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:vg('<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:vg('<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:vg('<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:vg('<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:vg('<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:vg('<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:vg('<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:vg('<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>')}},Sg={arrows:{good:"arrowGood",neutral:"arrowNeutral",bad:"arrowBad"},smiley:{good:"smileyGood",neutral:"smileyNeutral",bad:"smileyBad"},dots:{good:"dotGood",neutral:"dotNeutral",bad:"dotBad"}};uo`
621
621
  .o-icon-picker {
622
622
  position: absolute;
623
623
  z-index: ${le.IconPicker};
@@ -636,7 +636,7 @@
636
636
  outline: 1px solid gray;
637
637
  }
638
638
  }
639
- `;class Sg extends t.Component{constructor(){super(...arguments),this.icons=vg,this.iconSets=bg}onIconClick(e){e&&this.props.onIconPicked(e)}}Sg.template="o-spreadsheet-IconPicker",Sg.props={onIconPicked:Function},ho`
639
+ `;class Cg extends t.Component{constructor(){super(...arguments),this.icons=bg,this.iconSets=Sg}onIconClick(e){e&&this.props.onIconPicked(e)}}Cg.template="o-spreadsheet-IconPicker",Cg.props={onIconPicked:Function},uo`
640
640
  label {
641
641
  vertical-align: middle;
642
642
  }
@@ -906,13 +906,13 @@
906
906
  }
907
907
  }
908
908
  }
909
- `;class Cg extends t.Component{constructor(){super(...arguments),this.icons=vg,this.cellIsOperators=ys,this.iconSets=bg,this.getTextDecoration=uo,this.colorNumberString=vt}setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId(),this.state=t.useState({mode:"list",errors:[],rules:this.getDefaultRules()});const e=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(1===i.length){const e=this.conditionalFormats.find((e=>e.id===i[0]));e&&this.editConditionalFormat(e)}t.onWillUpdateProps((e=>{const t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(1===i.length){const e=this.conditionalFormats.find((e=>e.id===i[0]));e&&this.editConditionalFormat(e)}else this.switchToList()}})),t.useExternalListener(window,"click",this.closeMenus)}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId())}get isRangeValid(){return this.state.errors.includes(24)}errorMessage(e){return ws.Errors[e]||ws.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 mo({"font-weight":e.style.bold?"bold":"normal","text-decoration":uo(e.style),"font-style":e.style.italic?"italic":"normal",color:e.style.textColor||"none","background-color":e.style.fillColor||"none"});if("ColorScaleRule"===e.type){const t=vt(e.minimum.color),i=e.midpoint?vt(e.midpoint.color):null,o=vt(e.maximum.color),n="background-image: linear-gradient(to right, ";return i?n+t+", "+i+", "+o+")":n+t+", "+o+")"}return""}getDescription(e){switch(e.rule.type){case"CellIsRule":const t=ys[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 ws.ColorScale;case"IconSetRule":return ws.IconSet;default:return""}}saveConditionalFormat(){if(this.state.currentCF){if(this.state.currentCF.ranges.some((e=>!e.match(_t))))return void(this.state.errors=[25]);const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{rule:this.getEditorRule(),id:"edit"===this.state.mode?this.state.currentCF.id:this.env.model.uuidGenerator.uuidv4()},ranges:this.state.currentCF.ranges.map((t=>this.env.model.getters.getRangeDataFromXc(e,t))),sheetId:e});t.isSuccessful?this.switchToList():this.state.errors=t.reasons}}getEditorRule(){switch(this.state.currentCFType){case"CellIsRule":return this.state.rules.cellIs;case"ColorScaleRule":return this.state.rules.colorScale;case"IconSetRule":return this.state.rules.iconSet}throw new Error(`Invalid cf type: ${this.state.currentCFType}`)}getDefaultRules(){return{cellIs:{type:"CellIsRule",operator:"IsNotEmpty",values:[],style:{fillColor:"#b6d7a8"}},colorScale:{type:"ColorScaleRule",minimum:{type:"value",color:16777215},midpoint:void 0,maximum:{type:"value",color:6989903}},iconSet:{type:"IconSetRule",icons:{upper:"arrowGood",middle:"arrowNeutral",lower:"arrowBad"},upperInflectionPoint:{type:"percentage",value:"66",operator:"gt"},lowerInflectionPoint:{type:"percentage",value:"33",operator:"gt"}}}}addConditionalFormat(){this.state.mode="add",this.state.currentCFType="CellIsRule",this.state.currentCF={id:this.env.model.uuidGenerator.uuidv4(),ranges:this.env.model.getters.getSelectedZones().map((e=>this.env.model.getters.zoneToXC(this.env.model.getters.getActiveSheetId(),e)))}}deleteConditionalFormat(e){this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:e.id,sheetId:this.env.model.getters.getActiveSheetId()})}editConditionalFormat(e){if("reorder"!==this.state.mode)switch(this.state.mode="edit",this.state.currentCF=e,this.state.currentCFType=e.rule.type,e.rule.type){case"CellIsRule":this.state.rules.cellIs=e.rule;break;case"ColorScaleRule":this.state.rules.colorScale=e.rule;break;case"IconSetRule":this.state.rules.iconSet=e.rule}}reorderConditionalFormats(){this.state.mode="reorder"}reorderRule(e,t){this.env.model.dispatch("MOVE_CONDITIONAL_FORMAT",{cfId:e.id,direction:t,sheetId:this.env.model.getters.getActiveSheetId()})}changeRuleType(e){this.state.currentCFType!==e&&this.state.rules&&(this.state.errors=[],this.state.currentCFType=e)}onRangesChanged(e){this.state.currentCF&&(this.state.currentCF.ranges=e)}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(51))}get isValue2Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(52))}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.closeMenus()}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.closeMenus()}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes(58)||this.state.errors.includes(50)||this.state.errors.includes(47)||this.state.errors.includes(53);case"midpoint":return this.state.errors.includes(59)||this.state.errors.includes(54)||this.state.errors.includes(49);case"maximum":return this.state.errors.includes(60)||this.state.errors.includes(55);default:return!1}}setColorScaleColor(e,t){const i=this.state.rules.colorScale[e];i&&(i.color=Number.parseInt(t.substr(1),16)),this.closeMenus()}getPreviewGradient(){var e;const t=this.state.rules.colorScale,i=vt(t.minimum.color),o=vt((null===(e=t.midpoint)||void 0===e?void 0:e.color)||y),n=vt(t.maximum.color),s="background-image: linear-gradient(to right, ";return void 0===t.midpoint?s+i+", "+n+")":s+i+", "+o+", "+n+")"}getThresholdColor(e){return vt(e?e.color:y)}onMidpointChange(e){const t=e.target.value,i=this.state.rules.colorScale;i.midpoint="none"===t?void 0:{color:y,value:"",...i.midpoint,type:t}}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes(57)||this.state.errors.includes(62)||this.state.errors.includes(48);case"upperInflectionPoint":return this.state.errors.includes(56)||this.state.errors.includes(61)||this.state.errors.includes(48);default:return!0}}reverseIcons(){const e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t}setIconSet(e){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad}setIcon(e,t){this.state.rules.iconSet.icons[e]=t}}Cg.template="o-spreadsheet-ConditionalFormattingPanel",Cg.components={SelectionInput:Qu,IconPicker:Sg,ColorPickerWidget:sg},Cg.props={selection:{type:Object,optional:!0},onCloseSidePanel:Function},ho`
909
+ `;class Eg extends t.Component{constructor(){super(...arguments),this.icons=bg,this.cellIsOperators=xs,this.iconSets=Sg,this.getTextDecoration=go,this.colorNumberString=bt}setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId(),this.state=t.useState({mode:"list",errors:[],rules:this.getDefaultRules()});const e=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(1===i.length){const e=this.conditionalFormats.find((e=>e.id===i[0]));e&&this.editConditionalFormat(e)}t.onWillUpdateProps((e=>{const t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){const t=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(1===i.length){const e=this.conditionalFormats.find((e=>e.id===i[0]));e&&this.editConditionalFormat(e)}else this.switchToList()}})),t.useExternalListener(window,"click",this.closeMenus)}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId())}get isRangeValid(){return this.state.errors.includes(24)}errorMessage(e){return ys.Errors[e]||ys.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 fo({"font-weight":e.style.bold?"bold":"normal","text-decoration":go(e.style),"font-style":e.style.italic?"italic":"normal",color:e.style.textColor||"none","background-color":e.style.fillColor||"none"});if("ColorScaleRule"===e.type){const t=bt(e.minimum.color),i=e.midpoint?bt(e.midpoint.color):null,o=bt(e.maximum.color),n="background-image: linear-gradient(to right, ";return i?n+t+", "+i+", "+o+")":n+t+", "+o+")"}return""}getDescription(e){switch(e.rule.type){case"CellIsRule":const t=xs[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 ys.ColorScale;case"IconSetRule":return ys.IconSet;default:return""}}saveConditionalFormat(){if(this.state.currentCF){if(this.state.currentCF.ranges.some((e=>!e.match(Ft))))return void(this.state.errors=[25]);const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{rule:this.getEditorRule(),id:"edit"===this.state.mode?this.state.currentCF.id:this.env.model.uuidGenerator.uuidv4()},ranges:this.state.currentCF.ranges.map((t=>this.env.model.getters.getRangeDataFromXc(e,t))),sheetId:e});t.isSuccessful?this.switchToList():this.state.errors=t.reasons}}getEditorRule(){switch(this.state.currentCFType){case"CellIsRule":return this.state.rules.cellIs;case"ColorScaleRule":return this.state.rules.colorScale;case"IconSetRule":return this.state.rules.iconSet}throw new Error(`Invalid cf type: ${this.state.currentCFType}`)}getDefaultRules(){return{cellIs:{type:"CellIsRule",operator:"IsNotEmpty",values:[],style:{fillColor:"#b6d7a8"}},colorScale:{type:"ColorScaleRule",minimum:{type:"value",color:16777215},midpoint:void 0,maximum:{type:"value",color:6989903}},iconSet:{type:"IconSetRule",icons:{upper:"arrowGood",middle:"arrowNeutral",lower:"arrowBad"},upperInflectionPoint:{type:"percentage",value:"66",operator:"gt"},lowerInflectionPoint:{type:"percentage",value:"33",operator:"gt"}}}}addConditionalFormat(){this.state.mode="add",this.state.currentCFType="CellIsRule",this.state.currentCF={id:this.env.model.uuidGenerator.uuidv4(),ranges:this.env.model.getters.getSelectedZones().map((e=>this.env.model.getters.zoneToXC(this.env.model.getters.getActiveSheetId(),e)))}}deleteConditionalFormat(e){this.env.model.dispatch("REMOVE_CONDITIONAL_FORMAT",{id:e.id,sheetId:this.env.model.getters.getActiveSheetId()})}editConditionalFormat(e){if("reorder"!==this.state.mode)switch(this.state.mode="edit",this.state.currentCF=e,this.state.currentCFType=e.rule.type,e.rule.type){case"CellIsRule":this.state.rules.cellIs=e.rule;break;case"ColorScaleRule":this.state.rules.colorScale=e.rule;break;case"IconSetRule":this.state.rules.iconSet=e.rule}}reorderConditionalFormats(){this.state.mode="reorder"}reorderRule(e,t){this.env.model.dispatch("MOVE_CONDITIONAL_FORMAT",{cfId:e.id,direction:t,sheetId:this.env.model.getters.getActiveSheetId()})}changeRuleType(e){this.state.currentCFType!==e&&this.state.rules&&(this.state.errors=[],this.state.currentCFType=e)}onRangesChanged(e){this.state.currentCF&&(this.state.currentCF.ranges=e)}toggleMenu(e){const t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(51))}get isValue2Invalid(){var e;return!!(null===(e=this.state.errors)||void 0===e?void 0:e.includes(52))}toggleStyle(e){const t=this.state.rules.cellIs.style;t[e]=!t[e],this.closeMenus()}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.closeMenus()}isValueInvalid(e){switch(e){case"minimum":return this.state.errors.includes(58)||this.state.errors.includes(50)||this.state.errors.includes(47)||this.state.errors.includes(53);case"midpoint":return this.state.errors.includes(59)||this.state.errors.includes(54)||this.state.errors.includes(49);case"maximum":return this.state.errors.includes(60)||this.state.errors.includes(55);default:return!1}}setColorScaleColor(e,t){const i=this.state.rules.colorScale[e];i&&(i.color=Number.parseInt(t.substr(1),16)),this.closeMenus()}getPreviewGradient(){var e;const t=this.state.rules.colorScale,i=bt(t.minimum.color),o=bt((null===(e=t.midpoint)||void 0===e?void 0:e.color)||y),n=bt(t.maximum.color),s="background-image: linear-gradient(to right, ";return void 0===t.midpoint?s+i+", "+n+")":s+i+", "+o+", "+n+")"}getThresholdColor(e){return bt(e?e.color:y)}onMidpointChange(e){const t=e.target.value,i=this.state.rules.colorScale;i.midpoint="none"===t?void 0:{color:y,value:"",...i.midpoint,type:t}}isInflectionPointInvalid(e){switch(e){case"lowerInflectionPoint":return this.state.errors.includes(57)||this.state.errors.includes(62)||this.state.errors.includes(48);case"upperInflectionPoint":return this.state.errors.includes(56)||this.state.errors.includes(61)||this.state.errors.includes(48);default:return!0}}reverseIcons(){const e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t}setIconSet(e){const t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad}setIcon(e,t){this.state.rules.iconSet.icons[e]=t}}Eg.template="o-spreadsheet-ConditionalFormattingPanel",Eg.components={SelectionInput:Ju,IconPicker:Cg,ColorPickerWidget:rg},Eg.props={selection:{type:Object,optional:!0},onCloseSidePanel:Function},uo`
910
910
  .o-custom-currency {
911
911
  .o-format-proposals {
912
912
  color: black;
913
913
  }
914
914
  }
915
- `;class Eg extends t.Component{setup(){this.availableCurrencies=[],this.state=t.useState({selectedCurrencyIndex:0,currencyCode:"",currencySymbol:"",selectedFormatIndex:0}),t.onWillStart((()=>this.updateAvailableCurrencies()))}get formatProposals(){const e=this.availableCurrencies[this.state.selectedCurrencyIndex],t=this.initProposalBases(e.decimalPlaces),i=e.position,o="before"===e.position?"after":"before",n=this.state.currencySymbol.trim()?this.state.currencySymbol:"",s=this.state.currencyCode.trim()?this.state.currencyCode:"";return s||n?[...this.createFormatProposals(t,n,s,i),...this.createFormatProposals(t,n,s,o)]:[]}get isSameFormat(){const e=this.formatProposals[this.state.selectedFormatIndex];return!!e&&e.format===this.getCommonFormat()}async updateAvailableCurrencies(){var e,t;if(0===rr.getAll().length){(await(null===(t=(e=this.env).loadCurrencies)||void 0===t?void 0:t.call(e))||[]).forEach(((e,t)=>{rr.add(t.toString(),e)}))}const i={name:this.env._t(Rs.Custom),code:"",symbol:"",decimalPlaces:2,position:"after"};this.availableCurrencies=[i,...rr.getAll()]}updateSelectCurrency(e){const t=e.target;this.state.selectedCurrencyIndex=parseInt(t.value,10);const i=this.availableCurrencies[this.state.selectedCurrencyIndex];this.state.currencyCode=i.code,this.state.currencySymbol=i.symbol}updateCode(e){const t=e.target;this.state.currencyCode=t.value,this.initAvailableCurrencies()}updateSymbol(e){const t=e.target;this.state.currencySymbol=t.value,this.initAvailableCurrencies()}updateSelectFormat(e){const t=e.target;this.state.selectedFormatIndex=parseInt(t.value,10)}apply(){const e=this.formatProposals[this.state.selectedFormatIndex];this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),format:e.format})}initAvailableCurrencies(){this.state.selectedCurrencyIndex=0}initProposalBases(e){const t=[{format:"#,##0",example:"1,000"}],i=e?"."+"0".repeat(e):"";return i&&t.push({format:"#,##0"+i,example:"1,000"+i}),t}createFormatProposals(e,t,i,o){let n=[];if(t)for(let i of e)n.push(this.createFormatProposal(o,i.example,i.format,t));if(i)for(let s of e){const e=("after"===o?" ":"")+i+" "+t;n.push(this.createFormatProposal(o,s.example,s.format,e))}return n}createFormatProposal(e,t,i,o){const n="[$"+o+"]";return{example:"before"===e?o+t:t+o,format:"before"===e?n+i:i+n}}getCommonFormat(){const e=this.env.model.getters.getSelectedZones(),t=this.env.model.getters.getActiveSheetId(),i=e.map((e=>this.env.model.getters.getEvaluatedCellsInZone(t,e))).flat(),o=i[0].format;return i.every((e=>e.format===o))?o:void 0}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:"")}}Eg.template="o-spreadsheet-CustomCurrencyPanel",Eg.props={onCloseSidePanel:Function},ho`
915
+ `;class wg extends t.Component{setup(){this.availableCurrencies=[],this.state=t.useState({selectedCurrencyIndex:0,currencyCode:"",currencySymbol:"",selectedFormatIndex:0}),t.onWillStart((()=>this.updateAvailableCurrencies()))}get formatProposals(){const e=this.availableCurrencies[this.state.selectedCurrencyIndex],t=this.initProposalBases(e.decimalPlaces),i=e.position,o="before"===e.position?"after":"before",n=this.state.currencySymbol.trim()?this.state.currencySymbol:"",s=this.state.currencyCode.trim()?this.state.currencyCode:"";return s||n?[...this.createFormatProposals(t,n,s,i),...this.createFormatProposals(t,n,s,o)]:[]}get isSameFormat(){const e=this.formatProposals[this.state.selectedFormatIndex];return!!e&&e.format===this.getCommonFormat()}async updateAvailableCurrencies(){var e,t;if(0===ar.getAll().length){(await(null===(t=(e=this.env).loadCurrencies)||void 0===t?void 0:t.call(e))||[]).forEach(((e,t)=>{ar.add(t.toString(),e)}))}const i={name:this.env._t(Ts.Custom),code:"",symbol:"",decimalPlaces:2,position:"after"};this.availableCurrencies=[i,...ar.getAll()]}updateSelectCurrency(e){const t=e.target;this.state.selectedCurrencyIndex=parseInt(t.value,10);const i=this.availableCurrencies[this.state.selectedCurrencyIndex];this.state.currencyCode=i.code,this.state.currencySymbol=i.symbol}updateCode(e){const t=e.target;this.state.currencyCode=t.value,this.initAvailableCurrencies()}updateSymbol(e){const t=e.target;this.state.currencySymbol=t.value,this.initAvailableCurrencies()}updateSelectFormat(e){const t=e.target;this.state.selectedFormatIndex=parseInt(t.value,10)}apply(){const e=this.formatProposals[this.state.selectedFormatIndex];this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),format:e.format})}initAvailableCurrencies(){this.state.selectedCurrencyIndex=0}initProposalBases(e){const t=[{format:"#,##0",example:"1,000"}],i=e?"."+"0".repeat(e):"";return i&&t.push({format:"#,##0"+i,example:"1,000"+i}),t}createFormatProposals(e,t,i,o){let n=[];if(t)for(let i of e)n.push(this.createFormatProposal(o,i.example,i.format,t));if(i)for(let s of e){const e=("after"===o?" ":"")+i+" "+t;n.push(this.createFormatProposal(o,s.example,s.format,e))}return n}createFormatProposal(e,t,i,o){const n="[$"+o+"]";return{example:"before"===e?o+t:t+o,format:"before"===e?n+i:i+n}}getCommonFormat(){const e=this.env.model.getters.getSelectedZones(),t=this.env.model.getters.getActiveSheetId(),i=e.map((e=>this.env.model.getters.getEvaluatedCellsInZone(t,e))).flat(),o=i[0].format;return i.every((e=>e.format===o))?o:void 0}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:"")}}wg.template="o-spreadsheet-CustomCurrencyPanel",wg.props={onCloseSidePanel:Function},uo`
916
916
  .o-find-and-replace {
917
917
  .o-far-item {
918
918
  display: block;
@@ -945,7 +945,7 @@
945
945
  }
946
946
  }
947
947
  }
948
- `;class wg 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}}}}wg.template="o-spreadsheet-FindAndReplacePanel",wg.props={onCloseSidePanel:Function};const yg=new Co;yg.add("ConditionalFormatting",{title:s("Conditional formatting"),Body:Cg}),yg.add("ChartPanel",{title:s("Chart"),Body:mg}),yg.add("FindAndReplace",{title:s("Find and Replace"),Body:wg}),yg.add("CustomCurrency",{title:s("Custom currency format"),Body:Eg});const xg=new class extends Co{constructor(){super(...arguments),this.mapping={},this.uuidGenerator=new Di}add(e,t){const i={...t,id:this.uuidGenerator.uuidv4()};return super.add(e,i)}};ho`
948
+ `;class yg 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}}}}yg.template="o-spreadsheet-FindAndReplacePanel",yg.props={onCloseSidePanel:Function};const xg=new Eo;xg.add("ConditionalFormatting",{title:s("Conditional formatting"),Body:Eg}),xg.add("ChartPanel",{title:s("Chart"),Body:fg}),xg.add("FindAndReplace",{title:s("Find and Replace"),Body:yg}),xg.add("CustomCurrency",{title:s("Custom currency format"),Body:wg});const Ig=new class extends Eo{constructor(){super(...arguments),this.mapping={},this.uuidGenerator=new ki}add(e,t){const i={...t,id:this.uuidGenerator.uuidv4()};return super.add(e,i)}};uo`
949
949
  div.o-figure {
950
950
  box-sizing: border-box;
951
951
  position: absolute;
@@ -1018,7 +1018,7 @@
1018
1018
  }
1019
1019
  }
1020
1020
  }
1021
- `;class Ig extends t.Component{constructor(){super(...arguments),this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.figureRef=t.useRef("figure"),this.menuButtonRef=t.useRef("menuButton"),this.menuButtonRect=Vn(this.menuButtonRef)}get isSelected(){return this.env.model.getters.getSelectedFigureId()===this.props.figure.id}get figureRegistry(){return hr}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:i,height:o}=this.props.figure;return mo({left:`${e}px`,top:`${t}px`,width:`${i}px`,height:`${o}px`,"z-index":String(le.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)",mo(t)}setup(){const e=hr.get(this.props.figure.tag).borderWidth;this.borderWidth=void 0!==e?e:1,t.useEffect(((e,t,i)=>{e===t&&(null==i||i.focus({preventScroll:!0}))}),(()=>[this.env.model.getters.getSelectedFigureId(),this.props.figure.id,this.figureRef.el]))}clickAnchor(e,t,i){this.props.onClickAnchor(e,t,i)}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 i={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+i[0],y:t.y+i[1]}),e.stopPropagation(),e.preventDefault()}}onContextMenu(e){if(this.env.isDashboard())return;const t={x:e.clientX,y:e.clientY};this.openContextMenu(t)}showMenu(){const{x:e,y:t,width:i}=this.menuButtonRect,o={x:e>=H?e-H:e+i,y:t};this.openContextMenu(o)}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.position=e,this.menuState.menuItems=hr.get(this.props.figure.tag).menuBuilder(this.props.figure.id,this.props.onFigureDeleted,this.env)}}function Rg(e,t,i=(()=>{})){const o=e=>{e.preventDefault(),i(e)},n=t=>{t.preventDefault(),e(t)},s=e=>{e.preventDefault(),t(e),window.removeEventListener("mousedown",o),window.removeEventListener("mouseup",s),window.removeEventListener("dragstart",r),window.removeEventListener("mousemove",n),window.removeEventListener("wheel",n)};function r(e){e.preventDefault()}window.addEventListener("mousedown",o),window.addEventListener("mouseup",s),window.addEventListener("dragstart",r),window.addEventListener("mousemove",n),window.addEventListener("wheel",n,{passive:!1})}function Tg(e,t,i,o=!1){let n,s,r,a,l,c=null;const h=e.model.getters,d=h.getActiveSheetId(),u=kn();let g,p;const m=i=>{if(n=i,c)return;const{x:r,y:f}=h.getMainViewportCoordinates();let{top:v,left:b,bottom:S,right:C}=h.getActiveMainViewport(),{scrollX:E,scrollY:w}=h.getActiveSheetDOMScrollInfo();const{xSplit:y,ySplit:x}=h.getPaneDivisions(d);let I=!1,R=Ht;const T=n.clientX-u.left;if(g=h.getColIndex(T),"vertical"!==o){const t=s.clientX-u.left,i=h.getEdgeScrollCol(T,t,a);if(i.canEdgeScroll){let t;switch(I=!0,R=Math.min(R,i.delay),i.direction){case"reset":g=y,t=y;break;case 1:g=C,t=b+1;break;case-1:for(g=b-1;e.model.getters.isColHidden(d,g);)g--;t=g}E=h.getColDimensions(d,t).start-r}}const A=n.clientY-u.top;if(p=h.getRowIndex(A),"horizontal"!==o){const t=s.clientY-u.top,i=h.getEdgeScrollRow(A,t,l);if(i.canEdgeScroll){let t;switch(I=!0,R=Math.min(R,i.delay),i.direction){case"reset":p=x,t=x;break;case 1:p=S,t=v+i.direction;break;case-1:for(p=v-1;e.model.getters.isRowHidden(d,p);)p--;t=p}w=e.model.getters.getRowDimensions(d,t).start-f}}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))),s=n};Rg(m,(()=>{clearTimeout(c),i()}),(e=>{s=e,r=e,a=r.clientX-u.left,l=r.clientY-u.top}))}Ig.template="o-spreadsheet-FigureComponent",Ig.components={Menu:qn},Ig.defaultProps={onFigureDeleted:()=>{},onMouseDown:()=>{},onClickAnchor:()=>{}},Ig.props={figure:Object,style:{type:String,optional:!0},onFigureDeleted:{type:Function,optional:!0},onMouseDown:{type:Function,optional:!0},onClickAnchor:{type:Function,optional:!0}},ho`
1021
+ `;class Rg extends t.Component{constructor(){super(...arguments),this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.figureRef=t.useRef("figure"),this.menuButtonRef=t.useRef("menuButton"),this.menuButtonRect=zn(this.menuButtonRef)}get isSelected(){return this.env.model.getters.getSelectedFigureId()===this.props.figure.id}get figureRegistry(){return dr}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:i,height:o}=this.props.figure;return fo({left:`${e}px`,top:`${t}px`,width:`${i}px`,height:`${o}px`,"z-index":String(le.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)",fo(t)}setup(){const e=dr.get(this.props.figure.tag).borderWidth;this.borderWidth=void 0!==e?e:1,t.useEffect(((e,t,i)=>{e===t&&(null==i||i.focus({preventScroll:!0}))}),(()=>[this.env.model.getters.getSelectedFigureId(),this.props.figure.id,this.figureRef.el]))}clickAnchor(e,t,i){this.props.onClickAnchor(e,t,i)}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 i={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+i[0],y:t.y+i[1]}),e.stopPropagation(),e.preventDefault()}}onContextMenu(e){if(this.env.isDashboard())return;const t={x:e.clientX,y:e.clientY};this.openContextMenu(t)}showMenu(){const{x:e,y:t,width:i}=this.menuButtonRect,o={x:e>=H?e-H:e+i,y:t};this.openContextMenu(o)}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.position=e,this.menuState.menuItems=dr.get(this.props.figure.tag).menuBuilder(this.props.figure.id,this.props.onFigureDeleted,this.env)}}function Tg(e,t,i=(()=>{})){const o=e=>{e.preventDefault(),i(e)},n=t=>{t.preventDefault(),e(t)},s=e=>{e.preventDefault(),t(e),window.removeEventListener("mousedown",o),window.removeEventListener("mouseup",s),window.removeEventListener("dragstart",r),window.removeEventListener("mousemove",n),window.removeEventListener("wheel",n)};function r(e){e.preventDefault()}window.addEventListener("mousedown",o),window.addEventListener("mouseup",s),window.addEventListener("dragstart",r),window.addEventListener("mousemove",n),window.addEventListener("wheel",n,{passive:!1})}function Ag(e,t,i,o=!1){let n,s,r,a,l,c=null;const h=e.model.getters,d=h.getActiveSheetId(),u=Ln();let g,p;const m=i=>{if(n=i,c)return;const{x:r,y:f}=h.getMainViewportCoordinates();let{top:v,left:b,bottom:S,right:C}=h.getActiveMainViewport(),{scrollX:E,scrollY:w}=h.getActiveSheetDOMScrollInfo();const{xSplit:y,ySplit:x}=h.getPaneDivisions(d);let I=!1,R=$t;const T=n.clientX-u.left;if(g=h.getColIndex(T),"vertical"!==o){const t=s.clientX-u.left,i=h.getEdgeScrollCol(T,t,a);if(i.canEdgeScroll){let t;switch(I=!0,R=Math.min(R,i.delay),i.direction){case"reset":g=y,t=y;break;case 1:g=C,t=b+1;break;case-1:for(g=b-1;e.model.getters.isColHidden(d,g);)g--;t=g}E=h.getColDimensions(d,t).start-r}}const A=n.clientY-u.top;if(p=h.getRowIndex(A),"horizontal"!==o){const t=s.clientY-u.top,i=h.getEdgeScrollRow(A,t,l);if(i.canEdgeScroll){let t;switch(I=!0,R=Math.min(R,i.delay),i.direction){case"reset":p=x,t=x;break;case 1:p=S,t=v+i.direction;break;case-1:for(p=v-1;e.model.getters.isRowHidden(d,p);)p--;t=p}w=e.model.getters.getRowDimensions(d,t).start-f}}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))),s=n};Tg(m,(()=>{clearTimeout(c),i()}),(e=>{s=e,r=e,a=r.clientX-u.left,l=r.clientY-u.top}))}Rg.template="o-spreadsheet-FigureComponent",Rg.components={Menu:Zn},Rg.defaultProps={onFigureDeleted:()=>{},onMouseDown:()=>{},onClickAnchor:()=>{}},Rg.props={figure:Object,style:{type:String,optional:!0},onFigureDeleted:{type:Function,optional:!0},onMouseDown:{type:Function,optional:!0},onClickAnchor:{type:Function,optional:!0}},uo`
1022
1022
  .o-autofill {
1023
1023
  position: absolute;
1024
1024
  height: ${8}px;
@@ -1046,9 +1046,9 @@
1046
1046
  pointer-events: none;
1047
1047
  white-space: nowrap;
1048
1048
  }
1049
- `;class Ag 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 mo({top:`${t}px`,left:`${e}px`,visibility:this.props.isVisible?"visible":"hidden"})}get handlerStyle(){const{left:e,top:t}=this.state.handler?this.state.position:this.props.position;return mo({top:`${t}px`,left:`${e}px`})}get styleNextValue(){const{left:e,top:t}=this.state.position;return mo({top:`${t+5}px`,left:`${e+15}px`})}getTooltip(){const e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=Mg),e}onMouseDown(e){let t,i;this.state.handler=!0;const o=e.clientX-this.props.position.left,n=e.clientY-this.props.position.top;Tg(this.env,((e,s,r)=>{if(this.state.position={left:r.clientX-o,top:r.clientY-n},t!==e||i!==s){const o=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getNumberCols(o),r=this.env.model.getters.getNumberRows(o);t=-1===e?t:De(e,0,n),i=-1===s?i:De(s,0,r),void 0!==t&&void 0!==i&&this.env.model.dispatch("AUTOFILL_SELECT",{col:t,row:i})}}),(()=>{this.state.handler=!1,this.state.position={...this.props.position},this.env.model.dispatch("AUTOFILL")}))}onDblClick(){this.env.model.dispatch("AUTOFILL_AUTO")}}Ag.template="o-spreadsheet-Autofill",Ag.props={position:Object,isVisible:Boolean};class Mg extends t.Component{}Mg.template=t.xml`
1049
+ `;class Mg 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 fo({top:`${t}px`,left:`${e}px`,visibility:this.props.isVisible?"visible":"hidden"})}get handlerStyle(){const{left:e,top:t}=this.state.handler?this.state.position:this.props.position;return fo({top:`${t}px`,left:`${e}px`})}get styleNextValue(){const{left:e,top:t}=this.state.position;return fo({top:`${t+5}px`,left:`${e+15}px`})}getTooltip(){const e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=Og),e}onMouseDown(e){let t,i;this.state.handler=!0;const o=e.clientX-this.props.position.left,n=e.clientY-this.props.position.top;Ag(this.env,((e,s,r)=>{if(this.state.position={left:r.clientX-o,top:r.clientY-n},t!==e||i!==s){const o=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getNumberCols(o),r=this.env.model.getters.getNumberRows(o);t=-1===e?t:De(e,0,n),i=-1===s?i:De(s,0,r),void 0!==t&&void 0!==i&&this.env.model.dispatch("AUTOFILL_SELECT",{col:t,row:i})}}),(()=>{this.state.handler=!1,this.state.position={...this.props.position},this.env.model.dispatch("AUTOFILL")}))}onDblClick(){this.env.model.dispatch("AUTOFILL_AUTO")}}Mg.template="o-spreadsheet-Autofill",Mg.props={position:Object,isVisible:Boolean};class Og extends t.Component{}Og.template=t.xml`
1050
1050
  <div t-esc="props.content"/>
1051
- `,Mg.props={content:String},ho`
1051
+ `,Og.props={content:String},uo`
1052
1052
  .o-client-tag {
1053
1053
  position: absolute;
1054
1054
  border-top-left-radius: 4px;
@@ -1058,7 +1058,7 @@
1058
1058
  opacity: 0;
1059
1059
  pointer-events: none;
1060
1060
  }
1061
- `;class Og extends t.Component{get tagStyle(){const{col:e,row:t,color:i}=this.props,{height:o}=this.env.model.getters.getSheetViewDimensionWithHeaders(),{x:n,y:s}=this.env.model.getters.getVisibleRect({left:e,top:t,right:e,bottom:t});return mo({bottom:o-s+15+"px",left:n-1+"px",border:`1px solid ${i}`,"background-color":i,opacity:this.props.active?"opacity:1 !important":void 0})}}Og.template="o-spreadsheet-ClientTag",Og.props={active:Boolean,name:String,color:String,col:Number,row:Number},ho`
1061
+ `;class Ng extends t.Component{get tagStyle(){const{col:e,row:t,color:i}=this.props,{height:o}=this.env.model.getters.getSheetViewDimensionWithHeaders(),{x:n,y:s}=this.env.model.getters.getVisibleRect({left:e,top:t,right:e,bottom:t});return fo({bottom:o-s+15+"px",left:n-1+"px",border:`1px solid ${i}`,"background-color":i,opacity:this.props.active?"opacity:1 !important":void 0})}}Ng.template="o-spreadsheet-ClientTag",Ng.props={active:Boolean,name:String,color:String,col:Number,row:Number},uo`
1062
1062
  .o-autocomplete-dropdown {
1063
1063
  pointer-events: auto;
1064
1064
  background-color: #fff;
@@ -1077,7 +1077,7 @@
1077
1077
  }
1078
1078
  }
1079
1079
  }
1080
- `;class Ng extends t.Component{}Ng.template="o-spreadsheet-TextValueProvider",Ng.props={values:Array,selectedIndex:Number,onValueSelected:Function};class _g{constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){let i=window.getSelection();this.removeSelection();let o=document.createRange();if(e==t&&0===e)o.setStart(this.el,0),o.setEnd(this.el,0),i.addRange(o);else{const n=this.getText().length;(e<0||t>n)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${n}`),e<0&&(e=0),t>n&&(t=n),e>n&&(e=n));let s=this.findChildAtCharacterIndex(e),r=this.findChildAtCharacterIndex(t);o.setStart(s.node,s.offset),i.addRange(o),i.extend(r.node,r.offset)}}findChildAtCharacterIndex(e){let t,i,o=Pn(this.el),n=e,s=!0;do{t=o.next(),t.done||t.value.hasChildNodes()||(t.value.textContent&&t.value.textContent.length<n?n-=t.value.textContent.length:t.value.textContent&&t.value.textContent.length>=n&&o.return(t.value),i=t.value),t.done||"P"!==t.value.nodeName||(s?s=!1:n--)}while(!t.done&&n);return t.value?{node:t.value,offset:n}:{node:i,offset:n}}setText(e){if(this.el.innerHTML="",0!==e.length)for(const t of e){const e=document.createElement("p");if(0===t.length||t.every((e=>!e.value&&!e.class)))e.appendChild(document.createElement("br")),this.el.appendChild(e);else{for(const i of t){if(!i.value&&!i.class)continue;const t=document.createElement("span");t.innerText=i.value,t.style.color=i.color||"",i.class&&t.classList.add(i.class),e.appendChild(t)}this.el.appendChild(e)}}}scrollSelectionIntoView(){var e;const t=null===(e=document.getSelection())||void 0===e?void 0:e.focusNode;if(!t||!this.el.contains(t))return;const i=t instanceof HTMLElement?t:t.parentElement;null==i||i.scrollIntoView({block:"nearest"})}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){let{startElement:e,endElement:t,startSelectionOffset:i,endSelectionOffset:o}=this.getStartAndEndSelection();return{start:this.findSelectionIndex(e,i),end:this.findSelectionIndex(t,o)}}findSelectionIndex(e,t){let i=0,o=Pn(this.el),n=o.next(),s=!0;for(;!n.done&&n.value!==e;)n.value.hasChildNodes()||n.value.textContent&&(i+=n.value.textContent.length),("P"===n.value.nodeName||"DIV"===n.value.nodeName&&n.value!==this.el)&&(s?s=!1:i++),n=o.next();if(n.value!==e)return 0;if(n.value.hasChildNodes()){const e=[...n.value.childNodes].slice(0,t);i+=e.reduce(((t,i,o)=>{if(null!==i.textContent){let n=i.textContent.length;return"P"===i.nodeName&&o!==e.length-1&&n++,t+n}return t}),0)}else i+=t;return"P"!==e.nodeName||s||""!=e.textContent||i++,i}getStartAndEndSelection(){const e=document.getSelection();return{startElement:e.anchorNode||this.el,startSelectionOffset:e.anchorOffset,endElement:e.focusNode||this.el,endSelectionOffset:e.focusOffset}}getText(){let e="",t=Pn(this.el),i=t.next(),o=!0;for(;!i.done;)i.value.hasChildNodes()||(e+=i.value.textContent),("P"===i.value.nodeName||"DIV"===i.value.nodeName&&i.value!==this.el)&&(o?o=!1:e+=ce),i=t.next();return e}}ho`
1080
+ `;class _g extends t.Component{}_g.template="o-spreadsheet-TextValueProvider",_g.props={values:Array,selectedIndex:Number,onValueSelected:Function};class Fg{constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){let i=window.getSelection();this.removeSelection();let o=document.createRange();if(e==t&&0===e)o.setStart(this.el,0),o.setEnd(this.el,0),i.addRange(o);else{const n=this.getText().length;(e<0||t>n)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${n}`),e<0&&(e=0),t>n&&(t=n),e>n&&(e=n));let s=this.findChildAtCharacterIndex(e),r=this.findChildAtCharacterIndex(t);o.setStart(s.node,s.offset),i.addRange(o),i.extend(r.node,r.offset)}}findChildAtCharacterIndex(e){let t,i,o=Un(this.el),n=e,s=!0;do{t=o.next(),t.done||t.value.hasChildNodes()||(t.value.textContent&&t.value.textContent.length<n?n-=t.value.textContent.length:t.value.textContent&&t.value.textContent.length>=n&&o.return(t.value),i=t.value),t.done||"P"!==t.value.nodeName||(s?s=!1:n--)}while(!t.done&&n);return t.value?{node:t.value,offset:n}:{node:i,offset:n}}setText(e){if(this.el.innerHTML="",0!==e.length)for(const t of e){const e=document.createElement("p");if(0===t.length||t.every((e=>!e.value&&!e.class)))e.appendChild(document.createElement("br")),this.el.appendChild(e);else{for(const i of t){if(!i.value&&!i.class)continue;const t=document.createElement("span");t.innerText=i.value,t.style.color=i.color||"",i.class&&t.classList.add(i.class),e.appendChild(t)}this.el.appendChild(e)}}}scrollSelectionIntoView(){var e;const t=null===(e=document.getSelection())||void 0===e?void 0:e.focusNode;if(!t||!this.el.contains(t))return;const i=t instanceof HTMLElement?t:t.parentElement;null==i||i.scrollIntoView({block:"nearest"})}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){let{startElement:e,endElement:t,startSelectionOffset:i,endSelectionOffset:o}=this.getStartAndEndSelection();return{start:this.findSelectionIndex(e,i),end:this.findSelectionIndex(t,o)}}findSelectionIndex(e,t){let i=0,o=Un(this.el),n=o.next(),s=!0;for(;!n.done&&n.value!==e;)n.value.hasChildNodes()||n.value.textContent&&(i+=n.value.textContent.length),("P"===n.value.nodeName||"DIV"===n.value.nodeName&&n.value!==this.el)&&(s?s=!1:i++),n=o.next();if(n.value!==e)return 0;if(n.value.hasChildNodes()){const e=[...n.value.childNodes].slice(0,t);i+=e.reduce(((t,i,o)=>{if(null!==i.textContent){let n=i.textContent.length;return"P"===i.nodeName&&o!==e.length-1&&n++,t+n}return t}),0)}else i+=t;return"P"!==e.nodeName||s||""!=e.textContent||i++,i}getStartAndEndSelection(){const e=document.getSelection();return{startElement:e.anchorNode||this.el,startSelectionOffset:e.anchorOffset,endElement:e.focusNode||this.el,endSelectionOffset:e.focusOffset}}getText(){let e="",t=Un(this.el),i=t.next(),o=!0;for(;!i.done;)i.value.hasChildNodes()||(e+=i.value.textContent),("P"===i.value.nodeName||"DIV"===i.value.nodeName&&i.value!==this.el)&&(o?o=!1:e+=ce),i=t.next();return e}}uo`
1081
1081
  .o-formula-assistant {
1082
1082
  .o-formula-assistant-head {
1083
1083
  background-color: #f2f2f2;
@@ -1103,7 +1103,7 @@
1103
1103
  color: gray;
1104
1104
  }
1105
1105
  }
1106
- `;class Fg 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)}}Fg.template="o-spreadsheet-FunctionDescriptionProvider",Fg.props={functionName:String,functionDescription:Object,argToFocus:Number};const Dg=Wu.content,kg="selector-flag",Lg="#4a4e4d",Pg="#3da4ab",Ug={OPERATOR:Pg,NUMBER:"#02c39a",STRING:"#00a82d",FUNCTION:Lg,DEBUGGER:Pg,LEFT_PAREN:Lg,RIGHT_PAREN:Lg,COMMA:Lg,MATCHING_PAREN:"#000000"};ho`
1106
+ `;class Dg 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)}}Dg.template="o-spreadsheet-FunctionDescriptionProvider",Dg.props={functionName:String,functionDescription:Object,argToFocus:Number};const kg=Gu.content,Lg="selector-flag",Pg="#4a4e4d",Ug="#3da4ab",Vg={OPERATOR:Ug,NUMBER:"#02c39a",STRING:"#00a82d",FUNCTION:Pg,DEBUGGER:Ug,LEFT_PAREN:Pg,RIGHT_PAREN:Pg,COMMA:Pg,MATCHING_PAREN:"#000000"};uo`
1107
1107
  .o-composer-container {
1108
1108
  .o-composer {
1109
1109
  overflow-y: auto;
@@ -1128,7 +1128,7 @@
1128
1128
 
1129
1129
  span {
1130
1130
  white-space: pre-wrap;
1131
- &.${kg}:after {
1131
+ &.${Lg}:after {
1132
1132
  content: "${"␣"}";
1133
1133
  color: ${"#a9a9a9"};
1134
1134
  }
@@ -1142,12 +1142,12 @@
1142
1142
  pointer-events: none;
1143
1143
  }
1144
1144
  }
1145
- `;class Vg extends t.Component{constructor(){super(...arguments),this.composerRef=t.useRef("o_composer"),this.contentHelper=new _g(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:i}=this.props.rect;let o={};return t>this.props.delimitation.height-(t+i)&&(o.top="-3px",o.transform="translate(0, -100%)"),e+300>this.props.delimitation.width&&(o.right="0px"),o.width="300px",mo(o)}return mo({width:"300px"})}setup(){t.onMounted((()=>{const e=this.composerRef.el;this.contentHelper.updateEl(e),this.processContent(),this.contentHelper.scrollSelectionIntoView()})),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 i=e.shiftKey?"left":"right";this.env.model.dispatch("STOP_EDITION"),this.env.model.selection.moveAnchorCell(i,1)}processEnterKey(e){var t;if(e.preventDefault(),e.stopPropagation(),e.altKey||e.ctrlKey){const e=this.contentHelper.getCurrentSelection(),t=this.env.model.getters.getCurrentContent(),i=t.slice(0,e.start)+ce+t.slice(e.end);return this.env.model.dispatch("SET_CURRENT_CONTENT",{content:i,selection:{start:e.start+1,end:e.start+1}}),this.processContent(),void this.contentHelper.scrollSelectionIntoView()}if(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 i=e.shiftKey?"up":"down";this.env.model.selection.moveAnchorCell(i,1)}processEscapeKey(){this.env.model.dispatch("STOP_EDITION",{cancel:!0})}processF4Key(){this.env.model.dispatch("CYCLE_EDITION_REFERENCES"),this.processContent()}onCompositionStart(){this.compositionActive=!0}onCompositionEnd(){this.compositionActive=!1}onKeydown(e){let t=this.keyMapping[e.key];t?t.call(this,e):(e.stopPropagation(),this.updateCursorIfNeeded())}updateCursorIfNeeded(){if(!this.env.model.getters.isSelectingForComposer()){const{start:e,end:t}=this.contentHelper.getCurrentSelection();this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:e,end:t}),this.isKeyStillDown=!0}}onInput(){"inactive"!==this.props.focus&&this.shouldProcessInputEvents&&(this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION"),this.env.model.dispatch("SET_CURRENT_CONTENT",{content:this.contentHelper.getText(),selection:this.contentHelper.getCurrentSelection()}))}onKeyup(e){if(this.isKeyStillDown=!1,"inactive"===this.props.focus||["Control","Alt","Shift","Tab","Enter","F4"].includes(e.key))return;if(this.autoCompleteState.showProvider&&["ArrowUp","ArrowDown"].includes(e.key))return;if(this.env.model.getters.isSelectingForComposer()&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return;if(e.preventDefault(),e.stopPropagation(),this.autoCompleteState.showProvider=!1,e.ctrlKey&&" "===e.key)return this.showAutocomplete(""),void this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION");const{start:t,end:i}=this.env.model.getters.getComposerSelection(),{start:o,end:n}=this.contentHelper.getCurrentSelection();o===t&&n===i||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(Wu.content).filter((([e,{hidden:t}])=>!t)).map((([e,{description:t}])=>({text:e,description:t})));t=e?"true"===e.toLowerCase()||"false"===e.toLowerCase()?[]:_i(e,t,(e=>e.text)):t.sort(((e,t)=>e.text.localeCompare(t.text))),this.autoCompleteState.values=t.slice(0,10),this.autoCompleteState.selectedIndex=0}onMousedown(e){e.button>0||this.contentHelper.removeSelection()}onClick(){if(this.env.model.getters.isReadonly())return;const e=this.contentHelper.getCurrentSelection();this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION"),"inactive"===this.props.focus&&this.props.onComposerContentFocused(e),this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",e),this.processTokenAtCursor()}onBlur(){this.isKeyStillDown=!1}processContent(){if(this.compositionActive)return;const e=(null==(t=this.composerRef.el)?void 0:t.scrollTop)||0;var t;this.contentHelper.removeAll(),this.shouldProcessInputEvents=!1,"inactive"!==this.props.focus&&(this.contentHelper.el.focus(),this.contentHelper.selectRange(0,0));const i=this.getContentLines();if(0!==i.length&&0!==i.length[0]){this.contentHelper.setText(i);const{start:t,end:o}=this.env.model.getters.getComposerSelection();"inactive"!==this.props.focus&&this.contentHelper.selectRange(t,o),function(e,t){e&&(e.scrollTop=t)}(this.composerRef.el,e)}this.shouldProcessInputEvents=!0}getContentLines(){let e=this.env.model.getters.getCurrentContent();const t=e.startsWith("=")&&this.env.model.getters.getCurrentTokens().length>0;return""===e?[]:t&&"inactive"!==this.props.focus?this.splitHtmlContentIntoLines(this.getColoredTokens()):this.splitHtmlContentIntoLines([{value:e}])}getColoredTokens(){const e=this.env.model.getters.getCurrentTokens(),t=this.env.model.getters.getTokenAtCursor(),i=[],{end:o,start:n}=this.env.model.getters.getComposerSelection();for(const s of e){switch(s.type){case"OPERATOR":case"NUMBER":case"FUNCTION":case"COMMA":case"STRING":i.push({value:s.value,color:Ug[s.type]||"#000"});break;case"REFERENCE":const{xc:e,sheetName:o}=Pt(s.value);i.push({value:s.value,color:this.rangeColor(e,o)||"#000"});break;case"SYMBOL":let n=s.value;["TRUE","FALSE"].includes(n.toUpperCase())?i.push({value:s.value,color:Ug.NUMBER}):i.push({value:s.value,color:"#000"});break;case"LEFT_PAREN":case"RIGHT_PAREN":t&&["LEFT_PAREN","RIGHT_PAREN"].includes(t.type)&&t.parenIndex&&t.parenIndex===s.parenIndex?i.push({value:s.value,color:Ug.MATCHING_PAREN}):i.push({value:s.value,color:Ug[s.type]||"#000"});break;default:i.push({value:s.value,color:"#000"})}this.env.model.getters.showSelectionIndicator()&&o===n&&o===s.end&&(i[i.length-1].class=kg)}return i}splitHtmlContentIntoLines(e){const t=[];let i=[];for(const o of e)if(o.value.includes(ce)){const e=o.value.split(ce),n=e.pop();for(const n of e)i.push({color:o.color,value:n}),t.push(i),i=[];i.push({...o,value:n})}else i.push(o);i.length&&t.push(i);const o=[];for(const e of t)e.every(this.isContentEmpty)?o.push([e[0]]):o.push(e.filter((e=>!this.isContentEmpty(e))));return o}isContentEmpty(e){return!(e.value||e.class)}rangeColor(e,t){if("inactive"===this.props.focus)return;const i=this.env.model.getters.getHighlights(),o=t?this.env.model.getters.getSheetIdByName(t):this.env.model.getters.getEditionSheet(),n=i.find((t=>{if(t.sheetId!==o)return!1;let i=this.env.model.getters.getRangeFromSheetXC(o,e).zone;return i=1===so(i)?this.env.model.getters.expandZone(o,i):i,Gi(i,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}=Pt(e.value);if("FUNCTION"===e.type||"SYMBOL"===e.type&&!_t.test(t))this.showAutocomplete(e.value);else if(e.functionContext&&"UNKNOWN"!==e.type){const t=e.functionContext,i=t.parent.toUpperCase(),o=Dg[i],n=t.argPosition;this.functionDescriptionState.functionName=i,this.functionDescriptionState.functionDescription=o,this.functionDescriptionState.argToFocus=o.getArgToFocus(n+1)-1,this.functionDescriptionState.showDescription=!0}}}}autoComplete(e){if(e){const t=this.env.model.getters.getTokenAtCursor();if(t){let i=t.end,o=t.end;["SYMBOL","FUNCTION"].includes(t.type)&&(i=t.start);const n=this.env.model.getters.getCurrentTokens();if(n.length){e+="(";const i=n.map((e=>e.start)).indexOf(t.start);if(i+1<n.length){"LEFT_PAREN"===n[i+1].type&&o++}}this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:i,end:o})}this.env.model.dispatch("REPLACE_COMPOSER_CURSOR_SELECTION",{text:e})}this.processTokenAtCursor()}}Vg.template="o-spreadsheet-Composer",Vg.components={TextValueProvider:Ng,FunctionDescriptionProvider:Fg},Vg.defaultProps={inputStyle:""},Vg.props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerContentFocused:Function,inputStyle:{type:String,optional:!0},rect:{type:Object,optional:!0},delimitation:{type:Object,optional:!0},onComposerUnmounted:{type:Function,optional:!0}};const zg=3*.4*window.devicePixelRatio||1;ho`
1145
+ `;class zg extends t.Component{constructor(){super(...arguments),this.composerRef=t.useRef("o_composer"),this.contentHelper=new Fg(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:i}=this.props.rect;let o={};return t>this.props.delimitation.height-(t+i)&&(o.top="-3px",o.transform="translate(0, -100%)"),e+300>this.props.delimitation.width&&(o.right="0px"),o.width="300px",fo(o)}return fo({width:"300px"})}setup(){t.onMounted((()=>{const e=this.composerRef.el;this.contentHelper.updateEl(e),this.processContent(),this.contentHelper.scrollSelectionIntoView()})),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 Ku(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 i=e.shiftKey?"left":"right";this.env.model.dispatch("STOP_EDITION"),this.env.model.selection.moveAnchorCell(i,1)}processEnterKey(e){var t;if(e.preventDefault(),e.stopPropagation(),e.altKey||e.ctrlKey){const e=this.contentHelper.getCurrentSelection(),t=this.env.model.getters.getCurrentContent(),i=t.slice(0,e.start)+ce+t.slice(e.end);return this.env.model.dispatch("SET_CURRENT_CONTENT",{content:i,selection:{start:e.start+1,end:e.start+1}}),this.processContent(),void this.contentHelper.scrollSelectionIntoView()}if(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 i=e.shiftKey?"up":"down";this.env.model.selection.moveAnchorCell(i,1)}processEscapeKey(){this.env.model.dispatch("STOP_EDITION",{cancel:!0})}processF4Key(){this.env.model.dispatch("CYCLE_EDITION_REFERENCES"),this.processContent()}onCompositionStart(){this.compositionActive=!0}onCompositionEnd(){this.compositionActive=!1}onKeydown(e){let t=this.keyMapping[e.key];t?t.call(this,e):(e.stopPropagation(),this.updateCursorIfNeeded())}updateCursorIfNeeded(){if(!this.env.model.getters.isSelectingForComposer()){const{start:e,end:t}=this.contentHelper.getCurrentSelection();this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:e,end:t}),this.isKeyStillDown=!0}}onInput(){"inactive"!==this.props.focus&&this.shouldProcessInputEvents&&(this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION"),this.env.model.dispatch("SET_CURRENT_CONTENT",{content:this.contentHelper.getText(),selection:this.contentHelper.getCurrentSelection()}))}onKeyup(e){if(this.isKeyStillDown=!1,"inactive"===this.props.focus||["Control","Alt","Shift","Tab","Enter","F4"].includes(e.key))return;if(this.autoCompleteState.showProvider&&["ArrowUp","ArrowDown"].includes(e.key))return;if(this.env.model.getters.isSelectingForComposer()&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return;if(e.preventDefault(),e.stopPropagation(),this.autoCompleteState.showProvider=!1,e.ctrlKey&&" "===e.key)return this.showAutocomplete(""),void this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION");const{start:t,end:i}=this.env.model.getters.getComposerSelection(),{start:o,end:n}=this.contentHelper.getCurrentSelection();o===t&&n===i||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(Gu.content).filter((([e,{hidden:t}])=>!t)).map((([e,{description:t}])=>({text:e,description:t})));t=e?"true"===e.toLowerCase()||"false"===e.toLowerCase()?[]:Fi(e,t,(e=>e.text)):t.sort(((e,t)=>e.text.localeCompare(t.text))),this.autoCompleteState.values=t.slice(0,10),this.autoCompleteState.selectedIndex=0}onMousedown(e){e.button>0||this.contentHelper.removeSelection()}onClick(){if(this.env.model.getters.isReadonly())return;const e=this.contentHelper.getCurrentSelection();this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION"),"inactive"===this.props.focus&&this.props.onComposerContentFocused(e),this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",e),this.processTokenAtCursor()}onBlur(){this.isKeyStillDown=!1}processContent(){if(this.compositionActive)return;const e=(null==(t=this.composerRef.el)?void 0:t.scrollTop)||0;var t;this.contentHelper.removeAll(),this.shouldProcessInputEvents=!1,"inactive"!==this.props.focus&&(this.contentHelper.el.focus(),this.contentHelper.selectRange(0,0));const i=this.getContentLines();if(0!==i.length&&0!==i.length[0]){this.contentHelper.setText(i);const{start:t,end:o}=this.env.model.getters.getComposerSelection();"inactive"!==this.props.focus&&this.contentHelper.selectRange(t,o),function(e,t){e&&(e.scrollTop=t)}(this.composerRef.el,e)}this.shouldProcessInputEvents=!0}getContentLines(){let e=this.env.model.getters.getCurrentContent();const t=e.startsWith("=")&&this.env.model.getters.getCurrentTokens().length>0;return""===e?[]:t&&"inactive"!==this.props.focus?this.splitHtmlContentIntoLines(this.getColoredTokens()):this.splitHtmlContentIntoLines([{value:e}])}getColoredTokens(){const e=this.env.model.getters.getCurrentTokens(),t=this.env.model.getters.getTokenAtCursor(),i=[],{end:o,start:n}=this.env.model.getters.getComposerSelection();for(const s of e){switch(s.type){case"OPERATOR":case"NUMBER":case"FUNCTION":case"COMMA":case"STRING":i.push({value:s.value,color:Vg[s.type]||"#000"});break;case"REFERENCE":const{xc:e,sheetName:o}=Ut(s.value);i.push({value:s.value,color:this.rangeColor(e,o)||"#000"});break;case"SYMBOL":let n=s.value;["TRUE","FALSE"].includes(n.toUpperCase())?i.push({value:s.value,color:Vg.NUMBER}):i.push({value:s.value,color:"#000"});break;case"LEFT_PAREN":case"RIGHT_PAREN":t&&["LEFT_PAREN","RIGHT_PAREN"].includes(t.type)&&t.parenIndex&&t.parenIndex===s.parenIndex?i.push({value:s.value,color:Vg.MATCHING_PAREN}):i.push({value:s.value,color:Vg[s.type]||"#000"});break;default:i.push({value:s.value,color:"#000"})}this.env.model.getters.showSelectionIndicator()&&o===n&&o===s.end&&(i[i.length-1].class=Lg)}return i}splitHtmlContentIntoLines(e){const t=[];let i=[];for(const o of e)if(o.value.includes(ce)){const e=o.value.split(ce),n=e.pop();for(const n of e)i.push({color:o.color,value:n}),t.push(i),i=[];i.push({...o,value:n})}else i.push(o);i.length&&t.push(i);const o=[];for(const e of t)e.every(this.isContentEmpty)?o.push([e[0]]):o.push(e.filter((e=>!this.isContentEmpty(e))));return o}isContentEmpty(e){return!(e.value||e.class)}rangeColor(e,t){if("inactive"===this.props.focus)return;const i=this.env.model.getters.getHighlights(),o=t?this.env.model.getters.getSheetIdByName(t):this.env.model.getters.getEditionSheet(),n=i.find((t=>{if(t.sheetId!==o)return!1;let i=this.env.model.getters.getRangeFromSheetXC(o,e).zone;return i=1===ro(i)?this.env.model.getters.expandZone(o,i):i,qi(i,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}=Ut(e.value);if("FUNCTION"===e.type||"SYMBOL"===e.type&&!Ft.test(t))this.showAutocomplete(e.value);else if(e.functionContext&&"UNKNOWN"!==e.type){const t=e.functionContext,i=t.parent.toUpperCase(),o=kg[i],n=t.argPosition;this.functionDescriptionState.functionName=i,this.functionDescriptionState.functionDescription=o,this.functionDescriptionState.argToFocus=o.getArgToFocus(n+1)-1,this.functionDescriptionState.showDescription=!0}}}}autoComplete(e){if(e){const t=this.env.model.getters.getTokenAtCursor();if(t){let i=t.end,o=t.end;["SYMBOL","FUNCTION"].includes(t.type)&&(i=t.start);const n=this.env.model.getters.getCurrentTokens();if(n.length){e+="(";const i=n.map((e=>e.start)).indexOf(t.start);if(i+1<n.length){"LEFT_PAREN"===n[i+1].type&&o++}}this.env.model.dispatch("CHANGE_COMPOSER_CURSOR_SELECTION",{start:i,end:o})}this.env.model.dispatch("REPLACE_COMPOSER_CURSOR_SELECTION",{text:e})}this.processTokenAtCursor()}}zg.template="o-spreadsheet-Composer",zg.components={TextValueProvider:_g,FunctionDescriptionProvider:Dg},zg.defaultProps={inputStyle:""},zg.props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerContentFocused:Function,inputStyle:{type:String,optional:!0},rect:{type:Object,optional:!0},delimitation:{type:Object,optional:!0},onComposerUnmounted:{type:Function,optional:!0}};const Bg=3*.4*window.devicePixelRatio||1;uo`
1146
1146
  div.o-grid-composer {
1147
1147
  z-index: ${le.GridComposer};
1148
1148
  box-sizing: border-box;
1149
1149
  position: absolute;
1150
- border: ${zg}px solid ${E};
1150
+ border: ${Bg}px solid ${E};
1151
1151
 
1152
1152
  display: flex;
1153
1153
  align-items: center;
@@ -1163,7 +1163,7 @@
1163
1163
  padding: 6px 7px;
1164
1164
  border-radius: 4px;
1165
1165
  }
1166
- `;class Bg extends t.Component{setup(){this.gridComposerRef=t.useRef("gridComposer"),this.composerState=t.useState({rect:void 0,delimitation:void 0});const{sheetId:e,col:i,row:o}=this.env.model.getters.getActivePosition();this.zone=this.env.model.getters.expandZone(e,oo({col:i,row:o})),this.rect=this.env.model.getters.getVisibleRect(this.zone),this.isCellReferenceVisible=!1,t.onMounted((()=>{const e=this.gridComposerRef.el;this.composerState.rect={x:this.rect.x,y:this.rect.y,width:e.clientWidth,height:e.clientHeight},this.composerState.delimitation={width:e.parentElement.clientWidth,height:e.parentElement.clientHeight}})),t.onWillUpdateProps((()=>{if(this.isCellReferenceVisible)return;const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone();at(this.env.model.getters.getVisibleRect(t),this.rect)&&e===this.env.model.getters.getCurrentEditedCell().sheetId||(this.isCellReferenceVisible=!0)}))}get shouldDisplayCellReference(){return this.isCellReferenceVisible}get cellReference(){const{col:e,row:t,sheetId:i}=this.env.model.getters.getCurrentEditedCell();return`${i!==this.env.model.getters.getActiveSheetId()?Fe(this.env.model.getters.getSheetName(i))+"!":""}${Bt(e,t)}`}get cellReferenceStyle(){const{x:e,y:t}=this.rect;return mo({left:e-zg+"px",top:t-28+"px"})}get containerStyle(){const e=this.env.model.getters.getCurrentContent().startsWith("="),t=this.env.model.getters.getActiveCell(),i=this.env.model.getters.getActivePosition(),o=this.env.model.getters.getCellComputedStyle(i),{x:n,y:s,width:r,height:a}=this.rect,l=!e&&o.fillColor||"#ffffff",c=!e&&o.textColor||"#000000",h=!e&&o.fontSize||10,d=!e&&o.bold?"bold":void 0,u=!e&&o.italic?"italic":"normal",g=e?"none":uo(o);let p="left";return e||(p=o.align||t.defaultAlign),mo({left:n-1+"px",top:`${s}px`,"min-width":`${r+1}px`,"min-height":`${a+1}px`,background:l,color:c,"font-size":`${Pe(h)}px`,"font-weight":d,"font-style":u,"text-decoration":g,"text-align":p})}get composerStyle(){const e=this.props.gridDims.height-this.rect.y;return mo({"max-width":`${this.props.gridDims.width-this.rect.x}px`,"max-height":`${e}px`})}}Bg.template="o-spreadsheet-GridComposer",Bg.components={Composer:Vg},Bg.props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerUnmounted:Function,onComposerContentFocused:Function,gridDims:Object};const Hg=ho`
1166
+ `;class Hg extends t.Component{setup(){this.gridComposerRef=t.useRef("gridComposer"),this.composerState=t.useState({rect:void 0,delimitation:void 0});const{sheetId:e,col:i,row:o}=this.env.model.getters.getActivePosition();this.zone=this.env.model.getters.expandZone(e,no({col:i,row:o})),this.rect=this.env.model.getters.getVisibleRect(this.zone),this.isCellReferenceVisible=!1,t.onMounted((()=>{const e=this.gridComposerRef.el;this.composerState.rect={x:this.rect.x,y:this.rect.y,width:e.clientWidth,height:e.clientHeight},this.composerState.delimitation={width:e.parentElement.clientWidth,height:e.parentElement.clientHeight}})),t.onWillUpdateProps((()=>{if(this.isCellReferenceVisible)return;const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone();lt(this.env.model.getters.getVisibleRect(t),this.rect)&&e===this.env.model.getters.getCurrentEditedCell().sheetId||(this.isCellReferenceVisible=!0)}))}get shouldDisplayCellReference(){return this.isCellReferenceVisible}get cellReference(){const{col:e,row:t,sheetId:i}=this.env.model.getters.getCurrentEditedCell();return`${i!==this.env.model.getters.getActiveSheetId()?Fe(this.env.model.getters.getSheetName(i))+"!":""}${Ht(e,t)}`}get cellReferenceStyle(){const{x:e,y:t}=this.rect;return fo({left:e-Bg+"px",top:t-28+"px"})}get containerStyle(){const e=this.env.model.getters.getCurrentContent().startsWith("="),t=this.env.model.getters.getActiveCell(),i=this.env.model.getters.getActivePosition(),o=this.env.model.getters.getCellComputedStyle(i),{x:n,y:s,width:r,height:a}=this.rect,l=!e&&o.fillColor||"#ffffff",c=!e&&o.textColor||"#000000",h=!e&&o.fontSize||10,d=!e&&o.bold?"bold":void 0,u=!e&&o.italic?"italic":"normal",g=e?"none":go(o);let p="left";return e||(p=o.align||t.defaultAlign),fo({left:n-1+"px",top:`${s}px`,"min-width":`${r+1}px`,"min-height":`${a+1}px`,background:l,color:c,"font-size":`${Ue(h)}px`,"font-weight":d,"font-style":u,"text-decoration":g,"text-align":p})}get composerStyle(){const e=this.props.gridDims.height-this.rect.y;return fo({"max-width":`${this.props.gridDims.width-this.rect.x}px`,"max-height":`${e}px`})}}Hg.template="o-spreadsheet-GridComposer",Hg.components={Composer:zg},Hg.props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerUnmounted:Function,onComposerContentFocused:Function,gridDims:Object};const $g=uo`
1167
1167
  .o-filter-icon {
1168
1168
  color: ${I};
1169
1169
  position: absolute;
@@ -1187,7 +1187,7 @@
1187
1187
  }
1188
1188
  }
1189
1189
  }
1190
- `;class $g extends t.Component{get style(){const{x:e,y:t}=this.props.position;return`top:${t}px;left:${e}px`}}$g.style=Hg,$g.template="o-spreadsheet-FilterIcon",$g.props={position:Object,isActive:Boolean,onClick:Function};const Wg=ho``;class Gg extends t.Component{getVisibleFilterHeaders(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getFilterHeaders(e).filter((e=>this.isPositionVisible(e.col,e.row)))}getFilterHeaderPosition(e){const t=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getRowDimensionsInViewport(t,e.row),o=this.env.model.getters.getColDimensionsInViewport(t,e.col),n=Math.floor((i.size-B)/2);return{x:o.end-B+this.props.gridPosition.x-2-1,y:i.end-B+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:i,row:o}=e;this.env.model.dispatch("OPEN_CELL_POPOVER",{col:i,row:o,popoverType:"FilterMenu"})}isPositionVisible(e,t){const i=this.env.model.getters.getVisibleRect({left:e,right:e,top:t,bottom:t});return!(0===i.width||0===i.height)}}Gg.style=Wg,Gg.template="o-spreadsheet-FilterIconsOverlay",Gg.components={FilterIcon:$g},Gg.defaultProps={gridPosition:{x:0,y:0}},Gg.props={gridPosition:{type:Object,optional:!0}};class qg 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 i of["topLeft","topRight","bottomLeft","bottomRight"]){const o=e.filter((e=>this.getFigureContainer(e)===i));o.length>0&&t.push({type:i,figures:o,style:this.getContainerStyle(i),inverseViewportStyle:this.getInverseViewportPositionStyle(i)})}return this.dnd.figId&&t.push({type:"dnd",figures:[this.getDndFigure()],style:this.getContainerStyle("dnd"),inverseViewportStyle:this.getInverseViewportPositionStyle("dnd")}),t}getContainerStyle(e){const{width:t,height:i}=this.env.model.getters.getMainViewportRect(),{x:o,y:n}=this.env.model.getters.getMainViewportCoordinates(),s=["bottomRight","topRight"].includes(e)?o:0,r=t-s,a=["bottomRight","bottomLeft"].includes(e)?n:0;return mo({left:`${s}px`,top:`${a}px`,width:`${r}px`,height:`${i-a}px`})}getInverseViewportPositionStyle(e){const{scrollX:t,scrollY:i}=this.env.model.getters.getActiveSheetScrollInfo(),{x:o,y:n}=this.env.model.getters.getMainViewportCoordinates();return mo({left:`${["bottomRight","topRight"].includes(e)?-(o+t):0}px`,top:`${["bottomRight","bottomLeft"].includes(e)?-(n+i):0}px`})}getFigureContainer(e){const{x:t,y:i}=this.env.model.getters.getMainViewportCoordinates();return e.id===this.dnd.figId?"dnd":e.x<t&&e.y<i?"topLeft":e.x<t?"bottomLeft":e.y<i?"topRight":"bottomRight"}startDraggingFigure(e,t){if(t.button>0||this.env.model.getters.isReadonly())return;if(!this.env.model.dispatch("SELECT_FIGURE",{id:e.id}).isSuccessful)return;const i=this.env.model.getters.getActiveSheetId(),o=t.clientX,n=t.clientY,{x:s,y:r}=this.internalToScreenCoordinates(e);this.dnd.x=s,this.dnd.y=r,this.dnd.width=e.width,this.dnd.height=e.height;Rg((t=>{const{x:i,y:a}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:l,scrollY:c}=this.env.model.getters.getActiveSheetScrollInfo(),h=i?0:-l,d=a?0:-c;this.dnd.figId=e.id;let u=t.clientX-o;this.dnd.x=Math.max(s+u,h);let g=t.clientY-n;this.dnd.y=Math.max(r+g,d)}),(t=>{if(!this.dnd.figId)return;let{x:o,y:n}=this.screenCoordinatesToInternal(this.dnd);this.dnd.figId=void 0,this.env.model.dispatch("UPDATE_FIGURE",{sheetId:i,id:e.id,x:o,y:n})}))}startResize(e,t,i,o){o.stopPropagation();const n=o.clientX,s=o.clientY,{x:r,y:a}=this.internalToScreenCoordinates(e);this.dnd.x=r,this.dnd.y=a,this.dnd.width=e.width,this.dnd.height=e.height;const l=hr.get(e.tag).keepRatio||!1,c=hr.get(e.tag).minFigSize||80;let h;h=l&&0!=t&&0!=i?o=>{this.dnd.figId=e.id;const l=Math.min(t*(n-o.clientX),e.width-c),h=Math.min(i*(s-o.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=r+e.width*d),i<0&&(this.dnd.y=a+e.height*d)}:o=>{this.dnd.figId=e.id;const l=Math.max(t*(o.clientX-n),c-e.width),h=Math.max(i*(o.clientY-s),c-e.height);this.dnd.width=e.width+l,this.dnd.height=e.height+h,t<0&&(this.dnd.x=r-l),i<0&&(this.dnd.y=a-h)};Rg(h,(o=>{if(!this.dnd.figId)return;this.dnd.figId=void 0;let{x:n,y:s}=this.screenCoordinatesToInternal(this.dnd);const r={x:n,y:s};t&&(r.width=this.dnd.width),i&&(r.height=this.dnd.height),this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:e.id,...r})}))}getDndFigure(){const e=this.getVisibleFigures().find((e=>e.id===this.dnd.figId));if(!e)throw new Error("Dnd figure not found");return{...e,x:this.dnd.x,y:this.dnd.y,width:this.dnd.width,height:this.dnd.height}}getFigureStyle(e){return e.id!==this.dnd.figId?"":mo({opacity:"0.9",cursor:"grabbing"})}internalToScreenCoordinates({x:e,y:t}){const{x:i,y:o}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:n,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo();return{x:e=e<i?e:e-n,y:t=t<o?t:t-s}}screenCoordinatesToInternal({x:e,y:t}){const{x:i,y:o}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:n,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo();return{x:e=i&&e<i?e:e+n,y:t=o&&t<o?t:t+s}}}function Zg(e,i,o){let n={col:void 0,row:void 0};const{Date:s}=window;let r=0,a=0,l=0;function c(){return{col:e.model.getters.getColIndex(r),row:e.model.getters.getRowIndex(a)}}const{pause:h,resume:d}=function(e,i){let o;const{setInterval:n,clearInterval:s}=window;return t.useEffect((()=>(o=n(e,i),()=>s(o))),(()=>[i])),{pause:()=>{s(o),o=void 0},resume:()=>{void 0===o&&(o=n(e,i))}}}((function(){const{col:e,row:t}=c(),i=s.now()-l;i>300&&(e!==n.col||t!==n.row)&&p(void 0,void 0);if(i>300){if(e<0||t<0)return;p(e,t)}}),200);function u(e){r=e.offsetX,a=e.offsetY,l=s.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,o({col:e,row:t}))}return t.onMounted((()=>{const e=i.el;e.addEventListener("mousemove",u),e.addEventListener("mouseleave",h),e.addEventListener("mouseenter",d),e.addEventListener("mousedown",g)})),t.onWillUnmount((()=>{const e=i.el;e.removeEventListener("mousemove",u),e.removeEventListener("mouseleave",h),e.removeEventListener("mouseenter",d),e.removeEventListener("mousedown",g)})),n}qg.template="o-spreadsheet-FiguresContainer",qg.components={FigureComponent:Ig},qg.props={onFigureDeleted:Function};class jg extends t.Component{setup(){this.gridOverlay=t.useRef("gridOverlay"),Zg(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,i,o){let n=null,s=null;function r(e){1===e.touches.length&&(n=e.touches[0].clientX,s=e.touches[0].clientY)}function a(){n=null,s=null}function l(e){if(1!==e.touches.length)return;o()&&(e.preventDefault(),e.stopPropagation());const t=e.touches[0].clientX,r=e.touches[0].clientY;i(n-t,s-r),n=t,s=r}t.onMounted((()=>{e.el.addEventListener("touchstart",r),e.el.addEventListener("touchend",a),e.el.addEventListener("touchmove",l)})),t.onWillUnmount((()=>{e.el.removeEventListener("touchstart",r),e.el.removeEventListener("touchend",a),e.el.removeEventListener("touchmove",l)}))}(this.gridOverlay,this.props.onGridMoved,(()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetDOMScrollInfo();return e>0}))}get gridOverlayEl(){if(!this.gridOverlay.el)throw new Error("GridOverlay el is not defined.");return this.gridOverlay.el}onMouseDown(e){if(e.button>0)return;const[t,i]=this.getCartesianCoordinates(e);this.props.onCellClicked(t,i,{shiftKey:e.shiftKey,ctrlKey:e.ctrlKey})}onDoubleClick(e){const[t,i]=this.getCartesianCoordinates(e);this.props.onCellDoubleClicked(t,i)}onContextMenu(e){e.preventDefault();const[t,i]=this.getCartesianCoordinates(e);this.props.onCellRightClicked(t,i,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){return[this.env.model.getters.getColIndex(e.offsetX),this.env.model.getters.getRowIndex(e.offsetY)]}}jg.template="o-spreadsheet-GridOverlay",jg.components={FiguresContainer:qg},jg.defaultProps={onCellHovered:()=>{},onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{},onFigureDeleted:()=>{}},jg.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 Xg extends t.Component{constructor(){super(...arguments),this.zIndex=le.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}}}}Xg.template="o-spreadsheet-GridPopover",Xg.components={Popover:Hn},Xg.props={hoveredCell:Object,onClosePopover:Function,onMouseWheel:Function,gridRect:Object};class Yg 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),i=this._getElementIndex(t);if(i<0)return;const o=this._getDimensionsInViewport(i);t-o.start<this.PADDING&&i!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=o.start,this.state.activeElement=this._getPreviousVisibleElement(i)):o.end-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=o.end,this.state.activeElement=i):this.state.resizerIsActive=!1}_computeGrabDisplay(e){const t=this._getElementIndex(this._getEvOffset(e)),i=this._getActiveElements(),o=this._getSelectedZoneStart(),n=this._getSelectedZoneEnd();i.has(o)&&o<=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),i=this.state.draggerLinePosition,o=this._getElementSize(this.state.activeElement),n=i-o+this.MIN_ELEMENT_SIZE,s=this._getMaxSize();Rg((e=>{this.state.delta=this._getClientPosition(e)-t,this.state.draggerLinePosition=i+this.state.delta,this.state.draggerLinePosition<n&&(this.state.draggerLinePosition=n,this.state.delta=this.MIN_ELEMENT_SIZE-o),this.state.draggerLinePosition>s&&(this.state.draggerLinePosition=s,this.state.delta=s-i)}),(e=>{this.state.isResizing=!1,0!==this.state.delta&&this._updateSize()}))}select(e){if(e.button>0)return;const t=this._getElementIndex(this._getEvOffset(e));t<0||(!0!==this.state.waitingForMove?("editing"===this.env.model.getters.getEditionMode()&&this.env.model.selection.getBackToDefault(),this.startSelection(e,t)):this.startMovement(e))}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;const t=this._getDimensionsInViewport(this._getSelectedZoneStart()),i=this._getDimensionsInViewport(this._getSelectedZoneEnd()),o=t.start;this.state.draggerLinePosition=o,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=o,this.state.draggerShadowThickness=i.end-t.start;Tg(this.env,((e,i)=>{let o="COL"===this._getType()?e:i;if(o>=0){const e=this._getDimensionsInViewport(o);o<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=e.start,this.state.draggerShadowPosition=e.start,this.state.base=o):this._getSelectedZoneEnd()<o?(this.state.draggerLinePosition=e.end,this.state.draggerShadowPosition=e.end-this.state.draggerShadowThickness,this.state.base=o+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;Tg(this.env,((e,t)=>{let i="COL"===this._getType()?e:t;i!==this.lastSelectedElementIndex&&-1!==i&&(this._increaseSelection(i),this.lastSelectedElementIndex=i)}),(()=>{this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this.env.model.dispatch(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 i=this._getType();this.props.onOpenContextMenu(i,e.clientX,e.clientY)}}ho`
1190
+ `;class Wg extends t.Component{get style(){const{x:e,y:t}=this.props.position;return`top:${t}px;left:${e}px`}}Wg.style=$g,Wg.template="o-spreadsheet-FilterIcon",Wg.props={position:Object,isActive:Boolean,onClick:Function};const Gg=uo``;class qg extends t.Component{getVisibleFilterHeaders(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getFilterHeaders(e).filter((e=>this.isPositionVisible(e.col,e.row)))}getFilterHeaderPosition(e){const t=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getRowDimensionsInViewport(t,e.row),o=this.env.model.getters.getColDimensionsInViewport(t,e.col),n=Math.floor((i.size-B)/2);return{x:o.end-B+this.props.gridPosition.x-2-1,y:i.end-B+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:i,row:o}=e;this.env.model.dispatch("OPEN_CELL_POPOVER",{col:i,row:o,popoverType:"FilterMenu"})}isPositionVisible(e,t){const i=this.env.model.getters.getVisibleRect({left:e,right:e,top:t,bottom:t});return!(0===i.width||0===i.height)}}qg.style=Gg,qg.template="o-spreadsheet-FilterIconsOverlay",qg.components={FilterIcon:Wg},qg.defaultProps={gridPosition:{x:0,y:0}},qg.props={gridPosition:{type:Object,optional:!0}};class Zg 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 i of["topLeft","topRight","bottomLeft","bottomRight"]){const o=e.filter((e=>this.getFigureContainer(e)===i));o.length>0&&t.push({type:i,figures:o,style:this.getContainerStyle(i),inverseViewportStyle:this.getInverseViewportPositionStyle(i)})}return this.dnd.figId&&t.push({type:"dnd",figures:[this.getDndFigure()],style:this.getContainerStyle("dnd"),inverseViewportStyle:this.getInverseViewportPositionStyle("dnd")}),t}getContainerStyle(e){const{width:t,height:i}=this.env.model.getters.getMainViewportRect(),{x:o,y:n}=this.env.model.getters.getMainViewportCoordinates(),s=["bottomRight","topRight"].includes(e)?o:0,r=t-s,a=["bottomRight","bottomLeft"].includes(e)?n:0;return fo({left:`${s}px`,top:`${a}px`,width:`${r}px`,height:`${i-a}px`})}getInverseViewportPositionStyle(e){const{scrollX:t,scrollY:i}=this.env.model.getters.getActiveSheetScrollInfo(),{x:o,y:n}=this.env.model.getters.getMainViewportCoordinates();return fo({left:`${["bottomRight","topRight"].includes(e)?-(o+t):0}px`,top:`${["bottomRight","bottomLeft"].includes(e)?-(n+i):0}px`})}getFigureContainer(e){const{x:t,y:i}=this.env.model.getters.getMainViewportCoordinates();return e.id===this.dnd.figId?"dnd":e.x<t&&e.y<i?"topLeft":e.x<t?"bottomLeft":e.y<i?"topRight":"bottomRight"}startDraggingFigure(e,t){if(t.button>0||this.env.model.getters.isReadonly())return;if(!this.env.model.dispatch("SELECT_FIGURE",{id:e.id}).isSuccessful)return;const i=this.env.model.getters.getActiveSheetId(),o=t.clientX,n=t.clientY,{x:s,y:r}=this.internalToScreenCoordinates(e);this.dnd.x=s,this.dnd.y=r,this.dnd.width=e.width,this.dnd.height=e.height;Tg((t=>{const{x:i,y:a}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:l,scrollY:c}=this.env.model.getters.getActiveSheetScrollInfo(),h=i?0:-l,d=a?0:-c;this.dnd.figId=e.id;let u=t.clientX-o;this.dnd.x=Math.max(s+u,h);let g=t.clientY-n;this.dnd.y=Math.max(r+g,d)}),(t=>{if(!this.dnd.figId)return;let{x:o,y:n}=this.screenCoordinatesToInternal(this.dnd);this.dnd.figId=void 0,this.env.model.dispatch("UPDATE_FIGURE",{sheetId:i,id:e.id,x:o,y:n})}))}startResize(e,t,i,o){o.stopPropagation();const n=o.clientX,s=o.clientY,{x:r,y:a}=this.internalToScreenCoordinates(e);this.dnd.x=r,this.dnd.y=a,this.dnd.width=e.width,this.dnd.height=e.height;const l=dr.get(e.tag).keepRatio||!1,c=dr.get(e.tag).minFigSize||80;let h;h=l&&0!=t&&0!=i?o=>{this.dnd.figId=e.id;const l=Math.min(t*(n-o.clientX),e.width-c),h=Math.min(i*(s-o.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=r+e.width*d),i<0&&(this.dnd.y=a+e.height*d)}:o=>{this.dnd.figId=e.id;const l=Math.max(t*(o.clientX-n),c-e.width),h=Math.max(i*(o.clientY-s),c-e.height);this.dnd.width=e.width+l,this.dnd.height=e.height+h,t<0&&(this.dnd.x=r-l),i<0&&(this.dnd.y=a-h)};Tg(h,(o=>{if(!this.dnd.figId)return;this.dnd.figId=void 0;let{x:n,y:s}=this.screenCoordinatesToInternal(this.dnd);const r={x:n,y:s};t&&(r.width=this.dnd.width),i&&(r.height=this.dnd.height),this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:e.id,...r})}))}getDndFigure(){const e=this.getVisibleFigures().find((e=>e.id===this.dnd.figId));if(!e)throw new Error("Dnd figure not found");return{...e,x:this.dnd.x,y:this.dnd.y,width:this.dnd.width,height:this.dnd.height}}getFigureStyle(e){return e.id!==this.dnd.figId?"":fo({opacity:"0.9",cursor:"grabbing"})}internalToScreenCoordinates({x:e,y:t}){const{x:i,y:o}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:n,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo();return{x:e=e<i?e:e-n,y:t=t<o?t:t-s}}screenCoordinatesToInternal({x:e,y:t}){const{x:i,y:o}=this.env.model.getters.getMainViewportCoordinates(),{scrollX:n,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo();return{x:e=i&&e<i?e:e+n,y:t=o&&t<o?t:t+s}}}function jg(e,i,o){let n={col:void 0,row:void 0};const{Date:s}=window;let r=0,a=0,l=0;function c(){return{col:e.model.getters.getColIndex(r),row:e.model.getters.getRowIndex(a)}}const{pause:h,resume:d}=function(e,i){let o;const{setInterval:n,clearInterval:s}=window;return t.useEffect((()=>(o=n(e,i),()=>s(o))),(()=>[i])),{pause:()=>{s(o),o=void 0},resume:()=>{void 0===o&&(o=n(e,i))}}}((function(){const{col:e,row:t}=c(),i=s.now()-l;i>300&&(e!==n.col||t!==n.row)&&p(void 0,void 0);if(i>300){if(e<0||t<0)return;p(e,t)}}),200);function u(e){r=e.offsetX,a=e.offsetY,l=s.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,o({col:e,row:t}))}return t.onMounted((()=>{const e=i.el;e.addEventListener("mousemove",u),e.addEventListener("mouseleave",h),e.addEventListener("mouseenter",d),e.addEventListener("mousedown",g)})),t.onWillUnmount((()=>{const e=i.el;e.removeEventListener("mousemove",u),e.removeEventListener("mouseleave",h),e.removeEventListener("mouseenter",d),e.removeEventListener("mousedown",g)})),n}Zg.template="o-spreadsheet-FiguresContainer",Zg.components={FigureComponent:Rg},Zg.props={onFigureDeleted:Function};class Xg extends t.Component{setup(){this.gridOverlay=t.useRef("gridOverlay"),jg(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,i,o){let n=null,s=null;function r(e){1===e.touches.length&&(n=e.touches[0].clientX,s=e.touches[0].clientY)}function a(){n=null,s=null}function l(e){if(1!==e.touches.length)return;o()&&(e.preventDefault(),e.stopPropagation());const t=e.touches[0].clientX,r=e.touches[0].clientY;i(n-t,s-r),n=t,s=r}t.onMounted((()=>{e.el.addEventListener("touchstart",r),e.el.addEventListener("touchend",a),e.el.addEventListener("touchmove",l)})),t.onWillUnmount((()=>{e.el.removeEventListener("touchstart",r),e.el.removeEventListener("touchend",a),e.el.removeEventListener("touchmove",l)}))}(this.gridOverlay,this.props.onGridMoved,(()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetDOMScrollInfo();return e>0}))}get gridOverlayEl(){if(!this.gridOverlay.el)throw new Error("GridOverlay el is not defined.");return this.gridOverlay.el}onMouseDown(e){if(e.button>0)return;const[t,i]=this.getCartesianCoordinates(e);this.props.onCellClicked(t,i,{shiftKey:e.shiftKey,ctrlKey:e.ctrlKey})}onDoubleClick(e){const[t,i]=this.getCartesianCoordinates(e);this.props.onCellDoubleClicked(t,i)}onContextMenu(e){e.preventDefault();const[t,i]=this.getCartesianCoordinates(e);this.props.onCellRightClicked(t,i,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){return[this.env.model.getters.getColIndex(e.offsetX),this.env.model.getters.getRowIndex(e.offsetY)]}}Xg.template="o-spreadsheet-GridOverlay",Xg.components={FiguresContainer:Zg},Xg.defaultProps={onCellHovered:()=>{},onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{},onFigureDeleted:()=>{}},Xg.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 Yg extends t.Component{constructor(){super(...arguments),this.zIndex=le.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}}}}Yg.template="o-spreadsheet-GridPopover",Yg.components={Popover:$n},Yg.props={hoveredCell:Object,onClosePopover:Function,onMouseWheel:Function,gridRect:Object};class Kg 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),i=this._getElementIndex(t);if(i<0)return;const o=this._getDimensionsInViewport(i);t-o.start<this.PADDING&&i!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=o.start,this.state.activeElement=this._getPreviousVisibleElement(i)):o.end-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=o.end,this.state.activeElement=i):this.state.resizerIsActive=!1}_computeGrabDisplay(e){const t=this._getElementIndex(this._getEvOffset(e)),i=this._getActiveElements(),o=this._getSelectedZoneStart(),n=this._getSelectedZoneEnd();i.has(o)&&o<=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),i=this.state.draggerLinePosition,o=this._getElementSize(this.state.activeElement),n=i-o+this.MIN_ELEMENT_SIZE,s=this._getMaxSize();Tg((e=>{this.state.delta=this._getClientPosition(e)-t,this.state.draggerLinePosition=i+this.state.delta,this.state.draggerLinePosition<n&&(this.state.draggerLinePosition=n,this.state.delta=this.MIN_ELEMENT_SIZE-o),this.state.draggerLinePosition>s&&(this.state.draggerLinePosition=s,this.state.delta=s-i)}),(e=>{this.state.isResizing=!1,0!==this.state.delta&&this._updateSize()}))}select(e){if(e.button>0)return;const t=this._getElementIndex(this._getEvOffset(e));t<0||(!0!==this.state.waitingForMove?("editing"===this.env.model.getters.getEditionMode()&&this.env.model.selection.getBackToDefault(),this.startSelection(e,t)):this.startMovement(e))}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;const t=this._getDimensionsInViewport(this._getSelectedZoneStart()),i=this._getDimensionsInViewport(this._getSelectedZoneEnd()),o=t.start;this.state.draggerLinePosition=o,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=o,this.state.draggerShadowThickness=i.end-t.start;Ag(this.env,((e,i)=>{let o="COL"===this._getType()?e:i;if(o>=0){const e=this._getDimensionsInViewport(o);o<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=e.start,this.state.draggerShadowPosition=e.start,this.state.base=o):this._getSelectedZoneEnd()<o?(this.state.draggerLinePosition=e.end,this.state.draggerShadowPosition=e.end-this.state.draggerShadowThickness,this.state.base=o+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;Ag(this.env,((e,t)=>{let i="COL"===this._getType()?e:t;i!==this.lastSelectedElementIndex&&-1!==i&&(this._increaseSelection(i),this.lastSelectedElementIndex=i)}),(()=>{this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this.env.model.dispatch(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 i=this._getType();this.props.onOpenContextMenu(i,e.clientX,e.clientY)}}uo`
1191
1191
  .o-col-resizer {
1192
1192
  position: absolute;
1193
1193
  top: 0;
@@ -1246,7 +1246,7 @@
1246
1246
  top: calc(${L}px / 2 - ${k}px / 2);
1247
1247
  }
1248
1248
  }
1249
- `,Yg.props={onOpenContextMenu:Function};class Kg extends Yg{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),i=this.env.model.getters.getActiveCols();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"COL",sheetId:this.env.model.getters.getActiveSheetId(),elements:i.has(e)?[...i]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),i=this._getSelectedZoneEnd();for(let o=t;o<=i;o++)e.push(o);const o=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"COL",base:this.state.base,elements:e});!o.isSuccessful&&o.reasons.includes(2)&&this.env.raiseError(Ts)}_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 i;for(i=e-1;i>=0&&this.env.model.getters.isColHidden(t,i);i--);return i}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),elements:e,dimension:"COL"})}unhideStyleValue(e){return this._getDimensionsInViewport(e).start}}Kg.template="o-spreadsheet-ColResizer",ho`
1249
+ `,Kg.props={onOpenContextMenu:Function};class Qg extends Kg{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),i=this.env.model.getters.getActiveCols();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"COL",sheetId:this.env.model.getters.getActiveSheetId(),elements:i.has(e)?[...i]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),i=this._getSelectedZoneEnd();for(let o=t;o<=i;o++)e.push(o);const o=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"COL",base:this.state.base,elements:e});!o.isSuccessful&&o.reasons.includes(2)&&this.env.raiseError(As)}_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 i;for(i=e-1;i>=0&&this.env.model.getters.isColHidden(t,i);i--);return i}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),elements:e,dimension:"COL"})}unhideStyleValue(e){return this._getDimensionsInViewport(e).start}}Qg.template="o-spreadsheet-ColResizer",uo`
1250
1250
  .o-row-resizer {
1251
1251
  position: absolute;
1252
1252
  top: ${O}px;
@@ -1307,7 +1307,7 @@
1307
1307
  background-color: lightgrey;
1308
1308
  }
1309
1309
  }
1310
- `,Kg.props={onOpenContextMenu:Function};class Qg extends Yg{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),i=this.env.model.getters.getActiveRows();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"ROW",sheetId:this.env.model.getters.getActiveSheetId(),elements:i.has(e)?[...i]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),i=this._getSelectedZoneEnd();for(let o=t;o<=i;o++)e.push(o);const o=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",base:this.state.base,elements:e});!o.isSuccessful&&o.reasons.includes(2)&&this.env.raiseError(Ts)}_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 i;for(i=e-1;i>=0&&this.env.model.getters.isRowHidden(t,i);i--);return i}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",elements:e})}unhideStyleValue(e){return this._getDimensionsInViewport(e).start}}Qg.template="o-spreadsheet-RowResizer",ho`
1310
+ `,Qg.props={onOpenContextMenu:Function};class Jg extends Kg{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),i=this.env.model.getters.getActiveRows();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"ROW",sheetId:this.env.model.getters.getActiveSheetId(),elements:i.has(e)?[...i]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),i=this._getSelectedZoneEnd();for(let o=t;o<=i;o++)e.push(o);const o=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",base:this.state.base,elements:e});!o.isSuccessful&&o.reasons.includes(2)&&this.env.raiseError(As)}_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 i;for(i=e-1;i>=0&&this.env.model.getters.isRowHidden(t,i);i--);return i}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",elements:e})}unhideStyleValue(e){return this._getDimensionsInViewport(e).start}}Jg.template="o-spreadsheet-RowResizer",uo`
1311
1311
  .o-overlay {
1312
1312
  .all {
1313
1313
  position: absolute;
@@ -1318,7 +1318,7 @@
1318
1318
  height: ${O}px;
1319
1319
  }
1320
1320
  }
1321
- `,Qg.props={onOpenContextMenu:Function};class Jg extends t.Component{selectAll(){this.env.model.selection.selectAll()}}function ep(e,i,o){const n=t.useRef(e);t.useEffect((function(){const e=n.el,t=window.devicePixelRatio||1,s=e.getContext("2d",{alpha:!1}),r={ctx:s,dpr:t,thinLineWidth:.4*t},{width:a,height:l}=o();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;`),s.translate(-m,-m),s.scale(t,t),i.drawGrid(r)}))}function tp(e){function t(e,t){return e*(0===t?1:F)}return i=>{const o=t(i.shiftKey?i.deltaY:i.deltaX,i.deltaMode),n=t(i.shiftKey?i.deltaX:i.deltaY,i.deltaMode);e(o,n)}}Jg.template="o-spreadsheet-HeadersOverlay",Jg.components={ColResizer:Kg,RowResizer:Qg},Jg.props={onOpenContextMenu:Function},ho`
1321
+ `,Jg.props={onOpenContextMenu:Function};class ep extends t.Component{selectAll(){this.env.model.selection.selectAll()}}function tp(e,i,o){const n=t.useRef(e);t.useEffect((function(){const e=n.el,t=window.devicePixelRatio||1,s=e.getContext("2d",{alpha:!1}),r={ctx:s,dpr:t,thinLineWidth:.4*t},{width:a,height:l}=o();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;`),s.translate(-m,-m),s.scale(t,t),i.drawGrid(r)}))}function ip(e){function t(e,t){return e*(0===t?1:F)}return i=>{const o=t(i.shiftKey?i.deltaY:i.deltaX,i.deltaMode),n=t(i.shiftKey?i.deltaX:i.deltaY,i.deltaMode);e(o,n)}}ep.template="o-spreadsheet-HeadersOverlay",ep.components={ColResizer:Qg,RowResizer:Jg},ep.props={onOpenContextMenu:Function},uo`
1322
1322
  .o-border {
1323
1323
  position: absolute;
1324
1324
  &:hover {
@@ -1328,7 +1328,7 @@
1328
1328
  .o-moving {
1329
1329
  cursor: grabbing;
1330
1330
  }
1331
- `;class ip extends t.Component{get style(){const e=["n","w","e"].includes(this.props.orientation),t=["n","w","s"].includes(this.props.orientation),i=["n","s"].includes(this.props.orientation),o=["w","e"].includes(this.props.orientation),n=this.props.zone,s=this.env.model.getters.getVisibleRect(n),r=s.x,a=s.x+s.width-4,l=s.y,c=s.y+s.height-4;return mo({left:`${t?r:a}px`,top:`${e?l:c}px`,width:`${i?a-r:4}px`,height:`${o?c-l:4}px`})}onMouseDown(e){this.props.onMoveHighlight(e.clientX,e.clientY)}}ip.template="o-spreadsheet-Border",ip.props={zone:Object,orientation:String,isMoving:Boolean,onMoveHighlight:Function},ho`
1331
+ `;class op extends t.Component{get style(){const e=["n","w","e"].includes(this.props.orientation),t=["n","w","s"].includes(this.props.orientation),i=["n","s"].includes(this.props.orientation),o=["w","e"].includes(this.props.orientation),n=this.props.zone,s=this.env.model.getters.getVisibleRect(n),r=s.x,a=s.x+s.width-4,l=s.y,c=s.y+s.height-4;return fo({left:`${t?r:a}px`,top:`${e?l:c}px`,width:`${i?a-r:4}px`,height:`${o?c-l:4}px`})}onMouseDown(e){this.props.onMoveHighlight(e.clientX,e.clientY)}}op.template="o-spreadsheet-Border",op.props={zone:Object,orientation:String,isMoving:Boolean,onMoveHighlight:Function},uo`
1332
1332
  .o-corner {
1333
1333
  position: absolute;
1334
1334
  height: 6px;
@@ -1350,11 +1350,11 @@
1350
1350
  .o-resizing {
1351
1351
  cursor: grabbing;
1352
1352
  }
1353
- `;class op extends t.Component{constructor(){super(...arguments),this.isTop="n"===this.props.orientation[0],this.isLeft="w"===this.props.orientation[1]}get style(){const e=this.props.zone,t=this.isLeft?e.left:e.right,i=this.isTop?e.top:e.bottom,o=this.env.model.getters.getVisibleRect({left:t,right:t,top:i,bottom:i});if(o.width*o.height==0)return"display:none";return mo({left:(this.isLeft?o.x:o.x+o.width)-4+"px",top:(this.isTop?o.y:o.y+o.height)-4+"px","background-color":this.props.color})}onMouseDown(e){this.props.onResizeHighlight(this.isLeft,this.isTop)}}op.template="o-spreadsheet-Corner",op.props={zone:Object,color:String,orientation:String,isResizing:Boolean,onResizeHighlight:Function},ho`
1353
+ `;class np extends t.Component{constructor(){super(...arguments),this.isTop="n"===this.props.orientation[0],this.isLeft="w"===this.props.orientation[1]}get style(){const e=this.props.zone,t=this.isLeft?e.left:e.right,i=this.isTop?e.top:e.bottom,o=this.env.model.getters.getVisibleRect({left:t,right:t,top:i,bottom:i});if(o.width*o.height==0)return"display:none";return fo({left:(this.isLeft?o.x:o.x+o.width)-4+"px",top:(this.isTop?o.y:o.y+o.height)-4+"px","background-color":this.props.color})}onMouseDown(e){this.props.onResizeHighlight(this.isLeft,this.isTop)}}np.template="o-spreadsheet-Corner",np.props={zone:Object,color:String,orientation:String,isResizing:Boolean,onResizeHighlight:Function},uo`
1354
1354
  .o-highlight {
1355
1355
  z-index: ${le.Highlight};
1356
1356
  }
1357
- `;class np extends t.Component{constructor(){super(...arguments),this.highlightState=t.useState({shiftingMode:"none"})}onResizeHighlight(e,t){const i=this.env.model.getters.getActiveSheet();this.highlightState.shiftingMode="isResizing";const o=this.props.zone,n=e?o.right:o.left,s=t?o.bottom:o.top;let r=e?o.left:o.right,a=t?o.top:o.bottom,l=o;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(i.id,l)});Tg(this.env,((e,t)=>{if(r!==e||a!==t){const o=this.env.model.getters.getActiveSheetId();r=De(-1===e?r:e,0,this.env.model.getters.getNumberCols(o)-1),a=De(-1===t?a:t,0,this.env.model.getters.getNumberRows(o)-1);let c={left:Math.min(n,r),top:Math.min(s,a),right:Math.max(n,r),bottom:Math.max(s,a)};c=this.env.model.getters.expandZone(o,c),Gi(c,l)||(this.env.model.dispatch("CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(i.id,c)}),l=c)}}),(()=>{this.highlightState.shiftingMode="none",this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION")}))}onMoveHighlight(e,t){this.highlightState.shiftingMode="isMoving";const i=this.props.zone,o=kn(),n=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getColIndex(e-o.left),r=this.env.model.getters.getRowIndex(t-o.top),a=-i.left,l=this.env.model.getters.getNumberCols(n)-i.right-1,c=-i.top,h=this.env.model.getters.getNumberRows(n)-i.bottom-1;let d=i;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(n,d)});let u=s,g=r;Tg(this.env,((e,t)=>{if(u!==e||g!==t){u=-1===e?u:e,g=-1===t?g:t;const o=De(u-s,a,l),p=De(g-r,c,h);let m={left:i.left+o,top:i.top+p,right:i.right+o,bottom:i.bottom+p};m=this.env.model.getters.expandZone(n,m),Gi(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")}))}}np.template="o-spreadsheet-Highlight",np.components={Corner:op,Border:ip},np.props={zone:Object,color:String};class sp{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}}ho`
1357
+ `;class sp extends t.Component{constructor(){super(...arguments),this.highlightState=t.useState({shiftingMode:"none"})}onResizeHighlight(e,t){const i=this.env.model.getters.getActiveSheet();this.highlightState.shiftingMode="isResizing";const o=this.props.zone,n=e?o.right:o.left,s=t?o.bottom:o.top;let r=e?o.left:o.right,a=t?o.top:o.bottom,l=o;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(i.id,l)});Ag(this.env,((e,t)=>{if(r!==e||a!==t){const o=this.env.model.getters.getActiveSheetId();r=De(-1===e?r:e,0,this.env.model.getters.getNumberCols(o)-1),a=De(-1===t?a:t,0,this.env.model.getters.getNumberRows(o)-1);let c={left:Math.min(n,r),top:Math.min(s,a),right:Math.max(n,r),bottom:Math.max(s,a)};c=this.env.model.getters.expandZone(o,c),qi(c,l)||(this.env.model.dispatch("CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(i.id,c)}),l=c)}}),(()=>{this.highlightState.shiftingMode="none",this.env.model.dispatch("STOP_COMPOSER_RANGE_SELECTION")}))}onMoveHighlight(e,t){this.highlightState.shiftingMode="isMoving";const i=this.props.zone,o=Ln(),n=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getColIndex(e-o.left),r=this.env.model.getters.getRowIndex(t-o.top),a=-i.left,l=this.env.model.getters.getNumberCols(n)-i.right-1,c=-i.top,h=this.env.model.getters.getNumberRows(n)-i.bottom-1;let d=i;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{range:this.env.model.getters.getRangeDataFromZone(n,d)});let u=s,g=r;Ag(this.env,((e,t)=>{if(u!==e||g!==t){u=-1===e?u:e,g=-1===t?g:t;const o=De(u-s,a,l),p=De(g-r,c,h);let m={left:i.left+o,top:i.top+p,right:i.right+o,bottom:i.bottom+p};m=this.env.model.getters.expandZone(n,m),qi(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")}))}}sp.template="o-spreadsheet-Highlight",sp.components={Corner:np,Border:op},sp.props={zone:Object,color:String};class rp{constructor(e,t){this.el=e,this.direction=t}get scroll(){return"horizontal"===this.direction?this.el.scrollLeft:this.el.scrollTop}set scroll(e){"horizontal"===this.direction?this.el.scrollLeft=e:this.el.scrollTop=e}}uo`
1358
1358
  .o-scrollbar {
1359
1359
  position: absolute;
1360
1360
  overflow: auto;
@@ -1370,7 +1370,7 @@
1370
1370
  border-left: 1px solid #e2e3e3;
1371
1371
  }
1372
1372
  }
1373
- `;class rp extends t.Component{setup(){this.scrollbarRef=t.useRef("scrollbar"),this.scrollbar=new sp(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 mo({width:`${this.props.width}px`,height:`${this.props.height}px`})}get positionCss(){return mo(this.props.position)}onScroll(e){this.props.offset!==this.scrollbar.scroll&&this.props.onScroll(this.scrollbar.scroll)}}rp.template=t.xml`
1373
+ `;class ap extends t.Component{setup(){this.scrollbarRef=t.useRef("scrollbar"),this.scrollbar=new rp(this.scrollbarRef.el,this.props.direction),t.onMounted((()=>{this.scrollbar.el=this.scrollbarRef.el})),t.useEffect((()=>{this.scrollbar.scroll!==this.props.offset&&(this.scrollbar.scroll=this.props.offset)}),(()=>[this.scrollbar.scroll,this.props.offset]))}get sizeCss(){return fo({width:`${this.props.width}px`,height:`${this.props.height}px`})}get positionCss(){return fo(this.props.position)}onScroll(e){this.props.offset!==this.scrollbar.scroll&&this.props.onScroll(this.scrollbar.scroll)}}ap.template=t.xml`
1374
1374
  <div
1375
1375
  t-attf-class="o-scrollbar {{props.direction}}"
1376
1376
  t-on-scroll="onScroll"
@@ -1378,7 +1378,7 @@
1378
1378
  t-att-style="positionCss">
1379
1379
  <div t-att-style="sizeCss"/>
1380
1380
  </div>
1381
- `,rp.defaultProps={width:1,height:1},rp.props={width:{type:Number,optional:!0},height:{type:Number,optional:!0},direction:String,position:Object,offset:Number,onScroll:Function};class ap 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})}}ap.components={ScrollBar:rp},ap.template=t.xml`
1381
+ `,ap.defaultProps={width:1,height:1},ap.props={width:{type:Number,optional:!0},height:{type:Number,optional:!0},direction:String,position:Object,offset:Number,onScroll:Function};class lp 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})}}lp.components={ScrollBar:ap},lp.template=t.xml`
1382
1382
  <ScrollBar
1383
1383
  t-if="isDisplayed"
1384
1384
  width="width"
@@ -1386,7 +1386,7 @@
1386
1386
  offset="offset"
1387
1387
  direction="'horizontal'"
1388
1388
  onScroll.bind="onScroll"
1389
- />`,ap.defaultProps={leftOffset:0},ap.props={leftOffset:{type:Number,optional:!0}};class lp 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})}}lp.components={ScrollBar:rp},lp.template=t.xml`
1389
+ />`,lp.defaultProps={leftOffset:0},lp.props={leftOffset:{type:Number,optional:!0}};class cp 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})}}cp.components={ScrollBar:ap},cp.template=t.xml`
1390
1390
  <ScrollBar
1391
1391
  t-if="isDisplayed"
1392
1392
  height="height"
@@ -1394,13 +1394,13 @@
1394
1394
  offset="offset"
1395
1395
  direction="'vertical'"
1396
1396
  onScroll.bind="onScroll"
1397
- />`,lp.defaultProps={topOffset:0},lp.props={topOffset:{type:Number,optional:!0}};const cp={ROW:na,COL:oa,CELL:ia};class hp extends t.Component{constructor(){super(...arguments),this.HEADER_HEIGHT=O,this.HEADER_WIDTH=N,this.keyDownMapping={ENTER:()=>{this.env.model.getters.getActiveCell().type===tn.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===tn.empty?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()},DELETE:()=>{this.env.model.dispatch("DELETE_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},BACKSPACE:()=>{this.env.model.dispatch("DELETE_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},ESCAPE:()=>{this.env.model.getters.hasOpenedPopover()?this.closeOpenedPopover():this.menuState.isOpen?this.closeMenu():this.env.model.dispatch("CLEAN_CLIPBOARD_HIGHLIGHT")},"CTRL+A":()=>this.env.model.selection.loopSelection(),"CTRL+Z":()=>this.env.model.dispatch("REQUEST_UNDO"),"CTRL+Y":()=>this.env.model.dispatch("REQUEST_REDO"),"CTRL+B":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"CTRL+I":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"CTRL+U":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"ALT+=":()=>{var e;const t=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getSelectedZone(),{anchor:o}=this.env.model.getters.getSelection(),n=this.env.model.getters.getAutomaticSums(t,i,o.cell);if(this.env.model.getters.isSingleCellOrMerge(t,i)||this.env.model.getters.isEmpty(t,i)&&n.length<=1){const i=(null===(e=n[0])||void 0===e?void 0:e.zone)?this.env.model.getters.zoneToXC(t,n[0].zone):"",o=`=SUM(${i})`;this.props.onGridComposerCellFocused(o,{start:5,end:5+i.length})}else this.env.model.dispatch("SUM_SELECTION")},"CTRL+HOME":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:i}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,i)},"CTRL+END":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,"COL",this.env.model.getters.getNumberCols(e)-1,0),i=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,i)},"SHIFT+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},i=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:i,zone:t})},"CTRL+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},i=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:i,zone:t})},"CTRL+SHIFT+ ":()=>{this.env.model.selection.selectAll()},"SHIFT+PAGEDOWN":()=>{this.env.model.dispatch("ACTIVATE_NEXT_SHEET")},"SHIFT+PAGEUP":()=>{this.env.model.dispatch("ACTIVATE_PREVIOUS_SHEET")},PAGEDOWN:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PAGEUP:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP"),"CTRL+K":()=>Kr(this.env)}}setup(){this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.hiddenInput=t.useRef("hiddenInput"),this.canvasPosition=Vn(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())),ep("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimensionWithHeaders())),t.useEffect((()=>this.focus()),(()=>[this.env.model.getters.getActiveSheetId()])),this.onMouseWheel=tp(((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 mo({top:"26px",left:"48px",height:"calc(100% - 41px)",width:"calc(100% - 63px)"})}onClosePopover(){this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.focus()}focus(){var e;this.env.model.getters.getSelectedFigureId()||"inactive"!==this.env.model.getters.getEditionMode()||null===(e=this.hiddenInput.el)||void 0===e||e.focus()}get gridEl(){if(!this.gridRef.el)throw new Error("Grid el is not defined.");return this.gridRef.el}getAutofillPosition(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{left:t.x+t.width-4,top:t.y+t.height-4}}get isAutofillVisible(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(0===t.width||0===t.height)}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t,height:e,gridOffsetX:N,gridOffsetY:O})}moveCanvas(e,t){const{scrollX:i,scrollY:o}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:i+e,offsetY:o+t})}getClientPositionKey(e){var t,i,o;return`${e.id}-${null===(t=e.position)||void 0===t?void 0:t.sheetId}-${null===(i=e.position)||void 0===i?void 0:i.col}-${null===(o=e.position)||void 0===o?void 0:o.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,{ctrlKey:i,shiftKey:o}){i&&this.env.model.dispatch("PREPARE_SELECTION_INPUT_EXPANSION"),this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),"editing"===this.env.model.getters.getEditionMode()&&this.env.model.dispatch("STOP_EDITION"),o?this.env.model.selection.setAnchorCorner(e,t):i?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t);let n=e,s=t;Tg(this.env,((e,t)=>{(e!==n&&-1!=e||t!==s&&-1!=t)&&(n=-1===e?n:e,s=-1===t?s:t,this.env.model.selection.setAnchorCorner(n,s))}),(()=>{this.env.model.dispatch("STOP_SELECTION_INPUT"),this.env.model.getters.isPaintingFormat()&&this.env.model.dispatch("PASTE",{target:this.env.model.getters.getSelectedZones()})}))}onCellDoubleClicked(e,t){const i=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:i,col:e,row:t}));this.env.model.getters.getEvaluatedCell({sheetId:i,col:e,row:t}).type===tn.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 i=this.keyDownMapping[t];return i?(e.preventDefault(),e.stopPropagation(),void i()):void 0}onInput(e){(e.isComposing||"insertFromPaste"!==e.inputType)&&e.data&&(e.preventDefault(),e.stopPropagation(),this.props.onGridComposerCellFocused(e.data))}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:i,top:o}=t;let n="CELL";this.env.model.dispatch("STOP_EDITION"),this.env.model.getters.getActiveCols().has(i)?n="COL":this.env.model.getters.getActiveRows().has(o)&&(n="ROW");const{x:s,y:r,width:a,height:l}=this.env.model.getters.getVisibleRect(t);this.toggleContextMenu(n,s+a,r+l)}onCellRightClicked(e,t,{x:i,y:o}){const n=this.env.model.getters.getSelectedZones();let s="CELL";Zi(e,t,n[n.length-1])?this.env.model.getters.getActiveCols().has(e)?s="COL":this.env.model.getters.getActiveRows().has(t)&&(s="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(s,i,o)}toggleContextMenu(e,t,i){this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:i},this.menuState.menuItems=cp[e].getMenuItems()}copy(e,t){if(!this.gridEl.contains(document.activeElement))return;const i=t.clipboardData;if(!i)return void this.displayWarningCopyPasteNotSupported();if("inactive"!==this.env.model.getters.getEditionMode())return;e?Cr(this.env):this.env.model.dispatch("COPY");const o=this.env.model.getters.getClipboardContent();for(const e in o)i.setData(e,o[e]);t.preventDefault()}paste(e){if(!this.gridEl.contains(document.activeElement))return;const t=e.clipboardData;if(t){if(t.types.indexOf(on.PlainText)>-1){const e=t.getData(on.PlainText),i=this.env.model.getters.getSelectedZones();this.env.model.getters.getClipboardTextContent()===e?Ir(this.env,i):Rr(this.env,i,e)}}else this.displayWarningCopyPasteNotSupported()}displayWarningCopyPasteNotSupported(){this.env.raiseError(s("Copy/Paste is not supported in this browser."))}closeMenu(){this.menuState.isOpen=!1,this.focus()}}hp.template="o-spreadsheet-Grid",hp.components={GridComposer:Bg,GridOverlay:jg,GridPopover:Xg,HeadersOverlay:Jg,Menu:qn,Autofill:Ag,ClientTag:Og,Highlight:np,Popover:Hn,VerticalScrollBar:lp,HorizontalScrollBar:ap,FilterIconsOverlay:Gg},hp.props={sidePanelIsOpen:Boolean,exposeFocus:Function,focusComposer:String,onComposerContentFocused:Function,onGridComposerCellFocused:Function};class dp{constructor(e){this.xmlString=e}toString(){return this.xmlString}}const up=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart"],gp="000000",pp={arrow:"3Arrows",smiley:"3Symbols",dot:"3TrafficLights1"},mp={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"},fp="http://schemas.openxmlformats.org/drawingml/2006/main",vp="http://schemas.openxmlformats.org/drawingml/2006/chart",bp={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"},Sp={document:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",sheet:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",sharedStrings:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",styles:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",drawing:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing",chart:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart",theme:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",table:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/table",hyperlink:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",image:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"},Cp="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Ep=.75,wp=.1317,yp=8.43,xp=12.75,Ip=30,Rp=100,Tp=164,Ap={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}]},Mp=["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"],Op="[Content_Types].xml";var Np;!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"}(Np||(Np={}));class _p{constructor(){this._parsingWarnings=new Set,this._conversionWarnings=new Set}addParsingWarning(e){this._parsingWarnings.add(e)}addConversionWarning(e){this._conversionWarnings.add(e)}get warnings(){return[...this._parsingWarnings,...this._conversionWarnings]}generateNotSupportedWarning(e,t,i){let o=`${e} ${t?'"'+t+'" is':"are"} not yet supported. `;i&&(o+=`Only ${i.join(", ")} are currently supported.`),this._conversionWarnings.has(o)||this._conversionWarnings.add(o)}}const Fp=["thin"],Dp=["general","left","center","right"],kp=["Arial"],Lp=["solid"],Pp=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWith","containsBlanks","notContainsBlanks"],Up={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},Vp={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"},zp={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"};const Bp={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},Hp={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},$p={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"},Wp={b:"bottom",t:"top",l:"left",r:"right",tr:"right"},Gp={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},qp={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"},Zp={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},jp={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},Xp={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"},Yp={"image/avif":"avif","image/bmp":"bmp","image/gif":"gif","image/vnd.microsoft.icon":"ico","image/jpeg":"jpeg","image/png":"png","image/tiff":"tiff","image/webp":"webp"};function Kp(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=gp;else{if(!e.indexed)return;t=Xp[e.indexed]}var i;return t=6===(i=t).length?"#"+i+"FF":"#"+i.slice(2)+i.slice(0,2),e.tint&&(t=function(e,t){const i=xt(e),o=Rt(i);t<0&&(o.l=o.l*(1+t));t>0&&(o.l=o.l*(1-t)+(100-100*(1-t)));return yt(It(o))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function Qp(e,t){const i=e.split("/"),o=t.split("/");let n="",s=0;for(let e=0;e<i.length-1;e++)i[e]===o[e]?s++:n+="../";return n+=o.slice(s).join("/"),n}function Jp(e,t=0){const i={};for(let o=0;o<e.length;o++)e[o]&&(i[o+t]=e[o]);return i}function em(e){const t=[];for(let i of Object.keys(e).map(Number))t[i]=e[i];return t}function tm(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,((e,t)=>String.fromCharCode(parseInt(t,16))))}const im=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function om(e,t,i){var o,n,s;if(0===e)return;let r=Zp[e]||(null===(o=t.find((t=>t.id===e)))||void 0===o?void 0:o.format);if(r)try{let e=r.replace(/(.*?);.*/,"$1");e=e.replace(/\[(.*)-[A-Z0-9]{3}\]/g,"[$1]"),e=e.replace(/\[\$\]/g,"");const t=(null===(n=e.match(/"/g))||void 0===n?void 0:n.length)||0;if(t/2+((null===(s=e.match(/\[/g))||void 0===s?void 0:s.length)||0)>1)throw new Error("Multiple escaped blocks in format");if(e=e.replace(/"(.*)"/g,"[$$$1]"),e=e.replace(/_.{1}/g,""),e=e.replace(/\*.{1}/g,""),e=e.replace(/\\ /g," "),e=e.replace(/\\./g,(e=>e[1])),function(e){return null!==e.match(im)}(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 hi(0,e),!0}catch(e){return!1}}(e))return e}catch(e){}i.generateNotSupportedWarning(Np.NumFmtIdNotSupported,r||`nmFmtId ${e}`)}function nm(e,t){const i=e.borders.map((e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(Np.DiagonalBorderNotSupported)}(e,t);const i={top:sm(e.top,t),bottom:sm(e.bottom,t),left:sm(e.left,t),right:sm(e.right,t)};return Object.keys(i).forEach((e=>void 0===i[e]&&delete i[e])),i}));return Jp(i,1)}function sm(e,t){if(!e)return;!function(e,t){Fp.includes(e.style)||t.generateNotSupportedWarning(Np.BorderStyleNotSupported,e.style,Fp)}(e,t);const i=Vp[e.style];return i?[i,Kp(e.color)]:void 0}function rm(e,t){return Jp(e.styles.map((i=>am({fontStyle:e.fonts[i.fontId],fillStyle:e.fills[i.fillId],alignment:i.alignment},t))),1)}function am(e,t){var i,o,n,s,r,a,l,c,h,d,u,g;return function(e,t,i){e&&e.name&&!kp.includes(e.name)&&i.generateNotSupportedWarning(Np.FontNotSupported,e.name,kp);t&&t.patternType&&!Lp.includes(t.patternType)&&i.generateNotSupportedWarning(Np.FillStyleNotSupported,t.patternType,Lp)}(null==e?void 0:e.fontStyle,null==e?void 0:e.fillStyle,t),function(e,t){e&&!Dp.includes(e)&&t.generateNotSupportedWarning(Np.HorizontalAlignmentNotSupported,e,Dp)}(null===(i=null==e?void 0:e.alignment)||void 0===i?void 0:i.horizontal,t),function(e,t){e&&t.generateNotSupportedWarning(Np.VerticalAlignmentNotSupported)}(null===(o=null==e?void 0:e.alignment)||void 0===o?void 0:o.vertical,t),{bold:null===(n=e.fontStyle)||void 0===n?void 0:n.bold,italic:null===(s=e.fontStyle)||void 0===s?void 0:s.italic,strikethrough:null===(r=e.fontStyle)||void 0===r?void 0:r.strike,underline:null===(a=e.fontStyle)||void 0===a?void 0:a.underline,align:(null===(l=e.alignment)||void 0===l?void 0:l.horizontal)?zp[e.alignment.horizontal]:void 0,fillColor:"solid"===(null===(c=e.fillStyle)||void 0===c?void 0:c.patternType)?Kp(null===(h=e.fillStyle)||void 0===h?void 0:h.fgColor):Kp(null===(d=e.fillStyle)||void 0===d?void 0:d.bgColor),textColor:Kp(null===(u=e.fontStyle)||void 0===u?void 0:u.color),fontSize:null===(g=e.fontStyle)||void 0===g?void 0:g.size}}function lm(e,t){const i=[];for(let o of e.styles){const n=om(o.numFmtId,e.numFmts,t);n&&(i[o.numFmtId]=n)}return Jp(i,1)}function cm(e,t,i){const o=[];let n=1;for(let r of e){if(0===r.cfRules.length)continue;gm(r,t,i);const e=r.cfRules[0];let a;const l=[];if(void 0!==e.dxfId||"colorScale"===e.type||"iconSet"===e.type){switch(e.type){case"aboveAverage":case"containsErrors":case"notContainsErrors":case"dataBar":case"duplicateValues":case"expression":case"top10":case"uniqueValues":case"timePeriod":continue;case"colorScale":const t=hm(n++,r);t&&o.push(t);continue;case"iconSet":const c=dm(n++,r,i);c&&o.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;a=Bp[e.type],l.push(e.text);break;case"containsBlanks":case"notContainsBlanks":a=Bp[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;a=(s=e.operator).slice(0,1).toUpperCase()+s.slice(1),l.push(e.formula[0]),2===e.formula.length&&l.push(e.formula[1])}a&&void 0!==e.dxfId&&o.push({id:(n++).toString(),ranges:r.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:a,values:l,style:am({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},i)}})}}var s;return o}function hm(e,t){const i=t.cfRules[0].colorScale;if(!i||i.cfvos.length!==i.colors.length||i.cfvos.length<2||i.cfvos.length>3)return;const o=[];for(let e=0;e<i.cfvos.length;e++)o.push({color:(n=Kp(i.colors[e])||"#FFFFFF",9===n.length&&(n=n.slice(0,7)),parseInt(n.replace("#",""),16)),type:Hp[i.cfvos[e].type],value:i.cfvos[e].value});var n;const s=o[0],r=2===o.length?o[1]:o[2],a=3===o.length?o[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"ColorScaleRule",minimum:s,midpoint:a,maximum:r}}}function dm(e,t,i){const o=t.cfRules[0].iconSet;if(!o)return;let n=o.cfvos,s=o.cfIcons;if(n.length<3||s&&s.length<3)return;n.length>3&&(n=[n[0],n[Math.floor(n.length/2)],n[n.length-1]]),s&&s.length>3&&(s=[s[0],s[Math.floor(s.length/2)],s[s.length-1]]);const r=[];for(let e=1;e<=2;e++){const t=Hp[n[e].type];if("value"===t)return;r.push({value:n[e].value||"",operator:n[e].gte?"ge":"gt",type:t})}let a={lower:s?um(s[0].iconSet,s[0].iconId):um(o.iconSet,0),middle:s?um(s[1].iconSet,s[1].iconId):um(o.iconSet,1),upper:s?um(s[2].iconSet,s[2].iconId):um(o.iconSet,2)};o.reverse&&(a={upper:a.lower,middle:a.middle,lower:a.upper});for(let e of Object.keys(a))if(!a[e])switch(i.generateNotSupportedWarning(Np.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=bg.dots.good;break;case"middle":a[e]=bg.dots.neutral;break;case"lower":a[e]=bg.dots.bad}return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"IconSetRule",icons:a,upperInflectionPoint:r[1],lowerInflectionPoint:r[0]}}}function um(e,t){const i=$p[e];return i?0===t?bg[i].bad:1===t?bg[i].neutral:bg[i].good:""}function gm(e,t,i){if(e.cfRules.length>1&&i.generateNotSupportedWarning(Np.MultipleRulesCfNotSupported),Pp.includes(e.cfRules[0].type)||i.generateNotSupportedWarning(Np.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const o=t[e.cfRules[0].dxfId];o.border&&i.generateNotSupportedWarning(Np.CfFormatBorderNotSupported),o.alignment&&i.generateNotSupportedWarning(Np.CfFormatAlignmentNotSupported),o.numFmt&&i.generateNotSupportedWarning(Np.CfFormatNumFmtNotSupported)}}class pm{constructor(e=new fm){this.scope=e,this.code=""}append(...e){this.code+=e.map((e=>e.toString())).join("\n")+"\n"}return(e){return new mm(this.scope,this.code,e)}toString(){return vm(this.code)}}class mm{constructor(e,t,i){this.scope=e,this.returnExpression=i,this.code=vm(t)}toString(){return this.code}wrapInClosure(){const e=this.scope.nextVariableName(),t=new pm(this.scope);return t.append(`const ${e} = () => {`),t.append(this.code),t.append(`return ${this.returnExpression};`),t.append("}"),t.return(e)}assignResultToVariable(){if(this.scope.isAlreadyDeclared(this.returnExpression))return this;const e=this.scope.nextVariableName(),t=new pm(this.scope);return t.append(this.code),t.append(`const ${e} = ${this.returnExpression};`),t.return(e)}}class fm{constructor(){this.nextId=1,this.declaredVariables=new Set}nextVariableName(){const e="_"+this.nextId++;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}}function vm(e){let t="",i=0;const o=e.split("\n").map((e=>e.trim())).filter((e=>""!==e));for(const e of o)e.startsWith("}")&&i--,t+="\t".repeat(i)+e+"\n",e.endsWith("{")&&i++;return t.trim()}const bm=Wu.content,Sm=["%"],Cm="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(Sm);function Em(e){const t=(e=gt(e)).split(""),i=[];for(;t.length;){let e=Nm(t)||xm(t)||Rm(t)||Am(t)||wm(t)||_m(t)||Tm(t)||Om(t);e||(e={type:"UNKNOWN",value:t.shift()}),i.push(e)}return i}function wm(e){return"?"===e[0]?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const ym={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function xm(e){if(e[0]in ym){const t=e.shift();return{type:ym[t],value:t}}return null}function Im(e,t){for(let i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0}function Rm(e){for(let t of Cm)if(Im(e,t))return e.splice(0,t.length),{type:"OPERATOR",value:t};return null}function Tm(e){const t=ot(e).match(qt);return t?(e.splice(0,t[0].length),{type:"NUMBER",value:t[0]}):null}function Am(e){if('"'===e[0]){const t=e.shift();let i=t;for(;e[0]&&(e[0]!==t||"\\"===i[i.length-1]);)i+=e.shift();return'"'===e[0]&&(i+=e.shift()),{type:"STRING",value:i}}return null}const Mm=/\w|\.|!|\$/;function Om(e){let t="";if("'"===e[0]){let i=e.shift();for(t+=i;e[0];)if(i=e.shift(),t+=i,"'"===i){if(!e[0]||"'"!==e[0])break;i=e.shift(),t+=i}if("'"!==i)return{type:"UNKNOWN",value:t}}for(;e[0]&&e[0].match(Mm);)t+=e.shift();if(t.length){const e=t;if(e.toUpperCase()in bm)return{type:"FUNCTION",value:e};return e.match(_t)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}function Nm(e){let t=0;for(;e[0]===ce;)t++,e.shift();if(t)return{type:"SPACE",value:ce.repeat(t)};for(;" "===e[0];)t++,e.shift();return t?{type:"SPACE",value:" ".repeat(t)}:null}function _m(e){return Im(e,Y)?(e.splice(0,Y.length),{type:"INVALID_REFERENCE",value:Y}):null}const Fm=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,Dm=["-","+"],km=["%"],Lm=["*","+","&"],Pm={"^":30,"%":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function Um(e){var t,i,o;const n=e.shift();if(!n)throw new h(ae);switch(n.type){case"DEBUGGER":const r=Bm(e,1e3);return r.debug=!0,r;case"NUMBER":return{type:"NUMBER",value:ei(n.value)};case"STRING":return{type:"STRING",value:Me(n.value)};case"FUNCTION":const a=function(e){var t;zm(e,"LEFT_PAREN",s("Missing opening parenthesis"));const i=e[0];if("RIGHT_PAREN"===(null==i?void 0:i.type))return zm(e,"RIGHT_PAREN"),[];const o=[];o.push(Vm(e));for(;"RIGHT_PAREN"!==(null===(t=e[0])||void 0===t?void 0:t.type);)zm(e,"COMMA",s("Wrong function call")),o.push(Vm(e));return zm(e,"RIGHT_PAREN"),o}(e);return{type:"FUNCALL",value:n.value,args:a};case"INVALID_REFERENCE":throw new u;case"REFERENCE":if(":"===(null===(t=e[0])||void 0===t?void 0:t.value)&&"REFERENCE"===(null===(i=e[1])||void 0===i?void 0:i.type)){e.shift();const t=e.shift();return{type:"REFERENCE",value:`${n.value}:${null==t?void 0:t.value}`}}return{type:"REFERENCE",value:n.value};case"SYMBOL":if(["TRUE","FALSE"].includes(n.value.toUpperCase()))return{type:"BOOLEAN",value:"TRUE"===n.value.toUpperCase()};if(n.value&&Fm.test(n.value)&&"LEFT_PAREN"===(null===(o=e[0])||void 0===o?void 0:o.type))throw new p(n.value);throw new h(s("Invalid formula"));case"LEFT_PAREN":const l=Bm(e);return zm(e,"RIGHT_PAREN",s("Missing closing parenthesis")),l;case"OPERATOR":const c=n.value;if(Dm.includes(c))return{type:"UNARY_OPERATION",value:c,operand:Bm(e,Pm[c])};throw new h(s("Unexpected token: %s",n.value));default:throw new h(s("Unexpected token: %s",n.value))}}function Vm(e){const t=e[0];return"COMMA"===(null==t?void 0:t.type)||"RIGHT_PAREN"===(null==t?void 0:t.type)?{type:"EMPTY",value:""}:Bm(e)}function zm(e,t,i=ae){const o=e.shift();if(!o||o.type!==t)throw new h(i)}function Bm(e,t=0){var i;if(0===e.length)throw new h(ae);let o=Um(e);for(;"OPERATOR"===(null===(i=e[0])||void 0===i?void 0:i.type)&&Pm[e[0].value]>t;){const t=e.shift().value;if(km.includes(t))o={type:"UNARY_OPERATION",value:t,operand:o,postfix:!0};else{o={type:"BIN_OPERATION",value:t,left:o,right:Bm(e,Pm[t])}}}return o}function Hm(e){return $m(Em(e))}function $m(e){"="===(e=e.filter((e=>"SPACE"!==e.type)))[0].value&&e.splice(0,1);const t=Bm(e);if(e.length)throw new h(ae);return t}function Wm(e,t,i){switch(t===e.type&&(e=i(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>Wm(e,t,i)))};case"UNARY_OPERATION":return{...e,operand:Wm(e.operand,t,i)};case"BIN_OPERATION":return{...e,right:Wm(e.right,t,i),left:Wm(e.left,t,i)};default:return e}}function Gm(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>Gm(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?qm(e)+e.value:e.value+Zm(e);case"BIN_OPERATION":return qm(e)+e.value+Zm(e)}}function qm(e){const t=e.value,i="left"in e?e.left:e.operand,o=i.value;return"BIN_OPERATION"===i.type&&Pm[o]<Pm[t]?`(${Gm(i)})`:Gm(i)}function Zm(e){const t=e.value,i="right"in e?e.right:e.operand,o=Pm[i.value],n=Pm[t];let s=!1;return"BIN_OPERATION"!==i.type?s=!1:o<n?s=!0:o!==n||Lm.includes(t)||(s=!0),s?`(${Gm(i)})`:Gm(i)}var jm;!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"}(jm||(jm={}));const Xm=(e,t=(()=>!0))=>[{goTo:e,guard:t}],Ym=(e,t=(()=>!0))=>({goTo:e,guard:t}),Km={[jm.LeftRef]:{REFERENCE:Xm(jm.Separator),NUMBER:Xm(jm.FullRowSeparator),SYMBOL:[Ym(jm.FullColumnSeparator,(e=>Ft(e.value))),Ym(jm.FullRowSeparator,(e=>Dt(e.value)))]},[jm.FullColumnSeparator]:{SPACE:Xm(jm.FullColumnSeparator),OPERATOR:Xm(jm.RightColumnRef,(e=>":"===e.value))},[jm.FullRowSeparator]:{SPACE:Xm(jm.FullRowSeparator),OPERATOR:Xm(jm.RightRowRef,(e=>":"===e.value))},[jm.Separator]:{SPACE:Xm(jm.Separator),OPERATOR:Xm(jm.RightRef,(e=>":"===e.value))},[jm.RightRef]:{SPACE:Xm(jm.RightRef),NUMBER:Xm(jm.Found),REFERENCE:Xm(jm.Found,(e=>Lt(e.value))),SYMBOL:Xm(jm.Found,(e=>kt(e.value)))},[jm.RightColumnRef]:{SPACE:Xm(jm.RightColumnRef),SYMBOL:Xm(jm.Found,(e=>kt(e.value))),REFERENCE:Xm(jm.Found,(e=>Lt(e.value)))},[jm.RightRowRef]:{SPACE:Xm(jm.RightRowRef),NUMBER:Xm(jm.Found),REFERENCE:Xm(jm.Found,(e=>Lt(e.value)))},[jm.Found]:{}};function Qm(e){var t;let i=0,o=Km[jm.LeftRef];const n=[];for(;void 0!==o;){const s=e[i++];if(!s)return null;const r=null===(t=o[s.type])||void 0===t?void 0:t.find((e=>e.guard(s))),a=r?r.goTo:void 0;switch(a){case void 0:return null;case jm.Found:return n.push(s),e.splice(0,i),{type:"REFERENCE",value:ot(n.map((e=>e.value)))};default:o=Km[a],n.push(s)}}return null}function Jm(e){const t=Em(e),i=[];for(;t.length;)i.push(Qm(t)||t.shift());return i}const ef=Wu.content,tf={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},of={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"},nf={};function sf(e){const t=Jm(e),{dependencies:i,constantValues:o}=function(e){const t={numbers:[],strings:[]},i=[];for(const o of e)switch(o.type){case"INVALID_REFERENCE":case"REFERENCE":i.push(o.value);break;case"STRING":const e=Me(o.value);t.strings.includes(e)||t.strings.push(e);break;case"NUMBER":{const e=ei(o.value);t.numbers.includes(e)||t.numbers.push(e);break}}return{dependencies:i,constantValues:t}}(t),n=function(e,t,i){return ot(e.map((e=>{switch(e.type){case"STRING":const o=Me(e.value);return`|S${i.strings.indexOf(o)}|`;case"NUMBER":return`|N${i.numbers.indexOf(ei(e.value))}|`;case"REFERENCE":case"INVALID_REFERENCE":return`|${t.indexOf(e.value)}|`;case"SPACE":return"";default:return e.value}})))}(t,i,o);if(!nf[n]){const r=$m([...t]),a=new fm;if("BIN_OPERATION"===r.type&&":"===r.value)throw new h(s("Invalid formula"));if("EMPTY"===r.type)throw new h(s("Invalid formula"));const l=g(r),c=new pm;c.append(`// ${n}`),c.append(l),c.append(`return ${l.returnExpression};`);let d=new Function("deps","ref","range","ctx",c.toString());function u(e){const t=ef[e.value.toUpperCase()],i=e.args,o=i.length;if(o<t.minArgRequired)throw new h(s("Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.",e.value.toUpperCase(),t.minArgRequired.toString(),o.toString()));if(o>t.maxArgPossible)throw new h(s("Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.",e.value.toUpperCase(),t.maxArgPossible.toString(),o.toString()));const n=t.nbrArgRepeating;if(n>1){const i=t.args.length-n;if((o-i)%n!=0)throw new h(s("Invalid number of arguments for the %s function. Expected all arguments after position %s to be supplied by groups of %s arguments",e.value.toUpperCase(),i.toString(),n.toString()))}let r=[];for(let n=0;n<o;n++){const o=t.getArgToFocus(n+1)-1;if(0<=o&&o<t.args.length){const a=i[n],l=t.args[o],c=l.type||[],d=c.includes("META"),u=l.lazy,p=c.some((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e)),m=c.every((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e));if(m&&"REFERENCE"!==a.type)throw new h(s("Function %s expects the parameter %s to be reference to a cell or range, not a %s.",e.value.toUpperCase(),(n+1).toString(),a.type.toLowerCase()));const f=g(a,d,p,{functionName:e.value.toUpperCase(),paramIndex:n+1});r.push(u?f.wrapInClosure():f)}}return r}function g(e,t=!1,n=!1,r={}){const l=new pm(a);if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&t)throw new h(s("Argument must be a reference to a cell or range."));switch(e.debug&&l.append("debugger;"),e.type){case"BOOLEAN":return l.return(`{ value: ${e.value} }`);case"NUMBER":return l.return(`{ value: this.constantValues.numbers[${o.numbers.indexOf(e.value)}] }`);case"STRING":return l.return(`{ value: this.constantValues.strings[${o.strings.indexOf(e.value)}] }`);case"REFERENCE":const s=i.indexOf(e.value);return n?l.return(`range(deps[${s}])`):l.return(`ref(deps[${s}], ${t?"true":"false"}, "${r.functionName||tf["="]}", ${r.paramIndex})`);case"FUNCALL":const a=u(e).map((e=>e.assignResultToVariable()));l.append(...a);const c=e.value.toUpperCase();return l.append(`ctx.__lastFnCalled = '${c}';`),l.return(`ctx['${c}'](${a.map((e=>e.returnExpression))})`);case"UNARY_OPERATION":{const t=of[e.value],i=g(e.operand,!1,!1,{functionName:t}).assignResultToVariable();return l.append(i),l.append(`ctx.__lastFnCalled = '${t}';`),l.return(`ctx['${t}'](${i.returnExpression})`)}case"BIN_OPERATION":{const t=tf[e.value],i=g(e.left,!1,!1,{functionName:t}).assignResultToVariable(),o=g(e.right,!1,!1,{functionName:t}).assignResultToVariable();return l.append(i),l.append(o),l.append(`ctx.__lastFnCalled = '${t}';`),l.return(`ctx['${t}'](${i.returnExpression}, ${o.returnExpression})`)}case"EMPTY":return l.return("undefined")}}nf[n]={execute:d}}return{execute:nf[n].execute,dependencies:i,constantValues:o,tokens:t}}function rf(e){return function(e){let t=[],i="";return e.map(((e,o)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(i=""),e.type){case"FUNCTION":i=e.value;break;case"LEFT_PAREN":t.push({parent:i,argPosition:0}),i="";break;case"RIGHT_PAREN":t.pop();break;case"COMMA":t.length&&t[t.length-1].argPosition++}if(t.length){const i=t[t.length-1];i.parent&&(e.functionContext=Object.assign({},i))}return e}))}(function(e){let t=1;const i=[];return e.map((e=>("LEFT_PAREN"===e.type?(i.push(t),e.parenIndex=t,t++):"RIGHT_PAREN"===e.type&&(e.parenIndex=i.pop()),e)))}(function(e){let t=0;return e.map((e=>{const i=e.value.toString().length,o=Object.assign({},e,{start:t,end:t+i,length:i});return t=o.end,o}))}(Jm(e))))}function af(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function lf(e){return Math.round(Ep*e*100)/100}function cf(e){return Math.round(wp*e*100)/100}function hf(e){if(e)return{style:e[0],color:{rgb:e[1]}}}function df(e,t){let i={};e.style&&(i=t.styles[e.style]);const o=function(e,t){if(e.format)return t.formats[e.format];if(e.isFormula){const t=Em(e.content||""),i=Wu.content;if(!t.filter((e=>"FUNCTION"===e.type)).every((e=>i[e.value.toUpperCase()].isExported)))return e.computedFormat}return}(e,t),n={};if(e.border){const i=t.borders[e.border];n.left=hf(i.left),n.right=hf(i.right),n.bottom=hf(i.bottom),n.top=hf(i.top)}const s={font:{size:(null==i?void 0:i.fontSize)||G,color:{rgb:(null==i?void 0:i.textColor)?i.textColor:"000000"},family:2,name:"Arial"},fill:(null==i?void 0:i.fillColor)?{fgColor:{rgb:i.fillColor}}:{reservedAttribute:"none"},numFmt:o?{format:o,id:0}:void 0,border:n||{},alignment:{vertical:"center",horizontal:i.align}};return s.font.strike=!!(null==i?void 0:i.strikethrough)||void 0,s.font.underline=!!(null==i?void 0:i.underline)||void 0,s.font.bold=!!(null==i?void 0:i.bold)||void 0,s.font.italic=!!(null==i?void 0:i.italic)||void 0,s}function uf(e,t){const{id:i}=pf(t.font,e.fonts),{id:o}=pf(t.fill,e.fills),{id:n}=pf(t.border,e.borders),s=function(e,t){if(!e)return 0;let i=jp[e.format];if(!i){const{id:o}=pf(e,t);i=o+Tp}return i}(t.numFmt,e.numFmts),r={fontId:i,fillId:o,borderId:n,numFmtId:s,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal}},{id:a}=pf(r,e.styles);return a}function gf(e,t,i){let o,n=e.find((e=>e.path===t));return n?(o=`rId${(n.rels.length+1).toString()}`,n.rels.push({...i,id:o})):(o="rId1",e.push({path:t,rels:[{...i,id:o}]})),o}function pf(e,t){for(let[i,o]of Object.entries(t))if(JSON.stringify(o)===JSON.stringify(e))return{id:parseInt(i,10),list:t};let i=t.findIndex((t=>JSON.stringify(t)===JSON.stringify(e)));return-1===i&&(t.push(e),i=t.length-1),{id:i,list:t}}const mf=[];function ff(e){const t=mf.findIndex((t=>t===e));return-1===t?(mf.push(e),mf.length):t+1}const vf=[];function bf(e){const t=vf.findIndex((t=>t===e));return-1===t?(vf.push(e),vf.length):t+1}function Sf(e){return Math.round(914400*e/96)}function Cf(e,t,i){let o,n,s=e;if(({xc:s,sheetName:o}=Pt(e)),o){const e=i.sheets.findIndex((e=>e.name===o));if(e<0)throw new Error("Unable to find a sheet with the name "+o);n=e}else n=Number(t);const r=ki(s);return void 0===r.right&&(r.right=i.sheets[n].colNumber),void 0===r.bottom&&(r.bottom=i.sheets[n].rowNumber),(r.right-r.left+1)*(r.bottom-r.top+1)}function Ef(e){return Math.round(96*e/914400)}function wf(e,t){var i;let o=0;for(let n=0;n<e;n++){const e=t.cols.find((e=>n>=e.min&&n<=e.max));(null==e?void 0:e.width)?o+=e.width:(null===(i=t.sheetFormat)||void 0===i?void 0:i.defaultColWidth)?o+=t.sheetFormat.defaultColWidth:o+=yp}return o/wp}function yf(e,t){var i;let o=0;for(let n=0;n<e;n++){const e=t.rows[n];(null==e?void 0:e.height)?o+=e.height:(null===(i=t.sheetFormat)||void 0===i?void 0:i.defaultRowHeight)?o+=t.sheetFormat.defaultRowHeight:o+=xp}return o/Ep}function xf(e){let t=1;return e.figures.map((i=>function(e,t,i){const o=wf(e.anchors[0].col,i)+Ef(e.anchors[0].colOffset),n=wf(e.anchors[1].col,i)+Ef(e.anchors[1].colOffset),s=yf(e.anchors[0].row,i)+Ef(e.anchors[0].rowOffset),r=yf(e.anchors[1].row,i)+Ef(e.anchors[1].rowOffset),a=n-o,l=r-s,c=If(e.data);return c?{id:t,x:o,y:s,width:a,height:l,tag:"chart",data:If(e.data)}:void 0}(i,(t++).toString(),e))).filter(et)}function If(e){var t;const i=null===(t=e.dataSets[0].label)||void 0===t?void 0:t.replace(/\$/g,"");let o=e.dataSets.map((e=>e.range.replace(/\$/g,"")));return"pie"===e.type&&o.reverse(),{dataSets:o,dataSetsHaveTitle:!1,labelRange:i,title:e.title||"",type:e.type,background:Kp({rgb:e.backgroundColor})||"#FFFFFF",verticalAxisPosition:e.verticalAxisPosition,legendPosition:e.legendPosition,stacked:e.stacked||!1,aggregated:!1,labelsAsText:!1}}const Rf=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),Tf=new RegExp(/SUBTOTAL\(([0-9]*),/g),Af=new RegExp(Tt.source,"ig");function Mf(e,t){const i=function(e){const t={};for(let i of e.rows)for(let e of i.cells)e.formula&&void 0!==e.formula.sharedIndex&&e.formula.content&&(t[e.formula.sharedIndex]={refCellXc:e.xc,formula:e.formula.content});return t}(e);for(let o of e.rows.map((e=>e.cells)).flat())(null==o?void 0:o.formula)&&(o.formula.content=void 0===o.formula.sharedIndex||o.formula.content?"="+o.formula.content:"="+Nf(o.xc,i[o.formula.sharedIndex]),o.formula.content=Of(o.formula.content,t))}function Of(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(Tf,((e,t)=>{const i=qp[t];return i?i+"(":e}))).replace(Rf,((e,i,o,n)=>{var s;i=Number(i)-1,n=n.replace(/\$/g,"");const r=t.externalBooks[i].sheetNames.findIndex((e=>e===o));if(-1===r)return e;const a=null===(s=t.externalBooks[i].datasets.find((e=>e.sheetId===r)))||void 0===s?void 0:s.data;if(!a)return e;const l=a&&a[n];return(Number(l)?l:`"${l}"`)||e}))}function Nf(e,t){const i=zt(t.refCellXc);let o,n=t.formula.slice();do{if(o=Af.exec(n),o){const t=zt(o[0].replace("$","")),s=zt(e),r={colFixed:o[0].startsWith("$"),rowFixed:o[0].includes("$",1)},a={col:s.col-i.col,row:s.row-i.row},l={col:r.colFixed?t.col:t.col+a.col,row:r.rowFixed?t.row:t.row+a.row};n=n.slice(0,o.index)+Bt(l.col,l.row,r)+n.slice(o.index+o[0].length)}}while(o);return n}function _f(e,t){return e.sheets.map((i=>{Mf(i,e);const o=function(e){const t=[0,0];for(let i of e.rows)t[0]=Math.max(t[0],...i.cells.map((e=>zt(e.xc).col))),t[1]=Math.max(t[1],i.index);return t[0]=Math.max(t[0],Ip),t[1]=Math.max(t[1],Rp),t}(i),n=i.sheetViews[0];return{id:i.sheetName,areGridLinesVisible:!n||n.showGridLines,name:i.sheetName,colNumber:o[0],rowNumber:o[1],cells:kf(i,e,o,t),merges:i.merges,cols:Ff(i,o[0]),rows:Df(i,o[1]),conditionalFormats:cm(i.cfs,e.dxfs,t),figures:xf(i),isVisible:i.isVisible,panes:n?{xSplit:n.pane.xSplit,ySplit:n.pane.ySplit}:{xSplit:0,ySplit:0},filterTables:[]}}))}function Ff(e,t){var i;const o={};for(let s=1;s<t+1;s++){const t=e.cols.find((e=>e.min<=s&&s<=e.max));let r;r=t&&t.width?t.width:(null===(i=e.sheetFormat)||void 0===i?void 0:i.defaultColWidth)?e.sheetFormat.defaultColWidth:yp,o[s-1]={size:(n=r,n?Math.round(n/wp*100)/100:n),isHidden:null==t?void 0:t.hidden}}var n;return o}function Df(e,t){var i;const o={};for(let s=1;s<t+1;s++){const t=e.rows.find((e=>e.index===s));let r;r=t&&t.height?t.height:(null===(i=e.sheetFormat)||void 0===i?void 0:i.defaultRowHeight)?e.sheetFormat.defaultRowHeight:xp,o[s-1]={size:(n=r,n?Math.round(n/Ep*100)/100:n),isHidden:null==t?void 0:t.hidden}}var n;return o}function kf(e,t,i,o){const n={},s=t.sharedStrings.map((e=>e.replace(/\n/g,"")));const r=e.hyperlinks.reduce(((e,t)=>(e[t.xc]=t,e)),{});for(let i of e.rows)for(let e of i.cells)n[e.xc]={content:Lf(e,r,s,o),style:e.styleIndex?e.styleIndex+1:void 0,border:e.styleIndex?t.styles[e.styleIndex].borderId+1:void 0,format:e.styleIndex?t.styles[e.styleIndex].numFmtId+1:void 0};for(let o of e.rows.filter((e=>e.styleIndex)))for(let e=1;e<=i[0];e++){const i=Bt(e-1,o.index-1);let s=n[i];s||(s={},n[i]=s),s.style=s.style?s.style:o.styleIndex+1,s.border=s.border?s.border:t.styles[o.styleIndex].borderId+1,s.format=s.format?s.format:t.styles[o.styleIndex].numFmtId+1}for(let o of e.cols.filter((e=>e.styleIndex)))for(let e=o.min;e<=Math.min(o.max,i[0]);e++)for(let s=1;s<=i[1];s++){const i=Bt(e-1,s-1);let r=n[i];r||(r={},n[i]=r),r.style=r.style?r.style:o.styleIndex+1,r.border=r.border?r.border:t.styles[o.styleIndex].borderId+1,r.format=r.format?r.format:t.styles[o.styleIndex].numFmtId+1}return n}function Lf(e,t,i,o){let n;switch(e.type){case"sharedString":n=i[parseInt(e.value,10)];break;case"boolean":n=Number(e.value)?"TRUE":"FALSE";break;case"date":case"error":case"inlineStr":case"number":case"str":n=e.value}return n&&t[e.xc]&&(n=function(e,t,i){const o=e.display||t;e.relTarget||e.location||i.generateNotSupportedWarning(Np.BadlyFormattedHyperlink);const n=e.relTarget?e.relTarget:Qe(Pt(e.location).sheetName);return je(o,n)}(t[e.xc],n,o)),e.formula&&(n=e.formula.content),n}const Pf={fillColor:"#000000",textColor:"#ffffff",bold:!0},Uf={bold:!0},Vf=["thin","#000000FF"];function zf(e,t){for(const i of t.sheets)for(const t of i.tables){const o=e.sheets.find((e=>e.name===i.sheetName));o&&t.autoFilter&&(o.filterTables||(o.filterTables=[]),o.filterTables.push({range:t.ref}))}!function(e,t){var i,o,n,s;const r=em(e.styles),a=em(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=Li(t.ref);for(let e=0;e<t.headerRowCount;e++)Bf(Pf,{...h,bottom:h.top+e},c.cells,r);for(let e=0;e<t.totalsRowCount;e++)Bf(Uf,{...h,top:h.bottom-e},c.cells,r);(null===(i=t.style)||void 0===i?void 0:i.showFirstColumn)&&Bf(Uf,{...h,right:h.left},c.cells,r),(null===(o=t.style)||void 0===o?void 0:o.showLastColumn)&&Bf(Uf,{...h,left:h.right},c.cells,r);for(let e=h.left;e<=h.right;e++)for(let i=h.top;i<=h.bottom;i++){const o=Bt(e,i),r=c.cells[o],l={left:e===h.left||(null===(n=t.style)||void 0===n?void 0:n.showColumnStripes)?Vf:void 0,right:e===h.right?Vf:void 0,top:i===h.top||(null===(s=t.style)||void 0===s?void 0:s.showRowStripes)||i>h.bottom-t.totalsRowCount?Vf:void 0,bottom:i===h.bottom?Vf:void 0},d=(null==r?void 0:r.border)?{...a[r.border],...l}:l;let u=a.findIndex((e=>at(e,d)));-1===u&&(u=a.length,a.push(d)),r?r.border=u:c.cells[o]={border:u}}}e.styles=Jp(r),e.borders=Jp(a)}(e,t),function(e,t){for(let i of e){const e=t.find((e=>e.sheetName===i.name)).tables;for(let t of e){const e=t.name+"[";for(let o of Ji(Li(t.ref))){const n=Bt(o.col,o.row),s=i.cells[n];if(s&&s.content&&s.content.startsWith("=")){let i;for(;-1!==(i=s.content.indexOf(e));){let o=s.content.slice(i+e.length),r=o.indexOf("]");o.startsWith("[")&&(r=o.indexOf("]",r+1),r=o.indexOf("]",r+1)),o=o.slice(0,r);const a=Hf(o,t,n);s.content=s.content.slice(0,i)+a+s.content.slice(e.length+i+r+1)}}}}}}(e.sheets,t.sheets)}function Bf(e,t,i,o){for(let n=t.left;n<=t.right;n++)for(let s=t.top;s<=t.bottom;s++){const t=Bt(n,s),r=i[t],a=(null==r?void 0:r.style)?{...o[r.style],...e}:e;let l=o.findIndex((e=>at(e,a)));-1===l&&(l=o.length,o.push(a)),r?r.style=l:i[t]={style:l}}}function Hf(e,t,i){const o=e.split(","),n=Li(t.ref),s={...n};let r=!0;if(1===o.length){const e=t.cols.findIndex((e=>e.name===o[0]));s.left=s.right=e+n.left,t.headerRowCount&&(s.top+=t.headerRowCount),t.totalsRowCount&&(s.bottom-=1)}else{switch(o[0].slice(1,o[0].length-1)){case"#All":s.top=t.headerRowCount?n.top+t.headerRowCount:n.top,s.bottom=n.bottom;break;case"#Data":s.top=t.headerRowCount?n.top+t.headerRowCount:n.top,s.bottom=t.totalsRowCount?n.bottom+1:n.bottom;break;case"#This Row":s.top=s.bottom=zt(i).row;break;case"#Headers":s.top=s.bottom=n.top,t.headerRowCount||(r=!1);break;case"#Totals":s.top=s.bottom=n.bottom,t.totalsRowCount||(r=!1)}const e=o[1].slice(1,o[1].length-1),a=t.cols.findIndex((t=>t.name===e));s.left=s.right=a+n.left}return r?s.top!==s.bottom?Ui(s):Bt(s.left,s.top):Y}function $f(e,t,i){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:i}}function Wf(e){return String(e).replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\'/g,"&apos;")}function Gf(e){return new dp(e.map((([e,t])=>`${e}="${Wf(t)}"`)).join(" "))}function qf(e,t="text/xml"){const i=(new DOMParser).parseFromString(e.toString(),t),o=i.querySelector("parsererror");if(o){const t=o.innerHTML,i=parseInt(t.split(":")[0],10),n=e.toString().trim().split("\n"),s=n.slice(Math.max(i-3,0),Math.min(i+2,n.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${s}`)}return i}function Zf(e,t){return Xf`
1397
+ />`,cp.defaultProps={topOffset:0},cp.props={topOffset:{type:Number,optional:!0}};const hp={ROW:sa,COL:na,CELL:oa};class dp extends t.Component{constructor(){super(...arguments),this.HEADER_HEIGHT=O,this.HEADER_WIDTH=N,this.keyDownMapping={ENTER:()=>{this.env.model.getters.getActiveCell().type===on.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===on.empty?this.props.onGridComposerCellFocused():this.props.onComposerContentFocused()},DELETE:()=>{this.env.model.dispatch("DELETE_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},BACKSPACE:()=>{this.env.model.dispatch("DELETE_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},ESCAPE:()=>{this.env.model.getters.hasOpenedPopover()?this.closeOpenedPopover():this.menuState.isOpen?this.closeMenu():this.env.model.dispatch("CLEAN_CLIPBOARD_HIGHLIGHT")},"CTRL+A":()=>this.env.model.selection.loopSelection(),"CTRL+Z":()=>this.env.model.dispatch("REQUEST_UNDO"),"CTRL+Y":()=>this.env.model.dispatch("REQUEST_REDO"),"CTRL+B":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"CTRL+I":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"CTRL+U":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"ALT+=":()=>{var e;const t=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getSelectedZone(),{anchor:o}=this.env.model.getters.getSelection(),n=this.env.model.getters.getAutomaticSums(t,i,o.cell);if(this.env.model.getters.isSingleCellOrMerge(t,i)||this.env.model.getters.isEmpty(t,i)&&n.length<=1){const i=(null===(e=n[0])||void 0===e?void 0:e.zone)?this.env.model.getters.zoneToXC(t,n[0].zone):"",o=`=SUM(${i})`;this.props.onGridComposerCellFocused(o,{start:5,end:5+i.length})}else this.env.model.dispatch("SUM_SELECTION")},"CTRL+HOME":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:i}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,i)},"CTRL+END":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,"COL",this.env.model.getters.getNumberCols(e)-1,0),i=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,i)},"SHIFT+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},i=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:i,zone:t})},"CTRL+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},i=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:i,zone:t})},"CTRL+SHIFT+ ":()=>{this.env.model.selection.selectAll()},"SHIFT+PAGEDOWN":()=>{this.env.model.dispatch("ACTIVATE_NEXT_SHEET")},"SHIFT+PAGEUP":()=>{this.env.model.dispatch("ACTIVATE_PREVIOUS_SHEET")},PAGEDOWN:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PAGEUP:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP"),"CTRL+K":()=>Qr(this.env)}}setup(){this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.hiddenInput=t.useRef("hiddenInput"),this.canvasPosition=zn(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())),tp("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimensionWithHeaders())),t.useEffect((()=>this.focus()),(()=>[this.env.model.getters.getActiveSheetId()])),this.onMouseWheel=ip(((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 fo({top:"26px",left:"48px",height:"calc(100% - 41px)",width:"calc(100% - 63px)"})}onClosePopover(){this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.focus()}focus(){var e;this.env.model.getters.getSelectedFigureId()||"inactive"!==this.env.model.getters.getEditionMode()||null===(e=this.hiddenInput.el)||void 0===e||e.focus()}get gridEl(){if(!this.gridRef.el)throw new Error("Grid el is not defined.");return this.gridRef.el}getAutofillPosition(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{left:t.x+t.width-4,top:t.y+t.height-4}}get isAutofillVisible(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(0===t.width||0===t.height)}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t,height:e,gridOffsetX:N,gridOffsetY:O})}moveCanvas(e,t){const{scrollX:i,scrollY:o}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:i+e,offsetY:o+t})}getClientPositionKey(e){var t,i,o;return`${e.id}-${null===(t=e.position)||void 0===t?void 0:t.sheetId}-${null===(i=e.position)||void 0===i?void 0:i.col}-${null===(o=e.position)||void 0===o?void 0:o.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,{ctrlKey:i,shiftKey:o}){i&&this.env.model.dispatch("PREPARE_SELECTION_INPUT_EXPANSION"),this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),"editing"===this.env.model.getters.getEditionMode()&&this.env.model.dispatch("STOP_EDITION"),o?this.env.model.selection.setAnchorCorner(e,t):i?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t);let n=e,s=t;Ag(this.env,((e,t)=>{(e!==n&&-1!=e||t!==s&&-1!=t)&&(n=-1===e?n:e,s=-1===t?s:t,this.env.model.selection.setAnchorCorner(n,s))}),(()=>{this.env.model.dispatch("STOP_SELECTION_INPUT"),this.env.model.getters.isPaintingFormat()&&this.env.model.dispatch("PASTE",{target:this.env.model.getters.getSelectedZones()})}))}onCellDoubleClicked(e,t){const i=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:i,col:e,row:t}));this.env.model.getters.getEvaluatedCell({sheetId:i,col:e,row:t}).type===on.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(),Ku(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 i=this.keyDownMapping[t];return i?(e.preventDefault(),e.stopPropagation(),void i()):void 0}onInput(e){(e.isComposing||"insertFromPaste"!==e.inputType)&&e.data&&(e.preventDefault(),e.stopPropagation(),this.props.onGridComposerCellFocused(e.data))}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:i,top:o}=t;let n="CELL";this.env.model.dispatch("STOP_EDITION"),this.env.model.getters.getActiveCols().has(i)?n="COL":this.env.model.getters.getActiveRows().has(o)&&(n="ROW");const{x:s,y:r,width:a,height:l}=this.env.model.getters.getVisibleRect(t);this.toggleContextMenu(n,s+a,r+l)}onCellRightClicked(e,t,{x:i,y:o}){const n=this.env.model.getters.getSelectedZones();let s="CELL";ji(e,t,n[n.length-1])?this.env.model.getters.getActiveCols().has(e)?s="COL":this.env.model.getters.getActiveRows().has(t)&&(s="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(s,i,o)}toggleContextMenu(e,t,i){this.env.model.getters.hasOpenedPopover()&&this.closeOpenedPopover(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:i},this.menuState.menuItems=hp[e].getMenuItems()}copy(e,t){if(!this.gridEl.contains(document.activeElement))return;const i=t.clipboardData;if(!i)return void this.displayWarningCopyPasteNotSupported();if("inactive"!==this.env.model.getters.getEditionMode())return;e?Er(this.env):this.env.model.dispatch("COPY");const o=this.env.model.getters.getClipboardContent();for(const e in o)i.setData(e,o[e]);t.preventDefault()}paste(e){if(!this.gridEl.contains(document.activeElement))return;const t=e.clipboardData;if(t){if(t.types.indexOf(nn.PlainText)>-1){const e=t.getData(nn.PlainText),i=this.env.model.getters.getSelectedZones();this.env.model.getters.getClipboardTextContent()===e?Rr(this.env,i):Tr(this.env,i,e)}}else this.displayWarningCopyPasteNotSupported()}displayWarningCopyPasteNotSupported(){this.env.raiseError(s("Copy/Paste is not supported in this browser."))}closeMenu(){this.menuState.isOpen=!1,this.focus()}}dp.template="o-spreadsheet-Grid",dp.components={GridComposer:Hg,GridOverlay:Xg,GridPopover:Yg,HeadersOverlay:ep,Menu:Zn,Autofill:Mg,ClientTag:Ng,Highlight:sp,Popover:$n,VerticalScrollBar:cp,HorizontalScrollBar:lp,FilterIconsOverlay:qg},dp.props={sidePanelIsOpen:Boolean,exposeFocus:Function,focusComposer:String,onComposerContentFocused:Function,onGridComposerCellFocused:Function};class up{constructor(e){this.xmlString=e}toString(){return this.xmlString}}const gp=["areaChart","area3DChart","lineChart","line3DChart","stockChart","radarChart","scatterChart","pieChart","pie3DChart","doughnutChart","barChart","bar3DChart","ofPieChart","surfaceChart","surface3DChart","bubbleChart"],pp="000000",mp={arrow:"3Arrows",smiley:"3Symbols",dot:"3TrafficLights1"},fp={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"},vp="http://schemas.openxmlformats.org/drawingml/2006/main",bp="http://schemas.openxmlformats.org/drawingml/2006/chart",Sp={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"},Cp={document:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",sheet:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",sharedStrings:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",styles:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",drawing:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing",chart:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart",theme:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",table:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/table",hyperlink:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",image:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"},Ep="http://schemas.openxmlformats.org/officeDocument/2006/relationships",wp=.75,yp=.1317,xp=8.43,Ip=12.75,Rp=30,Tp=100,Ap=164,Mp={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}]},Op=["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"],Np="[Content_Types].xml";var _p;!function(e){e.DiagonalBorderNotSupported="Diagonal Borders",e.BorderStyleNotSupported="Border style",e.FillStyleNotSupported="Fill Style",e.FontNotSupported="Font",e.HorizontalAlignmentNotSupported="Horizontal Alignment",e.VerticalAlignmentNotSupported="Vertical Alignments",e.MultipleRulesCfNotSupported="Multiple rules conditional formats",e.CfTypeNotSupported="Conditional format type",e.CfFormatBorderNotSupported="Borders in conditional formats",e.CfFormatAlignmentNotSupported="Alignment in conditional formats",e.CfFormatNumFmtNotSupported="Num formats in conditional formats",e.CfIconSetEmptyIconNotSupported="IconSets with empty icons",e.BadlyFormattedHyperlink="Badly formatted hyperlink",e.NumFmtIdNotSupported="Number format"}(_p||(_p={}));class Fp{constructor(){this._parsingWarnings=new Set,this._conversionWarnings=new Set}addParsingWarning(e){this._parsingWarnings.add(e)}addConversionWarning(e){this._conversionWarnings.add(e)}get warnings(){return[...this._parsingWarnings,...this._conversionWarnings]}generateNotSupportedWarning(e,t,i){let o=`${e} ${t?'"'+t+'" is':"are"} not yet supported. `;i&&(o+=`Only ${i.join(", ")} are currently supported.`),this._conversionWarnings.has(o)||this._conversionWarnings.add(o)}}const Dp=["thin"],kp=["general","left","center","right"],Lp=["Arial"],Pp=["solid"],Up=["expression","cellIs","colorScale","iconSet","containsText","notContainsText","beginsWith","endsWith","containsBlanks","notContainsBlanks"],Vp={b:"boolean",d:"date",e:"error",inlineStr:"inlineStr",n:"number",s:"sharedString",str:"str"},zp={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"},Bp={general:void 0,left:"left",center:"center",right:"right",fill:"left",justify:"left",centerContinuous:"center",distributed:"center"};const Hp={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},$p={num:"number",percent:"percentage",max:"value",min:"value",percentile:"percentile",formula:"formula"},Wp={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"},Gp={b:"bottom",t:"top",l:"left",r:"right",tr:"right"},qp={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},Zp={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"},jp={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},Xp={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},Yp={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"},Kp={"image/avif":"avif","image/bmp":"bmp","image/gif":"gif","image/vnd.microsoft.icon":"ico","image/jpeg":"jpeg","image/png":"png","image/tiff":"tiff","image/webp":"webp"};function Qp(e){if(!e)return;let t;if(e.rgb)t=e.rgb;else if(e.auto)t=pp;else{if(!e.indexed)return;t=Yp[e.indexed]}var i;return t=6===(i=t).length?"#"+i+"FF":"#"+i.slice(2)+i.slice(0,2),e.tint&&(t=function(e,t){const i=It(e),o=Tt(i);t<0&&(o.l=o.l*(1+t));t>0&&(o.l=o.l*(1-t)+(100-100*(1-t)));return xt(Rt(o))}(t,e.tint)),t=t.toUpperCase(),9===t.length&&t.endsWith("FF")&&(t=t.slice(0,7)),t}function Jp(e,t){const i=e.split("/"),o=t.split("/");let n="",s=0;for(let e=0;e<i.length-1;e++)i[e]===o[e]?s++:n+="../";return n+=o.slice(s).join("/"),n}function em(e,t=0){const i={};for(let o=0;o<e.length;o++)e[o]&&(i[o+t]=e[o]);return i}function tm(e){const t=[];for(let i of Object.keys(e).map(Number))t[i]=e[i];return t}function im(e){return e.replace(/_x([0-9a-zA-Z]{4})_/g,((e,t)=>String.fromCharCode(parseInt(t,16))))}const om=/^(yy|yyyy|m{1,5}|d{1,4}|h{1,2}|s{1,2}|am\/pm|a\/m|\s|-|\/|\.|:)+$/i;function nm(e,t,i){var o,n,s;if(0===e)return;let r=jp[e]||(null===(o=t.find((t=>t.id===e)))||void 0===o?void 0:o.format);if(r)try{let e=r.replace(/(.*?);.*/,"$1");e=e.replace(/\[(.*)-[A-Z0-9]{3}\]/g,"[$1]"),e=e.replace(/\[\$\]/g,"");const t=(null===(n=e.match(/"/g))||void 0===n?void 0:n.length)||0;if(t/2+((null===(s=e.match(/\[/g))||void 0===s?void 0:s.length)||0)>1)throw new Error("Multiple escaped blocks in format");if(e=e.replace(/"(.*)"/g,"[$$$1]"),e=e.replace(/_.{1}/g,""),e=e.replace(/\*.{1}/g,""),e=e.replace(/\\ /g," "),e=e.replace(/\\./g,(e=>e[1])),function(e){return null!==e.match(om)}(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 di(0,e),!0}catch(e){return!1}}(e))return e}catch(e){}i.generateNotSupportedWarning(_p.NumFmtIdNotSupported,r||`nmFmtId ${e}`)}function sm(e,t){const i=e.borders.map((e=>{!function(e,t){e.diagonal&&t.generateNotSupportedWarning(_p.DiagonalBorderNotSupported)}(e,t);const i={top:rm(e.top,t),bottom:rm(e.bottom,t),left:rm(e.left,t),right:rm(e.right,t)};return Object.keys(i).forEach((e=>void 0===i[e]&&delete i[e])),i}));return em(i,1)}function rm(e,t){if(!e)return;!function(e,t){Dp.includes(e.style)||t.generateNotSupportedWarning(_p.BorderStyleNotSupported,e.style,Dp)}(e,t);const i=zp[e.style];return i?[i,Qp(e.color)]:void 0}function am(e,t){return em(e.styles.map((i=>lm({fontStyle:e.fonts[i.fontId],fillStyle:e.fills[i.fillId],alignment:i.alignment},t))),1)}function lm(e,t){var i,o,n,s,r,a,l,c,h,d,u,g;return function(e,t,i){e&&e.name&&!Lp.includes(e.name)&&i.generateNotSupportedWarning(_p.FontNotSupported,e.name,Lp);t&&t.patternType&&!Pp.includes(t.patternType)&&i.generateNotSupportedWarning(_p.FillStyleNotSupported,t.patternType,Pp)}(null==e?void 0:e.fontStyle,null==e?void 0:e.fillStyle,t),function(e,t){e&&!kp.includes(e)&&t.generateNotSupportedWarning(_p.HorizontalAlignmentNotSupported,e,kp)}(null===(i=null==e?void 0:e.alignment)||void 0===i?void 0:i.horizontal,t),function(e,t){e&&t.generateNotSupportedWarning(_p.VerticalAlignmentNotSupported)}(null===(o=null==e?void 0:e.alignment)||void 0===o?void 0:o.vertical,t),{bold:null===(n=e.fontStyle)||void 0===n?void 0:n.bold,italic:null===(s=e.fontStyle)||void 0===s?void 0:s.italic,strikethrough:null===(r=e.fontStyle)||void 0===r?void 0:r.strike,underline:null===(a=e.fontStyle)||void 0===a?void 0:a.underline,align:(null===(l=e.alignment)||void 0===l?void 0:l.horizontal)?Bp[e.alignment.horizontal]:void 0,fillColor:"solid"===(null===(c=e.fillStyle)||void 0===c?void 0:c.patternType)?Qp(null===(h=e.fillStyle)||void 0===h?void 0:h.fgColor):Qp(null===(d=e.fillStyle)||void 0===d?void 0:d.bgColor),textColor:Qp(null===(u=e.fontStyle)||void 0===u?void 0:u.color),fontSize:null===(g=e.fontStyle)||void 0===g?void 0:g.size}}function cm(e,t){const i=[];for(let o of e.styles){const n=nm(o.numFmtId,e.numFmts,t);n&&(i[o.numFmtId]=n)}return em(i,1)}function hm(e,t,i){const o=[];let n=1;for(let r of e){if(0===r.cfRules.length)continue;pm(r,t,i);const e=r.cfRules[0];let a;const l=[];if(void 0!==e.dxfId||"colorScale"===e.type||"iconSet"===e.type){switch(e.type){case"aboveAverage":case"containsErrors":case"notContainsErrors":case"dataBar":case"duplicateValues":case"expression":case"top10":case"uniqueValues":case"timePeriod":continue;case"colorScale":const t=dm(n++,r);t&&o.push(t);continue;case"iconSet":const c=um(n++,r,i);c&&o.push(c);continue;case"containsText":case"notContainsText":case"beginsWith":case"endsWith":if(!e.text)continue;a=Hp[e.type],l.push(e.text);break;case"containsBlanks":case"notContainsBlanks":a=Hp[e.type];break;case"cellIs":if(!e.operator||!e.formula||0===e.formula.length)continue;a=(s=e.operator).slice(0,1).toUpperCase()+s.slice(1),l.push(e.formula[0]),2===e.formula.length&&l.push(e.formula[1])}a&&void 0!==e.dxfId&&o.push({id:(n++).toString(),ranges:r.sqref,stopIfTrue:e.stopIfTrue,rule:{type:"CellIsRule",operator:a,values:l,style:lm({fontStyle:t[e.dxfId].font,fillStyle:t[e.dxfId].fill},i)}})}}var s;return o}function dm(e,t){const i=t.cfRules[0].colorScale;if(!i||i.cfvos.length!==i.colors.length||i.cfvos.length<2||i.cfvos.length>3)return;const o=[];for(let e=0;e<i.cfvos.length;e++)o.push({color:(n=Qp(i.colors[e])||"#FFFFFF",9===n.length&&(n=n.slice(0,7)),parseInt(n.replace("#",""),16)),type:$p[i.cfvos[e].type],value:i.cfvos[e].value});var n;const s=o[0],r=2===o.length?o[1]:o[2],a=3===o.length?o[1]:void 0;return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"ColorScaleRule",minimum:s,midpoint:a,maximum:r}}}function um(e,t,i){const o=t.cfRules[0].iconSet;if(!o)return;let n=o.cfvos,s=o.cfIcons;if(n.length<3||s&&s.length<3)return;n.length>3&&(n=[n[0],n[Math.floor(n.length/2)],n[n.length-1]]),s&&s.length>3&&(s=[s[0],s[Math.floor(s.length/2)],s[s.length-1]]);const r=[];for(let e=1;e<=2;e++){const t=$p[n[e].type];if("value"===t)return;r.push({value:n[e].value||"",operator:n[e].gte?"ge":"gt",type:t})}let a={lower:s?gm(s[0].iconSet,s[0].iconId):gm(o.iconSet,0),middle:s?gm(s[1].iconSet,s[1].iconId):gm(o.iconSet,1),upper:s?gm(s[2].iconSet,s[2].iconId):gm(o.iconSet,2)};o.reverse&&(a={upper:a.lower,middle:a.middle,lower:a.upper});for(let e of Object.keys(a))if(!a[e])switch(i.generateNotSupportedWarning(_p.CfIconSetEmptyIconNotSupported),e){case"upper":a[e]=Sg.dots.good;break;case"middle":a[e]=Sg.dots.neutral;break;case"lower":a[e]=Sg.dots.bad}return{id:e.toString(),stopIfTrue:t.cfRules[0].stopIfTrue,ranges:t.sqref,rule:{type:"IconSetRule",icons:a,upperInflectionPoint:r[1],lowerInflectionPoint:r[0]}}}function gm(e,t){const i=Wp[e];return i?0===t?Sg[i].bad:1===t?Sg[i].neutral:Sg[i].good:""}function pm(e,t,i){if(e.cfRules.length>1&&i.generateNotSupportedWarning(_p.MultipleRulesCfNotSupported),Up.includes(e.cfRules[0].type)||i.generateNotSupportedWarning(_p.CfTypeNotSupported,e.cfRules[0].type),e.cfRules[0].dxfId){const o=t[e.cfRules[0].dxfId];o.border&&i.generateNotSupportedWarning(_p.CfFormatBorderNotSupported),o.alignment&&i.generateNotSupportedWarning(_p.CfFormatAlignmentNotSupported),o.numFmt&&i.generateNotSupportedWarning(_p.CfFormatNumFmtNotSupported)}}class mm{constructor(e=new vm){this.scope=e,this.code=""}append(...e){this.code+=e.map((e=>e.toString())).join("\n")+"\n"}return(e){return new fm(this.scope,this.code,e)}toString(){return bm(this.code)}}class fm{constructor(e,t,i){this.scope=e,this.returnExpression=i,this.code=bm(t)}toString(){return this.code}wrapInClosure(){const e=this.scope.nextVariableName(),t=new mm(this.scope);return t.append(`const ${e} = () => {`),t.append(this.code),t.append(`return ${this.returnExpression};`),t.append("}"),t.return(e)}assignResultToVariable(){if(this.scope.isAlreadyDeclared(this.returnExpression))return this;const e=this.scope.nextVariableName(),t=new mm(this.scope);return t.append(this.code),t.append(`const ${e} = ${this.returnExpression};`),t.return(e)}}class vm{constructor(){this.nextId=1,this.declaredVariables=new Set}nextVariableName(){const e="_"+this.nextId++;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}}function bm(e){let t="",i=0;const o=e.split("\n").map((e=>e.trim())).filter((e=>""!==e));for(const e of o)e.startsWith("}")&&i--,t+="\t".repeat(i)+e+"\n",e.endsWith("{")&&i++;return t.trim()}const Sm=Gu.content,Cm=["%"],Em="+,-,*,/,:,=,<>,>=,>,<=,<,^,&".split(",").concat(Cm);function wm(e){const t=(e=pt(e)).split(""),i=[];for(;t.length;){let e=_m(t)||Im(t)||Tm(t)||Mm(t)||ym(t)||Fm(t)||Am(t)||Nm(t);e||(e={type:"UNKNOWN",value:t.shift()}),i.push(e)}return i}function ym(e){return"?"===e[0]?(e.shift(),{type:"DEBUGGER",value:"?"}):null}const xm={",":"COMMA","(":"LEFT_PAREN",")":"RIGHT_PAREN"};function Im(e){if(e[0]in xm){const t=e.shift();return{type:xm[t],value:t}}return null}function Rm(e,t){for(let i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0}function Tm(e){for(let t of Em)if(Rm(e,t))return e.splice(0,t.length),{type:"OPERATOR",value:t};return null}function Am(e){const t=nt(e).match(Zt);return t?(e.splice(0,t[0].length),{type:"NUMBER",value:t[0]}):null}function Mm(e){if('"'===e[0]){const t=e.shift();let i=t;for(;e[0]&&(e[0]!==t||"\\"===i[i.length-1]);)i+=e.shift();return'"'===e[0]&&(i+=e.shift()),{type:"STRING",value:i}}return null}const Om=/\w|\.|!|\$/;function Nm(e){let t="";if("'"===e[0]){let i=e.shift();for(t+=i;e[0];)if(i=e.shift(),t+=i,"'"===i){if(!e[0]||"'"!==e[0])break;i=e.shift(),t+=i}if("'"!==i)return{type:"UNKNOWN",value:t}}for(;e[0]&&e[0].match(Om);)t+=e.shift();if(t.length){const e=t;if(e.toUpperCase()in Sm)return{type:"FUNCTION",value:e};return e.match(Ft)?{type:"REFERENCE",value:e}:{type:"SYMBOL",value:e}}return null}function _m(e){let t=0;for(;e[0]===ce;)t++,e.shift();if(t)return{type:"SPACE",value:ce.repeat(t)};for(;" "===e[0];)t++,e.shift();return t?{type:"SPACE",value:" ".repeat(t)}:null}function Fm(e){return Rm(e,Y)?(e.splice(0,Y.length),{type:"INVALID_REFERENCE",value:Y}):null}const Dm=/[a-zA-Z0-9\_]+(\.[a-zA-Z0-9\_]+)*/,km=["-","+"],Lm=["%"],Pm=["*","+","&"],Um={"^":30,"%":30,"*":20,"/":20,"+":15,"-":15,"&":13,">":10,"<>":10,">=":10,"<":10,"<=":10,"=":10};function Vm(e){var t,i,o;const n=e.shift();if(!n)throw new h(ae);switch(n.type){case"DEBUGGER":const r=Hm(e,1e3);return r.debug=!0,r;case"NUMBER":return{type:"NUMBER",value:ti(n.value)};case"STRING":return{type:"STRING",value:Me(n.value)};case"FUNCTION":const a=function(e){var t;Bm(e,"LEFT_PAREN",s("Missing opening parenthesis"));const i=e[0];if("RIGHT_PAREN"===(null==i?void 0:i.type))return Bm(e,"RIGHT_PAREN"),[];const o=[];o.push(zm(e));for(;"RIGHT_PAREN"!==(null===(t=e[0])||void 0===t?void 0:t.type);)Bm(e,"COMMA",s("Wrong function call")),o.push(zm(e));return Bm(e,"RIGHT_PAREN"),o}(e);return{type:"FUNCALL",value:n.value,args:a};case"INVALID_REFERENCE":throw new u;case"REFERENCE":if(":"===(null===(t=e[0])||void 0===t?void 0:t.value)&&"REFERENCE"===(null===(i=e[1])||void 0===i?void 0:i.type)){e.shift();const t=e.shift();return{type:"REFERENCE",value:`${n.value}:${null==t?void 0:t.value}`}}return{type:"REFERENCE",value:n.value};case"SYMBOL":if(["TRUE","FALSE"].includes(n.value.toUpperCase()))return{type:"BOOLEAN",value:"TRUE"===n.value.toUpperCase()};if(n.value&&Dm.test(n.value)&&"LEFT_PAREN"===(null===(o=e[0])||void 0===o?void 0:o.type))throw new p(n.value);throw new h(s("Invalid formula"));case"LEFT_PAREN":const l=Hm(e);return Bm(e,"RIGHT_PAREN",s("Missing closing parenthesis")),l;case"OPERATOR":const c=n.value;if(km.includes(c))return{type:"UNARY_OPERATION",value:c,operand:Hm(e,Um[c])};throw new h(s("Unexpected token: %s",n.value));default:throw new h(s("Unexpected token: %s",n.value))}}function zm(e){const t=e[0];return"COMMA"===(null==t?void 0:t.type)||"RIGHT_PAREN"===(null==t?void 0:t.type)?{type:"EMPTY",value:""}:Hm(e)}function Bm(e,t,i=ae){const o=e.shift();if(!o||o.type!==t)throw new h(i)}function Hm(e,t=0){var i;if(0===e.length)throw new h(ae);let o=Vm(e);for(;"OPERATOR"===(null===(i=e[0])||void 0===i?void 0:i.type)&&Um[e[0].value]>t;){const t=e.shift().value;if(Lm.includes(t))o={type:"UNARY_OPERATION",value:t,operand:o,postfix:!0};else{o={type:"BIN_OPERATION",value:t,left:o,right:Hm(e,Um[t])}}}return o}function $m(e){return Wm(wm(e))}function Wm(e){"="===(e=e.filter((e=>"SPACE"!==e.type)))[0].value&&e.splice(0,1);const t=Hm(e);if(e.length)throw new h(ae);return t}function Gm(e,t,i){switch(t===e.type&&(e=i(e)),e.type){case"FUNCALL":return{...e,args:e.args.map((e=>Gm(e,t,i)))};case"UNARY_OPERATION":return{...e,operand:Gm(e.operand,t,i)};case"BIN_OPERATION":return{...e,right:Gm(e.right,t,i),left:Gm(e.left,t,i)};default:return e}}function qm(e){switch(e.type){case"FUNCALL":const t=e.args.map((e=>qm(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?Zm(e)+e.value:e.value+jm(e);case"BIN_OPERATION":return Zm(e)+e.value+jm(e)}}function Zm(e){const t=e.value,i="left"in e?e.left:e.operand,o=i.value;return"BIN_OPERATION"===i.type&&Um[o]<Um[t]?`(${qm(i)})`:qm(i)}function jm(e){const t=e.value,i="right"in e?e.right:e.operand,o=Um[i.value],n=Um[t];let s=!1;return"BIN_OPERATION"!==i.type?s=!1:o<n?s=!0:o!==n||Pm.includes(t)||(s=!0),s?`(${qm(i)})`:qm(i)}var Xm;!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"}(Xm||(Xm={}));const Ym=(e,t=(()=>!0))=>[{goTo:e,guard:t}],Km=(e,t=(()=>!0))=>({goTo:e,guard:t}),Qm={[Xm.LeftRef]:{REFERENCE:Ym(Xm.Separator),NUMBER:Ym(Xm.FullRowSeparator),SYMBOL:[Km(Xm.FullColumnSeparator,(e=>Dt(e.value))),Km(Xm.FullRowSeparator,(e=>kt(e.value)))]},[Xm.FullColumnSeparator]:{SPACE:Ym(Xm.FullColumnSeparator),OPERATOR:Ym(Xm.RightColumnRef,(e=>":"===e.value))},[Xm.FullRowSeparator]:{SPACE:Ym(Xm.FullRowSeparator),OPERATOR:Ym(Xm.RightRowRef,(e=>":"===e.value))},[Xm.Separator]:{SPACE:Ym(Xm.Separator),OPERATOR:Ym(Xm.RightRef,(e=>":"===e.value))},[Xm.RightRef]:{SPACE:Ym(Xm.RightRef),NUMBER:Ym(Xm.Found),REFERENCE:Ym(Xm.Found,(e=>Pt(e.value))),SYMBOL:Ym(Xm.Found,(e=>Lt(e.value)))},[Xm.RightColumnRef]:{SPACE:Ym(Xm.RightColumnRef),SYMBOL:Ym(Xm.Found,(e=>Lt(e.value))),REFERENCE:Ym(Xm.Found,(e=>Pt(e.value)))},[Xm.RightRowRef]:{SPACE:Ym(Xm.RightRowRef),NUMBER:Ym(Xm.Found),REFERENCE:Ym(Xm.Found,(e=>Pt(e.value)))},[Xm.Found]:{}};function Jm(e){var t;let i=0,o=Qm[Xm.LeftRef];const n=[];for(;void 0!==o;){const s=e[i++];if(!s)return null;const r=null===(t=o[s.type])||void 0===t?void 0:t.find((e=>e.guard(s))),a=r?r.goTo:void 0;switch(a){case void 0:return null;case Xm.Found:return n.push(s),e.splice(0,i),{type:"REFERENCE",value:nt(n.map((e=>e.value)))};default:o=Qm[a],n.push(s)}}return null}function ef(e){const t=wm(e),i=[];for(;t.length;)i.push(Jm(t)||t.shift());return i}const tf=Gu.content,of={"=":"EQ","+":"ADD","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",">=":"GTE","<>":"NE",">":"GT","<=":"LTE","<":"LT","^":"POWER","&":"CONCATENATE"},nf={"-":"UMINUS","+":"UPLUS","%":"UNARY.PERCENT"},sf={};function rf(e){const t=ef(e),{dependencies:i,constantValues:o}=function(e){const t={numbers:[],strings:[]},i=[];for(const o of e)switch(o.type){case"INVALID_REFERENCE":case"REFERENCE":i.push(o.value);break;case"STRING":const e=Me(o.value);t.strings.includes(e)||t.strings.push(e);break;case"NUMBER":{const e=ti(o.value);t.numbers.includes(e)||t.numbers.push(e);break}}return{dependencies:i,constantValues:t}}(t),n=function(e,t,i){return nt(e.map((e=>{switch(e.type){case"STRING":const o=Me(e.value);return`|S${i.strings.indexOf(o)}|`;case"NUMBER":return`|N${i.numbers.indexOf(ti(e.value))}|`;case"REFERENCE":case"INVALID_REFERENCE":return`|${t.indexOf(e.value)}|`;case"SPACE":return"";default:return e.value}})))}(t,i,o);if(!sf[n]){const r=Wm([...t]),a=new vm;if("BIN_OPERATION"===r.type&&":"===r.value)throw new h(s("Invalid formula"));if("EMPTY"===r.type)throw new h(s("Invalid formula"));const l=g(r),c=new mm;c.append(`// ${n}`),c.append(l),c.append(`return ${l.returnExpression};`);let d=new Function("deps","ref","range","ctx",c.toString());function u(e){const t=tf[e.value.toUpperCase()],i=e.args,o=i.length;if(o<t.minArgRequired)throw new h(s("Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.",e.value.toUpperCase(),t.minArgRequired.toString(),o.toString()));if(o>t.maxArgPossible)throw new h(s("Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.",e.value.toUpperCase(),t.maxArgPossible.toString(),o.toString()));const n=t.nbrArgRepeating;if(n>1){const i=t.args.length-n;if((o-i)%n!=0)throw new h(s("Invalid number of arguments for the %s function. Expected all arguments after position %s to be supplied by groups of %s arguments",e.value.toUpperCase(),i.toString(),n.toString()))}let r=[];for(let n=0;n<o;n++){const o=t.getArgToFocus(n+1)-1;if(0<=o&&o<t.args.length){const a=i[n],l=t.args[o],c=l.type||[],d=c.includes("META"),u=l.lazy,p=c.some((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e)),m=c.every((e=>"RANGE"===e||"RANGE<BOOLEAN>"===e||"RANGE<DATE>"===e||"RANGE<NUMBER>"===e||"RANGE<STRING>"===e));if(m&&"REFERENCE"!==a.type)throw new h(s("Function %s expects the parameter %s to be reference to a cell or range, not a %s.",e.value.toUpperCase(),(n+1).toString(),a.type.toLowerCase()));const f=g(a,d,p,{functionName:e.value.toUpperCase(),paramIndex:n+1});r.push(u?f.wrapInClosure():f)}}return r}function g(e,t=!1,n=!1,r={}){const l=new mm(a);if("REFERENCE"!==e.type&&("BIN_OPERATION"!==e.type||":"!==e.value)&&t)throw new h(s("Argument must be a reference to a cell or range."));switch(e.debug&&l.append("debugger;"),e.type){case"BOOLEAN":return l.return(`{ value: ${e.value} }`);case"NUMBER":return l.return(`{ value: this.constantValues.numbers[${o.numbers.indexOf(e.value)}] }`);case"STRING":return l.return(`{ value: this.constantValues.strings[${o.strings.indexOf(e.value)}] }`);case"REFERENCE":const s=i.indexOf(e.value);return n?l.return(`range(deps[${s}])`):l.return(`ref(deps[${s}], ${t?"true":"false"}, "${r.functionName||of["="]}", ${r.paramIndex})`);case"FUNCALL":const a=u(e).map((e=>e.assignResultToVariable()));l.append(...a);const c=e.value.toUpperCase();return l.append(`ctx.__lastFnCalled = '${c}';`),l.return(`ctx['${c}'](${a.map((e=>e.returnExpression))})`);case"UNARY_OPERATION":{const t=nf[e.value],i=g(e.operand,!1,!1,{functionName:t}).assignResultToVariable();return l.append(i),l.append(`ctx.__lastFnCalled = '${t}';`),l.return(`ctx['${t}'](${i.returnExpression})`)}case"BIN_OPERATION":{const t=of[e.value],i=g(e.left,!1,!1,{functionName:t}).assignResultToVariable(),o=g(e.right,!1,!1,{functionName:t}).assignResultToVariable();return l.append(i),l.append(o),l.append(`ctx.__lastFnCalled = '${t}';`),l.return(`ctx['${t}'](${i.returnExpression}, ${o.returnExpression})`)}case"EMPTY":return l.return("undefined")}}sf[n]={execute:d}}return{execute:sf[n].execute,dependencies:i,constantValues:o,tokens:t}}function af(e){return function(e){let t=[],i="";return e.map(((e,o)=>{switch(["SPACE","LEFT_PAREN"].includes(e.type)||(i=""),e.type){case"FUNCTION":i=e.value;break;case"LEFT_PAREN":t.push({parent:i,argPosition:0}),i="";break;case"RIGHT_PAREN":t.pop();break;case"COMMA":t.length&&t[t.length-1].argPosition++}if(t.length){const i=t[t.length-1];i.parent&&(e.functionContext=Object.assign({},i))}return e}))}(function(e){let t=1;const i=[];return e.map((e=>("LEFT_PAREN"===e.type?(i.push(t),e.parenIndex=t,t++):"RIGHT_PAREN"===e.type&&(e.parenIndex=i.pop()),e)))}(function(e){let t=0;return e.map((e=>{const i=e.value.toString().length,o=Object.assign({},e,{start:t,end:t+i,length:i});return t=o.end,o}))}(ef(e))))}function lf(e){switch(e){case"IsNotEmpty":case"NotContains":return"notContainsBlanks";case"IsEmpty":return"containsBlanks";default:return e.charAt(0).toLowerCase()+e.slice(1)}}function cf(e){return Math.round(wp*e*100)/100}function hf(e){return Math.round(yp*e*100)/100}function df(e){if(e)return{style:e[0],color:{rgb:e[1]}}}function uf(e,t){let i={};e.style&&(i=t.styles[e.style]);const o=function(e,t){if(e.format)return t.formats[e.format];if(e.isFormula){const t=wm(e.content||""),i=Gu.content;if(!t.filter((e=>"FUNCTION"===e.type)).every((e=>i[e.value.toUpperCase()].isExported)))return e.computedFormat}return}(e,t),n={};if(e.border){const i=t.borders[e.border];n.left=df(i.left),n.right=df(i.right),n.bottom=df(i.bottom),n.top=df(i.top)}const s={font:{size:(null==i?void 0:i.fontSize)||G,color:{rgb:(null==i?void 0:i.textColor)?i.textColor:"000000"},family:2,name:"Arial"},fill:(null==i?void 0:i.fillColor)?{fgColor:{rgb:i.fillColor}}:{reservedAttribute:"none"},numFmt:o?{format:o,id:0}:void 0,border:n||{},alignment:{vertical:"center",horizontal:i.align}};return s.font.strike=!!(null==i?void 0:i.strikethrough)||void 0,s.font.underline=!!(null==i?void 0:i.underline)||void 0,s.font.bold=!!(null==i?void 0:i.bold)||void 0,s.font.italic=!!(null==i?void 0:i.italic)||void 0,s}function gf(e,t){const{id:i}=mf(t.font,e.fonts),{id:o}=mf(t.fill,e.fills),{id:n}=mf(t.border,e.borders),s=function(e,t){if(!e)return 0;let i=Xp[e.format];if(!i){const{id:o}=mf(e,t);i=o+Ap}return i}(t.numFmt,e.numFmts),r={fontId:i,fillId:o,borderId:n,numFmtId:s,alignment:{vertical:t.alignment.vertical,horizontal:t.alignment.horizontal}},{id:a}=mf(r,e.styles);return a}function pf(e,t,i){let o,n=e.find((e=>e.path===t));return n?(o=`rId${(n.rels.length+1).toString()}`,n.rels.push({...i,id:o})):(o="rId1",e.push({path:t,rels:[{...i,id:o}]})),o}function mf(e,t){for(let[i,o]of Object.entries(t))if(JSON.stringify(o)===JSON.stringify(e))return{id:parseInt(i,10),list:t};let i=t.findIndex((t=>JSON.stringify(t)===JSON.stringify(e)));return-1===i&&(t.push(e),i=t.length-1),{id:i,list:t}}const ff=[];function vf(e){const t=ff.findIndex((t=>t===e));return-1===t?(ff.push(e),ff.length):t+1}const bf=[];function Sf(e){const t=bf.findIndex((t=>t===e));return-1===t?(bf.push(e),bf.length):t+1}function Cf(e){return Math.round(914400*e/96)}function Ef(e,t,i){let o,n,s=e;if(({xc:s,sheetName:o}=Ut(e)),o){const e=i.sheets.findIndex((e=>e.name===o));if(e<0)throw new Error("Unable to find a sheet with the name "+o);n=e}else n=Number(t);const r=Li(s);return void 0===r.right&&(r.right=i.sheets[n].colNumber),void 0===r.bottom&&(r.bottom=i.sheets[n].rowNumber),(r.right-r.left+1)*(r.bottom-r.top+1)}function wf(e){return Math.round(96*e/914400)}function yf(e,t){var i;let o=0;for(let n=0;n<e;n++){const e=t.cols.find((e=>n>=e.min&&n<=e.max));(null==e?void 0:e.width)?o+=e.width:(null===(i=t.sheetFormat)||void 0===i?void 0:i.defaultColWidth)?o+=t.sheetFormat.defaultColWidth:o+=xp}return o/yp}function xf(e,t){var i;let o=0;for(let n=0;n<e;n++){const e=t.rows[n];(null==e?void 0:e.height)?o+=e.height:(null===(i=t.sheetFormat)||void 0===i?void 0:i.defaultRowHeight)?o+=t.sheetFormat.defaultRowHeight:o+=Ip}return o/wp}function If(e){let t=1;return e.figures.map((i=>function(e,t,i){const o=yf(e.anchors[0].col,i)+wf(e.anchors[0].colOffset),n=yf(e.anchors[1].col,i)+wf(e.anchors[1].colOffset),s=xf(e.anchors[0].row,i)+wf(e.anchors[0].rowOffset),r=xf(e.anchors[1].row,i)+wf(e.anchors[1].rowOffset),a=n-o,l=r-s,c=Rf(e.data);return c?{id:t,x:o,y:s,width:a,height:l,tag:"chart",data:Rf(e.data)}:void 0}(i,(t++).toString(),e))).filter(tt)}function Rf(e){var t;const i=null===(t=e.dataSets[0].label)||void 0===t?void 0:t.replace(/\$/g,"");let o=e.dataSets.map((e=>e.range.replace(/\$/g,"")));return"pie"===e.type&&o.reverse(),{dataSets:o,dataSetsHaveTitle:!1,labelRange:i,title:e.title||"",type:e.type,background:Qp({rgb:e.backgroundColor})||"#FFFFFF",verticalAxisPosition:e.verticalAxisPosition,legendPosition:e.legendPosition,stacked:e.stacked||!1,aggregated:!1,labelsAsText:!1}}const Tf=new RegExp(/'?\[([0-9]*)\](.*)'?!(\$?[a-zA-Z]*\$?[0-9]*)/g),Af=new RegExp(/SUBTOTAL\(([0-9]*),/g),Mf=new RegExp(At.source,"ig");function Of(e,t){const i=function(e){const t={};for(let i of e.rows)for(let e of i.cells)e.formula&&void 0!==e.formula.sharedIndex&&e.formula.content&&(t[e.formula.sharedIndex]={refCellXc:e.xc,formula:e.formula.content});return t}(e);for(let o of e.rows.map((e=>e.cells)).flat())(null==o?void 0:o.formula)&&(o.formula.content=void 0===o.formula.sharedIndex||o.formula.content?"="+o.formula.content:"="+_f(o.xc,i[o.formula.sharedIndex]),o.formula.content=Nf(o.formula.content,t))}function Nf(e,t){return e=(e=(e=(e=e.replace("_xlfn.","")).replace(/#REF!/g,"#REF")).replace(Af,((e,t)=>{const i=Zp[t];return i?i+"(":e}))).replace(Tf,((e,i,o,n)=>{var s;i=Number(i)-1,n=n.replace(/\$/g,"");const r=t.externalBooks[i].sheetNames.findIndex((e=>e===o));if(-1===r)return e;const a=null===(s=t.externalBooks[i].datasets.find((e=>e.sheetId===r)))||void 0===s?void 0:s.data;if(!a)return e;const l=a&&a[n];return(Number(l)?l:`"${l}"`)||e}))}function _f(e,t){const i=Bt(t.refCellXc);let o,n=t.formula.slice();do{if(o=Mf.exec(n),o){const t=Bt(o[0].replace("$","")),s=Bt(e),r={colFixed:o[0].startsWith("$"),rowFixed:o[0].includes("$",1)},a={col:s.col-i.col,row:s.row-i.row},l={col:r.colFixed?t.col:t.col+a.col,row:r.rowFixed?t.row:t.row+a.row};n=n.slice(0,o.index)+Ht(l.col,l.row,r)+n.slice(o.index+o[0].length)}}while(o);return n}function Ff(e,t){return e.sheets.map((i=>{Of(i,e);const o=function(e){const t=[0,0];for(let i of e.rows)t[0]=Math.max(t[0],...i.cells.map((e=>Bt(e.xc).col))),t[1]=Math.max(t[1],i.index);return t[0]=Math.max(t[0],Rp),t[1]=Math.max(t[1],Tp),t}(i),n=i.sheetViews[0];return{id:i.sheetName,areGridLinesVisible:!n||n.showGridLines,name:i.sheetName,colNumber:o[0],rowNumber:o[1],cells:Lf(i,e,o,t),merges:i.merges,cols:Df(i,o[0]),rows:kf(i,o[1]),conditionalFormats:hm(i.cfs,e.dxfs,t),figures:If(i),isVisible:i.isVisible,panes:n?{xSplit:n.pane.xSplit,ySplit:n.pane.ySplit}:{xSplit:0,ySplit:0},filterTables:[]}}))}function Df(e,t){var i;const o={};for(let s=1;s<t+1;s++){const t=e.cols.find((e=>e.min<=s&&s<=e.max));let r;r=t&&t.width?t.width:(null===(i=e.sheetFormat)||void 0===i?void 0:i.defaultColWidth)?e.sheetFormat.defaultColWidth:xp,o[s-1]={size:(n=r,n?Math.round(n/yp*100)/100:n),isHidden:null==t?void 0:t.hidden}}var n;return o}function kf(e,t){var i;const o={};for(let s=1;s<t+1;s++){const t=e.rows.find((e=>e.index===s));let r;r=t&&t.height?t.height:(null===(i=e.sheetFormat)||void 0===i?void 0:i.defaultRowHeight)?e.sheetFormat.defaultRowHeight:Ip,o[s-1]={size:(n=r,n?Math.round(n/wp*100)/100:n),isHidden:null==t?void 0:t.hidden}}var n;return o}function Lf(e,t,i,o){const n={},s=t.sharedStrings.map((e=>e.replace(/\n/g,"")));const r=e.hyperlinks.reduce(((e,t)=>(e[t.xc]=t,e)),{});for(let i of e.rows)for(let e of i.cells)n[e.xc]={content:Pf(e,r,s,o),style:e.styleIndex?e.styleIndex+1:void 0,border:e.styleIndex?t.styles[e.styleIndex].borderId+1:void 0,format:e.styleIndex?t.styles[e.styleIndex].numFmtId+1:void 0};for(let o of e.rows.filter((e=>e.styleIndex)))for(let e=1;e<=i[0];e++){const i=Ht(e-1,o.index-1);let s=n[i];s||(s={},n[i]=s),s.style=s.style?s.style:o.styleIndex+1,s.border=s.border?s.border:t.styles[o.styleIndex].borderId+1,s.format=s.format?s.format:t.styles[o.styleIndex].numFmtId+1}for(let o of e.cols.filter((e=>e.styleIndex)))for(let e=o.min;e<=Math.min(o.max,i[0]);e++)for(let s=1;s<=i[1];s++){const i=Ht(e-1,s-1);let r=n[i];r||(r={},n[i]=r),r.style=r.style?r.style:o.styleIndex+1,r.border=r.border?r.border:t.styles[o.styleIndex].borderId+1,r.format=r.format?r.format:t.styles[o.styleIndex].numFmtId+1}return n}function Pf(e,t,i,o){let n;switch(e.type){case"sharedString":n=i[parseInt(e.value,10)];break;case"boolean":n=Number(e.value)?"TRUE":"FALSE";break;case"date":case"error":case"inlineStr":case"number":case"str":n=e.value}return n&&t[e.xc]&&(n=function(e,t,i){const o=e.display||t;e.relTarget||e.location||i.generateNotSupportedWarning(_p.BadlyFormattedHyperlink);const n=e.relTarget?e.relTarget:Je(Ut(e.location).sheetName);return Xe(o,n)}(t[e.xc],n,o)),e.formula&&(n=e.formula.content),n}const Uf={fillColor:"#000000",textColor:"#ffffff",bold:!0},Vf={bold:!0},zf=["thin","#000000FF"];function Bf(e,t){for(const i of t.sheets)for(const t of i.tables){const o=e.sheets.find((e=>e.name===i.sheetName));o&&t.autoFilter&&(o.filterTables||(o.filterTables=[]),o.filterTables.push({range:t.ref}))}!function(e,t){var i,o,n,s;const r=tm(e.styles),a=tm(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=Pi(t.ref);for(let e=0;e<t.headerRowCount;e++)Hf(Uf,{...h,bottom:h.top+e},c.cells,r);for(let e=0;e<t.totalsRowCount;e++)Hf(Vf,{...h,top:h.bottom-e},c.cells,r);(null===(i=t.style)||void 0===i?void 0:i.showFirstColumn)&&Hf(Vf,{...h,right:h.left},c.cells,r),(null===(o=t.style)||void 0===o?void 0:o.showLastColumn)&&Hf(Vf,{...h,left:h.right},c.cells,r);for(let e=h.left;e<=h.right;e++)for(let i=h.top;i<=h.bottom;i++){const o=Ht(e,i),r=c.cells[o],l={left:e===h.left||(null===(n=t.style)||void 0===n?void 0:n.showColumnStripes)?zf:void 0,right:e===h.right?zf:void 0,top:i===h.top||(null===(s=t.style)||void 0===s?void 0:s.showRowStripes)||i>h.bottom-t.totalsRowCount?zf:void 0,bottom:i===h.bottom?zf:void 0},d=(null==r?void 0:r.border)?{...a[r.border],...l}:l;let u=a.findIndex((e=>lt(e,d)));-1===u&&(u=a.length,a.push(d)),r?r.border=u:c.cells[o]={border:u}}}e.styles=em(r),e.borders=em(a)}(e,t),function(e,t){for(let i of e){const e=t.find((e=>e.sheetName===i.name)).tables;for(let t of e){const e=t.name+"[";for(let o of eo(Pi(t.ref))){const n=Ht(o.col,o.row),s=i.cells[n];if(s&&s.content&&s.content.startsWith("=")){let i;for(;-1!==(i=s.content.indexOf(e));){let o=s.content.slice(i+e.length),r=o.indexOf("]");o.startsWith("[")&&(r=o.indexOf("]",r+1),r=o.indexOf("]",r+1)),o=o.slice(0,r);const a=$f(o,t,n);s.content=s.content.slice(0,i)+a+s.content.slice(e.length+i+r+1)}}}}}}(e.sheets,t.sheets)}function Hf(e,t,i,o){for(let n=t.left;n<=t.right;n++)for(let s=t.top;s<=t.bottom;s++){const t=Ht(n,s),r=i[t],a=(null==r?void 0:r.style)?{...o[r.style],...e}:e;let l=o.findIndex((e=>lt(e,a)));-1===l&&(l=o.length,o.push(a)),r?r.style=l:i[t]={style:l}}}function $f(e,t,i){const o=e.split(","),n=Pi(t.ref),s={...n};let r=!0;if(1===o.length){const e=t.cols.findIndex((e=>e.name===o[0]));s.left=s.right=e+n.left,t.headerRowCount&&(s.top+=t.headerRowCount),t.totalsRowCount&&(s.bottom-=1)}else{switch(o[0].slice(1,o[0].length-1)){case"#All":s.top=t.headerRowCount?n.top+t.headerRowCount:n.top,s.bottom=n.bottom;break;case"#Data":s.top=t.headerRowCount?n.top+t.headerRowCount:n.top,s.bottom=t.totalsRowCount?n.bottom+1:n.bottom;break;case"#This Row":s.top=s.bottom=Bt(i).row;break;case"#Headers":s.top=s.bottom=n.top,t.headerRowCount||(r=!1);break;case"#Totals":s.top=s.bottom=n.bottom,t.totalsRowCount||(r=!1)}const e=o[1].slice(1,o[1].length-1),a=t.cols.findIndex((t=>t.name===e));s.left=s.right=a+n.left}return r?s.top!==s.bottom?Vi(s):Ht(s.left,s.top):Y}function Wf(e,t,i){return{content:(new XMLSerializer).serializeToString(e),path:t,contentType:i}}function Gf(e){return String(e).replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\'/g,"&apos;")}function qf(e){return new up(e.map((([e,t])=>`${e}="${Gf(t)}"`)).join(" "))}function Zf(e,t="text/xml"){const i=(new DOMParser).parseFromString(e.toString(),t),o=i.querySelector("parsererror");if(o){const t=o.innerHTML,i=parseInt(t.split(":")[0],10),n=e.toString().trim().split("\n"),s=n.slice(Math.max(i-3,0),Math.min(i+2,n.length)).join("\n");throw new Error(`XML string could not be parsed: ${t}\n${s}`)}return i}function jf(e,t){return Yf`
1398
1398
  <Override ContentType="${t}" PartName="${e}" />
1399
- `}function jf(e){return new dp(e.join("\n"))}function Xf(e,...t){let i=[e[0]];for(let o=0;o<t.length;o++){const n=t[o]instanceof dp?t[o]:Wf(t[o]);i.push(n+e[o+1])}return new dp(ot(i))}function Yf(e){return e.replace(/[a-z0-9]+:(?=[a-z0-9]+)/gi,"")}function Kf(e){return e.replace(/([a-z0-9]+):(?=[a-z0-9]+)/gi,"$1\\:")}class Qf{constructor(e){this.value=e}asString(){return tm(String(this.value))}asBool(){return Boolean(Number(this.value))}asNum(){return Number(this.value)}}class Jf{constructor(e,t,i){this.currentFile=void 0,this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=i,this.areNamespaceIgnored=null!==(new DOMParser).parseFromString("<t:test xmlns:t='a'/>","text/xml").querySelector("test"),this.relationships={},e.rels&&this.extractRelationships(e.rels).map((e=>{this.relationships[e.id]=e}))}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:"Relationship"},(e=>({id:this.extractAttr(e,"Id",{required:!0}).asString(),target:this.extractAttr(e,"Target",{required:!0}).asString(),type:this.extractAttr(e,"Type",{required:!0}).asString()})))}getListOfFiles(){return Object.values(this.xlsxFileStructure).flat().filter(et)}mapOnElements(e,t){var i;const o=[],n=this.currentFile;let s;if(e.children){const t=null===(i=this.querySelector(e.parent,e.query))||void 0===i?void 0:i.children;s=t||[]}else s=this.querySelectorAll(e.parent,e.query);if(s)for(let e of s)try{o.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=n,o}catchErrorOnElement(e,t){const i=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([i,e.message].join("\n"))}extractAttr(e,t,i){const o=e.attributes[t];o||this.handleMissingValue(e,`attribute "${t}"`,i);const n=(null==o?void 0:o.value)?o.value:null==i?void 0:i.default;return void 0===n?void 0:new Qf(n)}extractTextContent(e,t){var i;if(void 0!==(null==t?void 0:t.default)&&"string"!=typeof t.default)throw new Error("extractTextContent default value should be a string");const o="preserve"===(null===(i=null==e?void 0:e.attributes["xml:space"])||void 0===i?void 0:i.value);let n=null==e?void 0:e.textContent;return e&&null!==n||this.handleMissingValue(e,"text content",t),n&&(n=o?n:n.trim()),n?tm(n):null==t?void 0:t.default}extractChildAttr(e,t,i,o){var n;let s;s="number"==typeof t?e.children[t]:this.querySelector(e,t),s||this.handleMissingValue(e,"number"==typeof t?`child at index ${t}`:`child <${t}>`,o);const r=s?null===(n=this.extractAttr(s,i,o))||void 0===n?void 0:n.asString():null==o?void 0:o.default;return void 0!==r?new Qf(r):void 0}extractChildTextContent(e,t,i){if(void 0!==(null==i?void 0:i.default)&&"string"!=typeof i.default)throw new Error("extractTextContent default value should be a string");let o=this.querySelector(e,t);return o||this.handleMissingValue(e,`child <${t}>`,i),o?this.extractTextContent(o,i):null==i?void 0:i.default}handleMissingValue(e,t,i){if(null==i?void 0:i.required){if(!(null==i?void 0:i.default))throw new Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`);this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${i.default}`)}}extractColor(e,t,i){var o,n,s,r,a;if(!e)return i?{rgb:i}:void 0;const l=null===(o=this.extractAttr(e,"theme"))||void 0===o?void 0:o.asString();let c;if(void 0!==l){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");c=this.getThemeColor(l,t.clrScheme)}else c=null===(n=this.extractAttr(e,"rgb"))||void 0===n?void 0:n.asString();return{rgb:c,auto:null===(s=this.extractAttr(e,"auto"))||void 0===s?void 0:s.asBool(),indexed:null===(r=this.extractAttr(e,"indexed"))||void 0===r?void 0:r.asNum(),tint:null===(a=this.extractAttr(e,"tint"))||void 0===a?void 0:a.asNum()}}getTargetXmlFile(e){if(!e)throw new Error("Undefined target file");let t=e.target;t=t.replace("../",""),t=t.replace("./","");const i=this.getListOfFiles().find((e=>e.file.fileName.endsWith(t)));if(!i||!i.file)throw new Error("Cannot find target file");return i}querySelector(e,t){return t=this.areNamespaceIgnored?Yf(t):Kf(t),e.querySelector(t)}querySelectorAll(e,t){return t=this.areNamespaceIgnored?Yf(t):Kf(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 ev extends Jf{getTheme(){return{clrScheme:this.mapOnElements({query:"a:clrScheme",parent:this.rootFile.file.xml,children:!0},(e=>({name:e.tagName,value:this.extractChildAttr(e,0,"val",{required:!0,default:gp}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:gp}).asString()})))}}getSharedStrings(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"si"},(e=>"t"===e.children[0].tagName?this.extractTextContent(e)||"":this.mapOnElements({parent:e,query:"t"},(e=>this.extractTextContent(e)||"")).join("")))}}class tv extends Jf{constructor(e,t,i,o){super(e,t,i),this.theme=o}extractConditionalFormattings(){const e=this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > conditionalFormatting"},(e=>{var t;return{sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),pivot:null===(t=this.extractAttr(e,"pivot"))||void 0===t?void 0:t.asBool(),cfRules:this.extractCFRules(e,this.theme)}}));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:"extLst x14:conditionalFormatting"},(e=>{var t;return{sqref:this.extractChildTextContent(e,"xm:sqref",{required:!0}).split(" "),pivot:null===(t=this.extractAttr(e,"xm:pivot"))||void 0===t?void 0:t.asBool(),cfRules:this.extractCFRules(e,this.theme)}}))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:"cfRule, x14:cfRule"},(e=>{var i,o,n,s,r,a,l,c,h,d,u;const g=this.extractAttr(e,"type",{required:!0}).asString();if("dataBar"===g)throw new Error("Databars conditional formats are not supported.");return{type:g,priority:this.extractAttr(e,"priority",{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:null===(i=this.extractAttr(e,"dxfId"))||void 0===i?void 0:i.asNum(),stopIfTrue:null===(o=this.extractAttr(e,"stopIfTrue"))||void 0===o?void 0:o.asBool(),aboveAverage:null===(n=this.extractAttr(e,"aboveAverage"))||void 0===n?void 0:n.asBool(),percent:null===(s=this.extractAttr(e,"percent"))||void 0===s?void 0:s.asBool(),bottom:null===(r=this.extractAttr(e,"bottom"))||void 0===r?void 0:r.asBool(),operator:null===(a=this.extractAttr(e,"operator"))||void 0===a?void 0:a.asString(),text:null===(l=this.extractAttr(e,"text"))||void 0===l?void 0:l.asString(),timePeriod:null===(c=this.extractAttr(e,"timePeriod"))||void 0===c?void 0:c.asString(),rank:null===(h=this.extractAttr(e,"rank"))||void 0===h?void 0:h.asNum(),stdDev:null===(d=this.extractAttr(e,"stdDev"))||void 0===d?void 0:d.asNum(),equalAverage:null===(u=this.extractAttr(e,"equalAverage"))||void 0===u?void 0:u.asBool()}}))}extractCfFormula(e){return this.mapOnElements({parent:e,query:"formula"},(e=>this.extractTextContent(e,{required:!0})))}extractCfColorScale(e,t){const i=this.querySelector(e,"colorScale");if(i)return{colors:this.mapOnElements({parent:i,query:"color"},(e=>this.extractColor(e,t,"ffffff"))),cfvos:this.extractCFVos(i)}}extractCfIconSet(e){var t,i;const o=this.querySelector(e,"iconSet, x14:iconSet");if(o)return{iconSet:this.extractAttr(o,"iconSet",{default:"3TrafficLights1"}).asString(),showValue:this.extractAttr(o,"showValue",{default:!0}).asBool(),percent:this.extractAttr(o,"percent",{default:!0}).asBool(),reverse:null===(t=this.extractAttr(o,"reverse"))||void 0===t?void 0:t.asBool(),custom:null===(i=this.extractAttr(o,"custom"))||void 0===i?void 0:i.asBool(),cfvos:this.extractCFVos(o),cfIcons:this.extractCfIcons(o)}}extractCfIcons(e){const t=this.mapOnElements({parent:e,query:"cfIcon, x14:cfIcon"},(e=>({iconSet:this.extractAttr(e,"iconSet",{required:!0}).asString(),iconId:this.extractAttr(e,"iconId",{required:!0}).asNum()})));return 0===t.length?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:"cfvo, x14:cfvo"},(e=>{var t,i;return{type:this.extractAttr(e,"type",{required:!0}).asString(),gte:null===(t=this.extractAttr(e,"gte",{default:!0}))||void 0===t?void 0:t.asBool(),value:e.attributes.val?null===(i=this.extractAttr(e,"val"))||void 0===i?void 0:i.asString():this.extractChildTextContent(e,"f, xm:f")}}))}}class iv extends Jf{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},(e=>{const t=this.getChartType(e);if(!Gp[t])throw new Error(`Unsupported chart type ${t}`);const i=this.mapOnElements({parent:e,query:"c:title a:t"},(e=>e.textContent||"")).join(""),o=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString();return{title:i,type:Gp[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:Wp[this.extractChildAttr(e,"c:legendPos","val",{default:"b"}).asString()],stacked:"stacked"===o,fontColor:"000000"}}))[0]}extractChartDatasets(e){return this.mapOnElements({parent:e,query:"c:ser"},(e=>({label:this.extractChildTextContent(e,"c:cat c:f"),range:this.extractChildTextContent(e,"c:val c:f",{required:!0})})))}getChartType(e){const t=this.querySelector(e,"c:plotArea");if(!t)throw new Error("Missing plot area in the chart definition.");for(let e of t.children){const t=Yf(e.tagName);if(up.some((e=>e===t)))return t}throw new Error("Unknown chart type")}}class ov extends Jf{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},(e=>{if("twoCellAnchor"!==Yf(e.tagName))throw new Error("Only twoCellAnchor are supported for xlsx drawings.");const t=this.querySelector(e,"c:chart");if(!t)throw new Error("Only chart figures are currently supported.");return{anchors:[this.extractFigureAnchor("xdr:from",e),this.extractFigureAnchor("xdr:to",e)],data:this.extractChart(t)}}))}extractFigureAnchor(e,t){const i=this.querySelector(t,e);if(!i)throw new Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(i,"xdr:col",{required:!0})),colOffset:Number(this.extractChildTextContent(i,"xdr:colOff",{required:!0})),row:Number(this.extractChildTextContent(i,"xdr:row",{required:!0})),rowOffset:Number(this.extractChildTextContent(i,"xdr:rowOff",{required:!0}))}}extractChart(e){const t=this.extractAttr(e,"r:id",{required:!0}).asString(),i=this.getTargetXmlFile(this.relationships[t]),o=new iv(i,this.xlsxFileStructure,this.warningManager).extractChart();if(!o)throw new Error("Unable to extract chart definition");return o}}class nv extends Jf{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 sv extends Jf{getTable(){return this.mapOnElements({query:"table",parent:this.rootFile.file.xml},(e=>{var t;return{displayName:this.extractAttr(e,"displayName",{required:!0}).asString(),name:null===(t=this.extractAttr(e,"name"))||void 0===t?void 0:t.asString(),id:this.extractAttr(e,"id",{required:!0}).asString(),ref:this.extractAttr(e,"ref",{required:!0}).asString(),headerRowCount:this.extractAttr(e,"headerRowCount",{default:1}).asNum(),totalsRowCount:this.extractAttr(e,"totalsRowCount",{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)}}))[0]}extractTableCols(e){return this.mapOnElements({query:"tableColumn",parent:e},(e=>({id:this.extractAttr(e,"id",{required:!0}).asString(),name:this.extractAttr(e,"name",{required:!0}).asString(),colFormula:this.extractChildTextContent(e,"calculatedColumnFormula")})))}extractTableStyleInfo(e){return this.mapOnElements({query:"tableStyleInfo",parent:e},(e=>{var t,i,o,n,s;return{name:null===(t=this.extractAttr(e,"name"))||void 0===t?void 0:t.asString(),showFirstColumn:null===(i=this.extractAttr(e,"showFirstColumn"))||void 0===i?void 0:i.asBool(),showLastColumn:null===(o=this.extractAttr(e,"showLastColumn"))||void 0===o?void 0:o.asBool(),showRowStripes:null===(n=this.extractAttr(e,"showRowStripes"))||void 0===n?void 0:n.asBool(),showColumnStripes:null===(s=this.extractAttr(e,"showColumnStripes"))||void 0===s?void 0:s.asBool()}}))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:"autoFilter",parent:e},(e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,"ref",{required:!0}).asString()})))[0]}extractFilterColumns(e){return this.mapOnElements({query:"tableColumn",parent:e},(t=>({colId:this.extractAttr(e,"colId",{required:!0}).asNum(),hiddenButton:this.extractAttr(e,"hiddenButton",{default:!1}).asBool(),filters:this.extractSimpleFilter(t)})))}extractSimpleFilter(e){return this.mapOnElements({query:"filter",parent:e},(e=>({val:this.extractAttr(e,"val",{required:!0}).asString()})))}}class rv extends Jf{constructor(e,t,i,o){super(e,t,i),this.theme=o}getSheet(){return this.mapOnElements({query:"worksheet",parent:this.rootFile.file.xml},(e=>{const t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:[...this.extractTables(e),...this.extractPivotTables()],isVisible:"visible"===t.state}}))[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:"sheetView"},(e=>{const t=this.querySelector(e,"pane");return{tabSelected:this.extractAttr(e,"tabSelected",{default:!1}).asBool(),showFormulas:this.extractAttr(e,"showFormulas",{default:!1}).asBool(),showGridLines:this.extractAttr(e,"showGridLines",{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,"showRowColHeaders",{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,"xSplit",{default:0}).asNum():0,ySplit:t?this.extractAttr(t,"ySplit",{default:0}).asNum():0}}}))}extractSheetName(){const e=Qp(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=Qp(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id,i=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:"sheet"},(e=>({relationshipId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetId:this.extractAttr(e,"sheetId",{required:!0}).asString(),sheetName:this.extractAttr(e,"name",{required:!0}).asString(),state:this.extractAttr(e,"state",{default:"visible"}).asString()}))).find((e=>e.relationshipId===t));if(!i)throw new Error("Cannot find corresponding workbook sheet");return i}extractConditionalFormats(){return new tv(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractFigures(e){return this.mapOnElements({parent:e,query:"drawing"},(e=>{var t;const i=null===(t=this.extractAttr(e,"r:id",{required:!0}))||void 0===t?void 0:t.asString(),o=this.getTargetXmlFile(this.relationships[i]);return new ov(o,this.xlsxFileStructure,this.warningManager).extractFigures()}))[0]||[]}extractTables(e){return this.mapOnElements({query:"tablePart",parent:e},(e=>{var t;const i=null===(t=this.extractAttr(e,"r:id",{required:!0}))||void 0===t?void 0:t.asString(),o=this.getTargetXmlFile(this.relationships[i]);return new sv(o,this.xlsxFileStructure,this.warningManager).getTable()}))}extractPivotTables(){try{return Object.values(this.relationships).filter((e=>e.type.endsWith("pivotTable"))).map((e=>{const t=this.getTargetXmlFile(e);return new nv(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:yp.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:xp.toString()}).asNum()}}extractCols(e){return this.mapOnElements({parent:e,query:"cols col"},(e=>{var t,i,o,n,s,r,a;return{width:null===(t=this.extractAttr(e,"width"))||void 0===t?void 0:t.asNum(),customWidth:null===(i=this.extractAttr(e,"customWidth"))||void 0===i?void 0:i.asBool(),bestFit:null===(o=this.extractAttr(e,"bestFit"))||void 0===o?void 0:o.asBool(),hidden:null===(n=this.extractAttr(e,"hidden"))||void 0===n?void 0:n.asBool(),min:null===(s=this.extractAttr(e,"min",{required:!0}))||void 0===s?void 0:s.asNum(),max:null===(r=this.extractAttr(e,"max",{required:!0}))||void 0===r?void 0:r.asNum(),styleIndex:null===(a=this.extractAttr(e,"style"))||void 0===a?void 0:a.asNum()}}))}extractRows(e){return this.mapOnElements({parent:e,query:"sheetData row"},(e=>{var t,i,o,n,s;return{index:null===(t=this.extractAttr(e,"r",{required:!0}))||void 0===t?void 0:t.asNum(),cells:this.extractCells(e),height:null===(i=this.extractAttr(e,"ht"))||void 0===i?void 0:i.asNum(),customHeight:null===(o=this.extractAttr(e,"customHeight"))||void 0===o?void 0:o.asBool(),hidden:null===(n=this.extractAttr(e,"hidden"))||void 0===n?void 0:n.asBool(),styleIndex:null===(s=this.extractAttr(e,"s"))||void 0===s?void 0:s.asNum()}}))}extractCells(e){return this.mapOnElements({parent:e,query:"c"},(e=>{var t,i,o;return{xc:null===(t=this.extractAttr(e,"r",{required:!0}))||void 0===t?void 0:t.asString(),styleIndex:null===(i=this.extractAttr(e,"s"))||void 0===i?void 0:i.asNum(),type:Up[null===(o=this.extractAttr(e,"t",{default:"n"}))||void 0===o?void 0:o.asString()],value:this.extractChildTextContent(e,"v"),formula:this.extractCellFormula(e)}}))}extractCellFormula(e){var t,i;const o=this.querySelector(e,"f");if(o)return{content:this.extractTextContent(o),sharedIndex:null===(t=this.extractAttr(o,"si"))||void 0===t?void 0:t.asNum(),ref:null===(i=this.extractAttr(o,"ref"))||void 0===i?void 0:i.asString()}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:"hyperlink"},(e=>{var t,i,o,n;const s=null===(t=this.extractAttr(e,"r:id"))||void 0===t?void 0:t.asString();return{xc:null===(i=this.extractAttr(e,"ref",{required:!0}))||void 0===i?void 0:i.asString(),location:null===(o=this.extractAttr(e,"location"))||void 0===o?void 0:o.asString(),display:null===(n=this.extractAttr(e,"display"))||void 0===n?void 0:n.asString(),relTarget:s?this.relationships[s].target:void 0}}))}extractSharedFormulas(e){const t=this.querySelectorAll(e,"f[si][ref]"),i={};for(let e of t){const t=this.extractAttr(e,"si",{required:!0}).asNum(),o=this.extractTextContent(e,{required:!0});i[t]=o}const o=[];for(let e=0;e<Object.keys(i).length;e++)i[e]?o.push(i[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),o.push(""));return o}}class av extends Jf{constructor(e,t,i){super(e.styles,e,t),this.theme=i}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"numFmt"},(e=>this.extractNumFormats(e)))}extractNumFormats(e){return{id:this.extractAttr(e,"numFmtId",{required:!0}).asNum(),format:this.extractAttr(e,"formatCode",{required:!0,default:""}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"font"},(e=>this.extractFont(e)))}extractFont(e){var t,i,o,n;const s=this.extractChildAttr(e,"name","val",{default:"Arial"}).asString(),r=this.extractChildAttr(e,"sz","val",{default:G.toString()}).asNum(),a=this.extractColor(this.querySelector(e,"color"),this.theme),l=this.querySelector(e,"i")||void 0,c=l&&"0"!==(null===(t=l.attributes.val)||void 0===t?void 0:t.value),h=this.querySelector(e,"b")||void 0,d=h&&"0"!==(null===(i=h.attributes.val)||void 0===i?void 0:i.value),u=this.querySelector(e,"strike")||void 0,g=u&&"0"!==(null===(o=u.attributes.val)||void 0===o?void 0:o.value),p=this.querySelector(e,"u")||void 0;return{name:s,size:r,color:a,italic:c,bold:d,underline:p&&"none"!==(null===(n=p.attributes.val)||void 0===n?void 0:n.value),strike:g}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"fill"},(e=>this.extractFill(e)))}extractFill(e){var t;const i=e.children[0];return"patternFill"===i.tagName?{patternType:null===(t=i.attributes.patternType)||void 0===t?void 0:t.value,bgColor:this.extractColor(this.querySelector(i,"bgColor"),this.theme),fgColor:this.extractColor(this.querySelector(i,"fgColor"),this.theme)}:{patternType:"solid",fgColor:this.extractColor(this.querySelectorAll(i,"color")[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"border"},(e=>this.extractBorder(e)))}extractBorder(e){var t,i;const o={left:this.extractSingleBorder(e,"left",this.theme),right:this.extractSingleBorder(e,"right",this.theme),top:this.extractSingleBorder(e,"top",this.theme),bottom:this.extractSingleBorder(e,"bottom",this.theme),diagonal:this.extractSingleBorder(e,"diagonal",this.theme)};return o.diagonal&&(o.diagonalUp=null===(t=this.extractAttr(e,"diagonalUp"))||void 0===t?void 0:t.asBool(),o.diagonalDown=null===(i=this.extractAttr(e,"diagonalDown"))||void 0===i?void 0:i.asBool()),o}extractSingleBorder(e,t,i){const o=this.querySelector(e,t);if(o&&o.attributes.style)return{style:this.extractAttr(o,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(o.children[0],i,"000000")}}extractAlignment(e){var t,i,o,n,s,r,a;return{horizontal:this.extractAttr(e,"horizontal",{default:"general"}).asString(),vertical:this.extractAttr(e,"vertical",{default:"center"}).asString(),textRotation:null===(t=this.extractAttr(e,"textRotation"))||void 0===t?void 0:t.asNum(),wrapText:null===(i=this.extractAttr(e,"wrapText"))||void 0===i?void 0:i.asBool(),indent:null===(o=this.extractAttr(e,"indent"))||void 0===o?void 0:o.asNum(),relativeIndent:null===(n=this.extractAttr(e,"relativeIndent"))||void 0===n?void 0:n.asNum(),justifyLastLine:null===(s=this.extractAttr(e,"justifyLastLine"))||void 0===s?void 0:s.asBool(),shrinkToFit:null===(r=this.extractAttr(e,"shrinkToFit"))||void 0===r?void 0:r.asBool(),readingOrder:null===(a=this.extractAttr(e,"readingOrder"))||void 0===a?void 0:a.asNum()}}getDxfs(){return this.mapOnElements({query:"dxf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"font"),i=this.querySelector(e,"fill"),o=this.querySelector(e,"border"),n=this.querySelector(e,"numFmt"),s=this.querySelector(e,"alignment");return{font:t?this.extractFont(t):void 0,fill:i?this.extractFill(i):void 0,numFmt:n?this.extractNumFormats(n):void 0,alignment:s?this.extractAlignment(s):void 0,border:o?this.extractBorder(o):void 0}}))}getStyles(){return this.mapOnElements({query:"cellXfs xf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"alignment");return{fontId:this.extractAttr(e,"fontId",{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,"fillId",{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,"borderId",{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,"numFmtId",{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}}))}}class lv extends Jf{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"externalBook"},(e=>({rId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:"sheetName"},(e=>this.extractAttr(e,"val",{required:!0}).asString())),datasets:this.extractExternalSheetData(e)})))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:"sheetData"},(e=>{const t=this.mapOnElements({parent:e,query:"cell"},(e=>({xc:this.extractAttr(e,"r",{required:!0}).asString(),value:this.extractChildTextContent(e,"v",{required:!0})}))),i={};for(let e of t)i[e.xc]=e.value;return{sheetId:this.extractAttr(e,"sheetId",{required:!0}).asNum(),data:i}}))}}function cv(e,t){const i=function(e,t){const i=t[Op],o=i.querySelectorAll(`Override[ContentType="${e}"]`),n=[];for(let e of o){const t=null==e?void 0:e.attributes.PartName.value;n.push(t.substring(1))}return n}(e,t);return function(e,t){const i=[];for(let o of e){const e=hv(o,t);i.push({file:{fileName:o,xml:t[o]},rels:e?{fileName:e,xml:t[e]}:void 0})}return i}(i,t)}function hv(e,t){if(e===Op)return"_rels/.rels";let i="";const o=e.split("/");for(let e=0;e<o.length-1;e++)i+=o[e]+"/";return i+="_rels/",i+=o[o.length-1]+".rels",t[i]||(i=void 0),i}class dv{constructor(e){this.warningManager=new _p,this.xmls={};for(let t of Object.keys(e))(t.endsWith(".xml")||t.endsWith(".rels"))&&(this.xmls[t]=qf(new dp(e[t])))}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new ev(e.theme,e,this.warningManager).getTheme():void 0,i=e.sharedStrings?new ev(e.sharedStrings,e,this.warningManager).getSharedStrings():[],o=e.sheets.sort(((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0}))).map((i=>new rv(i,e,this.warningManager,t).getSheet())),n=e.externalLinks.map((t=>new lv(t,e,this.warningManager).getExternalBook())),s=new av(e,this.warningManager,t);return{fonts:s.getFonts(),fills:s.getFills(),borders:s.getBorders(),dxfs:s.getDxfs(),numFmts:s.getNumFormats(),styles:s.getStyles(),sheets:o,sharedStrings:i,externalBooks:n}}buildXlsxFileStructure(){const e={sheets:cv(bp.sheet,this.xmls),workbook:cv(bp.workbook,this.xmls)[0],styles:cv(bp.styles,this.xmls)[0],sharedStrings:cv(bp.sharedStrings,this.xmls)[0],theme:cv(bp.themes,this.xmls)[0],charts:cv(bp.chart,this.xmls),figures:cv(bp.drawing,this.xmls),tables:cv(bp.table,this.xmls),pivots:cv(bp.pivot,this.xmls),externalLinks:cv(bp.externalLink,this.xmls)};if(!e.workbook.rels)throw Error(s("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:12,sheets:_f(e,this.warningManager),styles:rm(e,this.warningManager),formats:lm(e,this.warningManager),borders:nm(e,this.warningManager),entities:{},revisionId:K};return zf(t,e),Object.keys(e.styles).map((t=>{e.styles[t]=lt(e.styles[t])})),t}}function uv(e){const t=Jm(e);let i=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&Tt.test(e.value)){const t=e.value.trim();return i.includes(t)||i.push(t),`${re}${i.indexOf(t)}${re}`}return e.value}))),dependencies:i}}const gv=12,pv="Sheet1";function mv(e,t){if(!e)return Cv();if(e["[Content_Types].xml"]){const i=new dv(e);if(e=i.convertXlsx(),t)for(let e of i.warningManager.warnings.sort())console.warn(e)}return"version"in(e=Ne(e))&&e.version<gv&&(e=function(e){for(let t=fv.findIndex((t=>t.from===e.version));t<fv.length;t++)e=fv[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,i=new Di;for(const o of e.sheets||[])for(const e of o.figures||[])t.has(e.id)&&(e.id+=i.uuidv4()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){e=Object.assign(Cv(),e,{version:gv}),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(pv,"Sheet1"));return e}(e),e}(e),e}const fv=[{description:"add the `activeSheet` field on data",from:1,to:2,applyMigration:e=>(e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e)},{description:"add an id field in each sheet",from:2,to:3,applyMigration(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}},{description:"activeSheet is now an id, not the name of a sheet",from:3,to:4,applyMigration(e){if(e.sheets&&e.activeSheet){const t=e.sheets.find((t=>t.name===e.activeSheet));e.activeSheet=t.id}return e}},{description:"add figures object in each sheets",from:4,to:5,applyMigration(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}},{description:"normalize the content of the cell if it is a formula to avoid parsing all the formula that vary only by the cells they use",from:5,to:6,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const i=t.cells[e];i.content&&i.content.startsWith("=")&&(i.formula=uv(i.content))}return e}},{description:"transform chart data structure",from:6,to:7,applyMigration(e){for(let t of e.sheets||[])for(let e in t.figures||[]){const{dataSets:i,...o}=t.figures[e].data,n=[];for(let e of i)if(e.labelCell){const t=Li(e.dataRange),i=e.labelCell+":"+Bt(t.right,t.bottom);n.push(i)}else n.push(e.dataRange);o.dataSetsHaveTitle=Boolean(i[0].labelCell),o.dataSets=n,t.figures[e].data=o}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){var t;const i=[],o=new RegExp(se,"g");for(let n of e.sheets||[]){if(!n.name)continue;const e=n.name,s=e.replace(o,"_");let r=1,a=s;for(;i.includes(a);)a=`${s}${r}`,r++;n.name=a,i.push(a);const l=t=>{if(void 0===t)return t;let i=t.replace(e,a),o=t;for(;o!==i;)o=i,i=o.replace(e,a);return o};for(let e in n.cells){const t=n.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(l))}for(let e of n.figures||[])if("chart"===e.type){const t=e.data.dataSets.map(l),i=l(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:i}}for(let e of n.conditionalFormats||[]){e.ranges=e.ranges.map(l);for(const i of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===(null===(t=e.rule[i])||void 0===t?void 0:t.type)&&(e.rule[i].value=l(e.rule[i].value))}}return e}},{description:"transform chart data structure with design attributes",from:8,to:9,applyMigration(e){for(const t of e.sheets||[])for(const e of t.figures||[])e.data.background=w,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stacked=!1;return e}},{description:"de-normalize formula to reduce exported json size (~30%)",from:9,to:10,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const i=t.cells[e];if(i.formula){let{text:e,dependencies:t}=i.formula;for(let[i,o]of Object.entries(t)){const t=`\\${re}${i}\\${re}`;e=e.replace(new RegExp(t,"g"),o)}i.content=e,delete i.formula}}return e}},{description:"normalize the formats of the cells",from:10,to:11,applyMigration(e){const t={};for(let i of e.sheets||[])for(let e in i.cells||[]){const o=i.cells[e];o.format&&(o.format=it(o.format,t))}return e.formats=t,e}},{description:"Add isVisible to sheets",from:11,to:12,applyMigration(e){for(let t of e.sheets||[])t.isVisible=!0;return e}}];function vv(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const i=[],o=[],n=e=>{if("CREATE_SHEET"===e.type)i.push(e.sheetId);else if("sheetId"in e&&!i.includes(e.sheetId))return{...e,sheetId:pv};return e};for(const e of t)"REMOTE_REVISION"===e.type?o.push({...e,commands:e.commands.map(n)}):o.push(e);return o}(e,t),t=bv(t,"SORT_CELLS"),t=function(e,t){var i;const o=[],n={};for(const t of e.sheets||[])null===(i=t.figures)||void 0===i||i.forEach((e=>{"chart"===e.tag&&(n[e.id]=e.data)}));for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const i of e.commands){let e=i;switch(i.type){case"CREATE_CHART":n[i.id]=i.definition;break;case"UPDATE_CHART":if(!n[i.id]){console.log(`Fix chart definition: chart with id ${i.id} not found.`);continue}const t={...n[i.id],...i.definition};e={...i,definition:t},n[i.id]=t}t.push(e)}o.push({...e,commands:t})}else o.push(e);return o}(e,t=bv(t,"SET_DECIMAL")),t}function bv(e,t){const i=[];for(const o of e)"REMOTE_REVISION"===o.type?i.push({...o,commands:o.commands.filter((e=>e.type!==t))}):i.push(o);return i}function Sv(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[],filterTables:[],isVisible:!0}}function Cv(e="Sheet1"){return{version:gv,sheets:[Sv(pv,e)],entities:{},styles:{},formats:{},borders:{},revisionId:K,uniqueFigureIds:!0}}function Ev(e,t){return{...Sv(e,t),charts:[],images:[]}}class wv{constructor(e,t){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t}exportForExcel(e){}allowDispatch(e){return 0}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map((e=>e.call(this,t))).flat()}chainValidations(...e){return t=>{for(const i of e){let e=i.call(this,t);Array.isArray(e)||(e=[e]);const o=e.filter((e=>0!==e));if(o.length)return o}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}wv.getters=[];class yv extends wv{constructor({getters:e,stateObserver:t,range:i,dispatch:o,uuidGenerator:n}){super(t,o),this.range=i,i.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=n}import(e){}export(e){}adaptRanges(e,t){}garbageCollectExternalResources(){}}class xv extends yv{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 i=t.slice().map((e=>null==e?void 0:e.slice().map((e=>({...e})))));this.history.update("borders",e.sheetIdTo,i)}break;case"DELETE_SHEET":const i={...this.borders};delete i[e.sheetId],this.history.update("borders",i);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_FORMATTING":if(e.border){const t=e.target.map((t=>this.getters.expandZone(e.sheetId,t)));this.setBorders(e.sheetId,t,e.border)}break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target);break;case"REMOVE_COLUMNS_ROWS":for(let t of e.elements)"COL"===e.dimension?this.shiftBordersHorizontally(e.sheetId,t+1,-1):this.shiftBordersVertically(e.sheetId,t+1,-1);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumns(e):this.handleAddRows(e)}}handleAddColumns(e){let t,i;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),t=e.base-1,i=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),t=e.base,i=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,i)}handleAddRows(e){let t,i;"before"===e.position?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity,{moveFirstTopBorder:!0}),t=e.base-1,i=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity,{moveFirstTopBorder:!1}),t=e.base,i=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,i)}getCellBorder({sheetId:e,col:t,row:i}){var o,n,s,r,a,l,c,h,d,u,g,p;const m={top:null===(s=null===(n=null===(o=this.borders[e])||void 0===o?void 0:o[t])||void 0===n?void 0:n[i])||void 0===s?void 0:s.horizontal,bottom:null===(l=null===(a=null===(r=this.borders[e])||void 0===r?void 0:r[t])||void 0===a?void 0:a[i+1])||void 0===l?void 0:l.horizontal,left:null===(d=null===(h=null===(c=this.borders[e])||void 0===c?void 0:c[t])||void 0===h?void 0:h[i])||void 0===d?void 0:d.vertical,right:null===(p=null===(g=null===(u=this.borders[e])||void 0===u?void 0:u[t+1])||void 0===g?void 0:g[i])||void 0===p?void 0:p.vertical};return m.bottom||m.left||m.right||m.top?m:null}ensureColumnBorderContinuity(e,t,i){const o=ze(t+1,i);for(let n=0;n<this.getters.getNumberRows(e);n++){const s=this.getCellBorder({sheetId:e,col:t,row:n}),r=this.getCellBorder({sheetId:e,col:i,row:n});if(s&&r){const t=this.getCommonSides(s,r);for(let i of o)this.addBorder(e,i,n,t)}}}ensureRowBorderContinuity(e,t,i){const o=ze(t+1,i);for(let n=0;n<this.getters.getNumberCols(e);n++){const s=this.getCellBorder({sheetId:e,col:n,row:t}),r=this.getCellBorder({sheetId:e,col:n,row:i});if(s&&r){const t=this.getCommonSides(s,r);for(let i of o)this.addBorder(e,n,i,t)}}}getCommonSides(e,t){const i={};for(let o of["top","bottom","left","right"])e[o]&&e[o]===t[o]&&(i[o]=e[o]);return i}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsRange(e){return this.borders[e]?ze(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,i,{moveFirstLeftBorder:o}={}){this.borders[e]&&(i<0&&this.moveBordersOfColumn(e,t,i,"vertical",{destructive:!1}),this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>i<0?e-t:t-e)).forEach((n=>{(n===t&&o||n!==t)&&this.moveBordersOfColumn(e,n,i,"vertical"),this.moveBordersOfColumn(e,n,i,"horizontal")})))}shiftBordersVertically(e,t,i,{moveFirstTopBorder:o}={}){this.borders[e]&&(i<0&&this.moveBordersOfRow(e,t,i,"horizontal",{destructive:!1}),this.getRowsRange(e).filter((e=>e>=t)).sort(((e,t)=>i<0?e-t:t-e)).forEach((n=>{(n===t&&o||n!==t)&&this.moveBordersOfRow(e,n,i,"horizontal"),this.moveBordersOfRow(e,n,i,"vertical")})))}moveBordersOfRow(e,t,i,o,{destructive:n}={destructive:!0}){const s=this.borders[e];s&&this.getColumnsWithBorders(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=s[r])||void 0===a?void 0:a[t+i])||void 0===l?void 0:l[o],u=null===(h=null===(c=s[r])||void 0===c?void 0:c[t])||void 0===h?void 0:h[o];this.history.update("borders",e,r,t+i,o,n?u:u||d),this.history.update("borders",e,r,t,o,void 0)}))}moveBordersOfColumn(e,t,i,o,{destructive:n}={destructive:!0}){const s=this.borders[e];s&&this.getRowsRange(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=s[t+i])||void 0===a?void 0:a[r])||void 0===l?void 0:l[o],u=null===(h=null===(c=s[t])||void 0===c?void 0:c[r])||void 0===h?void 0:h[o];this.history.update("borders",e,t+i,r,o,n?u:u||d),this.history.update("borders",e,t,r,o,void 0)}))}setBorder(e,t,i,o,n=!0){var s,r,a,l,c,h,d,u,g,p,m,f,v,b,S,C;!n&&(null===(l=null===(a=null===(r=null===(s=this.borders)||void 0===s?void 0:s[e])||void 0===r?void 0:r[t])||void 0===a?void 0:a[i])||void 0===l?void 0:l.vertical)||this.history.update("borders",e,t,i,"vertical",null==o?void 0:o.left),!n&&(null===(u=null===(d=null===(h=null===(c=this.borders)||void 0===c?void 0:c[e])||void 0===h?void 0:h[t])||void 0===d?void 0:d[i])||void 0===u?void 0:u.horizontal)||this.history.update("borders",e,t,i,"horizontal",null==o?void 0:o.top),!n&&(null===(f=null===(m=null===(p=null===(g=this.borders)||void 0===g?void 0:g[e])||void 0===p?void 0:p[t+1])||void 0===m?void 0:m[i])||void 0===f?void 0:f.vertical)||this.history.update("borders",e,t+1,i,"vertical",null==o?void 0:o.right),!n&&(null===(C=null===(S=null===(b=null===(v=this.borders)||void 0===v?void 0:v[e])||void 0===b?void 0:b[t])||void 0===S?void 0:S[i+1])||void 0===C?void 0:C.horizontal)||this.history.update("borders",e,t,i+1,"horizontal",null==o?void 0:o.bottom)}clearBorders(e,t){for(let i of t){for(let t=i.top;t<=i.bottom;t++){this.history.update("borders",e,i.right+1,t,"vertical",void 0);for(let o=i.left;o<=i.right;o++)this.history.update("borders",e,o,t,void 0)}for(let t=i.left;t<=i.right;t++)this.history.update("borders",e,t,i.bottom+1,"horizontal",void 0)}}addBorder(e,t,i,o){this.setBorder(e,t,i,{...this.getCellBorder({sheetId:e,col:t,row:i}),...o})}setBorders(e,t,i){if("clear"===i)return this.clearBorders(e,t);for(let o of t){if("h"===i||"hv"===i||"all"===i)for(let t=o.top+1;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++)this.addBorder(e,i,t,{top:Z});if("v"===i||"hv"===i||"all"===i)for(let t=o.top;t<=o.bottom;t++)for(let i=o.left+1;i<=o.right;i++)this.addBorder(e,i,t,{left:Z});if("left"===i||"all"===i||"external"===i)for(let t=o.top;t<=o.bottom;t++)this.addBorder(e,o.left,t,{left:Z});if("right"===i||"all"===i||"external"===i)for(let t=o.top;t<=o.bottom;t++)this.addBorder(e,o.right+1,t,{left:Z});if("top"===i||"all"===i||"external"===i)for(let t=o.left;t<=o.right;t++)this.addBorder(e,t,o.top,{top:Z});if("bottom"===i||"all"===i||"external"===i)for(let t=o.left;t<=o.right;t++)this.addBorder(e,t,o.bottom+1,{top:Z})}}addBordersToMerge(e,t){const{left:i,right:o,top:n,bottom:s}=t,r=this.getCellBorder({sheetId:e,col:i,row:n}),a=this.getCellBorder({sheetId:e,col:o,row:s});this.clearBorders(e,[t]),(null==r?void 0:r.top)&&this.setBorders(e,[{...t,bottom:n}],"top"),(null==r?void 0:r.left)&&this.setBorders(e,[{...t,right:i}],"left"),((null==a?void 0:a.bottom)||(null==r?void 0:r.bottom))&&this.setBorders(e,[{...t,top:s}],"bottom"),((null==a?void 0:a.right)||(null==r?void 0:r.right))&&this.setBorders(e,[{...t,left:o}],"right")}import(e){if(e.borders)for(let t of e.sheets)for(let[i,o]of Object.entries(t.cells))if(null==o?void 0:o.border){const n=e.borders[o.border],{col:s,row:r}=zt(i);this.setBorder(t.id,s,r,n,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Li(e))}export(e){let t=0;const i={};function o(e){for(let[t,o]of Object.entries(i))if(Ae(o)===Ae(e))return parseInt(t,10);return i[++t]=e,t}for(let t of e.sheets)for(let e=0;e<t.colNumber;e++)for(let i=0;i<t.rowNumber;i++){const n=this.getCellBorder({sheetId:t.id,col:e,row:i});if(n){const s=Bt(e,i),r=t.cells[s],a=o(n);r?r.border=a:t.cells[s]={border:a}}}e.borders=i}exportForExcel(e){this.export(e)}}xv.getters=["getCellBorder"];class Iv extends yv{constructor(){super(...arguments),this.nextId=1,this.cells={}}adaptRanges(e,t){for(const i of Object.keys(this.cells))for(const o of Object.values(this.cells[i]||{}))if(o.isFormula)for(const n of o.dependencies)if(!t||n.sheetId===t){const t=e(n);"NONE"!==t.changeType&&this.history.update("cells",i,o.id,"dependencies",o.dependencies.indexOf(n),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":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,i){for(let o of t)for(let t=o.top;t<=o.bottom;t++)for(let n=o.left;n<=o.right;n++)this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,format:i})}clearFormatting(e,t){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let o=i.top;o<=i.bottom;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,style:null,format:""})}handleAddColumnsRows(e,t){let i,o;"before"===e.position?(i=ze(e.base,e.base+e.quantity),o=e.base+e.quantity):(i=ze(e.base+1,e.base+e.quantity+1),o=e.base),t(e.sheetId,o,i)}import(e){for(let t of e.sheets)for(let i in t.cells){const o=t.cells[i],{col:n,row:s}=zt(i);if((null==o?void 0:o.content)||(null==o?void 0:o.format)||(null==o?void 0:o.style)){const i=this.importCell(t.id,o,e.styles,e.formats);this.history.update("cells",t.id,i.id,i),this.dispatch("UPDATE_CELL_POSITION",{cellId:i.id,col:n,row:s,sheetId:t.id})}}}export(e){const t={},i={};for(let o of e.sheets){const e={},n=Object.keys(this.cells[o.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const o of n){const n=this.getters.getCell(o);e[Bt(o.col,o.row)]={style:n.style?it(n.style,t):void 0,format:n.format?it(n.format,i):void 0,content:n.content||void 0}}o.cells=e}e.styles=t,e.formats=i}importCell(e,t,i,o){const n=t.style&&i[t.style]||void 0,s=t.format&&o[t.format]||void 0,r=this.getNextUid();return this.createCell(r,(null==t?void 0:t.content)||"",s,n,e)}exportForExcel(e){this.export(e)}getCells(e){return this.cells[e]||{}}getCellById(e){for(const t in this.cells){const i=this.cells[t][e];if(i)return i}}buildFormulaContent(e,t,i){const o=i||[...t.dependencies];return ot(t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=o.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,i=[{colFixed:!1,rowFixed:!1}]){const o=Bt((t=this.getters.expandZone(e,t)).left,t.top,i[0]),n=Bt(t.right,t.bottom,i.length>1?i[1]:i[0]),s=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),r=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=s.col===r.col&&s.row===r.row;return o==n||a?o:o+":"+n}setStyle(e,t,i){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let n=o.top;n<=o.bottom;n++){const o=this.getters.getCell({sheetId:e,col:t,row:n});this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,style:i?{...null==o?void 0:o.style,...i}:void 0})}}copyColumnStyle(e,t,i){for(let o=0;o<this.getters.getNumberRows(e);o++){const n=this.getFormat(e,t,o);if(n.style||n.format)for(let t of i)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,...n})}}copyRowStyle(e,t,i){for(let o=0;o<this.getters.getNumberCols(e);o++){const n=this.getFormat(e,o,t);if(n.style||n.format)for(let t of i)this.dispatch("UPDATE_CELL",{sheetId:e,col:o,row:t,...n})}}getFormat(e,t,i){const o={},n=this.getters.getMainCellPosition({sheetId:e,col:t,row:i}),s=this.getters.getCell(n);return s&&(s.style&&(o.style=s.style),s.format&&(o.format=s.format)),o}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,i,o){const n=this.getters.getCell({sheetId:e,col:t,row:i}),s="content"in o||"formula"in o,r=s?gt(null==o?void 0:o.content):(null==n?void 0:n.content)||"";let a;a=void 0!==o.style?o.style||void 0:n?n.style:void 0;let l=("format"in o?o.format:n&&n.format)||Ei(r);if((s&&!r&&!o.formula||!s&&(!n||""===n.content))&&!a&&!l)return void(n&&(this.history.update("cells",e,n.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:i,sheetId:e})));const c=(null==n?void 0:n.id)||this.getNextUid(),h=this.createCell(c,r,l,a,e);this.history.update("cells",e,h.id,h),this.dispatch("UPDATE_CELL_POSITION",{cellId:h.id,col:t,row:i,sheetId:e})}createCell(e,t,i,o,n){if(!t.startsWith("="))return this.createLiteralCell(e,t,i,o);try{return this.createFormulaCell(e,t,i,o,n)}catch(n){return this.createErrorFormula(e,t,i,o,n)}}createLiteralCell(e,t,i,o){return{id:e,content:t,style:o,format:i,isFormula:!1}}createFormulaCell(e,t,i,o,n){const s=sf(t);return s.dependencies.length?this.createFormulaCellWithDependencies(e,s,i,o,n):{id:e,content:t,style:o,format:i,isFormula:!0,compiledFormula:s,dependencies:[]}}createFormulaCellWithDependencies(e,t,i,o,n){const s=t.dependencies.map((e=>this.getters.getRangeFromSheetXC(n,e))),r=this.buildFormulaContent.bind(this);return{id:e,get content(){return r(n,{dependencies:this.dependencies,compiledFormula:this.compiledFormula})},style:o,format:i,isFormula:!0,compiledFormula:t,dependencies:s}}createErrorFormula(e,t,i,o,n){return{id:e,content:t,style:o,format:i,isFormula:!0,compiledFormula:{dependencies:[],tokens:Em(t),execute:function(){throw n}},dependencies:[]}}checkCellOutOfSheet(e,t,i){if(!this.getters.tryGetSheet(e))return 27;return Zi(t,i,this.getters.getSheetZone(e))?0:18}}Iv.getters=["zoneToXC","getCells","getFormulaCellContent","getCellStyle","buildFormulaContent","getCellById"];class Rv extends yv{constructor(){super(...arguments),this.charts={},this.createChart=function(e){const t=nr.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(i,o,n){const s=t.find((e=>e.match(o.type)));if(!s)throw new Error(`No builder for this chart: ${o.type}`);return s.createChart(o,n,e)}}(this.getters),this.validateChartDefinition=e=>function(e,t){const i=nr.getAll().find((e=>e.match(t.type)));if(!i)throw new Error("Unknown chart type.");return i.validateChartDefinition(e,t)}(this,e.definition)}adaptRanges(e){for(const[t,i]of Object.entries(this.charts))this.history.update("charts",t,null==i?void 0:i.updateRanges(e))}allowDispatch(e){switch(e.type){case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists));default:return 0}}handle(e){var t;switch(e.type){case"CREATE_CHART":this.addFigure(e.id,e.sheetId,e.position,e.size),this.addChart(e.id,e.definition);break;case"UPDATE_CHART":this.addChart(e.id,e.definition);break;case"DUPLICATE_SHEET":{const i=this.getters.getFigures(e.sheetId);for(const o of i)if("chart"===o.tag){const i=o.id.split(J).pop(),n=`${e.sheetIdTo}${J}${i}`,s=null===(t=this.charts[o.id])||void 0===t?void 0:t.copyForSheetId(e.sheetIdTo);s&&this.dispatch("CREATE_CHART",{id:n,position:{x:o.x,y:o.y},size:{width:o.width,height:o.height},definition:s.getDefinition(),sheetId:e.sheetIdTo})}break}case"DELETE_FIGURE":this.history.update("charts",e.id,void 0);break;case"DELETE_SHEET":for(let t of this.getChartIds(e.sheetId))this.history.update("charts",t,void 0)}}getContextCreationChart(e){var t;return null===(t=this.charts[e])||void 0===t?void 0:t.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){var t;const i=null===(t=this.charts[e])||void 0===t?void 0:t.type;if(!i)throw new Error("Chart not defined.");return i}isChartDefined(e){return e in this.charts&&void 0!==this.charts}getChartIds(e){return Object.entries(this.charts).filter((([,t])=>(null==t?void 0:t.sheetId)===e)).map((([e])=>e))}getChartDefinition(e){var t;const i=null===(t=this.charts[e])||void 0===t?void 0:t.getDefinition();if(!i)throw new Error(`There is no chart with the given figureId: ${e}`);return i}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)"chart"===e.tag&&(this.charts[e.id]=this.createChart(e.id,e.data,t.id))}export(e){var t;if(e.sheets)for(let i of e.sheets){const e=this.getters.getFigures(i.id),o=[];for(let i of e){const e=i;if(e&&"chart"===e.tag){const i=null===(t=this.charts[e.id])||void 0===t?void 0:t.getDefinition();i&&(e.data=i,o.push(e))}else o.push(e)}i.figures=o}}exportForExcel(e){var t;for(let i of e.sheets){const e=this.getters.getFigures(i.id),o=[];for(let i of e)if(i&&"chart"===i.tag){const e=null===(t=this.charts[i.id])||void 0===t?void 0:t.getDefinitionForExcel();e&&o.push({...i,data:e})}i.charts=o}}addFigure(e,t,i={x:0,y:0},o={width:536,height:335}){if(this.getters.getFigure(t,e))return;const n={id:e,x:i.x,y:i.y,width:o.width,height:o.height,tag:"chart"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:n})}addChart(e,t){const i=this.getters.getFigureSheetId(e);i&&this.history.update("charts",e,this.createChart(e,t,i))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.id)?84:0}checkChartExists(e){return this.getters.getFigureSheetId(e.id)?0:85}}function Tv(e){return""===e?NaN:Number(e)}Rv.getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];class Av extends yv{constructor(){super(...arguments),this.cfRules={}}loopThroughRangesOfSheet(e,t){for(const i of this.cfRules[e])for(const o of i.ranges){const n=t(o);switch(n.changeType){case"REMOVE":let t=i.ranges.slice();t.splice(i.ranges.indexOf(o),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(i),"ranges",t):this.removeConditionalFormatting(i.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(i),"ranges",i.ranges.indexOf(o),n.range)}}}adaptRanges(e,t){if(t)this.loopThroughRangesOfSheet(t,e);else for(const t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,e)}allowDispatch(e){switch(e.type){case"ADD_CONDITIONAL_FORMAT":return this.checkValidations(e,this.checkCFRule,this.checkEmptyRange);case"MOVE_CONDITIONAL_FORMAT":return this.checkValidReordering(e.cfId,e.direction,e.sheetId)}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const i={...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))};this.addConditionalFormatting(i,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId);break;case"MOVE_CONDITIONAL_FORMAT":this.reorderConditionalFormatting(e.cfId,e.direction,e.sheetId)}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map((e=>this.mapToConditionalFormatInternal(t.id,e)))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map((e=>this.mapToConditionalFormat(t.id,e))))}exportForExcel(e){this.export(e)}getConditionalFormats(e){var t;return(null===(t=this.cfRules[e])||void 0===t?void 0:t.map((t=>this.mapToConditionalFormat(e,t))))||[]}getRulesSelection(e,t){const i=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{i.add(e)}))})),Array.from(i)}getRulesByZone(e,t){const i=new Set;for(let o=t.top;o<=t.bottom;o++)for(let n=t.left;n<=t.right;n++){this.getRulesByCell(e,n,o).forEach((e=>{i.add(e.id)}))}return i}getRulesByCell(e,t,i){const o=[];for(let n of this.cfRules[e])for(let e of n.ranges)Zi(t,i,e.zone)&&o.push(n);return new Set(o.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e)))}}mapToConditionalFormatInternal(e,t){const i={...t,ranges:t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)))};return i}addConditionalFormatting(e,t){const i=this.cfRules[t].slice(),o=i.findIndex((t=>t.id===e.id)),n=this.mapToConditionalFormatInternal(t,e);o>-1?i.splice(o,1,n):i.push(n),this.history.update("cfRules",t,i)}checkValidReordering(e,t,i){if(!this.cfRules[i])return 27;const o=this.cfRules[i].findIndex((t=>t.id===e));if(-1===o)return 71;const n="up"===t?o-1:o+1;return n<0||n>=this.cfRules[i].length?71:0}checkEmptyRange(e){return e.ranges.length?0:24}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber(2,["Between","NotBetween"]),this.checkOperatorArgsNumber(1,["BeginsWith","ContainsText","EndsWith","GreaterThan","GreaterThanOrEqual","LessThan","LessThanOrEqual","NotContains"]),this.checkOperatorArgsNumber(0,["IsEmpty","IsNotEmpty"]));case"ColorScaleRule":return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case"IconSetRule":return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)))}return 0}checkOperatorArgsNumber(e,t){if(e>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");return i=>{if(t.includes(i.operator)){const t=[],o=e=>void 0===e||""===e;return e>=1&&o(i.values[0])&&t.push(51),e>=2&&o(i.values[1])&&t.push(52),t.length?t:0}return 0}}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return 53;case"max":return 55;case"mid":return 54;case"upperInflectionPoint":return 56;case"lowerInflectionPoint":return 57}return 0}checkFormulaCompilation(e,t){if("formula"!==e.type)return 0;try{sf(e.value||"")}catch(e){switch(t){case"min":return 58;case"max":return 60;case"mid":return 59;case"upperInflectionPoint":return 61;case"lowerInflectionPoint":return 62}}return 0}checkThresholds(e){return this.batchValidations((t=>e(t.minimum,"min")),(t=>e(t.maximum,"max")),(t=>t.midpoint?e(t.midpoint,"mid"):0))}checkInflectionPoints(e){return this.batchValidations((t=>e(t.lowerInflectionPoint,"lowerInflectionPoint")),(t=>e(t.upperInflectionPoint,"upperInflectionPoint")))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,i=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(i)?48:0}checkMinBiggerThanMax(e){const t=e.minimum.value,i=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&Tv(t)>=Tv(i)?47:0}checkMidBiggerThanMax(e){var t;const i=null===(t=e.midpoint)||void 0===t?void 0:t.value,o=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&Tv(i)>=Tv(o)?49:0}checkMinBiggerThanMid(e){var t;const i=e.minimum.value,o=null===(t=e.midpoint)||void 0===t?void 0:t.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&Tv(i)>=Tv(o)?50:0}removeConditionalFormatting(e,t){const i=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==i){const e=this.cfRules[t].slice();e.splice(i,1),this.history.update("cfRules",t,e)}}reorderConditionalFormatting(e,t,i){const o=this.cfRules[i].findIndex((t=>t.id===e)),n="up"===t?o-1:o+1;if(!(n<0||n>=this.cfRules[i].length)&&-1!==o&&-1!==n){const e=[...this.cfRules[i]],t=e[o];e[o]=e[n],e[n]=t,this.history.update("cfRules",i,e)}}}Av.getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];class Mv extends yv{constructor(){super(...arguments),this.figures={}}allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkFigureDuplicate(e.figure.id);case"UPDATE_FIGURE":case"DELETE_FIGURE":return this.checkFigureExists(e.sheetId,e.id);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":this.addFigure(e.figure,e.sheetId);break;case"UPDATE_FIGURE":const{type:t,sheetId:i,...o}=e,n=o;this.updateFigure(i,n);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId)}}updateFigure(e,t){if("id"in t)for(const[i,o]of Object.entries(t))switch(i){case"x":case"y":void 0!==o&&this.history.update("figures",e,t.id,i,Math.max(o,0));break;case"width":case"height":void 0!==o&&this.history.update("figures",e,t.id,i,o)}}addFigure(e,t){this.history.update("figures",t,e.id,e)}deleteSheet(e){this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){var i;return void 0===(null===(i=this.figures[e])||void 0===i?void 0:i[t])?70:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>null==t?void 0:t[e]))?82:0}getFigures(e){return Object.values(this.figures[e]||{}).filter(et)}getFigure(e,t){var i;return null===(i=this.figures[e])||void 0===i?void 0:i[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>{var i;return void 0!==(null===(i=this.figures[t])||void 0===i?void 0:i[e])}))}import(e){for(let t of e.sheets){const e={};t.figures.forEach((t=>{e[t.id]=t})),this.figures[t.id]=e}}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const i=void 0;t.figures.push({...e,data:i})}}exportForExcel(e){this.export(e)}}Mv.getters=["getFigures","getFigure","getFigureSheetId"];class Ov{constructor(e){this.filters=[],this.zone=e;const t=new Di;this.id=t.uuidv4();for(const i of ze(e.left,e.right+1)){const e={...this.zone,left:i,right:i};this.filters.push(new Nv(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 Ov(this.zone)}}class Nv{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 _v extends yv{constructor(){super(...arguments),this.tables={}}allowDispatch(e){switch(e.type){case"CREATE_FILTER_TABLE":if(!ro(...e.target))return 81;const t=$i(...e.target),i=()=>this.getFilterTables(e.sheetId).some((e=>qi(e.zone,t)))?78:0,o=()=>{const i=this.getters.getMergesInZone(e.sheetId,t);for(let e of i)if(qi(t,e))return 80;return 0};return this.checkValidations(e,i,o);case"ADD_MERGE":for(let t of e.target)for(let i of this.getFilterTables(e.sheetId))if(qi(i.zone,t))return 80}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break;case"DUPLICATE_SHEET":this.history.update("tables",e.sheetIdTo,Ne(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=$i(...e.target),i=this.createFilterTable(t);this.history.update("tables",e.sheetId,i.id,i);break}case"REMOVE_FILTER_TABLE":{const t={};for(const i of this.getFilterTables(e.sheetId))e.target.every((e=>!Wi(e,i.zone)))&&(t[i.id]=i);this.history.update("tables",e.sheetId,t);break}case"UPDATE_CELL":{const t=e.sheetId;for(let i of this.getFilterTables(t))this.canUpdateCellCmdExtendTable(e,i)&&this.extendTableDown(t,i);break}}}getFilters(e){return this.getFilterTables(e).map((e=>e.filters)).flat()}getFilterTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(et):[]}getFilter(e){var t;return null===(t=this.getFilterTable(e))||void 0===t?void 0:t.filters.find((t=>t.col===e.col))}getFilterId(e){var t;return null===(t=this.getFilter(e))||void 0===t?void 0:t.id}getFilterTable({sheetId:e,col:t,row:i}){return this.getFilterTables(e).find((e=>Zi(t,i,e.zone)))}getFilterTablesInZone(e,t){return this.getFilterTables(e).filter((e=>ji(e.zone,t)))}doesZonesContainFilter(e,t){for(const i of t)for(const t of this.getFilterTables(e))if(Wi(i,t.zone))return!0;return!1}onAddColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const i=Vi(t.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),o=[];for(const i of t.filters){const t=Vi(i.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);o.push(new Nv(i.id,t))}if(o.length<Ki(i).numberOfCols){for(let e=i.left;e<=i.right;e++)o.find((t=>t.col===e))||o.push(new Nv(this.uuidGenerator.uuidv4(),{...i,left:e,right:e}));o.sort(((e,t)=>e.col-t.col))}this.history.update("tables",e.sheetId,t.id,"zone",i),this.history.update("tables",e.sheetId,t.id,"filters",o)}}onDeleteColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const i=Hi(t.zone,"COL"===e.dimension?"left":"top",e.elements);if(i){if(Ui(i)!==Ui(t.zone)){const o=[];for(const i of t.filters){const t=Hi(i.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.elements);t&&o.push(new Nv(i.id,t))}this.history.update("tables",e.sheetId,t.id,"zone",i),this.history.update("tables",e.sheetId,t.id,"filters",o)}}else{const i={...this.tables[e.sheetId]};delete i[t.id],this.history.update("tables",e.sheetId,i)}}}createFilterTable(e){return new Ov(e)}extendTableDown(e,t){const i={...t.zone,bottom:t.zone.bottom+1};this.history.update("tables",e,t.id,"zone",i);for(let i=0;i<t.filters.length;i++){const o=t.filters[i],n={...o.zoneWithHeaders,bottom:o.zoneWithHeaders.bottom+1};this.history.update("tables",e,t.id,"filters",i,"zoneWithHeaders",n)}}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:i,row:o},n){var s;if(!e)return;const r=n.zone;if(!(r.bottom+1===o&&i>=r.left&&i<=r.right))return!1;for(const e of ze(r.left,r.right+1)){const i={sheetId:t,col:e,row:o};if(null===(s=this.getters.getCell(i))||void 0===s?void 0:s.content)return!1;if(this.getters.getFilter(i))return!1;if(this.getters.isInMerge(i))return!1}return!0}import(e){for(const t of e.sheets)for(const e of t.filterTables||[]){const i=this.createFilterTable(Li(e.range));this.history.update("tables",t.id,i.id,i)}}export(e){for(const t of e.sheets)for(const e of this.getFilterTables(t.id))t.filterTables.push({range:Ui(e.zone)})}exportForExcel(e){this.export(e)}}_v.getters=["doesZonesContainFilter","getFilter","getFilters","getFilterTable","getFilterTables","getFilterTablesInZone","getFilterId"];class Fv extends yv{constructor(){super(...arguments),this.sizes={}}handle(e){var t,i,o;switch(e.type){case"CREATE_SHEET":{const t=this.computeSheetSizes(e.sheetId),i={COL:t.COL.map((e=>({manualSize:void 0,computedSize:nt(e)}))),ROW:t.ROW.map((e=>({manualSize:void 0,computedSize:nt(e)})))};this.history.update("sizes",e.sheetId,i);break}case"DUPLICATE_SHEET":for(const t of this.sizes[e.sheetId].ROW)t.computedSize();for(const t of this.sizes[e.sheetId].COL)t.computedSize();this.history.update("sizes",e.sheetIdTo,Ne(this.sizes[e.sheetId]));break;case"DELETE_SHEET":const n={...this.sizes};delete n[e.sheetId],this.history.update("sizes",n);break;case"REMOVE_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];for(let i of[...e.elements].sort(((e,t)=>t-e)))t.splice(i,1);const i=Math.min(...e.elements);t=t.map(((t,o)=>"ROW"===e.dimension&&o>=i?{manualSize:t.manualSize,computedSize:nt((()=>this.getRowTallestCellSize(e.sheetId,o)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];const i=rt(e.position,e.base),o=t[e.base];t.splice(i,0,...Array(e.quantity).fill(o)),t=t.map(((t,i)=>"ROW"===e.dimension&&i>e.base+e.quantity?{manualSize:t.manualSize,computedSize:nt((()=>this.getRowTallestCellSize(e.sheetId,i)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"RESIZE_COLUMNS_ROWS":for(let t of e.elements)if("ROW"===e.dimension){const i=this.getRowTallestCellSize(e.sheetId,t);this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:nt(i)})}else this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:nt(e.size||_)});break;case"UPDATE_CELL":if(!(null===(o=null===(i=null===(t=this.sizes[e.sheetId])||void 0===t?void 0:t.ROW)||void 0===i?void 0:i[e.row])||void 0===o?void 0:o.manualSize)){const{sheetId:t,row:i}=e;this.history.update("sizes",t,"ROW",i,"computedSize",nt((()=>this.getRowTallestCellSize(t,i))))}break;case"ADD_MERGE":case"REMOVE_MERGE":for(let t of e.target)for(let i of ze(t.top,t.bottom+1)){const t=this.getRowTallestCellSize(e.sheetId,i);t!==this.getRowSize(e.sheetId,i)&&this.history.update("sizes",e.sheetId,"ROW",i,"computedSize",nt(t))}}}getColSize(e,t){return this.getHeaderSize(e,"COL",t)}getRowSize(e,t){return this.getHeaderSize(e,"ROW",t)}getHeaderSize(e,t,i){var o,n,s,r;return Math.round((null===(n=null===(o=this.sizes[e])||void 0===o?void 0:o[t][i])||void 0===n?void 0:n.manualSize)||(null===(r=null===(s=this.sizes[e])||void 0===s?void 0:s[t][i])||void 0===r?void 0:r.computedSize())||this.getDefaultHeaderSize(t))}computeSheetSizes(e){var t,i;const o={COL:[],ROW:[]};for(let t of ze(0,this.getters.getNumberCols(e)))o.COL.push(this.getHeaderSize(e,"COL",t));for(let n of ze(0,this.getters.getNumberRows(e))){let s=null===(i=null===(t=this.sizes[e])||void 0===t?void 0:t.ROW)||void 0===i?void 0:i[n].manualSize;if(!s){s=this.getRowTallestCellSize(e,n)}o.ROW.push(s)}return o}getDefaultHeaderSize(e){return"COL"===e?_:F}getCellHeight(e){const t=this.getters.getMerge(e);if(t&&t.bottom!==t.top)return F;return function(e){return e&&e.content?ke(Ve(e.style),e.isFormula?1:e.content.split(ce).length)+2*V:F}(this.getters.getCell(e))}getRowTallestCellSize(e,t){const i=this.getters.getRowCells(e,t);let o=0;for(let e=0;e<i.length;e++){const t=this.getters.getCellById(i[e]);if(!t)continue;const n=this.getters.getCellPosition(t.id),s=this.getCellHeight(n);s>o&&s>F&&(o=s)}return o<=F?F:o}import(e){for(let t of e.sheets){const e={COL:[],ROW:[]};for(let[i,o]of Object.entries(t.rows))o.size&&(e.ROW[i]=o.size);for(let[i,o]of Object.entries(t.cols))o.size&&(e.COL[i]=o.size);const i=this.computeSheetSizes(t.id);this.sizes[t.id]={COL:i.COL.map(((t,i)=>({manualSize:e.COL[i],computedSize:nt(t)}))),ROW:i.ROW.map(((t,i)=>({manualSize:e.ROW[i],computedSize:nt(t)})))}}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){var i,o;for(let n of e.sheets){void 0===n.rows&&(n.rows={});for(let e of ze(0,this.getters.getNumberRows(n.id)))(t||(null===(i=this.sizes[n.id].ROW[e])||void 0===i?void 0:i.manualSize))&&(n.rows[e]={...n.rows[e],size:this.getRowSize(n.id,e)});void 0===n.cols&&(n.cols={});for(let e of ze(0,this.getters.getNumberCols(n.id)))(t||(null===(o=this.sizes[n.id].COL[e])||void 0===o?void 0:o.manualSize))&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}}Fv.getters=["getRowSize","getColSize"];class Dv extends yv{constructor(){super(...arguments),this.hiddenHeaders={}}allowDispatch(e){switch(e.type){case"HIDE_COLUMNS_ROWS":{if(!this.getters.tryGetSheet(e.sheetId))return 27;const t="COL"===e.dimension?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),i="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=i?66:Math.min(...e.elements)<0||Math.max(...e.elements)>i?86:0}case"REMOVE_COLUMNS_ROWS":return this.getters.tryGetSheet(e.sheetId)?this.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,Ne(this.hiddenHeaders[e.sheetId]));break;case"DELETE_SHEET":this.history.update("hiddenHeaders",e.sheetId,void 0);break;case"REMOVE_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let i of[...e.elements].sort(((e,t)=>t-e)))t.splice(i,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]],i=rt(e.position,e.base);t.splice(i,0,...Array(e.quantity).fill(!1)),this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"HIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!0);break;case"UNHIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!1)}}canRemoveHeaders(e,t,i){const o=this.getAllVisibleHeaders(e,t);return n=i,!o.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=[[]],i=this.hiddenHeaders[e].COL;for(let e=0;e<i.length;e++){i[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getHiddenRowsGroups(e){const t=[[]],i=this.hiddenHeaders[e].ROW;for(let e=0;e<i.length;e++){i[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getAllVisibleHeaders(e,t){return ze(0,this.hiddenHeaders[e][t].length).filter((i=>!this.hiddenHeaders[e][t][i]))}import(e){var t,i;for(let o of e.sheets){this.hiddenHeaders[o.id]={COL:[],ROW:[]};for(let e=0;e<o.rowNumber;e++)this.hiddenHeaders[o.id].ROW[e]=Boolean(null===(t=o.rows[e])||void 0===t?void 0:t.isHidden);for(let e=0;e<o.colNumber;e++)this.hiddenHeaders[o.id].COL[e]=Boolean(null===(i=o.cols[e])||void 0===i?void 0:i.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let i of e.sheets){void 0===i.rows&&(i.rows={});for(let e=0;e<this.getters.getNumberRows(i.id);e++)(t||this.hiddenHeaders[i.id].ROW[e])&&(void 0===i.rows[e]&&(i.rows[e]={}),i.rows[e].isHidden=this.hiddenHeaders[i.id].ROW[e]);void 0===i.cols&&(i.cols={});for(let e=0;e<this.getters.getNumberCols(i.id);e++)(t||this.hiddenHeaders[i.id].COL[e])&&(void 0===i.cols[e]&&(i.cols[e]={}),i.cols[e].isHidden=this.hiddenHeaders[i.id].COL[e])}}}Dv.getters=["canRemoveHeaders","getHiddenColsGroups","getHiddenRowsGroups","isRowHiddenByUser","isColHiddenByUser"];class kv extends yv{constructor(e){super(e),this.images={},this.syncedImages=new Set,this.fileStore=e.external.fileStore}allowDispatch(e){return"CREATE_IMAGE"===e.type&&this.getters.getFigure(e.sheetId,e.figureId)?28:0}handle(e){switch(e.type){case"CREATE_IMAGE":this.addFigure(e.figureId,e.sheetId,e.position,e.size),this.history.update("images",e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const i of t)if("image"===i.tag){const t=i.id.split(J).pop(),o=`${e.sheetIdTo}${J}${t}`,n=this.getImage(i.id);if(n){const t={width:i.width,height:i.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:o,position:{x:i.x,y:i.y},size:t,definition:Ne(n)})}}break}case"DELETE_FIGURE":this.history.update("images",e.sheetId,e.id,void 0);break;case"DELETE_SHEET":this.history.update("images",e.sheetId,void 0)}}garbageCollectExternalResources(){var e;const t=new Set(this.getAllImages().map((e=>e.path)));for(const i of this.syncedImages)t.has(i)||null===(e=this.fileStore)||void 0===e||e.delete(i)}getImage(e){for(const t of Object.values(this.images))if(t&&t[e])return t[e];throw new Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,i,o){const n={id:e,x:i.x,y:i.y,width:o.width,height:o.height,tag:"image"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:n})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter((e=>"image"===e.tag));for(const i of e)this.history.update("images",t.id,i.id,i.data),this.syncedImages.add(i.data.path)}}export(e){var t;for(const i of e.sheets){const e=i.figures.filter((e=>"image"===e.tag));for(const o of e)o.data=null===(t=this.images[i.id])||void 0===t?void 0:t[o.id]}}exportForExcel(e){for(const t of e.sheets){const e=this.getters.getFigures(t.id),i=[];for(const t of e)if("image"===(null==t?void 0:t.tag)){const e=this.getImage(t.id);e&&i.push({...t,data:Ne(e)})}t.images=i}}getAllImages(){const e=[];for(const t in this.images)e.push(...Object.values(this.images[t]||{}).filter(et));return e}}kv.getters=["getImage","getImagePath","getImageSize"];class Lv extends yv{constructor(){super(...arguments),this.nextId=1,this.merges={},this.mergeCellMap={}}allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;for(const i of Object.values(t).filter(et))this.addMerge(e.sheetIdTo,i.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(e.sheetId,t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){const i=t?[t]:Object.keys(this.merges);for(const t of i)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(et)}getMerge({sheetId:e,col:t,row:i}){var o;const n=this.mergeCellMap[e],s=n?t in n&&(null===(o=n[t])||void 0===o?void 0:o[i]):void 0;return s?this.getMergeById(e,s):void 0}getMergesInZone(e,t){var i;const o=this.mergeCellMap[e];if(!o)return[];const n=new Set;for(const{col:e,row:s}of Ji(t)){const t=null===(i=o[e])||void 0===i?void 0:i[s];t&&n.add(t)}return Array.from(n).map((t=>this.getMergeById(e,t))).filter(et)}doesIntersectMerge(e,t){return Ji(t).some((({col:t,row:i})=>void 0!==this.getMerge({sheetId:e,col:t,row:i})))}doesColumnsHaveCommonMerges(e,t,i){const o=this.getters.getSheet(e);for(let n=0;n<this.getters.getNumberRows(e);n++)if(this.isInSameMerge(o.id,t,n,i,n))return!0;return!1}doesRowsHaveCommonMerges(e,t,i){const o=this.getters.getSheet(e);for(let n=0;n<=this.getters.getNumberCols(e);n++)if(this.isInSameMerge(o.id,n,t,n,i))return!0;return!1}expandZone(e,t){let{left:i,right:o,top:n,bottom:s}=t,r={left:i,right:o,top:n,bottom:s};for(let t in this.merges[e]){const i=this.getMergeById(e,parseInt(t));i&&qi(i,r)&&(r=$i(i,r))}return Gi(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,i,o,n){const s=this.getMerge({sheetId:e,col:t,row:i}),r=this.getMerge({sheetId:e,col:o,row:n});return!(!s||!r)&&Gi(s,r)}isInMerge({sheetId:e,col:t,row:i}){var o;const n=this.mergeCellMap[e];return!!n&&(t in n&&Boolean(null===(o=n[t])||void 0===o?void 0:o[i]))}getMainCellPosition(e){if(!this.isInMerge(e))return e;const t=this.getMerge(e).topLeft;return{sheetId:e.sheetId,col:t.col,row:t.row}}getBottomLeftCell(e){if(!this.isInMerge(e))return e;const{bottom:t,left:i}=this.getMerge(e);return{sheetId:e.sheetId,col:i,row:t}}isMergeHidden(e,t){const i=this.getters.getHiddenColsGroups(e),o=this.getters.getHiddenRowsGroups(e);for(let e of i)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of o)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const i=this.getMerge({sheetId:e,col:t.left,row:t.top});if(i)return Gi(t,i);const{numberOfCols:o,numberOfRows:n}=Ki(t);return 1===o&&1===n}isMergeDestructive(e,t){let{left:i,right:o,top:n,bottom:s}=t;o=De(o,0,this.getters.getNumberCols(e)-1),s=De(s,0,this.getters.getNumberRows(e)-1);for(let t=n;t<=s;t++)for(let s=i;s<=o;s++)if(s!==i||t!==n){const i=this.getters.getCell({sheetId:e,col:s,row:t});if(i&&""!==i.content)return!0}return!1}getMergeById(e,t){var i;const o=null===(i=this.merges[e])||void 0===i?void 0:i[t];return void 0!==o?Uv(t,o):void 0}checkDestructiveMerge({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;return t.some((t=>this.isMergeDestructive(e,t)))?3:0}checkOverlap({target:e}){for(const t of e)for(const i of e)if(t!==i&&qi(t,i))return 65;return 0}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;const{xSplit:i,ySplit:o}=this.getters.getPaneDivisions(e);for(const e of t)if(e.left<i&&e.right>=i||e.top<o&&e.bottom>=o)return 75;return 0}checkMergedContentUpdate(e){const{col:t,row:i,content:o}=e;if(void 0===o)return 0;const{col:n,row:s}=this.getMainCellPosition(e);return n===t&&s===i?0:4}checkMergeExists(e){const{sheetId:t,target:i}=e;for(const e of i){const{left:i,top:o}=e,n=this.getMerge({sheetId:t,col:i,row:o});if(void 0===n||!Gi(e,n))return 5}return 0}addMerge(e,t){let{left:i,right:o,top:n,bottom:s}=t;o=De(o,0,this.getters.getNumberCols(e)-1),s=De(s,0,this.getters.getNumberRows(e)-1);if(Bt(i,n)===Bt(o,s))return;const r=this.getters.getCell({sheetId:e,col:i,row:n});let a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,Ui({left:i,top:n,right:o,bottom:s})));let l=new Set;for(let t=n;t<=s;t++)for(let s=i;s<=o;s++){s===i&&t===n||this.dispatch("UPDATE_CELL",{sheetId:e,col:s,row:t,style:r?r.style:null,content:""});const o=this.getMerge({sheetId:e,col:s,row:t});o&&l.add(o.id),this.history.update("mergeCellMap",e,s,t,a)}for(let t of l){const{top:i,bottom:o,left:n,right:s}=this.getMergeById(e,t);for(let t=i;t<=o;t++)for(let i=n;i<=s;i++){const o={sheetId:e,col:i,row:t},n=this.getMerge(o);n&&n.id===a||(this.history.update("mergeCellMap",e,i,t,void 0),this.dispatch("CLEAR_CELL",o))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:i,top:o,bottom:n,right:s}=t,r=this.getMerge({sheetId:e,col:i,row:o});if(void 0!==r&&Gi(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=o;t<=n;t++)for(let o=i;o<=s;o++)this.history.update("mergeCellMap",e,o,t,void 0)}}applyRangeChangeOnSheet(e,t){const i=Object.entries(this.merges[e]||{});for(const[o,n]of i)if(n){const i=n.zone,s=t(n);switch(s.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,i);break;default:const{numberOfCols:t,numberOfRows:n}=Ki(s.range.zone);1===t&&1===n?this.removeMerge(e,i):this.history.update("merges",e,parseInt(o,10),s.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:i,row:o}of Ji(t))this.history.update("mergeCellMap",e,i,o,t.id)}import(e){const t=e.sheets||[];for(let e of t)this.history.update("merges",e.id,{}),this.history.update("mergeCellMap",e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let i of t)this.addMerge(e,Li(i))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...Pv(e))}}exportForExcel(e){this.export(e)}}function Pv(e){return Object.entries(e).map((([e,t])=>t?Uv(parseInt(e,10),t):void 0)).filter(et).map((e=>Bt(e.left,e.top)+":"+Bt(e.right,e.bottom)))}function Uv(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}Lv.getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge"];class Vv{constructor(e){this.providers=[],this.getters=e}allowDispatch(e){return"MOVE_RANGES"===e.type?1===e.target.length?0:26:0}beforeHandle(e){}handle(e){switch(e.type){case"REMOVE_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",i="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";const n=[...e.elements];n.sort(((e,t)=>t-e));const s=Be(n);this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};let r=n,a="NONE";for(let e of s){const s=Math.min(...e),l=Math.max(...e);if(n.zone[t]<=s&&s<=n.zone[i]){const e=Math.min(n.zone[i],l)-s+1;a="RESIZE",r=this.createAdaptedRange(r,o,a,-e)}else if(n.zone[t]>=s&&n.zone[i]<=l)a="REMOVE",r=n.clone({...this.getInvalidRange()});else if(n.zone[t]<=l&&n.zone[i]>=l){const e=l-n.zone[t]+1;a="RESIZE",r=this.createAdaptedRange(r,o,a,-e),r=this.createAdaptedRange(r,o,"MOVE",-(n.zone[t]-s))}else s<n.zone[t]&&(a="MOVE",r=this.createAdaptedRange(r,o,a,-(l-s+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",i="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(n.zone[t]<=e.base&&e.base<n.zone[i])return{changeType:"RESIZE",range:this.createAdaptedRange(n,o,"RESIZE",e.quantity)};if(e.base<n.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(n,o,"MOVE",e.quantity)}}else{if(n.zone[t]<e.base&&e.base<=n.zone[i])return{changeType:"RESIZE",range:this.createAdaptedRange(n,o,"RESIZE",e.quantity)};if(e.base<=n.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(n,o,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId!==e.sheetId)return{changeType:"NONE"};const i=this.getters.getSheetName(e.sheetId);return{changeType:"REMOVE",range:t=t.clone({...this.getInvalidRange(),invalidSheetName:i})}}),e.sheetId);break;case"RENAME_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.name&&t.invalidSheetName===e.name){const i=void 0,o=e.sheetId;return{changeType:"CHANGE",range:t.clone({sheetId:o,invalidSheetName:i})}}return{changeType:"NONE"}}));break;case"MOVE_RANGES":{const t=e.target[0];this.executeOnAllRanges((i=>{if(i.sheetId!==e.sheetId||!ji(i.zone,t))return{changeType:"NONE"};const o=e.targetSheetId,n=e.col-t.left,s=e.row-t.top,r=this.createAdaptedRange(i,"both","MOVE",[n,s]),a=e.sheetId!==o||r.prefixSheet;return{changeType:"MOVE",range:r.clone({sheetId:o,prefixSheet:a})}}));break}}}finalize(){}verifyRangeRemoved(e){return t=>{const i=e(t);return"NONE"===i.changeType||Pi(i.range.zone)?i:{range:i.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,i,o){const n=eo(e.unboundedZone,t,i,o);return e.clone({zone:n})}executeOnAllRanges(e,t){const i=this.verifyRangeRemoved(e);for(const e of this.providers)e(i,t)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,i,o){const n=e.map((e=>Mi.fromRange(e,this.getters)));return n.map((e=>{if(!Pi(e.zone))return e;const n=e.prefixSheet?e.sheetId:o,s={...e.unboundedZone,left:e.isFullRow&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:e.isFullRow?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.isFullCol&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:i),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:i)};return e.clone({sheetId:n,zone:s}).orderZone()}))}getRangeFromSheetXC(e,t){if(!_t.test(t))return new Mi({sheetId:"",zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let i,o=t,n=!1;t.includes("!")&&(({xc:o,sheetName:i}=Pt(t)),i&&(n=!0));const s=ki(o),r=Mi.getRangeParts(o,s),a=i&&!this.getters.getSheetIdByName(i)?i:void 0,l=this.getters.getSheetIdByName(i)||e;return new Mi({prefixSheet:n,zone:s,sheetId:l,invalidSheetName:a,parts:r},this.getters.getSheetSize).orderZone()}getSelectionRangeString(e,t){const i=Mi.fromRange(e,this.getters),o=this.getters.expandZone(i.sheetId,i.zone),n=i.clone({zone:{...o,bottom:i.isFullCol?void 0:o.bottom,right:i.isFullRow?void 0:o.right}});return this.getRangeString(n,t)}getRangeString(e,t){if(!e)return Y;if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return Y;if(e.zone.left<0||e.zone.top<0)return Y;const i=Mi.fromRange(e,this.getters);let o=i.sheetId!==t||i.invalidSheetName||i.prefixSheet,n="";if(o&&(n=i.invalidSheetName?i.invalidSheetName:Fe(this.getters.getSheetName(i.sheetId))),o&&!n)return Y;let s=this.getRangePartString(i,0);return i.parts&&2===i.parts.length&&(i.zone.top!==i.zone.bottom||i.zone.left!==i.zone.right||i.parts[0].rowFixed||i.parts[0].colFixed||i.parts[1].rowFixed||i.parts[1].colFixed)&&(s+=":",s+=this.getRangePartString(i,1)),`${o?n+"!":""}${s}`}getRangeDataFromXc(e,t){return this.getters.getRangeFromSheetXC(e,t).rangeData}getRangeDataFromZone(e,t){return{_sheetId:e,_zone:t}}getRangeFromRangeData(e){const t={prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]};return new Mi(t,this.getters.getSheetSize)}getRangePartString(e,t){const i=e.parts&&e.parts[t].colFixed?"$":"",o=Ut(0===t?e.zone.left:e.zone.right),n=e.parts&&e.parts[t].rowFixed?"$":"",s=String(0===t?e.zone.top+1:e.zone.bottom+1);let r="";return r=e.isFullCol?0===t&&e.unboundedZone.hasHeader?i+o+n+s:i+o:e.isFullRow?0===t&&e.unboundedZone.hasHeader?i+o+n+s:n+s:i+o+n+s,r}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:Y}}}Vv.getters=["getRangeString","getSelectionRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData"];class zv extends yv{constructor(){super(...arguments),this.sheetIdsMapName={},this.orderedSheetIds=[],this.sheets={},this.cellPosition={}}allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZones)(e);if(0!==t)return t;switch(e.type){case"HIDE_SHEET":return 1===this.getVisibleSheetIds().length?9:0;case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"MOVE_SHEET":try{const t=this.orderedSheetIds.findIndex((t=>t===e.sheetId));return this.findIndexOfTargetSheet(t,e.delta),0}catch(e){return 14}case"RENAME_SHEET":return this.isRenameAllowed(e);case"DELETE_SHEET":return this.orderedSheetIds.length>1?0:9;case"ADD_COLUMNS_ROWS":const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return e.base<0||e.base>t?86:e.quantity<=0?87:0;case"REMOVE_COLUMNS_ROWS":{const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return Math.min(...e.elements)<0||Math.max(...e.elements)>t?86:0}case"FREEZE_ROWS":return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case"FREEZE_COLUMNS":return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return 0}}handle(e){switch(e.type){case"SET_GRID_LINES_VISIBILITY":this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case"DELETE_CONTENT":this.clearZones(e.sheetId,e.target);break;case"CREATE_SHEET":const t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update("sheetIdsMapName",t.name,t.id);break;case"MOVE_SHEET":this.moveSheet(e.sheetId,e.delta);break;case"RENAME_SHEET":this.renameSheet(this.sheets[e.sheetId],e.name);break;case"HIDE_SHEET":this.hideSheet(e.sheetId);break;case"SHOW_SHEET":this.showSheet(e.sheetId);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case"UPDATE_CELL_POSITION":this.updateCellPosition(e);break;case"FREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,e.quantity,"COL");break;case"FREEZE_ROWS":this.setPaneDivisions(e.sheetId,e.quantity,"ROW");break;case"UNFREEZE_ROWS":this.setPaneDivisions(e.sheetId,0,"ROW");break;case"UNFREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,0,"COL");break;case"UNFREEZE_COLUMNS_ROWS":this.setPaneDivisions(e.sheetId,0,"COL"),this.setPaneDivisions(e.sheetId,0,"ROW")}}import(e){var t,i;for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let o of e.sheets){const e=o.name||n("Sheet")+(Object.keys(this.sheets).length+1),{colNumber:s,rowNumber:r}=this.getImportedSheetSize(o),a={id:o.id,name:e,numberOfCols:s,rows:Fi(r),areGridLinesVisible:void 0===o.areGridLinesVisible||o.areGridLinesVisible,isVisible:o.isVisible,panes:{xSplit:(null===(t=o.panes)||void 0===t?void 0:t.xSplit)||0,ySplit:(null===(i=o.panes)||void 0===i?void 0:i.ySplit)||0}};this.orderedSheetIds.push(a.id),this.sheets[a.id]=a}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(et).map((e=>{const t=this.sheets[e],i={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},conditionalFormats:[],figures:[],filterTables:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible};return(t.panes.xSplit||t.panes.ySplit)&&(i.panes=t.panes),i}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){var t;return null===(t=this.tryGetSheet(e))||void 0===t?void 0:t.name}getSheetIdByName(e){if(e){const t=_e(e);for(const e in this.sheetIdsMapName)if(e.toUpperCase()===t.toUpperCase())return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}getEvaluationSheets(){return this.sheets}doesHeaderExist(e,t,i){return"COL"===t?i>=0&&i<this.getNumberCols(e):i>=0&&i<this.getNumberRows(e)}getRow(e,t){const i=this.getSheet(e).rows[t];if(!i)throw new Error(`Row ${i} not found.`);return i}getCell({sheetId:e,col:t,row:i}){var o;const n=this.tryGetSheet(e),s=null===(o=null==n?void 0:n.rows[i])||void 0===o?void 0:o.cells[t];if(void 0!==s)return this.getters.getCellById(s)}getColsZone(e,t,i){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:i}}getRowCells(e,t){var i;return Object.values(null===(i=this.getSheet(e).rows[t])||void 0===i?void 0:i.cells).filter(et)}getRowsZone(e,t,i){return{top:t,bottom:i,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){let t=1;const i=this.orderedSheetIds.map(this.getSheetName.bind(this));let o=`${e}${t}`;for(;i.includes(o);)o=`${e}${t}`,t++;return o}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,i){const o={...this.getPaneDivisions(e)};"COL"===i?o.xSplit=t:"ROW"===i&&(o.ySplit=t),this.history.update("sheets",e,"panes",o)}isEmpty(e,t){return Ji(t).map((({col:t,row:i})=>this.getCell({sheetId:e,col:t,row:i}))).every((e=>!e||""===e.content))}updateCellPosition(e){const{sheetId:t,cellId:i,col:o,row:n}=e;i?this.setNewPosition(i,t,o,n):this.clearPosition(t,o,n)}setNewPosition(e,t,i,o){const n=this.cellPosition[e];n&&this.clearPosition(t,n.col,n.row),this.history.update("cellPosition",e,{row:o,col:i,sheetId:t}),this.history.update("sheets",t,"rows",o,"cells",i,e)}clearPosition(e,t,i){var o;const n=null===(o=this.sheets[e])||void 0===o?void 0:o.rows[i].cells[t];n&&(this.history.update("cellPosition",n,void 0),this.history.update("sheets",e,"rows",i,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}clearZones(e,t){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let o=i.top;o<=i.bottom;o++){this.sheets[e].rows[o].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:o})}}createSheet(e,t,i,o,n){const s={id:e,name:t,numberOfCols:i,rows:Fi(o),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},r=this.orderedSheetIds.slice();r.splice(n,0,s.id);const a=this.sheets;return this.history.update("orderedSheetIds",r),this.history.update("sheets",Object.assign({},a,{[s.id]:s})),s}moveSheet(e,t){const i=this.orderedSheetIds.slice(),o=i.findIndex((t=>t===e)),n=i.splice(o,1);let s=this.findIndexOfTargetSheet(o,t);i.splice(s,0,n[0]),this.history.update("orderedSheetIds",i)}findIndexOfTargetSheet(e,t){for(;0!=t&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(0===t)return e;throw new Error(s("There is not enough visible sheets"))}checkSheetName(e){const{orderedSheetIds:t,sheets:i}=this,o=e.name&&e.name.trim().toLowerCase();return t.find((e=>{var t;return(null===(t=i[e])||void 0===t?void 0:t.name.toLowerCase())===o}))?11:se.test(o)?13:0}checkSheetPosition(e){const{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?15:0}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?0:74}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?0:74}checkRowFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let i of t)if(i.top<e.quantity&&e.quantity<=i.bottom)return 65;return 0}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let i of t)if(i.left<e.quantity&&e.quantity<=i.right)return 65;return 0}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):10}renameSheet(e,t){const i=e.name;this.history.update("sheets",e.id,"name",t.trim());const o=Object.assign({},this.sheetIdsMapName);o[t]=e.id,delete o[i],this.history.update("sheetIdsMapName",o)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t){const i=this.getSheet(e),o=this.getDuplicateSheetName(i.name),n=Ne(i);n.id=t,n.name=o;for(let e=0;e<=n.numberOfCols;e++)for(let t=0;t<=n.rows.length;t++)n.rows[t]&&(n.rows[t].cells[e]=void 0);const s=this.orderedSheetIds.slice(),r=s.indexOf(e);s.splice(r+1,0,n.id),this.history.update("orderedSheetIds",s),this.history.update("sheets",Object.assign({},this.sheets,{[n.id]:n}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:i}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:n.id,col:e,row:i,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIdsMapName);a[n.name]=n.id,this.history.update("sheetIdsMapName",a)}getDuplicateSheetName(e){let t=1;const i=this.orderedSheetIds.map(this.getSheetName.bind(this)),o=s("Copy of %s",e);let n=o.toString();for(;i.includes(n);)n=`${o} (${t})`,t++;return n}deleteSheet(e){const t=e.name,i=Object.assign({},this.sheets);delete i[e.id],this.history.update("sheets",i);const o=this.orderedSheetIds.slice(),n=o.indexOf(e.id);o.splice(n,1),this.history.update("orderedSheetIds",o);const s=Object.assign({},this.sheetIdsMapName);delete s[t],this.history.update("sheetIdsMapName",s)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(let i of t)this.moveCellOnColumnsDeletion(e,i);const i=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",i-t.length);const o=t.filter((t=>t<e.panes.xSplit)).length;o&&this.setPaneDivisions(e.id,e.panes.xSplit-o,"COL")}removeRows(e,t){t.sort(((e,t)=>t-e));for(let i of Be(t))this.moveCellOnRowsDeletion(e,i[i.length-1],i[0]),i.map((t=>this.updateRowsStructureOnDeletion(t,e)));const i=t.filter((t=>t<e.panes.ySplit)).length;i&&this.setPaneDivisions(e.id,e.panes.ySplit-i,"ROW")}addColumns(e,t,i,o){const n="before"===i?t:t+1;this.moveCellsOnAddition(e,n,o,"columns");const s=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",s+o),n<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+o,"COL")}addRows(e,t,i,o){const n="before"===i?t:t+1;this.addEmptyRows(e,o),this.moveCellsOnAddition(e,n,o,"rows"),this.updateRowsStructureOnAddition(e,t,o),n<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+o,"ROW")}moveCellOnColumnsDeletion(e,t){for(let i=0;i<e.rows.length;i++){const o=e.rows[i];for(let n in o.cells){const s=Number(n),r=o.cells[n];r&&(s===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:s,row:i}),s>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r,col:s-1,row:i}))}}}moveCellsOnAddition(e,t,i,o){const n=[];for(let s=0;s<e.rows.length;s++){const r=e.rows[s];if("rows"!==o||s>=t)for(let a in r.cells){const l=Number(a),c=r.cells[a];c&&("rows"===o||l>=t)&&n.push({type:"UPDATE_CELL_POSITION",sheetId:e.id,cellId:c,col:l+("columns"===o?i:0),row:s+("rows"===o?i:0)})}}for(let e of n.reverse())this.dispatch(e.type,e)}moveCellOnRowsDeletion(e,t,i){const o=i-t+1;for(let n=0;n<e.rows.length;n++){const s=e.rows[n];if(n>=t&&n<=i)for(let t in s.cells){const i=Number(t);s.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:i,row:n})}if(n>i)for(let t in s.cells){const i=Number(t),r=s.cells[t];r&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r,col:i,row:n-o})}}}updateRowsStructureOnDeletion(e,t){const i=[],o=t.rows.map((e=>e.cells));for(let n in t.rows)Number(n)!==e&&i.push({cells:o.shift()});this.history.update("sheets",t.id,"rows",i)}updateRowsStructureOnAddition(e,t,i){const o=[],n=e.rows.map((e=>e.cells));e.rows.forEach((()=>o.push({cells:n.shift()}))),this.history.update("sheets",e.id,"rows",o)}addEmptyRows(e,t){const i=e.rows.slice();for(let e=0;e<t;e++)i.push({cells:{}});this.history.update("sheets",e.id,"rows",i)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(zt);let i=e.rowNumber,o=e.colNumber;for(let{col:e,row:n}of t)i=Math.max(i,n+1),o=Math.max(o,e+1);return{rowNumber:i,colNumber:o}}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?27:"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?12:0}checkZones(e){const t=[];if("zone"in e&&t.push(e.zone),"target"in e&&Array.isArray(e.target)&&t.push(...e.target),"ranges"in e&&Array.isArray(e.ranges)&&t.push(...e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone))),!t.every(Pi))return 25;if(t.length&&"sheetId"in e){const i=this.getSheetZone(e.sheetId);return t.every((e=>ji(e,i)))?0:18}return 0}}zv.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 Bv extends wv{constructor({getters:e,stateObserver:t,dispatch:i,uiActions:o,selection:n}){super(t,i),this.getters=e,this.ui=o,this.selection=n}drawGrid(e,t){}}Bv.layers=[];class Hv extends Bv{constructor(){super(...arguments),this.customColors=new Set,this.shouldUpdateColors=!1}handle(e){switch(e.type){case"UPDATE_CELL":case"UPDATE_CHART":case"CREATE_CHART":case"ADD_CONDITIONAL_FORMAT":this.shouldUpdateColors=!0}}finalize(){if(this.shouldUpdateColors){this.shouldUpdateColors=!1;for(const e of this.getCustomColors())this.tryToAddColor(e)}}getCustomColors(){let e=[];for(const t of this.getters.getSheetIds()){const i=Object.values(this.getters.getCells(t));e=e.concat(this.getColorsFromCells(i),this.getFormattingColors(t),this.getChartColors(t))}return function(e){const t=[{leadColor:Et(255,0,0),colors:[]},{leadColor:Et(255,128,0),colors:[]},{leadColor:Et(128,128,0),colors:[]},{leadColor:Et(128,255,0),colors:[]},{leadColor:Et(0,255,0),colors:[]},{leadColor:Et(0,255,128),colors:[]},{leadColor:Et(0,255,255),colors:[]},{leadColor:Et(0,127,255),colors:[]},{leadColor:Et(0,0,255),colors:[]},{leadColor:Et(127,0,255),colors:[]},{leadColor:Et(128,0,128),colors:[]},{leadColor:Et(255,0,128),colors:[]}];for(const i of e.map(xt)){let e=500,o=0;t.forEach(((t,n)=>{const s=(r=i,a=t.leadColor,Math.sqrt(Math.pow(r.r-a.r,2)+Math.pow(r.g-a.g,2)+Math.pow(r.b-a.b,2)));var r,a;e>s&&(e=s,o=n)})),t[o].colors.push(i)}return t.map((e=>e.colors.sort(((e,t)=>Rt(e).s-Rt(t).s)))).flat().map(yt)}([...new Set([...new Set([...e,...this.customColors])].filter(St).map(bt))]).filter((e=>!M.includes(e)))}getColorsFromCells(e){var t,i;const o=new Set;for(const n of e)(null===(t=n.style)||void 0===t?void 0:t.textColor)&&o.add(n.style.textColor),(null===(i=n.style)||void 0===i?void 0:i.fillColor)&&o.add(n.style.fillColor);return[...o]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),i=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(i.push(t.style.textColor),i.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(i.push(vt(t.minimum.color)),i.push(t.midpoint?vt(t.midpoint.color):void 0),i.push(vt(t.maximum.color)))}return i.filter(et)}getChartColors(e){const t=this.getters.getChartIds(e).map((e=>this.getters.getChart(e)));let i=new Set;for(let e of t){if(void 0===e)continue;const t=e.getDefinition().background;switch(void 0!==t&&i.add(t),e.type){case"gauge":const t=e.sectionRule.colors;i.add(t.lowerColor),i.add(t.middleColor),i.add(t.upperColor);break;case"scorecard":const o=e;i.add(o.baselineColorDown),i.add(o.baselineColorUp)}}return[...i]}tryToAddColor(e){const t=bt(e);e&&!M.includes(t)&&this.customColors.add(t)}}Hv.getters=["getCustomColors"];const $v=Wu.mapping;class Wv extends Bv{constructor(e){super(e),this.isUpToDate=!1,this.evaluatedCells={},this.evalContext=e.custom,this.lazyEvaluation=e.lazyEvaluation}handle(e){switch(nn.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 i=sf(e),o=this.getCompilationParameters((e=>this.getEvaluatedCell(this.getters.getCellPosition(e.id)))),n=[];for(let e of i.dependencies)n.push(this.getters.getRangeFromSheetXC(t,e));return i.execute(n,...o).value}getRangeFormattedValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.formattedValue))}getRangeValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.value))}getRangeFormats(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.format))}getEvaluatedCell({sheetId:e,col:t,row:i}){var o,n,s;return void 0===this.getters.getCell({sheetId:e,col:t,row:i})?mn(""):(null===(s=null===(n=null===(o=this.evaluatedCells[e])||void 0===o?void 0:o[t])||void 0===n?void 0:n[i])||void 0===s?void 0:s.call(n))||mn("")}getEvaluatedCells(e){const t=this.getters.getCells(e)||{},i={};for(let e of Object.keys(t)){const t=this.getters.getCellPosition(e);i[e]=this.getEvaluatedCell(t)}return i}getColEvaluatedCells(e,t){var i;return Object.values((null===(i=this.evaluatedCells[e])||void 0===i?void 0:i[t])||[]).filter(et).map((e=>e()))}getEvaluatedCellsInZone(e,t){return Ji(t).map((({col:t,row:i})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:i})))}setEvaluatedCell(e,t){const{col:i,row:o,sheetId:n}=this.getters.getCellPosition(e);this.evaluatedCells[n]||(this.evaluatedCells[n]={}),this.evaluatedCells[n][i]||(this.evaluatedCells[n][i]={}),this.evaluatedCells[n][i][o]=t,this.lazyEvaluation||this.evaluatedCells[n][i][o]()}*getAllCells(){for(const e of this.getters.getSheetIds()){const t=this.getters.getCells(e);for(const e in t)yield t[e]}}evaluate(){this.evaluatedCells={};const e=new Set,t=e=>{var t,n;const s=e.id,{col:r,row:a,sheetId:l}=this.getters.getCellPosition(s),c=null===(n=null===(t=this.evaluatedCells[l])||void 0===t?void 0:t[r])||void 0===n?void 0:n[a];return c||nt((()=>{try{switch(e.isFormula){case!0:return o(e);case!1:return gn(e.content,e.format)}}catch(t){return i(t,e)}}))},i=(e,t)=>{e instanceof Error||(e=new Error(e));const i=(null==e?void 0:e.errorType)||a.GenericError,o=n[2].__lastFnCalled||"",s=new c(i,e.message.replace("[[FUNCTION_NAME]]",o),void 0!==e.logLevel?e.logLevel:l.error);return Sn(t.content,s)},o=t=>{const i=t.id;if(e.has(i))throw new d;n[2].__originCellXC=()=>{const e=n[2].getters.getCellPosition(i);return Bt(e.col,e.row)},e.add(i);const o=t.compiledFormula.execute(t.dependencies,...n);if(e.delete(i),Array.isArray(o.value))throw new Error(s("This formula depends on invalid values"));return mn(o.value,t.format||o.format)},n=this.getCompilationParameters((e=>t(e)()));for(const e of this.getAllCells())this.setEvaluatedCell(e.id,t(e))}getCompilationParameters(e){const t=Object.assign(Object.create($v),this.evalContext,{getters:this.getters}),i=this.getters;const o=t=>{const i=e(t);if(i.type===tn.error)throw i.error;return i};return[function(e,t,n,r){if(t)return{value:Ui(e.zone)};if(!Pi(e.zone))throw new u;if(e.zone.bottom!==e.zone.top||e.zone.left!==e.zone.right)throw new Error(r?s("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",n.toString(),r.toString()):s("Function %s expects its parameters to be single values or single cell references, not ranges.",n.toString()));if(e.invalidSheetName)throw new Error(s("Invalid sheet name: %s",e.invalidSheetName));return function(e){let t;if(!i.tryGetSheet(e.sheetId))throw new Error(s("Invalid sheet name"));return t=i.getCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}),t&&""!==t.content?o(t):{value:null,format:null==t?void 0:t.format}}(e)},function(e){const n=e.sheetId;if(!Pi(e.zone))throw new u;const s=i.getSheetZone(n),r=[],a=Wi(e.zone,s);if(!a)return r.push([]),r;for(let i=a.left;i<=a.right;i++){const n=[];for(let s=a.top;s<=a.bottom;s++){const r=t.getters.getCell({sheetId:e.sheetId,col:i,row:s});n.push(r?o(r):void 0)}r.push(n)}return r},t]}exportForExcel(e){for(let t of e.sheets)for(const e in t.cells){const i={sheetId:t.id,...zt(e)},o=this.getters.getCell(i);if(o){const n=t.cells[e],s=this.getEvaluatedCell(i);n.value=s.value,n.isFormula=o.isFormula&&!this.isBadExpression(o.content),o.format!==s.format&&(n.computedFormat=s.format)}}}isBadExpression(e){try{return sf(e),!1}catch(e){return!0}}}Wv.getters=["evaluateFormula","getRangeFormattedValues","getRangeValues","getRangeFormats","getEvaluatedCell","getEvaluatedCells","getColEvaluatedCells","getEvaluatedCellsInZone"];class Gv extends Bv{constructor(){super(...arguments),this.charts={},this.createRuntimeChart=function(e){const t=nr.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(i){const o=t.find((e=>e.match(i.type)));if(!o)throw new Error("No runtime builder for this chart.");return o.getChartRuntime(i,e)}}(this.getters)}handle(e){if(nn.has(e.type)||sn.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 i=t.zone.left,o=t.zone.top,n=t.sheetId;return this.getters.getCellComputedStyle({sheetId:n,col:i,row:o}).fillColor||w}}Gv.getters=["getChartRuntime","getBackgroundOfSingleCellChart"];class qv extends Bv{constructor(){super(...arguments),this.isStale=!0,this.computedStyles={},this.computedIcons={},this.rulePredicate={CellIsRule:(e,t)=>{if(e.type===tn.error)return!1;const i=t.values.map(pn);switch(t.operator){case"IsEmpty":return""===e.value.toString().trim();case"IsNotEmpty":return""!==e.value.toString().trim();case"BeginsWith":return""!==i[0]&&e.value.toString().startsWith(i[0].toString());case"EndsWith":return""!==i[0]&&e.value.toString().endsWith(i[0].toString());case"Between":return e.value>=i[0]&&e.value<=i[1];case"NotBetween":return!(e.value>=i[0]&&e.value<=i[1]);case"ContainsText":return e.value.toString().indexOf(i[0].toString())>-1;case"NotContains":return!e.value||-1==e.value.toString().indexOf(i[0].toString());case"GreaterThan":return e.value>i[0];case"GreaterThanOrEqual":return e.value>=i[0];case"LessThan":return e.value<i[0];case"LessThanOrEqual":return e.value<=i[0];case"NotEqual":return""!==i[0]&&e.value!==i[0];case"Equal":return""===i[0]||e.value===i[0];default:console.warn(s("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}}}handle(e){switch((sn.has(e.type)||"UPDATE_CELL"===e.type&&"content"in e)&&(this.isStale=!0),e.type){case"ACTIVATE_SHEET":const t=e.sheetIdTo;this.computedStyles[t]=this.computedStyles[t]||{},this.computedIcons[t]=this.computedIcons[t]||{},this.isStale=!0;break;case"AUTOFILL_CELL":const i=this.getters.getActiveSheetId(),o=this.getters.getRulesByCell(i,e.originCol,e.originRow);for(const t of o)this.adaptRules(i,t,[Bt(e.col,e.row)],[]);break;case"PASTE_CONDITIONAL_FORMAT":this.pasteCf(e.origin,e.target,e.operation)}}finalize(){this.isStale&&(this.computeStyles(),this.isStale=!1)}getCellComputedStyle(e){var t;const{sheetId:i,col:o,row:n}=e,s=this.getters.getCell(e),r=this.computedStyles[i],a=r&&(null===(t=r[o])||void 0===t?void 0:t[n]),l={...null==s?void 0:s.style,...a};return this.getters.getEvaluatedCell(e).link&&!l.textColor&&(l.textColor=x),this.getters.isFilterHeader(e)&&(l.bold=!0),l}getConditionalIcon({col:e,row:t}){var i;const o=this.getters.getActiveSheetId(),n=this.computedIcons[o];return n&&(null===(i=n[e])||void 0===i?void 0:i[t])}computeStyles(){var e;const t=this.getters.getActiveSheetId();this.computedStyles[t]={},this.computedIcons[t]={};const i=this.computedStyles[t];for(let o of this.getters.getConditionalFormats(t).reverse())try{switch(o.rule.type){case"ColorScaleRule":for(let e of o.ranges)this.applyColorScale(e,o.rule);break;case"IconSetRule":for(let e of o.ranges)this.applyIcon(e,o.rule);break;default:for(let n of o.ranges){const s=this.getters.getRangeFromSheetXC(t,n).zone;for(let n=s.top;n<=s.bottom;n++)for(let r=s.left;r<=s.right;r++){const s=this.rulePredicate[o.rule.type];let a=this.getters.getEvaluatedCell({sheetId:t,col:r,row:n});s&&s(a,o.rule)&&(i[r]||(i[r]=[]),i[r][n]=Object.assign((null===(e=i[r])||void 0===e?void 0:e[n])||{},o.rule.style))}}}}catch(e){}}parsePoint(e,t,i){const o=this.getters.getActiveSheetId(),n=this.getters.getEvaluatedCellsInZone(o,this.getters.getRangeFromSheetXC(o,e).zone).filter((e=>e.type===tn.number)).map((e=>e.value));switch(t.type){case"value":return"max"===i?Math.max(...n):Math.min(...n);case"number":return Number(t.value);case"percentage":const e=Math.min(...n);return e+(Math.max(...n)-e)*Number(t.value)/100;case"percentile":return ti(n,Number(t.value)/100,!0);case"formula":const o=t.value&&this.getters.evaluateFormula(t.value);return o instanceof Promise?null:o;default:return null}}applyIcon(e,t){const i=this.parsePoint(e,t.lowerInflectionPoint),o=this.parsePoint(e,t.upperInflectionPoint);if(null===i||null===o||i>o)return;const n=this.getters.getActiveSheetId(),s=this.getters.getRangeFromSheetXC(n,e).zone,r=this.computedIcons[n],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=s.top;e<=s.bottom;e++)for(let l=s.left;l<=s.right;l++){const s=this.getters.getEvaluatedCell({sheetId:n,col:l,row:e});if(s.type!==tn.number)continue;const c=this.computeIcon(s.value,o,t.upperInflectionPoint.operator,i,t.lowerInflectionPoint.operator,a);r[l]||(r[l]=[]),r[l][e]=c}}computeIcon(e,t,i,o,n,s){return"ge"===i&&e>=t||"gt"===i&&e>t?s[0]:"ge"===n&&e>=o||"gt"===n&&e>o?s[1]:s[2]}applyColorScale(e,t){var i;const o=this.parsePoint(e,t.minimum,"min"),n=t.midpoint?this.parsePoint(e,t.midpoint):null,s=this.parsePoint(e,t.maximum,"max");if(null===o||null===s||o>=s||n&&(o>=n||n>=s))return;const r=this.getters.getActiveSheetId(),a=this.getters.getRangeFromSheetXC(r,e).zone,l=this.computedStyles[r],c=[];t.midpoint&&n?(c.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,n,t.minimum.color,t.midpoint.color)}),c.push({minValue:n,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(n,s,t.midpoint.color,t.maximum.color)})):c.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,s,t.minimum.color,t.maximum.color)});for(let e=a.top;e<=a.bottom;e++)for(let t=a.left;t<=a.right;t++){const a=this.getters.getEvaluatedCell({sheetId:r,col:t,row:e});if(a.type===tn.number){const r=De(a.value,o,s);let h;h=2===c.length&&n?r<=n?this.colorCell(r,c[0].minValue,c[0].minColor,c[0].colorDiffUnit):this.colorCell(r,c[1].minValue,c[1].minColor,c[1].colorDiffUnit):this.colorCell(r,c[0].minValue,c[0].minColor,c[0].colorDiffUnit),l[t]||(l[t]=[]),l[t][e]=(null===(i=l[t])||void 0===i?void 0:i[e])||{},l[t][e].fillColor=vt(h)}}}computeColorDiffUnits(e,t,i,o){const n=t-e;return[((i>>16)%256-(o>>16)%256)/n,((i>>8)%256-(o>>8)%256)/n,(i%256-o%256)/n]}colorCell(e,t,i,o){const[n,s,r]=o;return Math.round((i>>16)%256-n*(e-t))<<16|Math.round((i>>8)%256-s*(e-t))<<8|Math.round(i%256-r*(e-t))}adaptRules(e,t,i,o){if(0===i.length&&0===o.length)return;const n=this.getters.getConditionalFormats(e),s=n.findIndex((e=>e.id===t.id));let r=[];s>-1&&(r=n[s].ranges),r=r.concat(i);const a=Xi(r,o);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,i){const o=Bt(t.col,t.row);for(let n of this.getters.getConditionalFormats(e.sheetId))for(let s of n.ranges)if(Zi(e.col,e.row,this.getters.getRangeFromSheetXC(e.sheetId,s).zone)){const s=n,r=[];"CUT"===i&&r.push(Bt(e.col,e.row)),e.sheetId===t.sheetId?this.adaptRules(e.sheetId,s,[o],r):(this.adaptRules(t.sheetId,s,[o],[]),this.adaptRules(e.sheetId,s,[],r))}}}qv.getters=["getConditionalIcon","getCellComputedStyle"];class Zv extends Bv{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 i of this.getters.getFilters(e.sheetIdTo)){const o=i.zoneWithHeaders;t[i.id]=this.getFilterValues({sheetId:e.sheetId,col:o.left,row:o.top})}this.filterValues[e.sheetIdTo]=t}}finalize(){this.isEvaluationDirty&&(this.updateHiddenRows(),this.isEvaluationDirty=!1)}isRowFiltered(e,t){return e===this.getters.getActiveSheetId()&&this.hiddenRows.has(t)}getCellBorderWithFilterBorder(e){const{sheetId:t,col:i,row:o}=e;let n;for(let e of this.getters.getFilterTables(t)){const s=e.zone;if(Zi(i,o,s)){const e=this.intersectZoneWithViewport(t,s);n={top:o===e.top?j:void 0,bottom:o===e.bottom?j:void 0,left:i===e.left?j:void 0,right:i===e.right?j:void 0}}}const s=this.getters.getCellBorder(e),r={...n,...lt(s||{})};return tt(r)?null:r}getFilterHeaders(e){const t=[];for(let i of this.getters.getFilterTables(e)){const o=i.zone;if(!o)continue;const n=o.top;for(let i=o.left;i<=o.right;i++)this.getters.isColHidden(e,i)||this.getters.isRowHidden(e,n)||t.push({col:i,row:n})}return t}getFilterValues(e){const t=this.getters.getFilterId(e),i=e.sheetId;return t&&this.filterValues[i]&&this.filterValues[i][t]||[]}isFilterHeader({sheetId:e,col:t,row:i}){return this.getFilterHeaders(e).some((e=>e.col===t&&e.row===i))}isFilterActive(e){var t,i;const o=this.getters.getFilterId(e),n=e.sheetId;return Boolean(o&&(null===(i=null===(t=this.filterValues[n])||void 0===t?void 0:t[o])||void 0===i?void 0:i.length))}intersectZoneWithViewport(e,t){return{left:this.getters.findVisibleHeader(e,"COL",t.left,t.right),right:this.getters.findVisibleHeader(e,"COL",t.right,t.left),top:this.getters.findVisibleHeader(e,"ROW",t.top,t.bottom),bottom:this.getters.findVisibleHeader(e,"ROW",t.bottom,t.top)}}updateFilter({col:e,row:t,values:i,sheetId:o}){const n=this.getters.getFilterId({sheetId:o,col:e,row:t});n&&(this.filterValues[o]||(this.filterValues[o]={}),this.filterValues[o][n]=i)}updateHiddenRows(){var e,t;const i=this.getters.getActiveSheetId(),o=this.getters.getFilters(i).sort(((e,t)=>e.zoneWithHeaders.top-t.zoneWithHeaders.top)),n=new Set;for(let s of o){if(this.getters.isRowHiddenByUser(i,s.zoneWithHeaders.top))continue;if(n.has(s.zoneWithHeaders.top))continue;const o=null===(t=null===(e=this.filterValues[i])||void 0===e?void 0:e[s.id])||void 0===t?void 0:t.map(ct);if(o&&s.filteredZone)for(let e=s.filteredZone.top;e<=s.filteredZone.bottom;e++){const t=this.getCellValueAsString(i,s.col,e);o.includes(t)&&n.add(e)}}this.hiddenRows=n}getCellValueAsString(e,t,i){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:i}).formattedValue.toLowerCase()}exportForExcel(e){for(const t of e.sheets)for(const e of t.filterTables){const i=Li(e.range),o=[],n=[];for(const e of ze(0,Ki(i).numberOfCols)){const s={sheetId:t.id,col:i.left+e,row:i.top},r=this.getFilterValues(s),a=this.getters.getFilter(s);if(!a)continue;const l=(a.filteredZone?Ji(a.filteredZone).map((({col:e,row:i})=>this.getters.getEvaluatedCell({sheetId:t.id,col:e,row:i}))).filter((e=>e.type!==tn.empty)).map((e=>e.formattedValue)):[]).filter((e=>!r.includes(e)));o.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[Bt(c.col,c.row)]={...t.cells[Bt(c.col,c.row)],content:d,value:d,isFormula:!1}}e.filters=o}}getUniqueColNameForExcel(e,t,i){t||(t=`Column${e}`);let o=t,n=2;for(;i.includes(o);)o=t+String(n),n++;return o}}Zv.getters=["getCellBorderWithFilterBorder","getFilterHeaders","getFilterValues","isFilterHeader","isRowFiltered","isFilterActive"];class jv{constructor(e,t,i,o,n,s){this.getters=e,this.sheetId=t,this.boundaries=i,this.viewportWidth=o.width,this.viewportHeight=o.height,this.offsetScrollbarX=s.x,this.offsetScrollbarY=s.y,this.canScrollVertically=n.canScrollVertically,this.canScrollHorizontally=n.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){const e=this.getters.findLastVisibleColRowIndex(this.sheetId,"COL",{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,"ROW",{first:this.boundaries.top,last:this.boundaries.bottom}),{end:i,size:o}=this.getters.getColDimensions(this.sheetId,e),{end:n,size:s}=this.getters.getRowDimensions(this.sheetId,t),r=this.searchHeaderIndex("COL",i-this.viewportWidth,0),a=this.getters.getColSize(this.sheetId,r),l=this.searchHeaderIndex("ROW",n-this.viewportHeight,0),c=this.getters.getRowSize(this.sheetId,l);let h=i-this.offsetCorrectionX;this.canScrollHorizontally&&(h+=Math.max(_,Math.min(a,this.viewportWidth-o)),h=Math.max(h,this.viewportWidth));let d=n-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(F+5,Math.min(c,this.viewportHeight-s)),d=Math.max(d,this.viewportHeight)),{width:h,height:d}}getColIndex(e,t=!1){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex("COL",e-this.offsetCorrectionX,this.left,t)}getRowIndex(e,t=!1){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex("ROW",e-this.offsetCorrectionY,this.top,t)}adjustPosition(e){const t=this.sheetId;e||(e=this.getters.getSheetPosition(t));const i=this.getters.getMainCellPosition({sheetId:t,...e}),{col:o,row:n}=this.getters.getNextVisibleCellPosition(i);Zi(o,this.boundaries.top,this.boundaries)&&this.adjustPositionX(o),Zi(this.boundaries.left,n,this.boundaries)&&this.adjustPositionY(n)}adjustPositionX(e){const t=this.sheetId,{end:i}=this.getters.getColDimensions(t,e),o=this.getters.getNumberCols(t);if(this.offsetX+this.offsetCorrectionX+this.viewportWidth<i)for(let e=this.left;this.offsetX+this.offsetCorrectionX+this.viewportWidth<i&&!(e>o);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 i=this.left;i>=e&&!(i<0);i--)this.getters.isColHidden(t,i)||(this.offsetX=this.getters.getColDimensions(t,i).start-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX())}adjustPositionY(e){const t=this.sheetId,{end:i}=this.getters.getRowDimensions(t,e),o=this.getters.getNumberRows(t);if(this.offsetY+this.viewportHeight+this.offsetCorrectionY<i)for(let e=this.top;this.offsetY+this.viewportHeight+this.offsetCorrectionY<i&&!(e>o);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 i=this.top;i>=e&&!(i<0);i--)this.getters.isRowHidden(t,i)||(this.offsetY=this.getters.getRowDimensions(t,i).start-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY())}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getRect(e){const t=Wi(e,this.zone);if(t){return{x:this.getters.getColRowOffset("COL",this.zone.left,t.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset("ROW",this.zone.top,t.top)+this.offsetCorrectionY,width:Math.min(this.getters.getColRowOffset("COL",t.left,t.right+1),this.viewportWidth),height:Math.min(this.getters.getColRowOffset("ROW",t.top,t.bottom+1),this.viewportHeight)}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,i=0,o=!1){let n=0;const s=this.sheetId,r=this.getters.getNumberHeaders(s,e);for(let a=i;a<=r-1;a++){const i=o||"COL"!==e?a<this.top&&a>this.bottom:a<this.left&&a>this.right;if(!this.getters.isHeaderHidden(s,e,a)&&!i&&(n+="COL"===e?this.getters.getColSize(s,a):this.getters.getRowSize(s,a),n>t))return a}return-1}get zone(){return{left:this.left,right:this.right,top:this.top,bottom:this.bottom}}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetScrollbarX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetScrollbarY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){const{width:e}=this.getMaxSize();this.viewportWidth+this.offsetScrollbarX>e&&(this.offsetScrollbarX=Math.max(0,e-this.viewportWidth))}this.left=this.getColIndex(this.offsetScrollbarX,!0),this.right=this.getColIndex(this.offsetScrollbarX+this.viewportWidth,!0),-1===this.right&&(this.right=this.boundaries.right),this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){const{height:e}=this.getMaxSize();this.viewportHeight+this.offsetScrollbarY>e&&(this.offsetScrollbarY=Math.max(0,e-this.viewportHeight))}this.top=this.getRowIndex(this.offsetScrollbarY,!0),this.bottom=this.getRowIndex(this.offsetScrollbarY+this.viewportWidth,!0),-1===this.bottom&&(this.bottom=this.boundaries.bottom),this.adjustViewportZoneY()}adjustViewportZoneX(){const e=this.sheetId;this.left=this.searchHeaderIndex("COL",this.offsetScrollbarX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex("COL",this.viewportWidth,this.left)),-1===this.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 Xv extends Bv{constructor(){super(...arguments),this.viewports={},this.sheetViewWidth=1e3,this.sheetViewHeight=1e3,this.gridOffsetX=0,this.gridOffsetY=0,this.sheetsWithDirtyViewports=new Set}allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.checkScrollingDirection(e);case"RESIZE_SHEETVIEW":return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return 0}}handleEvent(e){switch(e.type){case"HeadersSelected":case"AlterZone":break;case"ZonesSelected":let{col:t,row:i}=to(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const o=e.previousAnchor.zone,n=e.anchor.zone,{top:s,bottom:r,left:a,right:l}=this.getters.getActiveMainViewport();o.left===n.left&&o.right===n.right&&(t=a>t||t>l?a:t),o.top===n.top&&o.bottom===n.bottom&&(i=s>i||i>r?s:i)}const o=this.getters.getActiveSheetId();t=Math.min(t,this.getters.getNumberCols(o)-1),i=Math.min(i,this.getters.getNumberRows(o)-1),this.refreshViewport(this.getters.getActiveSheetId(),{col:t,row:i})}}handle(e){var t;switch(this.cleanViewports(),e.type){case"START":this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case"UNDO":case"REDO":this.resetSheetViews();break;case"RESIZE_SHEETVIEW":this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case"SET_VIEWPORT_OFFSET":this.setSheetViewOffset(e.offsetX,e.offsetY);break;case"SHIFT_VIEWPORT_DOWN":const{top:i}=this.getActiveMainViewport(),o=this.getters.getActiveSheetId(),n=this.clipOffsetY(this.getters.getRowDimensions(o,i).start+this.sheetViewHeight);this.shiftVertically(n);break;case"SHIFT_VIEWPORT_UP":{const{top:e}=this.getActiveMainViewport(),t=this.getters.getActiveSheetId(),i=this.clipOffsetY(this.getters.getRowDimensions(t,e).end-this.sheetViewHeight);this.shiftVertically(i);break}case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"UPDATE_FILTER":this.resetViewports(e.sheetId);break;case"UPDATE_CELL":("content"in e||"format"in e||void 0!==(null===(t=e.style)||void 0===t?void 0:t.fontSize))&&this.sheetsWithDirtyViewports.add(e.sheetId);break;case"ACTIVATE_SHEET":this.setViewports(),this.refreshViewport(e.sheetIdTo);break;case"UNFREEZE_ROWS":case"UNFREEZE_COLUMNS":case"FREEZE_COLUMNS":case"FREEZE_ROWS":case"UNFREEZE_COLUMNS_ROWS":this.resetViewports(this.getters.getActiveSheetId());break;case"DELETE_SHEET":this.sheetsWithDirtyViewports.delete(e.sheetId);break;case"START_EDITION":const{col:s,row:r}=this.getters.getActivePosition();this.refreshViewport(this.getters.getActiveSheetId(),{col:s,row:r})}}finalize(){for(const e of this.sheetsWithDirtyViewports)this.resetViewports(e);this.sheetsWithDirtyViewports=new Set,this.setViewports()}setViewports(){var e;const t=this.getters.getSheetIds();for(const i of t)(null===(e=this.viewports[i])||void 0===e?void 0:e.bottomRight)||this.resetViewports(i)}getColIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getColIndex(e))))}getRowIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getRowIndex(e))))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getActiveMainViewport(){const e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getActiveSheetDOMScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetScrollbarX,scrollY:t.offsetScrollbarY}}getSheetViewVisibleCols(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>ze(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=>ze(e.top,e.bottom+1))).flat())].filter((t=>!this.getters.isHeaderHidden(e,"ROW",t)))}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:i,ySplit:o}=this.getters.getPaneDivisions(e);let{width:n,height:s}=t.getMaxSize();return{x:this.getters.getColDimensions(e,i).start,y:this.getters.getRowDimensions(e,o).start,width:n,height:s}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:i}=this.getMainViewportRect(),o=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-o.viewportWidth+1),maxOffsetY:Math.max(0,i-o.viewportHeight+1)}}getColRowOffsetInViewport(e,t,i){const o=this.getters.getActiveSheetId(),n=this.getters.getSheetViewVisibleCols(),s=this.getters.getSheetViewVisibleRows();if(i<t)return-this.getColRowOffsetInViewport(e,i,t);let r=0;const a="COL"===e?n:s;for(let n=t;n<i;n++)a.includes(n)&&(r+="COL"===e?this.getters.getColSize(o,n):this.getters.getRowSize(o,n));return r}isVisibleInViewport({sheetId:e,col:t,row:i}){return this.getSubViewports(e).some((e=>e.isVisible(t,i)))}getEdgeScrollCol(e,t,i){let o=!1,n=0,s=0;const{xSplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(o=!0,s=Gt(e-a),n=1):e<l&&i>=l&&c>0?(o=!0,s=Gt(l-e),n=-1):r&&t<l&&e>l&&(o=!0,s=Gt(e),n="reset"),{canEdgeScroll:o,direction:n,delay:s}}getEdgeScrollRow(e,t,i){let o=!1,n=0,s=0;const{ySplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(o=!0,s=Gt(e-a),n=1):e<l&&i>=l&&c>0?(o=!0,s=Gt(l-e),n=-1):r&&t<l&&e>l&&(o=!0,s=Gt(e),n="reset"),{canEdgeScroll:o,direction:n,delay:s}}getVisibleRect(e){const t=this.getters.getActiveSheetId(),i=this.getSubViewports(t).map((t=>t.getRect(e))).filter(et);if(0===i.length)return{x:0,y:0,width:0,height:0};const o=Math.min(...i.map((e=>e.x))),n=Math.min(...i.map((e=>e.y))),s=Math.max(...i.map((e=>e.x+e.width)))-o,r=Math.max(...i.map((e=>e.y+e.height)))-n;return{x:o+this.gridOffsetX,y:n+this.gridOffsetY,width:s,height:r}}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,i).start}}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(et)}checkPositiveDimension(e){return e.width<0||e.height<0?68:0}checkValuesAreDifferent(e){const{height:t,width:i}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===i&&e.height===t?76:0}checkScrollingDirection({offsetX:e,offsetY:t}){const i=this.getMainInternalViewport(this.getters.getActiveSheetId());return!i.canScrollHorizontally&&e>0||!i.canScrollVertically&&t>0?69:0}getMainViewport(e){const t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){const e=this.getters.getSheetIds();for(let t of Object.keys(this.viewports))e.includes(t)||delete this.viewports[t]}resetSheetViews(){for(let e of Object.keys(this.viewports)){const t=this.getters.getSheetPosition(e);this.resetViewports(e);const i=this.getSubViewports(e);Object.values(i).forEach((e=>{e.adjustPosition(t)}))}}resizeSheetView(e,t,i=0,o=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=i,this.gridOffsetY=o,this.recomputeViewports()}recomputeViewports(){for(let e of Object.keys(this.viewports))this.resetViewports(e)}setSheetViewOffset(e,t){const i=this.getters.getActiveSheetId(),{maxOffsetX:o,maxOffsetY:n}=this.getMaximumSheetOffset();Object.values(this.getSubViewports(i)).forEach((i=>i.setViewportOffset(De(e,0,o),De(t,0,n))))}clipOffsetY(e){const{height:t}=this.getMainViewportRect(),i=t-this.sheetViewHeight;return e=Math.min(e,i),e=Math.max(e,0)}getViewportOffset(e){var t,i;return{x:(null===(t=this.viewports[e])||void 0===t?void 0:t.bottomRight.offsetScrollbarX)||0,y:(null===(i=this.viewports[e])||void 0===i?void 0:i.bottomRight.offsetScrollbarY)||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e),o=this.getters.getNumberCols(e),n=this.getters.getNumberRows(e),s=this.getters.getColRowOffset("COL",0,t,e),r=this.getters.getColRowOffset("ROW",0,i,e),{xRatio:a,yRatio:l}=this.getFrozenSheetViewRatio(e),c=a<1,h=l<1,d=this.getViewportOffset(e),u={topLeft:i&&t&&new jv(this.getters,e,{left:0,right:t-1,top:0,bottom:i-1},{width:s,height:r},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:i&&new jv(this.getters,e,{left:t,right:o-1,top:0,bottom:i-1},{width:this.sheetViewWidth-s,height:r},{canScrollHorizontally:c,canScrollVertically:!1},{x:c?d.x:0,y:0})||void 0,bottomLeft:t&&new jv(this.getters,e,{left:0,right:t-1,top:i,bottom:n-1},{width:s,height:this.sheetViewHeight-r},{canScrollHorizontally:!1,canScrollVertically:h},{x:0,y:h?d.y:0})||void 0,bottomRight:new jv(this.getters,e,{left:t,right:o-1,top:i,bottom:n-1},{width:this.sheetViewWidth-s,height:this.sheetViewHeight-r},{canScrollHorizontally:c,canScrollVertically:h},{x:c?d.x:0,y:h?d.y:0})};this.viewports[e]=u}refreshViewport(e,t){Object.values(this.getSubViewports(e)).forEach((e=>{e.adjustViewportZone(),e.adjustPosition(t)}))}shiftVertically(e){const{top:t}=this.getActiveMainViewport(),{scrollX:i}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(i,e);const{anchor:o}=this.getters.getSelection(),n=this.getActiveMainViewport().top-t;this.selection.selectCell(o.cell.col,o.cell.row+n)}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],i=this.getters.getFigures(e),{scrollX:o,scrollY:n}=this.getActiveSheetScrollInfo(),{x:s,y:r}=this.getters.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const e of i)e.x>=s&&(e.x+e.width<=s+o||e.x>=a+o+s)||e.y>=r&&(e.y+e.height<=r+n||e.y>=l+n+r)||t.push(e);return t}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e),o=this.getters.getColDimensions(e,t).start,n=this.getters.getRowDimensions(e,i).start;return{xRatio:o/(this.sheetViewWidth+this.gridOffsetX),yRatio:n/(this.sheetViewHeight+this.gridOffsetY)}}}Xv.getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getActiveSheetDOMScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio"];class Yv{constructor(e,t,i){this.index=0,this.cells=e,this.getters=t,this.direction=i}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:i,tooltip:o}=En.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:i,tooltip:o,origin:{col:e.data.col,row:e.data.row}}}}class Kv extends Bv{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:De(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:De(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?0:45;case"AUTOFILL_AUTO":const i=this.getters.getSelectedZone();return i.top===i.bottom?0:1}return 0}handle(e){switch(e.type){case"AUTOFILL":this.autofill(!0);break;case"AUTOFILL_SELECT":this.select(e.col,e.row);break;case"AUTOFILL_AUTO":this.autofillAuto();break;case"AUTOFILL_CELL":this.autoFillMerge(e.originCol,e.originRow,e.col,e.row);const t=this.getters.getActiveSheetId();this.dispatch("UPDATE_CELL",{sheetId:t,col:e.col,row:e.row,style:e.style||null,content:e.content||"",format:e.format||""}),this.dispatch("SET_BORDER",{sheetId:t,col:e.col,row:e.row,border:e.border})}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),i=this.autofillZone;switch(this.direction){case"down":for(let o=t.left;o<=t.right;o++){const n=[];for(let e=t.top;e<=t.bottom;e++)n.push(Bt(o,e));const s=this.createGenerator(n);for(let t=i.top;t<=i.bottom;t++)this.computeNewCell(s,o,t,e)}break;case"up":for(let o=t.left;o<=t.right;o++){const n=[];for(let e=t.bottom;e>=t.top;e--)n.push(Bt(o,e));const s=this.createGenerator(n);for(let t=i.bottom;t>=i.top;t--)this.computeNewCell(s,o,t,e)}break;case"left":for(let o=t.top;o<=t.bottom;o++){const n=[];for(let e=t.right;e>=t.left;e--)n.push(Bt(e,o));const s=this.createGenerator(n);for(let t=i.right;t>=i.left;t--)this.computeNewCell(s,t,o,e)}break;case"right":for(let o=t.top;o<=t.bottom;o++){const n=[];for(let e=t.left;e<=t.right;e++)n.push(Bt(e,o));const s=this.createGenerator(n);for(let t=i.left;t<=i.right;t++)this.computeNewCell(s,t,o,e)}}e&&(this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0)}select(e,t){const i=this.getters.getSelectedZone();if(Zi(e,t,i))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,i.top-1,i.left,i.right),this.steps=i.top-t;break;case"down":this.saveZone(i.bottom+1,t,i.left,i.right),this.steps=t-i.bottom;break;case"left":this.saveZone(i.top,i.bottom,e,i.left-1),this.steps=i.left-e;break;case"right":this.saveZone(i.top,i.bottom,i.right+1,e),this.steps=e-i.right}this.autofill(!1)}}autofillAuto(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let i=e.left,o=e.bottom;if(i>0){let e=this.getters.getEvaluatedCell({sheetId:t,col:i-1,row:o});for(;e.type!==tn.empty;)o+=1,e=this.getters.getEvaluatedCell({sheetId:t,col:i-1,row:o})}if(o===e.bottom&&(i=e.right,i<=this.getters.getNumberCols(t))){let e=this.getters.getEvaluatedCell({sheetId:t,col:i+1,row:o});for(;e.type!==tn.empty;)o+=1,e=this.getters.getEvaluatedCell({sheetId:t,col:i+1,row:o})}o!==e.bottom&&(this.select(e.left,o-1),this.autofill(!0))}computeNewCell(e,t,i,o){const{cellData:n,tooltip:s,origin:r}=e.next(),{content:a,style:l,border:c,format:h}=n;this.tooltip=s,o&&this.dispatch("AUTOFILL_CELL",{originCol:r.col,originRow:r.row,col:t,row:i,content:a,style:l,border:c,format:h})}getRule(e,t){const i=wn.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((i=>i.condition(e,t)));return i&&i.generateRule(e,t)}createGenerator(e){const t=[],i=[],o=this.getters.getActiveSheetId();for(let t of e){const{col:e,row:n}=zt(t),s=this.getters.getCell({sheetId:o,col:e,row:n});i.push({col:e,row:n,cell:s,sheetId:o})}const n=i.map((e=>e.cell));for(let e of i){let i={type:"COPY_MODIFIER"};if(e&&e.cell){i=this.getRule(e.cell,n)||i}const o=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:o},rule:i})}return new Yv(t,this.getters,this.direction)}saveZone(e,t,i,o){this.autofillZone={top:e,bottom:t,left:i,right:o}}getDirection(e,t){const i=this.getters.getSelectedZone(),o={up:{number:i.top-t,value:"up"},down:{number:t-i.bottom,value:"down"},left:{number:i.left-e,value:"left"},right:{number:e-i.right,value:"right"}};if(1===Object.values(o).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(o).find((e=>e.number>0?1:0)).value;const n=o.up.number>0?"up":"down",s=o.left.number>0?"left":"right";return Math.abs(o[n].number)>=Math.abs(o[s].number)?o[n].value:o[s].value}autoFillMerge(e,t,i,o){const n=this.getters.getActiveSheetId(),s={sheetId:n,col:i,row:o},r={sheetId:n,col:e,row:t};if(this.getters.isInMerge(s)&&!this.getters.isInMerge(r)){const e=this.getters.getMerge(s);e&&this.dispatch("REMOVE_MERGE",{sheetId:n,target:[e]})}const a=this.getters.getMerge(r);(null==a?void 0:a.topLeft.col)===e&&(null==a?void 0:a.topLeft.row)===t&&this.dispatch("ADD_MERGE",{sheetId:n,target:[{top:o,bottom:o+a.bottom-a.top,left:i,right:i+a.right-a.left}]})}drawGrid(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:i}=e,{x:o,y:n,width:s,height:r}=this.getters.getVisibleRect(this.autofillZone);s>0&&r>0&&(t.strokeStyle="black",t.lineWidth=i,t.setLineDash([3]),t.strokeRect(o,n,s,r),t.setLineDash([]))}}Kv.layers=[5],Kv.getters=["getAutofillTooltip"];class Qv extends Bv{handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:i}=this.getters.getSelection();for(const o of t){const t=this.getAutomaticSums(e,o,i.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,i){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,i):this.sumData(e,t)}sumData(e,t){const i=this.dimensionsToSum(e,t),o=this.sumDimensions(e,t,i).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return i.has("ROW")&&i.has("COL")&&o.push(this.sumTotal(t)),o}sumAdjacentData(e,t,i){const{col:o,row:n}=Zi(i.col,i.row,t)?i:{col:t.left,row:t.top},s=this.findAdjacentData(e,o,n);return s?this.getters.isSingleCellOrMerge(e,t)||Qi($i(s,t))?[{position:{col:o,row:n},zone:s}]:this.sumDimensions(e,$i(s,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,i){const o=this.getters.getSheet(e),n=this.getters.getMainCellPosition({sheetId:e,col:t,row:i}),s=this.findSuitableZoneToSum(o,n.col,n.row);if(s)return this.getters.expandZone(e,s)}findSuitableZoneToSum(e,t,i){const o=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:i-1}),n=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:i});if(this.isNumber(n)&&!this.isNumber(o))return this.findHorizontalZone(e,t,i);const s=this.findVerticalZone(e,t,i);if(this.isZoneValid(s))return s;const r=this.findHorizontalZone(e,t,i);return this.isZoneValid(r)?r:void 0}findVerticalZone(e,t,i){const o={top:0,bottom:i-1,left:t,right:t},n=this.reduceZoneStart(e,o,o.bottom);return{...o,top:n}}findHorizontalZone(e,t,i){const o={top:i,bottom:i,left:0,right:t-1},n=this.reduceZoneStart(e,o,o.right);return{...o,left:n}}reduceZoneStart(e,t,i){const o=this.getters.getEvaluatedCellsInZone(e.id,t),n=ze(i,-1,-1),s=n.filter((e=>o[e]&&!o[e].isAutoSummable)),r=Math.max(...s),a=Be(n.filter((e=>this.isNumber(o[e]))))[0]||[];return Math.max(...a)<r?1/0:Math.min(...a)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){var t;return e.type===tn.number&&!(null===(t=e.format)||void 0===t?void 0:t.match(X))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){const i=new Set;return Qi(t)?(i.add(1===Ki(t).numberOfCols?"COL":"ROW"),i):(this.lastColIsEmpty(e,t)&&i.add("ROW"),this.lastRowIsEmpty(e,t)&&i.add("COL"),0===i.size&&i.add("COL"),i)}sumDimensions(e,t,i){return[...i.has("COL")?this.sumColumns(t,e):[],...i.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:i}=e;return{position:{col:i,row:t},zone:{...e,top:t,right:i-1}}}sumColumns(e,t){const i=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,i.bottom-1)},Ji(i).map((t=>({position:t,zone:{...e,right:t.col,left:t.col}})))}sumRows(e,t){const i=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,i.right-1)},Ji(i).map((t=>({position:t,zone:{...e,top:t.row,bottom:t.row}})))}dispatchCellUpdates(e,t){for(const i of t){const{col:t,row:o}=i.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,content:`=SUM(${this.getters.zoneToXC(e,i.zone)})`})}}nextEmptyRow(e,t){let i=t.bottom+1;const{left:o,right:n}=t;for(;!this.getters.isEmpty(e,{bottom:i,top:i,left:o,right:n});)i++;return{...t,top:i,bottom:i}}nextEmptyCol(e,t){let i=t.right+1;const{top:o,bottom:n}=t;for(;!this.getters.isEmpty(e,{left:i,right:i,top:o,bottom:n});)i++;return{...t,left:i,right:i}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}Qv.getters=["getAutomaticSums"];class Jv extends Bv{allowDispatch(e){if("OPEN_CELL_POPOVER"===e.type){try{is.get(e.popoverType)}catch(e){return 72}return 0}return 0}handle(e){switch(e.type){case"ACTIVATE_SHEET":case"CLOSE_CELL_POPOVER":this.persistentPopover=void 0;break;case"OPEN_CELL_POPOVER":this.persistentPopover={col:e.col,row:e.row,sheetId:this.getters.getActiveSheetId(),type:e.popoverType}}}getCellPopover({col:e,row:t}){var i,o;const n=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){const e=this.getters.getMainCellPosition(this.persistentPopover),t=null===(o=(i=is.get(this.persistentPopover.type)).onOpen)||void 0===o?void 0:o.call(i,e,this.getters);return(null==t?void 0:t.isOpen)?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}if(void 0===e||void 0===t||!this.getters.isVisibleInViewport({sheetId:n,col:e,row:t}))return{isOpen:!1};const s=this.getters.getMainCellPosition({sheetId:n,col:e,row:t}),r=is.getAll().map((e=>{var t;return null===(t=e.onHover)||void 0===t?void 0:t.call(e,s,this.getters)})).find((e=>null==e?void 0:e.isOpen));return(null==r?void 0:r.isOpen)?{...r,anchorRect:this.computePopoverAnchorRect(s)}:{isOpen:!1}}hasOpenedPopover(){return void 0!==this.persistentPopover}getPersistentPopoverTypeAtPosition({col:e,row:t}){if(this.persistentPopover&&this.persistentPopover.col===e&&this.persistentPopover.row===t)return this.persistentPopover.type}computePopoverAnchorRect({col:e,row:t}){const i=this.getters.getActiveSheetId(),o=this.getters.getMerge({sheetId:i,col:e,row:t});return o?this.getters.getVisibleRect(o):this.getters.getVisibleRect(oo({col:e,row:t}))}}Jv.getters=["getCellPopover","getPersistentPopoverTypeAtPosition","hasOpenedPopover"];var eb;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(eb||(eb={}));class tb extends Bv{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(eb.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(eb.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(eb.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),i=[];if(this.toSearch)for(const o of Object.values(t)){const{col:t,row:n}=this.getters.getCellPosition(o.id);if(o&&this.currentSearchRegex&&this.currentSearchRegex.test(this.getSearchableString({sheetId:e,col:t,row:n}))){const e={col:t,row:n,selected:!1};i.push(e)}}return i.sort(this.sortByRowThenColumn)}sortByRowThenColumn(e,t){return e.row===t.row?e.col-t.col:e.row>t.row?1:-1}selectNextCell(e){const t=this.searchMatches;if(!t.length)return void(this.selectedMatchIndex=null);let i;i=null===this.selectedMatchIndex?0:this.selectedMatchIndex+e,i=(i%t.length+t.length)%t.length,this.selectedMatchIndex=i,this.selection.selectCell(t[i].col,t[i].row);for(let e=0;e<this.searchMatches.length;e++)this.searchMatches[e].selected=e===this.selectedMatchIndex}clearSearch(){this.toSearch="",this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1}}replace(e){if(null===this.selectedMatchIndex||!this.currentSearchRegex)return;const t=this.searchMatches[this.selectedMatchIndex],i=this.getters.getActiveSheetId(),o=this.getters.getCell({sheetId:i,...t});if((null==o?void 0:o.isFormula)&&!this.searchOptions.searchFormulas)this.selectNextCell(eb.next);else{const o=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),n=this.getSearchableString({sheetId:i,col:t.col,row:t.row}).replace(o,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(eb.current)}}replaceAll(e){const t=this.searchMatches.length;for(let i=0;i<t;i++)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,i=this.getters.getActiveSheetId();for(const e of this.searchMatches){const o=this.getters.getMerge({sheetId:i,col:e.col,row:e.row}),n=o?o.left:e.col,s=o?o.right:e.col,r=o?o.top:e.row,a=o?o.bottom:e.row,{x:l,y:c,width:h,height:d}=this.getters.getVisibleRect({top:r,left:n,right:s,bottom:a});h>0&&d>0&&(t.fillStyle="#8B008B33",t.fillRect(l,c,h,d),e.selected&&(t.strokeStyle="#8B008B",t.strokeRect(l,c,h,d)))}}}tb.layers=[3],tb.getters=["getSearchMatches","getCurrentSelectedMatchIndex"];class ib extends Bv{isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,i){return"COL"===t?this.isColHidden(e,i):this.isRowHidden(e,i)}getNextVisibleCellPosition({sheetId:e,col:t,row:i}){return{sheetId:e,col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",i,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,i,o){if(i<=o)for(let n=i;n<=o;n++)if(this.getters.doesHeaderExist(e,t,n)&&!this.isHeaderHidden(e,t,n))return n;if(i>o)for(let n=i;n>=o;n--)if(this.getters.doesHeaderExist(e,t,n)&&!this.isHeaderHidden(e,t,n))return n}findLastVisibleColRowIndex(e,t,{last:i,first:o}){return ze(i,o,-1).find((i=>!this.isHeaderHidden(e,t,i)))||o}findFirstVisibleColRowIndex(e,t){const i=this.getters.getNumberHeaders(e,t);for(let o=0;o<i;o++){if("COL"===t&&!this.isColHidden(e,o))return o;if("ROW"===t&&!this.isRowHidden(e,o))return o}}exportForExcel(e){for(const t of e.sheets)for(const[e,i]of Object.entries(t.rows)){const o=this.isRowHidden(t.id,Number(e));i.isHidden=o}}}ib.getters=["getNextVisibleCellPosition","findVisibleHeader","findLastVisibleColRowIndex","findFirstVisibleColRowIndex","isRowHidden","isColHidden","isHeaderHidden"];class ob extends Bv{getHighlights(){return this.prepareHighlights(this.getters.getComposerHighlights().concat(this.getters.getSelectionInputHighlights()))}prepareHighlights(e){return e.filter((e=>e.zone.top>=0&&e.zone.left>=0&&e.zone.bottom<this.getters.getNumberRows(e.sheetId)&&e.zone.right<this.getters.getNumberCols(e.sheetId))).map((e=>{const{numberOfRows:t,numberOfCols:i}=Ki(e.zone),o=t*i==1?this.getters.expandZone(e.sheetId,e.zone):e.zone;return{...e,zone:o}}))}drawGrid(e){const{ctx:t,thinLineWidth:i}=e,o=this.getters.getActiveSheetId(),n=3*i;t.lineWidth=n;const s=this.getHighlights();for(let e of s.filter(((e,t)=>s.findIndex((t=>Gi(t.zone,e.zone)&&t.sheetId===o))===t))){const{x:i,y:o,width:s,height:r}=this.getters.getVisibleRect(e.zone);s>0&&r>0&&(t.strokeStyle=e.color,t.strokeRect(i+n/2,o+n/2,s-n,r-n),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(i+n,o+n,s-2*n,r-2*n))}}}ob.layers=[1],ob.getters=["getHighlights"];class nb extends Bv{constructor(){super(...arguments),this.boxes=[]}getColDimensionsInViewport(e,t){const i=Math.min(...this.getters.getSheetViewVisibleCols()),o=this.getters.getColRowOffsetInViewport("COL",i,t),n=this.getters.getColSize(e,t);return{start:o,size:n,end:o+(this.getters.isColHidden(e,t)?0:n)}}getRowDimensionsInViewport(e,t){const i=Math.min(...this.getters.getSheetViewVisibleRows()),o=this.getters.getColRowOffsetInViewport("ROW",i,t),n=this.getters.getRowSize(e,t);return{start:o,size:n,end:o+(this.getters.isRowHidden(e,t)?0:n)}}getHeaderOffset(e,t,i){let o=this.getters.getColRowOffsetInViewport(e,t,i);return this.getters.isDashboard()||(o+="ROW"===e?O:N),o}drawGrid(e,t){switch(t){case 0:this.boxes=this.getGridBoxes(),this.drawBackground(e),this.drawOverflowingCellBackground(e),this.drawCellBackground(e),this.drawBorders(e),this.drawTexts(e),this.drawIcon(e),this.drawFrozenPanes(e);break;case 7:this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e))}}drawBackground(e){const{ctx:t,thinLineWidth:i}=e,{width:o,height:n}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle="#ffffff",t.fillRect(0,0,o+m,n+m);const s=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),r=s?.1*i:0;if(s)for(const e of this.boxes)t.strokeStyle="#E2E3E3",t.lineWidth=i,t.strokeRect(e.x+r,e.y+r,e.width-2*r,e.height-2*r)}drawCellBackground(e){const{ctx:t}=e;for(const e of this.boxes){let i=e.style;i.fillColor&&"#ffffff"!==i.fillColor&&(t.fillStyle=i.fillColor||"#ffffff",t.fillRect(e.x,e.y,e.width,e.height)),e.error&&(t.fillStyle="red",t.beginPath(),t.moveTo(e.x+e.width-5,e.y),t.lineTo(e.x+e.width,e.y),t.lineTo(e.x+e.width,e.y+5),t.fill())}}drawOverflowingCellBackground(e){var t,i;const{ctx:o,thinLineWidth:n}=e;for(const e of this.boxes)if(e.content&&e.isOverflow){const s=e.content.align||"left";let r,a;const l=e.y+n/2,c=e.height-n,h=Math.min((null===(t=e.clipRect)||void 0===t?void 0:t.width)||1/0,e.content.width);"left"===s?(r=e.x+n/2,a=h-2*n):"right"===s?(r=e.x+e.width-n/2,a=2*n-h):(r=((null===(i=e.clipRect)||void 0===i?void 0:i.x)||e.x+e.width/2-e.content.width/2)+n/2,a=h-2*n),o.fillStyle="#ffffff",o.fillRect(r,l,a,c)}}drawBorders(e){const{ctx:t,thinLineWidth:i}=e;for(let e of this.boxes){const t=e.border;if(t){const{x:i,y:n,width:s,height:r}=e;t.left&&o(t.left,i,n,i,n+r),t.top&&o(t.top,i,n,i+s,n),t.right&&o(t.right,i+s,n,i+s,n+r),t.bottom&&o(t.bottom,i,n+r,i+s,n+r)}}function o([e,o],n,s,r,a){t.strokeStyle=o,t.lineWidth=("thin"===e?2:3)*i,t.beginPath(),t.moveTo(n,s),t.lineTo(r,a),t.stroke()}}drawTexts(e){const{ctx:t,thinLineWidth:i}=e;let o;t.textBaseline="top";for(let e of this.boxes)if(e.content){const n=e.style||{},s=e.content.align||"left",r=Ue(n);r!==o&&(o=r,t.font=r),t.fillStyle=n.textColor||"#000";let a=e.x;if(a+="left"===s?U+(e.image?e.image.size+P:0):"right"===s?e.width-U-(e.isFilterHeader?20:0):e.width/2,t.textAlign=s,e.clipRect){t.save(),t.beginPath();const{x:i,y:o,width:n,height:s}=e.clipRect;t.rect(i,o,n,s),t.clip()}const l=Ve(n),c=e.content.textLines.length;let h=this.computeTextYCoordinate(e,l,c);for(let o of e.content.textLines){if(t.fillText(o,Math.round(a),Math.round(h)),n.strikethrough||n.underline){const e=Le(t,o,n);let r=a;"right"===s?r-=e:"center"===s&&(r-=e/2),n.strikethrough&&t.fillRect(r,h+l/2,e,2.6*i),n.underline&&t.fillRect(r,h+l+1,e,1.3*i)}h+=U+l}e.clipRect&&t.restore()}}drawIcon(e){const{ctx:t}=e;for(const e of this.boxes)if(e.image){const i=e.image.image;if(e.image.clipIcon){t.save(),t.beginPath();const{x:i,y:o,width:n,height:s}=e.image.clipIcon;t.rect(i,o,n,s),t.clip()}const o=e.image.size,n=this.computeTextYCoordinate(e,o);t.drawImage(i,e.x+P,n,o,o),e.image.clipIcon&&t.restore()}}computeTextYCoordinate(e,t,i=1){const o=e.y+1,n=ke(t,i),s=e.height>n+2*U,r=e.verticalAlign||"middle";if(s){if("middle"===r)return o+(e.height-n)/2;if("bottom"===r)return o+e.height-n-U}return o+U}drawHeaders(e){const{ctx:t,thinLineWidth:i}=e,o=this.getters.getSheetViewVisibleCols(),n=o[0],s=o[o.length-1],r=this.getters.getSheetViewVisibleRows(),a=r[0],l=r[r.length-1],{width:c,height:h}=this.getters.getSheetViewDimensionWithHeaders(),d=this.getters.getSelectedZones(),u=function(e){const t=new Set;for(let i of e)for(let e of ze(i.left,i.right+1))t.add(e);return t}(d),g=function(e){const t=new Set;for(let i of e)for(let e of ze(i.top,i.bottom+1))t.add(e);return t}(d),p=this.getters.getActiveSheetId(),m=this.getters.getNumberCols(p),f=this.getters.getNumberRows(p),E=this.getters.getActiveCols(),w=this.getters.getActiveRows();t.font=`400 11px ${q}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=i,t.strokeStyle="#333";for(let e=n;e<=s;e++){const i={left:e,right:e,top:0,bottom:f-1},{x:o,width:n}=this.getters.getVisibleRect(i),s=this.getters.doesZonesContainFilter(p,[i]),r=E.has(e),a=u.has(e);t.fillStyle=r?s?I:S:a?s?T:b:s?R:v,t.fillRect(o,0,n,O)}for(let e=a;e<=l;e++){const i={top:e,bottom:e,left:0,right:m-1},{y:o,height:n}=this.getters.getVisibleRect(i),s=this.getters.doesZonesContainFilter(p,[i]),r=w.has(e),a=g.has(e);t.fillStyle=r?s?I:S:a?s?T:b:s?R:v,t.fillRect(0,o,N,n)}t.beginPath(),t.moveTo(N,0),t.lineTo(N,h),t.moveTo(0,O),t.lineTo(c,O),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(const e of o){const i=this.getters.getColSize(p,e),o=Ut(e);t.fillStyle=E.has(e)?"#fff":C;let s=this.getHeaderOffset("COL",n,e);t.fillText(o,s+i/2,13),t.moveTo(s+i,0),t.lineTo(s+i,O)}for(const e of r){const i=this.getters.getRowSize(p,e);t.fillStyle=w.has(e)?"#fff":C;let o=this.getHeaderOffset("ROW",a,e);t.fillText(String(e+1),24,o+i/2),t.moveTo(0,o+i),t.lineTo(N,o+i)}t.stroke()}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:i}=e,{x:o,y:n}=this.getters.getMainViewportCoordinates(),s=this.getters.isDashboard()?0:N,r=this.getters.isDashboard()?0:O;t.lineWidth=6*i,t.strokeStyle="#BCBCBC",t.beginPath(),o&&(t.moveTo(s+o,0),t.lineTo(s+o,r)),n&&(t.moveTo(0,r+n),t.lineTo(s,r+n)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:i}=e,{x:o,y:n}=this.getters.getMainViewportCoordinates(),s=this.getters.getSheetViewVisibleCols(),r=s[0],a=s[s.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:r,right:a,top:l[0],bottom:l[l.length-1]},h=this.getters.getVisibleRect(c),d=this.getters.isDashboard()?0:N,u=this.getters.isDashboard()?0:O;t.lineWidth=6*i,t.strokeStyle="#DADFE8",t.beginPath(),o&&(t.moveTo(d+o,u),t.lineTo(d+o,h.height+u)),n&&(t.moveTo(d,u+n),t.lineTo(h.width+d,u+n)),t.stroke()}findNextEmptyCol(e,t,i){const o=this.getters.getActiveSheetId();let n=e;for(;n<t;){const e={sheetId:o,col:n+1,row:i},t=this.getters.getEvaluatedCell(e),s=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==tn.empty||this.getters.isInMerge(e)||(null==s?void 0:s.left))return n;n++}return n}findPreviousEmptyCol(e,t,i){const o=this.getters.getActiveSheetId();let n=e;for(;n>t;){const e={sheetId:o,col:n-1,row:i},t=this.getters.getEvaluatedCell(e),s=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==tn.empty||this.getters.isInMerge(e)||(null==s?void 0:s.right))return n;n--}return n}computeCellAlignment(e,t){const i=this.getters.getCell(e);if((null==i?void 0:i.isFormula)&&this.getters.shouldShowFormulas())return"left";const{align:o}=this.getters.getCellStyle(e),n=this.getters.getEvaluatedCell(e);return t&&n.type===tn.number?"center"!==o?"left":o:o||n.defaultAlign}createZoneBox(e,t,i){const{left:o,right:n}=i,s=t.left,r=t.top,a={sheetId:e,col:s,row:r},c=this.getters.getEvaluatedCell(a),h=this.getters.shouldShowFormulas(),{x:d,y:u,width:g,height:p}=this.getters.getVisibleRect(t),{verticalAlign:m}=this.getters.getCellStyle(a),f={x:d,y:u,width:g,height:p,border:this.getters.getCellBorderWithFilterBorder(a)||void 0,style:this.getters.getCellComputedStyle(a),verticalAlign:m};if(c.type===tn.empty)return f;const v=this.getters.getConditionalIcon(a),b=Ve(f.style),S=v?P+b:0;v&&(f.image={type:"icon",size:b,clipIcon:{x:f.x,y:f.y,width:Math.min(S,g),height:p},image:vg[v].img}),f.isFilterHeader=this.getters.isFilterHeader(a);const C=f.isFilterHeader?19:0,E=this.getters.getCellComputedStyle(a),w=E.wrapping||"overflow",y="wrap"!==w||h?void 0:g-2*U,x=this.getters.getCellMultiLineText(a,y),I=Math.max(...x.map((e=>this.getters.getTextWidth(e,E)+U))),R=S+I+C,T=this.computeCellAlignment(a,R>g);f.content={textLines:x,width:"overflow"===w?I:g,align:T},c.type===tn.error&&c.error.logLevel>l.silent&&(f.error=c.error.message);const A=R>g||b>p;if(v||f.isFilterHeader)f.clipRect={x:f.x+S,y:f.y,width:Math.max(0,g-S-C),height:p};else if(A&&"overflow"===w){let e,i;switch(this.getters.isInMerge(a)?(e=this.getters.getMerge(a).right,i=s):(e=this.findNextEmptyCol(s,n,r),i=this.findPreviousEmptyCol(s,o,r),f.isOverflow=!0),T){case"left":{const i=oo({col:e,row:r}),{x:o,y:n,width:s,height:a}=this.getters.getVisibleRect($i(t,i));(s<R||b>a||x.length>1)&&(f.clipRect={x:o,y:n,width:s,height:a});break}case"right":{const e=oo({col:i,row:r}),{x:o,y:n,width:s,height:a}=this.getters.getVisibleRect($i(t,e));(s<R||b>a||x.length>1)&&(f.clipRect={x:o,y:n,width:s,height:a});break}case"center":{const o={...t,left:i,right:e},{x:n,y:s,height:r,width:a}=this.getters.getVisibleRect(o),l=R/2,c=f.x+f.width/2;if(n+a<c+l||n>c-l||b>r||x.length>1){const e=n>c-l?n:c-l,t=n+a-e;f.clipRect={x:e,y:s,width:t,height:r}}break}}}else("clip"===w||"wrap"===w||x.length>1)&&(f.clipRect={x:f.x,y:f.y,width:g,height:p});return f}getGridBoxes(){const e=[],t=this.getters.getSheetViewVisibleCols(),i=t[0],o=t[t.length-1],n=this.getters.getSheetViewVisibleRows(),s={left:i,right:o,top:n[0],bottom:n[n.length-1]},r=this.getters.getActiveSheetId();for(const i of n)for(const o of t){const t={sheetId:r,col:o,row:i};this.getters.isInMerge(t)||e.push(this.createZoneBox(r,oo(t),s))}for(const t of this.getters.getMerges(r))if(!this.getters.isMergeHidden(r,t)&&qi(t,s)){const i=this.createZoneBox(r,t,s),o=this.getters.getCellBorder({sheetId:r,col:t.right,row:t.bottom});i.border={...i.border,bottom:o?o.bottom:void 0,right:o?o.right:void 0},i.isMerge=!0,e.push(i)}return e}}nb.layers=[0,7],nb.getters=["getColDimensionsInViewport","getRowDimensionsInViewport"];class sb extends Bv{constructor(e,t,i){if(i&&t.length>1)throw new Error("Input with a single range cannot be instantiated with several range references.");super(e),this.inputHasSingleRange=i,this.ranges=[],this.focusedRangeIndex=null,this.willAddNewRange=!1,this.insertNewRange(0,t),this.activeSheet=this.getters.getActiveSheetId(),0===this.ranges.length&&(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}allowDispatch(e){switch(e.type){case"ADD_EMPTY_RANGE":if(this.inputHasSingleRange&&1===this.ranges.length)return 30;break;case"CHANGE_RANGE":if(this.inputHasSingleRange&&e.value.split(",").length>1)return 30}return 0}handleEvent(e){const t=Ui(e.anchor.zone),i=this.activeSheet,o=this.getters.getActiveSheetId(),n=this.getters.getSheetName(o);this.add([o===i?t:`${Fe(n)}!${t}`])}handle(e){switch(e.type){case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"FOCUS_RANGE":this.focus(this.getIndex(e.rangeId));break;case"CHANGE_RANGE":{const t=this.getIndex(e.rangeId);if(null!==t&&this.focusedRangeIndex!==t&&this.focus(t),null!==t){const i=e.value.replace(/^,+/,"").split(",").map((e=>e.trim()));this.setRange(t,i)}break}case"ADD_EMPTY_RANGE":this.insertNewRange(this.ranges.length,[""]),this.focusLast();break;case"REMOVE_RANGE":const t=this.getIndex(e.rangeId);null!==t&&this.removeRange(t);break;case"STOP_SELECTION_INPUT":this.willAddNewRange=!1;break;case"PREPARE_SELECTION_INPUT_EXPANSION":{const e=this.focusedRangeIndex;null===e||this.inputHasSingleRange||(this.willAddNewRange=""!==this.ranges[e].xc.trim());break}case"ACTIVATE_SHEET":if(e.sheetIdFrom!==e.sheetIdTo){const{col:t,row:i}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),o=this.getters.expandZone(e.sheetIdTo,oo({col:t,row:i}));this.selection.resetAnchor(this,{cell:{col:t,row:i},zone:o})}}}getSelectionInputValue(){return this.cleanInputs(this.ranges.map((e=>e.xc?e.xc:"")))}getSelectionInputHighlights(){return this.ranges.map((e=>this.inputToHighlights(e))).flat()}focus(e){this.focusedRangeIndex=e}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null}add(e){null!==this.focusedRangeIndex&&0!==e.length&&(this.willAddNewRange?(this.insertNewRange(this.ranges.length,e),this.focusLast(),this.willAddNewRange=!1):this.setRange(this.focusedRangeIndex,e))}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){const i=Math.max(0,...this.ranges.map((e=>Number(e.id))));this.ranges.splice(e,0,...t.map(((e,t)=>({xc:e,id:i+t+1,color:ft[(i+t)%ft.length]}))))}setRange(e,t){const[,...i]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,i),i.length&&this.focus(e+i.length)}removeRange(e){this.ranges.splice(e,1),null!==this.focusedRangeIndex&&this.focusLast()}inputToHighlights({xc:e,color:t}){const i=this.cleanInputs([e]).filter((e=>this.getters.isRangeValid(e))).filter((e=>this.shouldBeHighlighted(this.activeSheet,e)));return i.map((e=>{const{sheetName:i}=Pt(e);return{zone:this.getters.getRangeFromSheetXC(this.activeSheet,e).zone,sheetId:i&&this.getters.getSheetIdByName(i)||this.activeSheet,color:t}}))}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:i}=Pt(t),o=this.getters.getSheetIdByName(i),n=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(o===n||void 0===o&&n===e)}getIndex(e){const t=this.ranges.findIndex((t=>t.id===e));return t>=0?t:null}}sb.layers=[1],sb.getters=[];class rb extends Bv{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,i;if("FOCUS_RANGE"===e.type){const o=null===(t=this.currentInput)||void 0===t?void 0:t.getIndex(e.rangeId);if(this.focusedInputId===e.id&&(null===(i=this.currentInput)||void 0===i?void 0:i.focusedRangeIndex)===o)return 29}return this.currentInput?this.currentInput.allowDispatch(e):0}handle(e){var t;switch(e.type){case"ENABLE_NEW_SELECTION_INPUT":this.initInput(e.id,e.initialRanges||[],e.hasSingleRange);break;case"DISABLE_SELECTION_INPUT":this.focusedInputId===e.id&&this.unfocus(),delete this.inputs[e.id];break;case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"ADD_EMPTY_RANGE":case"REMOVE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id];this.selection.capture(t,{cell:{col:0,row:0},zone:oo({col:0,row:0})},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}break;case"FOCUS_RANGE":case"CHANGE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id],i=t.ranges.find((t=>t.id===e.rangeId)),o=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(o,(null==i?void 0:i.xc)||"A1").zone;this.selection.capture(t,{cell:{col:n.left,row:n.top},zone:n},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}}null===(t=this.currentInput)||void 0===t||t.handle(e)}getSelectionInput(e){return this.inputs[e]?this.inputs[e].ranges.map(((t,i)=>Object.assign({},t,{color:this.focusedInputId===e&&null!==this.inputs[e].focusedRangeIndex&&this.isRangeValid(t.xc)?t.color:null,isFocused:this.focusedInputId===e&&this.inputs[e].focusedRangeIndex===i}))):[]}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:i}=Pt(e);return null!==t.match(_t)&&(!i||void 0!==this.getters.getSheetIdByName(i))}getSelectionInputValue(e){return this.inputs[e].getSelectionInputValue()}getSelectionInputHighlights(){return this.focusedInputId?this.inputs[this.focusedInputId].getSelectionInputHighlights():[]}initInput(e,t,i=!1){if(this.inputs[e]=new sb(this.config,t,i),0===t.length){const t=this.inputs[e],i={zone:oo({col:0,row:0}),cell:{col:0,row:0}};this.selection.capture(t,i,{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e}}unfocus(){this.selection.release(this.currentInput),this.focusedInputId=null}}rb.layers=[1],rb.getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];class ab{constructor(){this.subscriptions={}}on(e,t,i){if(!i)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:i})}trigger(e,t){const i=this.subscriptions[e]||[];for(let e=0,o=i.length;e<o;e++){const o=i[e];o.callback.call(o.owner,t)}}off(e,t){const i=this.subscriptions[e];i&&(this.subscriptions[e]=i.filter((e=>e.owner!==t)))}clear(){this.subscriptions={}}}function lb(e,t){return{...e,definition:fr(e.definition,t)}}function cb(e,t){if(e.sheetId!==t.sheetId)return e;if(("FREEZE_COLUMNS"===e.type?"COL":"ROW")!==t.dimension)return e;let i=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));for(let t of e)i>t&&i--}if("ADD_COLUMNS_ROWS"===t.type){i=i>("before"===t.position?t.base-1:t.base)?i+t.quantity:i}return i>0?{...e,quantity:i}:void 0}ju.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],lb),ju.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],lb),ju.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const i=t.sheetId;if(e.targetSheetId===i||e.sheetId===i)return;return e})),ju.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),ju.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){var i;if(e.name===t.name)return{...e,name:(null===(i=e.name)||void 0===i?void 0:i.match(/\d+/))?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),ju.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE","CREATE_FILTER_TABLE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const i=[];for(const o of e.target)for(const e of t.target)qi(o,e)||i.push({...o});if(i.length)return{...e,target:i};return})),ju.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],cb),ju.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],cb),ju.addTransformation("CREATE_FILTER_TABLE",["CREATE_FILTER_TABLE","ADD_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;for(const i of e.target)for(const e of t.target)if(qi(e,i))return;return e}));const hb=[{match:function(e){return"sheetId"in e},fn:gb},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const i=gb(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;const o=[];for(const i of e.target){const e=ss(i,t);e&&o.push(e)}if(!o.length)return"IGNORE_COMMAND";return{...e,target:o}}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const i=gb(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const i="COL"===t.dimension?"col":"row";let o=e[i];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(o))return"IGNORE_COMMAND";for(let t of e)o>=t&&o--}"ADD_COLUMNS_ROWS"===t.type&&(o>t.base||o===t.base&&"before"===t.position)&&(o+=t.quantity);return{...e,[i]:o}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const i of t.target){if(!(e.col===i.left&&e.row===i.top)&&Zi(e.col,e.row,i))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e&&"sheetId"in e},fn:function(e,t){const i=gb(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type){if(t.dimension!==e.dimension)return e;const i="ADD_COLUMNS_ROWS"===e.type,o=i?"base":"elements";let n=i?[e[o]]:e[o];if("REMOVE_COLUMNS_ROWS"===t.type&&(n=n.map((e=>{if(t.elements.includes(e))return;const i=t.elements.sort(((e,t)=>t-e));for(let t of i)e>t&&e--;return e})).filter(et)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;n=n.map((i=>i>e?i+t.quantity:i))}if(n.length){let t=n;return i&&(t=n[0]),{...e,[o]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}},{match:function(e){return"ranges"in e},fn:function(e,t){const i=[],o="DELETE_SHEET"===t.type&&t.sheetId;for(const n of e.ranges)if(n._sheetId!==t.sheetId)i.push({...n,_zone:n._zone});else{const e=ss(n._zone,t);e&&o!==n._sheetId&&i.push({...n,_zone:e})}if(!i.length)return"IGNORE_COMMAND";return{...e,ranges:i}}}];function db(e,t){const i=ju.getTransformation(e.type,t.type);return i?i(e,t):function(e,t){for(const{match:i,fn:o}of hb)if(i(e)){const i=o(e,t);if("SKIP_TRANSFORMATION"===i)continue;if("IGNORE_COMMAND"===i)return;e=i}return e}(e,t)}function ub(e,t){let i=[...e];for(const e of t)i=i.map((t=>db(t,e))).filter(et);return i}function gb(e,t){const i="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===i?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class pb{constructor(e,t,i,o){this._commands=[],this._changes=[],this.id=e,this.clientId=t,this._commands=[...i],this._changes=o?[...o]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class mb extends Error{}class fb extends ab{constructor(e,t,i=K){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=i,this.clients={},this.clientId="local",this.pendingMessages=[],this.waitingAck=!1,this.waitingUndoRedoAck=!1,this.isReplayingInitialRevisions=!1,this.processedRevisions=new Set,this.uuidGenerator=new Di,this.debouncedMove=function(e,t,i){let o;return function(){const n=this,s=arguments,r=i&&!o;clearTimeout(o),o=setTimeout((function(){o=null,i||e.apply(n,s)}),t),r&&e.apply(n,s)}}(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t){if(!e.length||!t.length||!this.canApplyOptimisticUpdate())return;const i=new pb(this.uuidGenerator.uuidv4(),this.clientId,e,t);this.revisions.append(i.id,i),this.trigger("new-local-state-update",{id:i.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:i.id,clientId:i.clientId,commands:i.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_UNDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_REDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:"local",name:"local"},this.clientId="local"),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this))}loadInitialMessages(e){this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1}leave(){delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}snapshot(e){const t=this.uuidGenerator.uuidv4();this.transportService.sendMessage({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){const e=this.clients[this.clientId];if(!e)throw new mb("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(et))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}_move(e){var t;if(!this.clients[this.clientId])return;const i=null===(t=this.clients[this.clientId])||void 0===t?void 0:t.position;if((null==i?void 0:i.col)===e.col&&i.row===e.row&&i.sheetId===e.sheetId)return;const o=i?"CLIENT_MOVED":"CLIENT_JOINED",n=this.getClient();this.clients[this.clientId]={...n,position:e},this.transportService.sendMessage({type:o,version:1,client:{...n,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:i}=e,o=new pb(e.nextRevisionId,t,i);if(o.clientId!==this.clientId){this.revisions.insert(o.id,o,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:ub(i,t)})}break;case"SNAPSHOT_CREATED":{const t=new pb(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 vb=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];class bb extends Bv{constructor(){super(...arguments),this.availableColors=new Set(vb),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(vb));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 mb)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const i of this.getters.getConnectedClients())if(i.id!==this.getters.getClient().id&&i.position&&i.position.sheetId===e&&this.isPositionValid(i.position)){const e=i.position;this.colors[i.id]||(this.colors[i.id]=this.chooseNewColor());const o=this.colors[i.id];t.push({...i,position:e,color:o})}return t}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:i}=e,o=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:n,col:s}=e.position,r=this.getters.expandZone(o,{top:n,bottom:n,left:s,right:s}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);if(c<=0||h<=0)continue;const d=e.color,u=`${d}10`;t.fillStyle=u,t.lineWidth=4*i,t.strokeStyle=d,t.globalCompositeOperation="multiply",t.fillRect(a,l,c,h),t.globalCompositeOperation="source-over",t.strokeRect(a,l,c,h),t.font=`bold ${G+1}px ${q}`}}}bb.getters=["getClientsToDisplay"],bb.layers=[6];class Sb extends Bv{allowDispatch(e){if("SORT_CELLS"===e.type){if(!Zi(e.col,e.row,e.zone))throw new Error(s("The anchor must be part of the provided zone"));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return 0}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{})}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;return Ji(t).some((({col:t,row:i})=>!this.getters.isInMerge({sheetId:e,col:t,row:i})))?63:0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const i=this.getters.getMerges(e).filter((e=>qi(e,t))),o=Ki(i[0]);let[n,s]=[o.numberOfCols,o.numberOfRows];return i.every((e=>{let[t,i]=[e.right-e.left+1,e.bottom-e.top+1];return t===n&&i===s}))?0:63}expand(e,t){const{left:i,right:o,top:n,bottom:s}=this.getters.expandZone(e,t);return{left:Math.max(0,i),right:Math.min(this.getters.getNumberCols(e)-1,o),top:Math.max(0,n),bottom:Math.min(this.getters.getNumberRows(e)-1,s)}}checkExpandedValues(e,t){const i=this.expand(e,t);let o;if(this.getters.doesIntersectMerge(e,i)){const{left:t,right:n,top:s,bottom:r}=i;for(let i=t;i<=n;i++)for(let t=s;t<=r;t++){const{col:n,row:s}=this.getters.getMainCellPosition({sheetId:e,col:i,row:t});if(o=this.getters.getEvaluatedCell({sheetId:e,col:n,row:s}),o.formattedValue)return!0}}else for(let t of this.getters.getEvaluatedCellsInZone(e,i))if(t.formattedValue)return!0;return!1}getContiguousZone(e,t){let i,{top:o,bottom:n,left:s,right:r}=t,a=!1;for(;!a;)a=!0,o>0&&(i=this.checkExpandedValues(e,{left:s-1,right:r+1,top:o-1,bottom:o-1}),i&&(a=!1,o--)),s>0&&(i=this.checkExpandedValues(e,{left:s-1,right:s-1,top:o-1,bottom:n+1}),i&&(a=!1,s--)),r<this.getters.getNumberCols(e)-1&&(i=this.checkExpandedValues(e,{left:r+1,right:r+1,top:o-1,bottom:n+1}),i&&(a=!1,r++)),n<this.getters.getNumberRows(e)-1&&(i=this.checkExpandedValues(e,{left:s-1,right:r+1,top:n+1,bottom:n+1}),i&&(a=!1,n++));return{left:s,right:r,top:o,bottom:n}}hasHeader(e,t){if(1===t[0].length)return!1;let i=t.map((t=>t.map((({col:t,row:i})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:i}).type))));return i[0][0]===tn.empty&&(i=i.slice(1)),!i.some((e=>e[0]===tn.empty))&&!!i.some((e=>e[1]!==tn.empty&&e[0]!==e[1]))}sortZone(e,t,i,o,n){const[s,r]=this.mainCellsSteps(e,i);let a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},i),c=this.mainCells(e,i);!n.sortHeaders&&this.hasHeader(e,c)&&(l.top+=r),c=this.mainCells(e,l);const h=function(e,t,i){const o=e.map(((e,t)=>({index:t,type:e.type,value:e.value})));let n=o.filter((e=>e.type===tn.empty)),s=o.filter((e=>e.type!==tn.empty));i&&(s.push(...n.map((e=>({...e,type:tn.number,value:0})))),n=[]);const r="descending"===t?-1:1;return s.sort(((e,t)=>{let i=br.indexOf(e.type)-br.indexOf(t.type);return 0===i&&(i=e.type===tn.text||e.type===tn.error?e.value.localeCompare(t.value):e.value-t.value),r*i})).concat(n)}(c[a-l.left].map((e=>this.getters.getEvaluatedCell(e))),o,Boolean(n.emptyCellAsZero)),d=h.map((e=>e.index)),[u,g]=[c.length,c[0].length],p=[];for(let e=0;e<u;e++){for(let t=0;t<g;t++){let{col:i,row:o,sheetId:n}=c[e][d[t]];const a=this.getters.getCell({sheetId:n,col:i,row:o});let h=l.left+e*s,u=l.top+t*r,g={sheetId:n,col:h,row:u,content:""};if(a){let e=a.content;if(a.isFormula){const t=u-this.getters.getCellPosition(a.id).row,i=this.getters.createAdaptedRanges(a.dependencies,0,t,n);e=this.getters.buildFormulaContent(n,a,i)}g.style=a.style,g.content=e,g.format=a.format}p.push(g)}for(const e of p)this.dispatch("UPDATE_CELL",e)}}mainCellsSteps(e,t){const i=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[i?i.right-i.left+1:1,i?i.bottom-i.top+1:1]}mainCells(e,t){const[i,o]=this.mainCellsSteps(e,t),n=[],s=ze(t.left,t.right+1,i),r=ze(t.top,t.bottom+1,o);for(const t of s){const i=[];n.push(i);for(const o of r)i.push({sheetId:e,col:t,row:o})}return n}}Sb.getters=["getContiguousZone"];class Cb extends Bv{constructor(){super(...arguments),this.showFormulas=!1}handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}Cb.getters=["shouldShowFormulas"];class Eb extends Bv{constructor(){super(...arguments),this.ctx=document.createElement("canvas").getContext("2d")}allowDispatch(e){switch(e.type){case"AUTORESIZE_ROWS":case"AUTORESIZE_COLUMNS":try{this.getters.getSheet(e.sheetId);break}catch(e){return 27}}return 0}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(let t of e.cols){const i=this.getColMaxWidth(e.sheetId,t);0!==i&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:i,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":for(let t of e.rows)this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"ROW",size:null,sheetId:e.sheetId})}}getCellWidth(e){const t=this.getCellText(e),i=this.getters.getCellComputedStyle(e),o=t.split(ce);let n=Math.max(...o.map((e=>this.getTextWidth(e,i))));this.getters.getConditionalIcon(e)&&(n+=function(e){return Ve(e)+2*P}(this.getters.getCellStyle(e)));if(this.getters.isFilterHeader(e)&&(n+=20),n>0&&(n+=2*z,"wrap"===this.getters.getCellStyle(e).wrapping)){const t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,n)}return n}getTextWidth(e,t){return Le(this.ctx,e,t)}getCellText(e,t=!1){const i=this.getters.getCell(e);return t&&(null==i?void 0:i.isFormula)?i.content:this.getters.getEvaluatedCell(e).formattedValue}getCellMultiLineText(e,t){const i=this.getters.getCellStyle(e),o=this.getters.getCellText(e,this.getters.shouldShowFormulas()),n=[];for(const e of o.split("\n")){const o=e.split(" ");if(!t){n.push(e);continue}let s="",r=t;for(let e of o){const o=this.splitWordToSpecificWidth(this.ctx,e,t,i),a=o.pop(),l=Le(this.ctx,a,i);if(o.length)""!==s&&(n.push(s),s="",r=t),o.forEach((e=>{n.push(e)})),s=a,r=t-l;else{const e=""===s?a:" "+a,o=Le(this.ctx,e,i);o<=r?(s+=e,r-=o):(n.push(s),s=a,r=t-l)}}""!==s&&n.push(s)}return n}getColDimensions(e,t){const i=this.getColRowOffset("COL",0,t,e),o=this.getters.getColSize(e,t);return{start:i,size:o,end:i+(this.getters.isColHidden(e,t)?0:o)}}getRowDimensions(e,t){const i=this.getColRowOffset("ROW",0,t,e),o=this.getters.getRowSize(e,t);return{start:i,size:o,end:i+(this.getters.isRowHidden(e,t)?0:o)}}getColRowOffset(e,t,i,o=this.getters.getActiveSheetId()){if(i<t)return-this.getColRowOffset(e,i,t);let n=0;for(let s=t;s<i;s++)this.getters.isHeaderHidden(o,e,s)||(n+="COL"===e?this.getters.getColSize(o,s):this.getters.getRowSize(o,s));return n}getColMaxWidth(e,t){const i=Ji(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,...i)}splitWordToSpecificWidth(e,t,i,o){if(Le(e,t,o)<=i)return[t];const n=[];let s="";for(let r of t){Le(e,s+r,o)>i?(n.push(s),s=r):s+=r}return n.push(s),n}}Eb.getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getColDimensions","getRowDimensions","getColRowOffset"];class wb{constructor(e,t,i,o){this.getters=t,this.dispatch=i,this.selection=o,this.operation=e,this.sheetId=t.getActiveSheetId()}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0}addMissingDimensions(e,t,i,o){const n=this.getters.getActiveSheetId(),s=t+o-this.getters.getNumberRows(n);s>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(n)-1,sheetId:n,quantity:s,position:"after"});const r=e+i-this.getters.getNumberCols(n);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(n)-1,sheetId:n,quantity:r,position:"after"})}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class yb extends wb{constructor(e,t,i,o,n){if(super(t,i,o,n),!e.length)return this.cells=[[]],this.zones=[],void(this.copiedTables=[]);const s=new Set(e.map((e=>e.left))),r=new Set(e.map((e=>e.right))),a=new Set(e.map((e=>e.top))),l=new Set(e.map((e=>e.bottom))),c=1===a.size&&1===l.size||1===s.size&&1===r.size?function(e){return e.reduce(((e,t)=>{const i=e.length;for(let o=0;o<i;o++)if(qi(e[o],t))return e[o]=$i(e[o],t),e;return e[i]=t,e}),[])}(e):[e[e.length-1]],h=c.map((e=>Ji(e))).flat(),d=[...new Set(h.map((e=>e.col)))].sort(((e,t)=>e-t)),u=[...new Set(h.map((e=>e.row)))].sort(((e,t)=>e-t)),g=[],p=i.getActiveSheetId();for(let e of u){let t=[];for(let o of d){const n={col:o,row:e,sheetId:p};t.push({cell:i.getCell(n),style:i.getCellComputedStyle(n),evaluatedCell:i.getEvaluatedCell(n),border:i.getCellBorder(n)||void 0,position:n})}g.push(t)}const m=[];for(const t of e)for(const e of this.getters.getFilterTablesInZone(p,t)){const t=[];for(const i of ze(e.zone.left,e.zone.right+1))t.push(this.getters.getFilterValues({sheetId:p,col:i,row:e.zone.top}));m.push({filtersValues:t,zone:e.zone})}this.cells=g,this.zones=c,this.copiedTables=m}isCutAllowed(e){return 1!==e.length?19:0}isPasteAllowed(e,t){const i=this.getters.getActiveSheetId();if("CUT"===this.operation&&void 0!==(null==t?void 0:t.pasteOption))return 21;if(e.length>1&&(this.cells.length>1||this.cells[0].length>1))return 20;const o=this.cells.length,n=this.cells[0].length;for(let t of this.getPasteZones(e))if(this.getters.doesIntersectMerge(i,t)&&(e.length>1||!this.getters.isSingleCellOrMerge(i,e[0])||o*n!=1))return 2;const{xSplit:s,ySplit:r}=this.getters.getPaneDivisions(i);for(const t of this.getPasteZones(e))if(t.left<s&&t.right>=s||t.top<r&&t.bottom>=r)return 75;return 0}paste(e,t){"COPY"===this.operation?this.pasteFromCopy(e,t):this.pasteFromCut(e,t);const i=this.cells.length,o=this.cells[0].length,n="CUT"===this.operation;(null==t?void 0:t.selectTarget)&&this.selectPastedZone(o,i,n,e)}pasteFromCopy(e,t){if(1===e.length){const i=this.cells.length,o=this.cells[0].length,n=this.pastedZones(e,o,i);for(const e of n)this.pasteZone(e.left,e.top,t)}else for(const i of e)for(let e=i.left;e<=i.right;e++)for(let o=i.top;o<=i.bottom;o++)this.pasteZone(e,o,t);void 0===(null==t?void 0:t.pasteOption)&&this.pasteCopiedTables(e)}pasteFromCut(e,t){this.clearClippedZones();const i=e[0];this.pasteZone(i.left,i.top,t),this.dispatch("MOVE_RANGES",{target:this.zones,sheetId:this.sheetId,targetSheetId:this.getters.getActiveSheetId(),col:i.left,row:i.top});for(const e of this.copiedTables)this.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.getters.getActiveSheetId(),target:[e.zone]});this.pasteCopiedTables(e)}pastedZones(e,t,i){const o=e[0],n=Math.max(1,Math.floor((o.right+1-o.left)/t)),s=Math.max(1,Math.floor((o.bottom+1-o.top)/i)),r=[];for(let e=0;e<n;e++)for(let n=0;n<s;n++){const s=o.top+n*i,a=o.left+e*t;r.push({left:a,top:s,bottom:s+i-1,right:a+t-1})}return r}getPasteZones(e){const t=this.cells;if(!t.length||!t[0].length)return e;const i=[],o=t.length,n=t[0].length,s=e[e.length-1],r=s.left,a=s.top,l=Math.max(1,Math.floor((s.right+1-r)/n)),c=Math.max(1,Math.floor((s.bottom+1-a)/o));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)i.push({left:r,top:a,right:r-1+e*n,bottom:a-1+t*o});return i}selectPastedZone(e,t,i,o){const n=o[0],s=n.left,r=n.top;if(t>1||e>1||i){const n=this.pastedZones(o,e,t),a=i?n[0]:$i(...n);this.selection.selectZone({cell:{col:s,row:r},zone:a})}}clearClippedZones(){for(const e of this.cells)for(const t of e)t.cell&&this.dispatch("CLEAR_CELL",t.position);this.dispatch("CLEAR_FORMATTING",{sheetId:this.sheetId,target:this.zones})}pasteZone(e,t,i){const o=this.cells.length,n=this.cells[0].length,s="onlyValue"!==(null==i?void 0:i.pasteOption)&&(null==i?void 0:i.shouldPasteCF),r=this.getters.getActiveSheetId();this.addMissingDimensions(n,o,e,t);for(let a=0;a<o;a++){const o=this.cells[a];for(let l=0;l<n;l++){const n=o[l],c={col:e+l,row:t+a,sheetId:r};"CUT"!==this.operation&&this.pasteMergeIfExist(n.position,c),this.pasteCell(n,c,this.operation,i),s&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{origin:n.position,target:c,operation:this.operation})}}}pasteCell(e,t,i,o){const{sheetId:n,col:s,row:r}=t,a=this.getters.getEvaluatedCell(t);if("onlyValue"!==(null==o?void 0:o.pasteOption)){const i=this.getters.getCellBorder(t),o=e.border,a={top:(null==i?void 0:i.top)||(null==o?void 0:o.top),bottom:(null==i?void 0:i.bottom)||(null==o?void 0:o.bottom),left:(null==i?void 0:i.left)||(null==o?void 0:o.left),right:(null==i?void 0:i.right)||(null==o?void 0:o.right)};this.dispatch("SET_BORDER",{sheetId:n,col:s,row:r,border:a})}if(e.cell){if("onlyFormat"===(null==o?void 0:o.pasteOption))return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.evaluatedCell.format});if("onlyValue"===(null==o?void 0:o.pasteOption)){const i=hi(e.evaluatedCell.value);return void this.dispatch("UPDATE_CELL",{...t,content:i})}let a=e.cell.content;if(e.cell.isFormula&&"COPY"===i){const t=s-e.position.col,o=r-e.position.row;a=this.getUpdatedContent(n,e.cell,t,o,i)}this.dispatch("UPDATE_CELL",{...t,content:a,style:e.cell.style||null,format:e.cell.format})}else a&&("onlyValue"===(null==o?void 0:o.pasteOption)?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===(null==o?void 0:o.pasteOption)?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,i,o,n){const s=this.getters.createAdaptedRanges(t.dependencies,i,o,e);return this.getters.buildFormulaContent(e,t,s)}pasteMergeIfExist(e,t){let{sheetId:i,col:o,row:n}=e;const{col:s,row:r}=this.getters.getMainCellPosition(e);if(s===o&&r===n){const s=this.getters.getMerge(e);if(!s)return;({sheetId:i,col:o,row:n}=t),this.dispatch("ADD_MERGE",{sheetId:i,force:!0,target:[{left:o,top:n,right:o+s.right-s.left,bottom:n+s.bottom-s.top}]})}}pasteCopiedTables(e){const t=this.getters.getActiveSheetId(),i=e[0],o=this.zones[0],n=[i.left-o.left,i.top-o.top];for(const e of this.copiedTables){const i=eo(e.zone,"both","MOVE",n);this.dispatch("CREATE_FILTER_TABLE",{sheetId:t,target:[i]});for(const o of ze(0,e.filtersValues.length))this.dispatch("UPDATE_FILTER",{sheetId:t,col:i.left+o,row:i.top,values:e.filtersValues[o]})}}getClipboardContent(){return{[on.PlainText]:this.getPlainTextContent(),[on.Html]:this.getHTMLContent()}}getPlainTextContent(){return this.cells.map((e=>e.map((e=>e.cell?this.getters.getCellText(e.position,this.getters.shouldShowFormulas()):"")).join("\t"))).join("\n")||"\t"}getHTMLContent(){if(1==this.cells.length&&1==this.cells[0].length)return this.getters.getCellText(this.cells[0][0].position);let e='<table border="1" style="border-collapse:collapse">';for(const t of this.cells){e+="<tr>";for(const i of t){e+=`<td style="${mo(go(i.style))}">`+Wf(this.getters.getCellText(i.position))+"</td>"}e+="</tr>"}return e+="</table>",e}isColRowDirtyingClipboard(e,t){if(!this.zones)return!1;for(let i of this.zones){if("COL"===t&&e<=i.right)return!0;if("ROW"===t&&e<=i.bottom)return!0}return!1}drawClipboard(e){const{ctx:t,thinLineWidth:i}=e;if(this.sheetId===this.getters.getActiveSheetId()&&this.zones&&this.zones.length){t.setLineDash([8,5]),t.strokeStyle=E,t.lineWidth=3.3*i;for(const e of this.zones){const{x:i,y:o,width:n,height:s}=this.getters.getVisibleRect(e);n>0&&s>0&&t.strokeRect(i,o,n,s)}}}}class xb{constructor(e,t,i){this.operation=e,this.getters=t,this.dispatch=i,this.sheetId=t.getActiveSheetId();const o=t.getSelectedFigureId();if(!o)throw new Error("No figure selected");const n=t.getFigure(this.sheetId,o);if(!n)throw new Error(`No figure for the given id: ${o}`);switch(this.copiedFigure={...n},n.tag){case"chart":this.copiedFigureContent=new Ib(i,t,this.sheetId,o);break;case"image":this.copiedFigureContent=new Rb(i,t,this.sheetId,o);break;default:throw new Error(`Unknow tag '${n.tag}' for the given figure id: ${o}`)}}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0===e.length?73:void 0!==(null==t?void 0:t.pasteOption)?22:0}paste(e){const t=this.getters.getActiveSheetId(),i={x:this.getters.getColDimensions(t,e[0].left).start,y:this.getters.getRowDimensions(t,e[0].top).start},o={height:this.copiedFigure.height,width:this.copiedFigure.width},n=(new Di).uuidv4();this.copiedFigureContent.paste(t,n,i,o),"CUT"===this.operation&&this.dispatch("DELETE_FIGURE",{sheetId:this.copiedFigureContent.sheetId,id:this.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{id:n})}getClipboardContent(){return{[on.PlainText]:"\t"}}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class Ib{constructor(e,t,i,o){this.dispatch=e,this.sheetId=i;const n=t.getChart(o);if(!n)throw new Error(`No chart for the given id: ${o}`);this.copiedChart=n.copyInSheetId(i)}paste(e,t,i,o){const n=this.copiedChart.copyInSheetId(e);this.dispatch("CREATE_CHART",{id:t,sheetId:e,position:i,size:o,definition:n.getDefinition()})}}class Rb{constructor(e,t,i,o){this.dispatch=e,this.sheetId=i;const n=t.getImage(o);this.copiedImage=Ne(n)}paste(e,t,i,o){const n=Ne(this.copiedImage);this.dispatch("CREATE_IMAGE",{figureId:t,sheetId:e,position:i,size:o,definition:n})}}class Tb extends wb{constructor(e,t,i,o){super("COPY",t,i,o),this.values=e.replace(/\r/g,"").split("\n").map((e=>e.split("\t")))}isPasteAllowed(e,t){const i=this.getters.getActiveSheetId(),o=this.getPasteZone(e);return this.getters.doesIntersectMerge(i,o)?2:0}paste(e){const t=this.values,i=this.getPasteZone(e),{left:o,top:n}=i,{numberOfCols:s,numberOfRows:r}=Ki(i),a=this.getters.getActiveSheetId();this.addMissingDimensions(s,r,o,n);for(let e=0;e<t.length;e++)for(let i=0;i<t[e].length;i++)this.dispatch("UPDATE_CELL",{row:n+e,col:o+i,content:t[e][i],sheetId:a});const l={left:o,top:n,right:o+s-1,bottom:n+r-1};this.selection.selectZone({cell:{col:o,row:n},zone:l})}getClipboardContent(){return{[on.PlainText]:this.values.map((e=>e.join("\t"))).join("\n")}}getPasteZone(e){const t=this.values.length,i=Math.max(...this.values.map((e=>e.length))),{left:o,top:n}=e[0];return{top:n,left:o,bottom:n+t-1,right:o+i-1}}}class Ab extends Bv{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 i=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);return this.state.isPasteAllowed(e.target,{pasteOption:i});case"PASTE_FROM_OS_CLIPBOARD":return new Tb(e.text,this.getters,this.dispatch,this.selection).isPasteAllowed(e.target);case"INSERT_CELL":{const{cut:t,paste:i}=this.getInsertCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(i)}case"DELETE_CELL":{const{cut:t,paste:i}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(i)}}return 0}handle(e){var t,i;switch(e.type){case"COPY":case"CUT":const o="target"in e&&e.target||this.getters.getSelectedZones();this.state=this.getClipboardState(o,e.type),this.status="visible";break;case"PASTE":if(!this.state)break;const n=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);this._isPaintingFormat=!1,this.state.paste(e.target,{pasteOption:n,shouldPasteCF:!0,selectTarget:!0}),"CUT"===this.state.operation&&(this.state=void 0),this.status="invisible";break;case"CLEAN_CLIPBOARD_HIGHLIGHT":this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:i}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!Pi(t[0])){for(const{col:t,row:i}of Ji(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:i,sheetId:this.getters.getActiveSheetId()});break}this.getClipboardStateForCopyCells(t,"CUT").paste(i);break}case"INSERT_CELL":{const{cut:t,paste:i}=this.getInsertCellsTargets(e.zone,e.shiftDimension);this.getClipboardStateForCopyCells(t,"CUT").paste(i);break}case"ADD_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(t=this.state)||void 0===t?void 0:t.operation))return;this.state.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.state=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(i=this.state)||void 0===i?void 0:i.operation))return;for(let t of e.elements){if(this.state.isColRowDirtyingClipboard(t,e.dimension)){this.state=void 0;break}}this.status="invisible";break;case"PASTE_FROM_OS_CLIPBOARD":new Tb(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:ln(e)&&(this.status="invisible")}}getClipboardContent(){var e;return(null===(e=this.state)||void 0===e?void 0:e.getClipboardContent())||{[on.PlainText]:"\t"}}getClipboardTextContent(){var e;return(null===(e=this.state)||void 0===e?void 0:e.getClipboardContent()[on.PlainText])||"\t"}isCutOperation(){return!!this.state&&"CUT"===this.state.operation}isPaintingFormat(){return this._isPaintingFormat}getDeleteCellsTargets(e,t){const i=this.getters.getActiveSheetId();let o;return o="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(i)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(i)-1},{cut:[o],paste:[e]}}getInsertCellsTargets(e,t){const i=this.getters.getActiveSheetId();let o,n;return"COL"===t?(o={...e,right:this.getters.getNumberCols(i)-1},n={...e,left:e.right+1,right:e.right+1}):(o={...e,bottom:this.getters.getNumberRows(i)-1},n={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(i)-1}),{cut:[o],paste:[n]}}getClipboardStateForCopyCells(e,t){return new yb(e,t,this.getters,this.dispatch,this.selection)}getClipboardState(e,t){return this.getters.getSelectedFigureId()?new xb(t,this.getters,this.dispatch):new yb(e,t,this.getters,this.dispatch,this.selection)}drawGrid(e){"visible"===this.status&&this.state&&this.state.drawClipboard(e)}}function Mb(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:i}=Pt(e.value),[o,n]=t.split(":"),s=i?`${Fe(i)}!`:"",r=Ob(o),a=n?`:${Ob(n)}`:"";return{...e,value:s+r+a}}function Ob(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=Nb(e,"colrow");break;case"colrow":e=Nb(e,"row");break;case"row":e=Nb(e,"col");break;case"col":e=Nb(e,"none")}return e}function Nb(e,t){let i;switch(e=e.replace(/\$/g,""),t){case"col":return"$"+e;case"row":return i=e.search(/[0-9]/),e.slice(0,i)+"$"+e.slice(i);case"colrow":return i=e.search(/[0-9]/),"$"+(e=e.slice(0,i)+"$"+e.slice(i));case"none":return e}}Ab.layers=[2],Ab.getters=["getClipboardContent","getClipboardTextContent","isCutOperation","isPaintingFormat"];const _b=s("The cell you are trying to edit has been deleted.");class Fb extends Bv{constructor(){super(...arguments),this.col=0,this.row=0,this.mode="inactive",this.sheetId="",this.currentContent="",this.currentTokens=[],this.selectionStart=0,this.selectionEnd=0,this.selectionInitialStart=0,this.initialContent="",this.previousRef="",this.previousRange=void 0,this.colorIndexByRange={}}allowDispatch(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":return this.validateSelection(this.currentContent.length,e.start,e.end);case"SET_CURRENT_CONTENT":return e.selection?this.validateSelection(e.content.length,e.selection.start,e.selection.end):0;case"START_EDITION":if(e.selection){const t=e.text||this.getComposerContent(this.getters.getActivePosition());return this.validateSelection(t.length,e.selection.start,e.selection.end)}return 0;default:return 0}}handleEvent(e){if("selecting"===this.mode)if("newAnchor"===e.mode)this.insertSelectedRange(e.anchor.zone);else this.replaceSelectedRanges(e.anchor.zone)}handle(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":this.selectionStart=e.start,this.selectionEnd=e.end;break;case"STOP_COMPOSER_RANGE_SELECTION":this.isSelectingForComposer()&&(this.mode="editing");break;case"START_EDITION":"inactive"!==this.mode&&e.text?this.setContent(e.text,e.selection):this.startEdition(e.text,e.selection),this.updateRangeColor();break;case"STOP_EDITION":e.cancel?(this.cancelEditionAndActivateSheet(),this.resetContent()):this.stopEdition(),this.colorIndexByRange={};break;case"SET_CURRENT_CONTENT":this.setContent(e.content,e.selection,!0),this.updateRangeColor();break;case"REPLACE_COMPOSER_CURSOR_SELECTION":this.replaceSelection(e.text);break;case"SELECT_FIGURE":this.cancelEditionAndActivateSheet(),this.resetContent();break;case"ADD_COLUMNS_ROWS":this.onAddElements(e);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case"START_CHANGE_HIGHLIGHT":this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const t=this.getters.getRangeFromRangeData(e.range),i=this.currentTokens.filter((e=>"REFERENCE"===e.type)).find((e=>{const{xc:i,sheetName:o}=Pt(e.value),n=o||this.getters.getSheetName(this.sheetId),s=this.getters.getActiveSheetId();if(this.getters.getSheetName(s)!==n)return!1;const r=this.getters.getRangeFromSheetXC(s,i);return Gi(this.getters.expandZone(s,r.zone),t.zone)}));this.previousRef=i.value,this.previousRange=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),this.previousRef),this.selectionInitialStart=i.start;break;case"CHANGE_HIGHLIGHT":const o=this.getters.getRangeFromRangeData(e.range),n=this.getRangeReference(o,this.previousRange.parts);this.selectionStart=this.selectionInitialStart,this.selectionEnd=this.selectionInitialStart+this.previousRef.length,this.replaceSelection(n),this.previousRef=n,this.selectionStart=this.currentContent.length,this.selectionEnd=this.currentContent.length;break;case"ACTIVATE_SHEET":if(this.currentContent.startsWith("=")||(this.cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){const t=this.getters.getActivePosition(),{col:i,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),n=this.getters.expandZone(e.sheetIdTo,oo({col:i,row:o}));this.selection.resetAnchor(this,{cell:{col:i,row:o},zone:n})}break;case"DELETE_SHEET":case"UNDO":case"REDO":!!this.getters.tryGetSheet(this.sheetId)||"inactive"===this.mode||(this.sheetId=this.getters.getActiveSheetId(),this.cancelEditionAndActivateSheet(),this.resetContent(),this.ui.notifyUI({type:"ERROR",text:_b}));break;case"CYCLE_EDITION_REFERENCES":this.cycleReferences()}}getEditionMode(){return this.mode}getCurrentContent(){return"inactive"===this.mode?this.getComposerContent(this.getters.getActivePosition()):this.currentContent}getEditionSheet(){return this.sheetId}getComposerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}getCurrentEditedCell(){return{sheetId:this.sheetId,col:this.col,row:this.row}}isSelectingForComposer(){return"selecting"===this.mode}showSelectionIndicator(){return this.isSelectingForComposer()&&this.canStartComposerRangeSelection()}getCurrentTokens(){return this.currentTokens}getTokenAtCursor(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return e===t&&0===t?void 0:this.currentTokens.find((i=>i.start<=e&&i.end>=t))}cycleReferences(){const e=this.getTokensInSelection(),t=e.filter((e=>"REFERENCE"===e.type));if(0===t.length)return;const i=e.map(Mb).map((e=>e.value)).join(""),o=this.currentContent,n=e[0].start,s=e[e.length-1].end,r=o.slice(0,n)+i+o.slice(s),a=r.length-o.length,l={start:t[0].start,end:t[t.length-1].end+a};1===t.length&&this.selectionStart===this.selectionEnd&&(l.start=l.end),this.dispatch("SET_CURRENT_CONTENT",{content:r,selection:l})}validateSelection(e,t,i){return t>=0&&t<=e&&i>=0&&i<=e?0:46}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:_b});const{top:t,left:i}=Bi({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",[...e.elements]);this.col=i,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:_b});const{top:t,left:i}=Bi({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",[...e.elements]);this.col=i,this.row=t}onAddElements(e){const{top:t,left:i}=zi({left:this.col,right:this.col,top:this.row,bottom:this.row},"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.col=i,this.row=t}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){const e=oo({col:this.col,row:this.row});this.selection.resetAnchor(this,{cell:{col:this.col,row:this.row},zone:e})}this.mode="selecting",this.selectionInitialStart=this.selectionStart}startEdition(e,t){var i;const o=this.getters.getActiveCell();e&&(null===(i=o.format)||void 0===i?void 0:i.includes("%"))&&Qt(e)&&(t=t||{start:e.length,end:e.length},e=`${e}%`);const{col:n,row:s,sheetId:r}=this.getters.getActivePosition();this.col=n,this.sheetId=r,this.row=s,this.initialContent=this.getComposerContent({sheetId:r,col:n,row:s}),this.mode="editing",this.setContent(e||this.initialContent,t),this.colorIndexByRange={};const a=oo({col:this.col,row:this.row});this.selection.capture(this,{cell:{col:this.col,row:this.row},zone:a},{handleEvent:this.handleEvent.bind(this),release:()=>{this.stopEdition()}})}stopEdition(){if("inactive"!==this.mode){this.cancelEditionAndActivateSheet();const e=this.col,t=this.row;let i=this.currentContent;if(!(this.initialContent!==i))return;if(i){const o=this.getters.getActiveSheetId(),n=this.getters.getEvaluatedCell({sheetId:o,col:this.col,row:this.row});if(i.startsWith("=")){const e=this.currentTokens.filter((e=>"LEFT_PAREN"===e.type)).length,t=this.currentTokens.filter((e=>"RIGHT_PAREN"===e.type)).length,o=e-t;o>0&&(i+=ot(new Array(o).fill(")")))}else n.link&&(i=je(i,n.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,col:e,row:t,content:i})}else this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,content:"",col:e,row:t});this.setContent("")}}cancelEditionAndActivateSheet(){if("inactive"===this.mode)return;this.cancelEdition();this.getters.getActiveSheetId()!==this.sheetId&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}getComposerContent(e){const t=this.getters.getCell(e);if(null==t?void 0:t.isFormula)return t.content;const{format:i,value:o,type:n,formattedValue:s}=this.getters.getEvaluatedCell(e);switch(n){case tn.text:case tn.empty:return o;case tn.boolean:return s;case tn.error:return(null==t?void 0:t.content)||"";case tn.number:return i&&fi(i)?s:this.numberComposerContent(o,i)}}numberComposerContent(e,t){return(null==t?void 0:t.includes("%"))?100*e+"%":function(e){const{integerDigits:t,decimalDigits:i}=gi(e,20);return i?`${t}.${i}`:t}(e)}cancelEdition(){"inactive"!==this.mode&&(this.mode="inactive",this.selection.release(this))}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,i){const o=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(o||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?rf(e):[],this.currentTokens.length>100&&i&&this.ui.notifyUI({type:"ERROR",text:s("This formula has over 100 parts. It can't be processed properly, consider splitting it into multiple cells")})),this.canStartComposerRangeSelection()&&this.startComposerRangeSelection()}insertSelectedRange(e){const t=Math.min(this.selectionStart,this.selectionEnd),i=this.getZoneReference(e);this.canStartComposerRangeSelection()?(this.insertText(i,t),this.selectionInitialStart=t):(this.insertText(","+i,t),this.selectionInitialStart=t+1)}replaceSelectedRanges(e){const t=this.getZoneReference(e);this.replaceText(t,this.selectionInitialStart,this.selectionEnd)}getZoneReference(e,t=[{colFixed:!1,rowFixed:!1}]){const i=this.getters.getActiveSheetId();let o=this.getters.zoneToXC(i,e,t);if(this.getters.getEditionSheet()!==this.getters.getActiveSheetId()){o=`${Fe(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${o}`}return o}getRangeReference(e,t=[{colFixed:!1,rowFixed:!1}]){let i=[...t];1===t.length&&so(e.zone)>1?i.push({...t[0]}):2===t.length&&1===so(e.zone)&&i.pop();const o=e.clone({parts:i});return this.getters.getSelectionRangeString(o,this.getters.getEditionSheet())}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),i=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,i)}replaceText(e,t,i){this.currentContent=this.currentContent.slice(0,t)+this.currentContent.slice(i,this.currentContent.length),this.insertText(e,t)}insertText(e,t){const i=this.currentContent.slice(0,t)+e+this.currentContent.slice(t),o=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:i,selection:{start:o,end:o}})}updateRangeColor(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return;const e=this.getters.getEditionSheet(),t=this.getReferencedRanges().map((t=>this.getters.getRangeString(t,e))),i={};for(const e of t)void 0!==this.colorIndexByRange[e]&&(i[e]=this.colorIndexByRange[e]);const o=new Set(Object.values(i));let n=0;const s=()=>{for(;o.has(n);)n++;return o.add(n),n};for(const e of t){const t=e in i?i[e]:s();i[e]=t}this.colorIndexByRange=i}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=this.getters.getEditionSheet(),t=e=>{const t=this.colorIndexByRange[e];return ft[t%ft.length]};return this.getReferencedRanges().map((i=>{const o=this.getters.getRangeString(i,e);return{zone:i.zone,color:t(o),sheetId:i.sheetId}}))}getReferencedRanges(){const e=this.getters.getEditionSheet();return this.currentTokens.filter((e=>"REFERENCE"===e.type)).map((t=>this.getters.getRangeFromSheetXC(e,t.value)))}canStartComposerRangeSelection(){if(this.currentContent.startsWith("=")){const e=this.getTokenAtCursor();if(!e)return!1;const t=this.currentTokens.map((e=>e.start)).indexOf(e.start);let i=t,o=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(o.type)||Sm.includes(o.value);){if("SPACE"!==o.type||i<1)return!1;i--,o=this.currentTokens[i]}for(i=t+1,o=this.currentTokens[i];o&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(o.type);){if("SPACE"!==o.type)return!1;i++,o=this.currentTokens[i]}return!0}return!1}getTokensInSelection(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return this.currentTokens.filter((i=>i.start<=e&&i.end>=e||i.start>=e&&i.start<t))}}Fb.getters=["getEditionMode","isSelectingForComposer","showSelectionIndicator","getCurrentContent","getEditionSheet","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights","getCurrentEditedCell"];const Db=[{name:s("Sum"),types:[tn.number],compute:e=>al.compute([e])},{name:s("Avg"),types:[tn.number],compute:e=>bl.compute([e])},{name:s("Min"),types:[tn.number],compute:e=>kl.compute([e])},{name:s("Max"),types:[tn.number],compute:e=>Nl.compute([e])},{name:s("Count"),types:[tn.number,tn.text,tn.boolean,tn.error],compute:e=>Rl.compute([e])},{name:s("Count Numbers"),types:[tn.number,tn.text,tn.boolean,tn.error],compute:e=>Il.compute([e])}];class kb extends Bv{constructor(e){super(e),this.gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]},this.selectedFigureId=null,this.sheetsData={},this.activeSheet=null,this.moveClient=e.moveClient}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{this.getters.getSheet(e.sheetIdTo);break}catch(e){return 27}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return 0}handleEvent(e){const t=e.anchor;let i=[];switch(e.mode){case"overrideSelection":i=[t.zone];break;case"updateAnchor":i=[...this.gridSelection.zones];const o=i.findIndex((t=>Gi(t,e.previousAnchor.zone)));o>=0&&(i[o]=t.zone);break;case"newAnchor":i=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,i),this.selection.resetDefaultAnchor(this,Ne(this.gridSelection.anchor));const{col:o,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:o,row:n}),this.selectedFigureId=null}handle(e){switch(e.type){case"START_EDITION":case"ACTIVATE_SHEET":this.selectedFigureId=null;break;case"DELETE_FIGURE":this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;case"DELETE_SHEET":this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null)}switch(e.type){case"START":const t=this.getters.getVisibleSheetIds()[0];this.dispatch("ACTIVATE_SHEET",{sheetIdTo:t,sheetIdFrom:t});const{col:i,row:o}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(i,o),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case"ACTIVATE_SHEET":if(this.getters.isSheetVisible(e.sheetIdTo)||this.dispatch("SHOW_SHEET",{sheetId:e.sheetIdTo}),this.setActiveSheet(e.sheetIdTo),this.sheetsData[e.sheetIdFrom]={gridSelection:Ne(this.gridSelection)},e.sheetIdTo in this.sheetsData)Object.assign(this,this.sheetsData[e.sheetIdTo]),this.selection.resetDefaultAnchor(this,Ne(this.gridSelection.anchor));else{const{col:t,row:i}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0});this.selectCell(t,i)}break;case"REMOVE_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);const{col:i,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:i,row:o})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:i,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:i,row:o})}break}case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"SELECT_FIGURE":this.selectedFigureId=e.id;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left");break;case"HIDE_SHEET":e.sheetId===this.getActiveSheetId()&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case"UNDO":case"REDO":case"DELETE_SHEET":const n=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of n)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:Ne(t)}}if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){const e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){const{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);const{col:t,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:i})}const s=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map((e=>this.getters.expandZone(s,e))),this.gridSelection.anchor.zone=this.getters.expandZone(s,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones)}this.selection.resetDefaultAnchor(this,Ne(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 i=t.left;i<=t.right;i++)e.add(i);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(let i of this.gridSelection.zones)if(0===i.left&&i.right===this.getters.getNumberCols(t)-1)for(let t=i.top;t<=i.bottom;t++)e.add(t);return e}getCurrentStyle(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return Ne(this.gridSelection.zones)}getSelectedZone(){return Ne(this.gridSelection.anchor.zone)}getSelection(){return Ne(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!==tn.empty)));let t=new Set,i=[];for(let o of e)t.add(o.type),i.push(o.value);let o={};for(let e of Db){let n;e.types.some((e=>t.has(e)))&&(n=e.compute(i)),o[e.name]=n}return o}getAggregate(){let e=0,t=0;const i=this.getters.getActiveSheetId(),o=this.gridSelection.zones.map(Ji).flat();for(const{col:n,row:s}of o){const o=this.getters.getEvaluatedCell({sheetId:i,col:n,row:s});o.type===tn.number&&(t++,e+=o.value)}return t<2?null:hi(e)}isSelected(e){return!!this.getters.getSelectedZones().find((t=>Gi(t,e)))}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let i=[];const o="COL"===e?"left":"top",n="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[n]-e[o]+1},((t,i)=>e[o]+i));i=i.concat(t)}return[...new Set(i)].sort()}setSelectionMixin(e,t){const{anchor:i,zones:o}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=i,this.gridSelection.zones=function(e){return e.reverse().filter(((e,t,i)=>t===i.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}(o)}selectCell(e,t){const i=this.getters.getActiveSheetId(),o=this.getters.expandZone(i,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:o,cell:{col:e,row:t}},[o])}setActiveSheet(e){const t=this.getters.getSheet(e);this.activeSheet=t}activateNextSheet(e){const t=this.getters.getSheetIds(),i=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[i]})}onColumnsRemoved(e){const{cell:t,zone:i}=this.gridSelection.anchor,o=Bi(i,"left",[...e.elements]);let n={left:t.col,right:t.col,top:t.row,bottom:t.row};n=Bi(n,"left",[...e.elements]);const s={cell:{col:n.left,row:n.top},zone:o};this.setSelectionMixin(s,[o])}onRowsRemoved(e){const{cell:t,zone:i}=this.gridSelection.anchor,o=Bi(i,"top",[...e.elements]);let n={left:t.col,right:t.col,top:t.row,bottom:t.row};n=Bi(n,"top",[...e.elements]);const s={cell:{col:n.left,row:n.top},zone:o};this.setSelectionMixin(s,[o])}onAddElements(e){const t=zi(this.gridSelection.anchor.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),i={cell:{col:t.left,row:t.top},zone:t};this.setSelectionMixin(i,[t])}onMoveElements(e){const t=e.elements.length;this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:"before"});const i="COL"===e.dimension,o=e.elements[0],n=e.elements[t-1],s=e.base<o,r=s&&i?t:0,a=s&&!i?t:0;this.dispatch("CUT",{target:[{left:i?o+r:0,right:i?n+r:this.getters.getNumberCols(e.sheetId)-1,top:i?0:o+a,bottom:i?this.getters.getNumberRows(e.sheetId)-1:n+a}]}),this.dispatch("PASTE",{target:[{left:i?e.base:0,right:i?e.base+t-1:this.getters.getNumberCols(e.sheetId)-1,top:i?0:e.base,bottom:i?this.getters.getNumberRows(e.sheetId)-1:e.base+t-1}]});const l=s?e.elements.map((e=>e+t)):e.elements;let c=e.base;for(const t of l){const i="COL"===e.dimension?this.getters.getColSize(e.sheetId,t):this.getters.getRowSize(e.sheetId,t);this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:i,elements:[c]}),c+=1}this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,elements:l})}isMoveElementAllowed(e){const t="COL"===e.dimension,i=e.elements[0],o=e.elements[e.elements.length-1],n=e.sheetId,s=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;return s(n,i-1,i)||s(n,o,o+1)||s(n,e.base-1,e.base)?2:0}clipSelection(e,t){const i=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;return{zones:t.zones.map((e=>({left:De(e.left,0,i),right:De(e.right,0,i),top:De(e.top,0,o),bottom:De(e.bottom,0,o)}))),anchor:{cell:{col:De(t.anchor.cell.col,0,i),row:De(t.anchor.cell.row,0,o)},zone:{left:De(t.anchor.zone.left,0,i),right:De(t.anchor.zone.right,0,i),top:De(t.anchor.zone.top,0,o),bottom:De(t.anchor.zone.bottom,0,o)}}}}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:i}=e,o=this.getSelectedZones();t.fillStyle="#f3f7fe";const n=1===o.length&&o[0].left===o[0].right&&o[0].top===o[0].bottom;t.fillStyle=n?"#f3f7fe":"#e9f0ff",t.strokeStyle=E,t.lineWidth=1.5*i;for(const e of o){const{x:i,y:o,width:n,height:s}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(i,o,n,s),t.globalCompositeOperation="source-over",t.strokeRect(i,o,n,s)}t.globalCompositeOperation="source-over";const s=this.getActivePosition();let r;t.strokeStyle=E,t.lineWidth=3*i,r=this.getters.isInMerge(s)?this.getters.getMerge(s):oo(s);const{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);c>0&&h>0&&t.strokeRect(a,l,c,h)}}kb.layers=[6],kb.getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getStatisticFnResults","getAggregate","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSelected","getElementsFromSelection"];const Lb=(new Co).add("sheet",zv).add("header visibility",Dv).add("filters",_v).add("cell",Iv).add("merge",Lv).add("headerSize",Fv).add("borders",xv).add("conditional formatting",Av).add("figures",Mv).add("chart",Rv).add("image",kv),Pb=(new Co).add("ui_sheet",Eb).add("header_visibility_ui",ib).add("ui_options",Cb).add("selectionInputManager",rb).add("highlight",ob).add("grid renderer",nb).add("autofill",Kv).add("find_and_replace",tb).add("sort",Sb).add("automatic_sum",Qv).add("format",class extends Bv{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,i){for(const o of t)for(const t of Ji(o)){const o=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==o){const n=yi(o,i);this.dispatch("SET_FORMATTING",{sheetId:e,target:[oo(t)],format:n})}}}getCellNumberFormat(e){var t;for(const i of[e]){const e=this.getters.getEvaluatedCell(i);if(e.type===tn.number&&!(null===(t=e.format)||void 0===t?void 0:t.match(X)))return e.format||Ci(e.value)}}}).add("cell_popovers",Jv).add("selection_multiuser",bb),Ub=(new Co).add("selection",kb).add("clipboard",Ab).add("edition",Fb),Vb=(new Co).add("evaluation",Wv).add("evaluation_filter",Zv).add("evaluation_chart",Gv).add("evaluation_cf",qv).add("viewport",Xv).add("custom_colors",Hv),zb=new Co;zb.add("link",{condition:(e,t)=>!!t.model.getters.getEvaluatedCell(e).link,action:(e,t)=>To(t.model.getters.getEvaluatedCell(e).link,t),sequence:5});class Bb{constructor(e){this.fileStore=e}async requestImage(){const e=await this.getImageFromUser(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageSize(t),mimetype:e.type}}getImageFromUser(){return new Promise(((e,t)=>{const i=document.createElement("input");i.setAttribute("type","file"),i.setAttribute("accept","image/*"),i.addEventListener("change",(async()=>{null===i.files||1!=i.files.length?t():e(i.files[0])})),i.click()}))}getImageSize(e){return new Promise(((t,i)=>{const o=new Image;o.src=e,o.addEventListener("load",(()=>{const e={width:o.width,height:o.height};t(e)})),o.addEventListener("error",i)}))}}const Hb=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];ho`
1399
+ `}function Xf(e){return new up(e.join("\n"))}function Yf(e,...t){let i=[e[0]];for(let o=0;o<t.length;o++){const n=t[o]instanceof up?t[o]:Gf(t[o]);i.push(n+e[o+1])}return new up(nt(i))}function Kf(e){return e.replace(/[a-z0-9]+:(?=[a-z0-9]+)/gi,"")}function Qf(e){return e.replace(/([a-z0-9]+):(?=[a-z0-9]+)/gi,"$1\\:")}class Jf{constructor(e){this.value=e}asString(){return im(String(this.value))}asBool(){return Boolean(Number(this.value))}asNum(){return Number(this.value)}}class ev{constructor(e,t,i){this.currentFile=void 0,this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=i,this.areNamespaceIgnored=null!==(new DOMParser).parseFromString("<t:test xmlns:t='a'/>","text/xml").querySelector("test"),this.relationships={},e.rels&&this.extractRelationships(e.rels).map((e=>{this.relationships[e.id]=e}))}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:"Relationship"},(e=>({id:this.extractAttr(e,"Id",{required:!0}).asString(),target:this.extractAttr(e,"Target",{required:!0}).asString(),type:this.extractAttr(e,"Type",{required:!0}).asString()})))}getListOfFiles(){return Object.values(this.xlsxFileStructure).flat().filter(tt)}mapOnElements(e,t){var i;const o=[],n=this.currentFile;let s;if(e.children){const t=null===(i=this.querySelector(e.parent,e.query))||void 0===i?void 0:i.children;s=t||[]}else s=this.querySelectorAll(e.parent,e.query);if(s)for(let e of s)try{o.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=n,o}catchErrorOnElement(e,t){const i=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([i,e.message].join("\n"))}extractAttr(e,t,i){const o=e.attributes[t];o||this.handleMissingValue(e,`attribute "${t}"`,i);const n=(null==o?void 0:o.value)?o.value:null==i?void 0:i.default;return void 0===n?void 0:new Jf(n)}extractTextContent(e,t){var i;if(void 0!==(null==t?void 0:t.default)&&"string"!=typeof t.default)throw new Error("extractTextContent default value should be a string");const o="preserve"===(null===(i=null==e?void 0:e.attributes["xml:space"])||void 0===i?void 0:i.value);let n=null==e?void 0:e.textContent;return e&&null!==n||this.handleMissingValue(e,"text content",t),n&&(n=o?n:n.trim()),n?im(n):null==t?void 0:t.default}extractChildAttr(e,t,i,o){var n;let s;s="number"==typeof t?e.children[t]:this.querySelector(e,t),s||this.handleMissingValue(e,"number"==typeof t?`child at index ${t}`:`child <${t}>`,o);const r=s?null===(n=this.extractAttr(s,i,o))||void 0===n?void 0:n.asString():null==o?void 0:o.default;return void 0!==r?new Jf(r):void 0}extractChildTextContent(e,t,i){if(void 0!==(null==i?void 0:i.default)&&"string"!=typeof i.default)throw new Error("extractTextContent default value should be a string");let o=this.querySelector(e,t);return o||this.handleMissingValue(e,`child <${t}>`,i),o?this.extractTextContent(o,i):null==i?void 0:i.default}handleMissingValue(e,t,i){if(null==i?void 0:i.required){if(!(null==i?void 0:i.default))throw new Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`);this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${i.default}`)}}extractColor(e,t,i){var o,n,s,r,a;if(!e)return i?{rgb:i}:void 0;const l=null===(o=this.extractAttr(e,"theme"))||void 0===o?void 0:o.asString();let c;if(void 0!==l){if(!t||!t.clrScheme)throw new Error("Color referencing a theme but no theme was provided");c=this.getThemeColor(l,t.clrScheme)}else c=null===(n=this.extractAttr(e,"rgb"))||void 0===n?void 0:n.asString();return{rgb:c,auto:null===(s=this.extractAttr(e,"auto"))||void 0===s?void 0:s.asBool(),indexed:null===(r=this.extractAttr(e,"indexed"))||void 0===r?void 0:r.asNum(),tint:null===(a=this.extractAttr(e,"tint"))||void 0===a?void 0:a.asNum()}}getTargetXmlFile(e){if(!e)throw new Error("Undefined target file");let t=e.target;t=t.replace("../",""),t=t.replace("./","");const i=this.getListOfFiles().find((e=>e.file.fileName.endsWith(t)));if(!i||!i.file)throw new Error("Cannot find target file");return i}querySelector(e,t){return t=this.areNamespaceIgnored?Kf(t):Qf(t),e.querySelector(t)}querySelectorAll(e,t){return t=this.areNamespaceIgnored?Kf(t):Qf(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 tv extends ev{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:pp}).asString(),lastClr:this.extractChildAttr(e,0,"lastClr",{default:pp}).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 iv extends ev{constructor(e,t,i,o){super(e,t,i),this.theme=o}extractConditionalFormattings(){const e=this.mapOnElements({parent:this.rootFile.file.xml,query:"worksheet > conditionalFormatting"},(e=>{var t;return{sqref:this.extractAttr(e,"sqref",{required:!0}).asString().split(" "),pivot:null===(t=this.extractAttr(e,"pivot"))||void 0===t?void 0:t.asBool(),cfRules:this.extractCFRules(e,this.theme)}}));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:"extLst x14:conditionalFormatting"},(e=>{var t;return{sqref:this.extractChildTextContent(e,"xm:sqref",{required:!0}).split(" "),pivot:null===(t=this.extractAttr(e,"xm:pivot"))||void 0===t?void 0:t.asBool(),cfRules:this.extractCFRules(e,this.theme)}}))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:"cfRule, x14:cfRule"},(e=>{var i,o,n,s,r,a,l,c,h,d,u;const g=this.extractAttr(e,"type",{required:!0}).asString();if("dataBar"===g)throw new Error("Databars conditional formats are not supported.");return{type:g,priority:this.extractAttr(e,"priority",{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:null===(i=this.extractAttr(e,"dxfId"))||void 0===i?void 0:i.asNum(),stopIfTrue:null===(o=this.extractAttr(e,"stopIfTrue"))||void 0===o?void 0:o.asBool(),aboveAverage:null===(n=this.extractAttr(e,"aboveAverage"))||void 0===n?void 0:n.asBool(),percent:null===(s=this.extractAttr(e,"percent"))||void 0===s?void 0:s.asBool(),bottom:null===(r=this.extractAttr(e,"bottom"))||void 0===r?void 0:r.asBool(),operator:null===(a=this.extractAttr(e,"operator"))||void 0===a?void 0:a.asString(),text:null===(l=this.extractAttr(e,"text"))||void 0===l?void 0:l.asString(),timePeriod:null===(c=this.extractAttr(e,"timePeriod"))||void 0===c?void 0:c.asString(),rank:null===(h=this.extractAttr(e,"rank"))||void 0===h?void 0:h.asNum(),stdDev:null===(d=this.extractAttr(e,"stdDev"))||void 0===d?void 0:d.asNum(),equalAverage:null===(u=this.extractAttr(e,"equalAverage"))||void 0===u?void 0:u.asBool()}}))}extractCfFormula(e){return this.mapOnElements({parent:e,query:"formula"},(e=>this.extractTextContent(e,{required:!0})))}extractCfColorScale(e,t){const i=this.querySelector(e,"colorScale");if(i)return{colors:this.mapOnElements({parent:i,query:"color"},(e=>this.extractColor(e,t,"ffffff"))),cfvos:this.extractCFVos(i)}}extractCfIconSet(e){var t,i;const o=this.querySelector(e,"iconSet, x14:iconSet");if(o)return{iconSet:this.extractAttr(o,"iconSet",{default:"3TrafficLights1"}).asString(),showValue:this.extractAttr(o,"showValue",{default:!0}).asBool(),percent:this.extractAttr(o,"percent",{default:!0}).asBool(),reverse:null===(t=this.extractAttr(o,"reverse"))||void 0===t?void 0:t.asBool(),custom:null===(i=this.extractAttr(o,"custom"))||void 0===i?void 0:i.asBool(),cfvos:this.extractCFVos(o),cfIcons:this.extractCfIcons(o)}}extractCfIcons(e){const t=this.mapOnElements({parent:e,query:"cfIcon, x14:cfIcon"},(e=>({iconSet:this.extractAttr(e,"iconSet",{required:!0}).asString(),iconId:this.extractAttr(e,"iconId",{required:!0}).asNum()})));return 0===t.length?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:"cfvo, x14:cfvo"},(e=>{var t,i;return{type:this.extractAttr(e,"type",{required:!0}).asString(),gte:null===(t=this.extractAttr(e,"gte",{default:!0}))||void 0===t?void 0:t.asBool(),value:e.attributes.val?null===(i=this.extractAttr(e,"val"))||void 0===i?void 0:i.asString():this.extractChildTextContent(e,"f, xm:f")}}))}}class ov extends ev{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"c:chartSpace"},(e=>{const t=this.getChartType(e);if(!qp[t])throw new Error(`Unsupported chart type ${t}`);const i=this.mapOnElements({parent:e,query:"c:title a:t"},(e=>e.textContent||"")).join(""),o=this.extractChildAttr(e,"c:grouping","val",{default:"clustered"}).asString();return{title:i,type:qp[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:Gp[this.extractChildAttr(e,"c:legendPos","val",{default:"b"}).asString()],stacked:"stacked"===o,fontColor:"000000"}}))[0]}extractChartDatasets(e){return this.mapOnElements({parent:e,query:"c:ser"},(e=>({label:this.extractChildTextContent(e,"c:cat c:f"),range:this.extractChildTextContent(e,"c:val c:f",{required:!0})})))}getChartType(e){const t=this.querySelector(e,"c:plotArea");if(!t)throw new Error("Missing plot area in the chart definition.");for(let e of t.children){const t=Kf(e.tagName);if(gp.some((e=>e===t)))return t}throw new Error("Unknown chart type")}}class nv extends ev{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"xdr:wsDr",children:!0},(e=>{if("twoCellAnchor"!==Kf(e.tagName))throw new Error("Only twoCellAnchor are supported for xlsx drawings.");const t=this.querySelector(e,"c:chart");if(!t)throw new Error("Only chart figures are currently supported.");return{anchors:[this.extractFigureAnchor("xdr:from",e),this.extractFigureAnchor("xdr:to",e)],data:this.extractChart(t)}}))}extractFigureAnchor(e,t){const i=this.querySelector(t,e);if(!i)throw new Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(i,"xdr:col",{required:!0})),colOffset:Number(this.extractChildTextContent(i,"xdr:colOff",{required:!0})),row:Number(this.extractChildTextContent(i,"xdr:row",{required:!0})),rowOffset:Number(this.extractChildTextContent(i,"xdr:rowOff",{required:!0}))}}extractChart(e){const t=this.extractAttr(e,"r:id",{required:!0}).asString(),i=this.getTargetXmlFile(this.relationships[t]),o=new ov(i,this.xlsxFileStructure,this.warningManager).extractChart();if(!o)throw new Error("Unable to extract chart definition");return o}}class sv extends ev{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 rv extends ev{getTable(){return this.mapOnElements({query:"table",parent:this.rootFile.file.xml},(e=>{var t;return{displayName:this.extractAttr(e,"displayName",{required:!0}).asString(),name:null===(t=this.extractAttr(e,"name"))||void 0===t?void 0:t.asString(),id:this.extractAttr(e,"id",{required:!0}).asString(),ref:this.extractAttr(e,"ref",{required:!0}).asString(),headerRowCount:this.extractAttr(e,"headerRowCount",{default:1}).asNum(),totalsRowCount:this.extractAttr(e,"totalsRowCount",{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)}}))[0]}extractTableCols(e){return this.mapOnElements({query:"tableColumn",parent:e},(e=>({id:this.extractAttr(e,"id",{required:!0}).asString(),name:this.extractAttr(e,"name",{required:!0}).asString(),colFormula:this.extractChildTextContent(e,"calculatedColumnFormula")})))}extractTableStyleInfo(e){return this.mapOnElements({query:"tableStyleInfo",parent:e},(e=>{var t,i,o,n,s;return{name:null===(t=this.extractAttr(e,"name"))||void 0===t?void 0:t.asString(),showFirstColumn:null===(i=this.extractAttr(e,"showFirstColumn"))||void 0===i?void 0:i.asBool(),showLastColumn:null===(o=this.extractAttr(e,"showLastColumn"))||void 0===o?void 0:o.asBool(),showRowStripes:null===(n=this.extractAttr(e,"showRowStripes"))||void 0===n?void 0:n.asBool(),showColumnStripes:null===(s=this.extractAttr(e,"showColumnStripes"))||void 0===s?void 0:s.asBool()}}))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:"autoFilter",parent:e},(e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,"ref",{required:!0}).asString()})))[0]}extractFilterColumns(e){return this.mapOnElements({query:"tableColumn",parent:e},(t=>({colId:this.extractAttr(e,"colId",{required:!0}).asNum(),hiddenButton:this.extractAttr(e,"hiddenButton",{default:!1}).asBool(),filters:this.extractSimpleFilter(t)})))}extractSimpleFilter(e){return this.mapOnElements({query:"filter",parent:e},(e=>({val:this.extractAttr(e,"val",{required:!0}).asString()})))}}class av extends ev{constructor(e,t,i,o){super(e,t,i),this.theme=o}getSheet(){return this.mapOnElements({query:"worksheet",parent:this.rootFile.file.xml},(e=>{const t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:[...this.extractTables(e),...this.extractPivotTables()],isVisible:"visible"===t.state}}))[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:"sheetView"},(e=>{const t=this.querySelector(e,"pane");return{tabSelected:this.extractAttr(e,"tabSelected",{default:!1}).asBool(),showFormulas:this.extractAttr(e,"showFormulas",{default:!1}).asBool(),showGridLines:this.extractAttr(e,"showGridLines",{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,"showRowColHeaders",{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,"xSplit",{default:0}).asNum():0,ySplit:t?this.extractAttr(t,"ySplit",{default:0}).asNum():0}}}))}extractSheetName(){const e=Jp(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=Jp(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find((t=>t.target===e)).id,i=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:"sheet"},(e=>({relationshipId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetId:this.extractAttr(e,"sheetId",{required:!0}).asString(),sheetName:this.extractAttr(e,"name",{required:!0}).asString(),state:this.extractAttr(e,"state",{default:"visible"}).asString()}))).find((e=>e.relationshipId===t));if(!i)throw new Error("Cannot find corresponding workbook sheet");return i}extractConditionalFormats(){return new iv(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractFigures(e){return this.mapOnElements({parent:e,query:"drawing"},(e=>{var t;const i=null===(t=this.extractAttr(e,"r:id",{required:!0}))||void 0===t?void 0:t.asString(),o=this.getTargetXmlFile(this.relationships[i]);return new nv(o,this.xlsxFileStructure,this.warningManager).extractFigures()}))[0]||[]}extractTables(e){return this.mapOnElements({query:"tablePart",parent:e},(e=>{var t;const i=null===(t=this.extractAttr(e,"r:id",{required:!0}))||void 0===t?void 0:t.asString(),o=this.getTargetXmlFile(this.relationships[i]);return new rv(o,this.xlsxFileStructure,this.warningManager).getTable()}))}extractPivotTables(){try{return Object.values(this.relationships).filter((e=>e.type.endsWith("pivotTable"))).map((e=>{const t=this.getTargetXmlFile(e);return new sv(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:xp.toString()}).asNum(),defaultRowHeight:this.extractAttr(t,"defaultRowHeight",{default:Ip.toString()}).asNum()}}extractCols(e){return this.mapOnElements({parent:e,query:"cols col"},(e=>{var t,i,o,n,s,r,a;return{width:null===(t=this.extractAttr(e,"width"))||void 0===t?void 0:t.asNum(),customWidth:null===(i=this.extractAttr(e,"customWidth"))||void 0===i?void 0:i.asBool(),bestFit:null===(o=this.extractAttr(e,"bestFit"))||void 0===o?void 0:o.asBool(),hidden:null===(n=this.extractAttr(e,"hidden"))||void 0===n?void 0:n.asBool(),min:null===(s=this.extractAttr(e,"min",{required:!0}))||void 0===s?void 0:s.asNum(),max:null===(r=this.extractAttr(e,"max",{required:!0}))||void 0===r?void 0:r.asNum(),styleIndex:null===(a=this.extractAttr(e,"style"))||void 0===a?void 0:a.asNum()}}))}extractRows(e){return this.mapOnElements({parent:e,query:"sheetData row"},(e=>{var t,i,o,n,s;return{index:null===(t=this.extractAttr(e,"r",{required:!0}))||void 0===t?void 0:t.asNum(),cells:this.extractCells(e),height:null===(i=this.extractAttr(e,"ht"))||void 0===i?void 0:i.asNum(),customHeight:null===(o=this.extractAttr(e,"customHeight"))||void 0===o?void 0:o.asBool(),hidden:null===(n=this.extractAttr(e,"hidden"))||void 0===n?void 0:n.asBool(),styleIndex:null===(s=this.extractAttr(e,"s"))||void 0===s?void 0:s.asNum()}}))}extractCells(e){return this.mapOnElements({parent:e,query:"c"},(e=>{var t,i,o;return{xc:null===(t=this.extractAttr(e,"r",{required:!0}))||void 0===t?void 0:t.asString(),styleIndex:null===(i=this.extractAttr(e,"s"))||void 0===i?void 0:i.asNum(),type:Vp[null===(o=this.extractAttr(e,"t",{default:"n"}))||void 0===o?void 0:o.asString()],value:this.extractChildTextContent(e,"v"),formula:this.extractCellFormula(e)}}))}extractCellFormula(e){var t,i;const o=this.querySelector(e,"f");if(o)return{content:this.extractTextContent(o),sharedIndex:null===(t=this.extractAttr(o,"si"))||void 0===t?void 0:t.asNum(),ref:null===(i=this.extractAttr(o,"ref"))||void 0===i?void 0:i.asString()}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:"hyperlink"},(e=>{var t,i,o,n;const s=null===(t=this.extractAttr(e,"r:id"))||void 0===t?void 0:t.asString();return{xc:null===(i=this.extractAttr(e,"ref",{required:!0}))||void 0===i?void 0:i.asString(),location:null===(o=this.extractAttr(e,"location"))||void 0===o?void 0:o.asString(),display:null===(n=this.extractAttr(e,"display"))||void 0===n?void 0:n.asString(),relTarget:s?this.relationships[s].target:void 0}}))}extractSharedFormulas(e){const t=this.querySelectorAll(e,"f[si][ref]"),i={};for(let e of t){const t=this.extractAttr(e,"si",{required:!0}).asNum(),o=this.extractTextContent(e,{required:!0});i[t]=o}const o=[];for(let e=0;e<Object.keys(i).length;e++)i[e]?o.push(i[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),o.push(""));return o}}class lv extends ev{constructor(e,t,i){super(e.styles,e,t),this.theme=i}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"numFmt"},(e=>this.extractNumFormats(e)))}extractNumFormats(e){return{id:this.extractAttr(e,"numFmtId",{required:!0}).asNum(),format:this.extractAttr(e,"formatCode",{required:!0,default:""}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"font"},(e=>this.extractFont(e)))}extractFont(e){var t,i,o,n;const s=this.extractChildAttr(e,"name","val",{default:"Arial"}).asString(),r=this.extractChildAttr(e,"sz","val",{default:G.toString()}).asNum(),a=this.extractColor(this.querySelector(e,"color"),this.theme),l=this.querySelector(e,"i")||void 0,c=l&&"0"!==(null===(t=l.attributes.val)||void 0===t?void 0:t.value),h=this.querySelector(e,"b")||void 0,d=h&&"0"!==(null===(i=h.attributes.val)||void 0===i?void 0:i.value),u=this.querySelector(e,"strike")||void 0,g=u&&"0"!==(null===(o=u.attributes.val)||void 0===o?void 0:o.value),p=this.querySelector(e,"u")||void 0;return{name:s,size:r,color:a,italic:c,bold:d,underline:p&&"none"!==(null===(n=p.attributes.val)||void 0===n?void 0:n.value),strike:g}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"fill"},(e=>this.extractFill(e)))}extractFill(e){var t;const i=e.children[0];return"patternFill"===i.tagName?{patternType:null===(t=i.attributes.patternType)||void 0===t?void 0:t.value,bgColor:this.extractColor(this.querySelector(i,"bgColor"),this.theme),fgColor:this.extractColor(this.querySelector(i,"fgColor"),this.theme)}:{patternType:"solid",fgColor:this.extractColor(this.querySelectorAll(i,"color")[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"border"},(e=>this.extractBorder(e)))}extractBorder(e){var t,i;const o={left:this.extractSingleBorder(e,"left",this.theme),right:this.extractSingleBorder(e,"right",this.theme),top:this.extractSingleBorder(e,"top",this.theme),bottom:this.extractSingleBorder(e,"bottom",this.theme),diagonal:this.extractSingleBorder(e,"diagonal",this.theme)};return o.diagonal&&(o.diagonalUp=null===(t=this.extractAttr(e,"diagonalUp"))||void 0===t?void 0:t.asBool(),o.diagonalDown=null===(i=this.extractAttr(e,"diagonalDown"))||void 0===i?void 0:i.asBool()),o}extractSingleBorder(e,t,i){const o=this.querySelector(e,t);if(o&&o.attributes.style)return{style:this.extractAttr(o,"style",{required:!0,default:"thin"}).asString(),color:this.extractColor(o.children[0],i,"000000")}}extractAlignment(e){var t,i,o,n,s,r,a;return{horizontal:this.extractAttr(e,"horizontal",{default:"general"}).asString(),vertical:this.extractAttr(e,"vertical",{default:"center"}).asString(),textRotation:null===(t=this.extractAttr(e,"textRotation"))||void 0===t?void 0:t.asNum(),wrapText:null===(i=this.extractAttr(e,"wrapText"))||void 0===i?void 0:i.asBool(),indent:null===(o=this.extractAttr(e,"indent"))||void 0===o?void 0:o.asNum(),relativeIndent:null===(n=this.extractAttr(e,"relativeIndent"))||void 0===n?void 0:n.asNum(),justifyLastLine:null===(s=this.extractAttr(e,"justifyLastLine"))||void 0===s?void 0:s.asBool(),shrinkToFit:null===(r=this.extractAttr(e,"shrinkToFit"))||void 0===r?void 0:r.asBool(),readingOrder:null===(a=this.extractAttr(e,"readingOrder"))||void 0===a?void 0:a.asNum()}}getDxfs(){return this.mapOnElements({query:"dxf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"font"),i=this.querySelector(e,"fill"),o=this.querySelector(e,"border"),n=this.querySelector(e,"numFmt"),s=this.querySelector(e,"alignment");return{font:t?this.extractFont(t):void 0,fill:i?this.extractFill(i):void 0,numFmt:n?this.extractNumFormats(n):void 0,alignment:s?this.extractAlignment(s):void 0,border:o?this.extractBorder(o):void 0}}))}getStyles(){return this.mapOnElements({query:"cellXfs xf",parent:this.rootFile.file.xml},(e=>{const t=this.querySelector(e,"alignment");return{fontId:this.extractAttr(e,"fontId",{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,"fillId",{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,"borderId",{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,"numFmtId",{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}}))}}class cv extends ev{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:"externalBook"},(e=>({rId:this.extractAttr(e,"r:id",{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:"sheetName"},(e=>this.extractAttr(e,"val",{required:!0}).asString())),datasets:this.extractExternalSheetData(e)})))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:"sheetData"},(e=>{const t=this.mapOnElements({parent:e,query:"cell"},(e=>({xc:this.extractAttr(e,"r",{required:!0}).asString(),value:this.extractChildTextContent(e,"v",{required:!0})}))),i={};for(let e of t)i[e.xc]=e.value;return{sheetId:this.extractAttr(e,"sheetId",{required:!0}).asNum(),data:i}}))}}function hv(e,t){const i=function(e,t){const i=t[Np],o=i.querySelectorAll(`Override[ContentType="${e}"]`),n=[];for(let e of o){const t=null==e?void 0:e.attributes.PartName.value;n.push(t.substring(1))}return n}(e,t);return function(e,t){const i=[];for(let o of e){const e=dv(o,t);i.push({file:{fileName:o,xml:t[o]},rels:e?{fileName:e,xml:t[e]}:void 0})}return i}(i,t)}function dv(e,t){if(e===Np)return"_rels/.rels";let i="";const o=e.split("/");for(let e=0;e<o.length-1;e++)i+=o[e]+"/";return i+="_rels/",i+=o[o.length-1]+".rels",t[i]||(i=void 0),i}class uv{constructor(e){this.warningManager=new Fp,this.xmls={};for(let t of Object.keys(e))(t.endsWith(".xml")||t.endsWith(".rels"))&&(this.xmls[t]=Zf(new up(e[t])))}convertXlsx(){const e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){const e=this.buildXlsxFileStructure(),t=e.theme?new tv(e.theme,e,this.warningManager).getTheme():void 0,i=e.sharedStrings?new tv(e.sharedStrings,e,this.warningManager).getSharedStrings():[],o=e.sheets.sort(((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0}))).map((i=>new av(i,e,this.warningManager,t).getSheet())),n=e.externalLinks.map((t=>new cv(t,e,this.warningManager).getExternalBook())),s=new lv(e,this.warningManager,t);return{fonts:s.getFonts(),fills:s.getFills(),borders:s.getBorders(),dxfs:s.getDxfs(),numFmts:s.getNumFormats(),styles:s.getStyles(),sheets:o,sharedStrings:i,externalBooks:n}}buildXlsxFileStructure(){const e={sheets:hv(Sp.sheet,this.xmls),workbook:hv(Sp.workbook,this.xmls)[0],styles:hv(Sp.styles,this.xmls)[0],sharedStrings:hv(Sp.sharedStrings,this.xmls)[0],theme:hv(Sp.themes,this.xmls)[0],charts:hv(Sp.chart,this.xmls),figures:hv(Sp.drawing,this.xmls),tables:hv(Sp.table,this.xmls),pivots:hv(Sp.pivot,this.xmls),externalLinks:hv(Sp.externalLink,this.xmls)};if(!e.workbook.rels)throw Error(s("Cannot find workbook relations file"));return e}convertImportedData(e){const t={version:12,sheets:Ff(e,this.warningManager),styles:am(e,this.warningManager),formats:cm(e,this.warningManager),borders:sm(e,this.warningManager),entities:{},revisionId:K};return Bf(t,e),Object.keys(e.styles).map((t=>{e.styles[t]=ct(e.styles[t])})),t}}function gv(e){const t=ef(e);let i=[];return{text:"".concat(...t.map((e=>{if("REFERENCE"===e.type&&At.test(e.value)){const t=e.value.trim();return i.includes(t)||i.push(t),`${re}${i.indexOf(t)}${re}`}return e.value}))),dependencies:i}}const pv=12,mv="Sheet1";function fv(e,t){if(!e)return Ev();if(e["[Content_Types].xml"]){const i=new uv(e);if(e=i.convertXlsx(),t)for(let e of i.warningManager.warnings.sort())console.warn(e)}return"version"in(e=Ne(e))&&e.version<pv&&(e=function(e){for(let t=vv.findIndex((t=>t.from===e.version));t<vv.length;t++)e=vv[t].applyMigration(e);return e}(e)),e=function(e){return e=function(e){if(e.uniqueFigureIds)return e;const t=new Set,i=new ki;for(const o of e.sheets||[])for(const e of o.figures||[])t.has(e.id)&&(e.id+=i.uuidv4()),t.add(e.id);return e.uniqueFigureIds=!0,e}(e),e=function(e){e=Object.assign(Ev(),e,{version:pv}),e.sheets=e.sheets?e.sheets.map(((e,t)=>Object.assign(Cv(`Sheet${t+1}`,`Sheet${t+1}`),e))):[],0===e.sheets.length&&e.sheets.push(Cv(mv,"Sheet1"));return e}(e),e}(e),e}const vv=[{description:"add the `activeSheet` field on data",from:1,to:2,applyMigration:e=>(e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e)},{description:"add an id field in each sheet",from:2,to:3,applyMigration(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}},{description:"activeSheet is now an id, not the name of a sheet",from:3,to:4,applyMigration(e){if(e.sheets&&e.activeSheet){const t=e.sheets.find((t=>t.name===e.activeSheet));e.activeSheet=t.id}return e}},{description:"add figures object in each sheets",from:4,to:5,applyMigration(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}},{description:"normalize the content of the cell if it is a formula to avoid parsing all the formula that vary only by the cells they use",from:5,to:6,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const i=t.cells[e];i.content&&i.content.startsWith("=")&&(i.formula=gv(i.content))}return e}},{description:"transform chart data structure",from:6,to:7,applyMigration(e){for(let t of e.sheets||[])for(let e in t.figures||[]){const{dataSets:i,...o}=t.figures[e].data,n=[];for(let e of i)if(e.labelCell){const t=Pi(e.dataRange),i=e.labelCell+":"+Ht(t.right,t.bottom);n.push(i)}else n.push(e.dataRange);o.dataSetsHaveTitle=Boolean(i[0].labelCell),o.dataSets=n,t.figures[e].data=o}return e}},{description:"remove single quotes in sheet names",from:7,to:8,applyMigration(e){var t;const i=[],o=new RegExp(se,"g");for(let n of e.sheets||[]){if(!n.name)continue;const e=n.name,s=e.replace(o,"_");let r=1,a=s;for(;i.includes(a);)a=`${s}${r}`,r++;n.name=a,i.push(a);const l=t=>{if(void 0===t)return t;let i=t.replace(e,a),o=t;for(;o!==i;)o=i,i=o.replace(e,a);return o};for(let e in n.cells){const t=n.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(l))}for(let e of n.figures||[])if("chart"===e.type){const t=e.data.dataSets.map(l),i=l(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:i}}for(let e of n.conditionalFormats||[]){e.ranges=e.ranges.map(l);for(const i of["minimum","maximum","midpoint","upperInflectionPoint","lowerInflectionPoint"])"formula"===(null===(t=e.rule[i])||void 0===t?void 0:t.type)&&(e.rule[i].value=l(e.rule[i].value))}}return e}},{description:"transform chart data structure with design attributes",from:8,to:9,applyMigration(e){for(const t of e.sheets||[])for(const e of t.figures||[])e.data.background=w,e.data.verticalAxisPosition="left",e.data.legendPosition="top",e.data.stacked=!1;return e}},{description:"de-normalize formula to reduce exported json size (~30%)",from:9,to:10,applyMigration(e){for(let t of e.sheets||[])for(let e in t.cells||[]){const i=t.cells[e];if(i.formula){let{text:e,dependencies:t}=i.formula;for(let[i,o]of Object.entries(t)){const t=`\\${re}${i}\\${re}`;e=e.replace(new RegExp(t,"g"),o)}i.content=e,delete i.formula}}return e}},{description:"normalize the formats of the cells",from:10,to:11,applyMigration(e){const t={};for(let i of e.sheets||[])for(let e in i.cells||[]){const o=i.cells[e];o.format&&(o.format=ot(o.format,t))}return e.formats=t,e}},{description:"Add isVisible to sheets",from:11,to:12,applyMigration(e){for(let t of e.sheets||[])t.isVisible=!0;return e}}];function bv(e,t){return t=function(e,t){if(0!==Object.keys(e).length)return t;const i=[],o=[],n=e=>{if("CREATE_SHEET"===e.type)i.push(e.sheetId);else if("sheetId"in e&&!i.includes(e.sheetId))return{...e,sheetId:mv};return e};for(const e of t)"REMOTE_REVISION"===e.type?o.push({...e,commands:e.commands.map(n)}):o.push(e);return o}(e,t),t=Sv(t,"SORT_CELLS"),t=function(e,t){var i;const o=[],n={};for(const t of e.sheets||[])null===(i=t.figures)||void 0===i||i.forEach((e=>{"chart"===e.tag&&(n[e.id]=e.data)}));for(const e of t)if("REMOTE_REVISION"===e.type){const t=[];for(const i of e.commands){let e=i;switch(i.type){case"CREATE_CHART":n[i.id]=i.definition;break;case"UPDATE_CHART":if(!n[i.id]){console.log(`Fix chart definition: chart with id ${i.id} not found.`);continue}const t={...n[i.id],...i.definition};e={...i,definition:t},n[i.id]=t}t.push(e)}o.push({...e,commands:t})}else o.push(e);return o}(e,t=Sv(t,"SET_DECIMAL")),t}function Sv(e,t){const i=[];for(const o of e)"REMOTE_REVISION"===o.type?i.push({...o,commands:o.commands.filter((e=>e.type!==t))}):i.push(o);return i}function Cv(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},cols:{},rows:{},merges:[],conditionalFormats:[],figures:[],filterTables:[],isVisible:!0}}function Ev(e="Sheet1"){return{version:pv,sheets:[Cv(mv,e)],entities:{},styles:{},formats:{},borders:{},revisionId:K,uniqueFigureIds:!0}}function wv(e,t){return{...Cv(e,t),charts:[],images:[]}}class yv{constructor(e,t){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t}exportForExcel(e){}allowDispatch(e){return 0}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map((e=>e.call(this,t))).flat()}chainValidations(...e){return t=>{for(const i of e){let e=i.call(this,t);Array.isArray(e)||(e=[e]);const o=e.filter((e=>0!==e));if(o.length)return o}return 0}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}yv.getters=[];class xv extends yv{constructor({getters:e,stateObserver:t,range:i,dispatch:o,uuidGenerator:n}){super(t,o),this.range=i,i.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=n}import(e){}export(e){}adaptRanges(e,t){}garbageCollectExternalResources(){}}class Iv extends xv{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 i=t.slice().map((e=>null==e?void 0:e.slice().map((e=>({...e})))));this.history.update("borders",e.sheetIdTo,i)}break;case"DELETE_SHEET":const i={...this.borders};delete i[e.sheetId],this.history.update("borders",i);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_FORMATTING":if(e.border){const t=e.target.map((t=>this.getters.expandZone(e.sheetId,t)));this.setBorders(e.sheetId,t,e.border)}break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target);break;case"REMOVE_COLUMNS_ROWS":for(let t of e.elements)"COL"===e.dimension?this.shiftBordersHorizontally(e.sheetId,t+1,-1):this.shiftBordersVertically(e.sheetId,t+1,-1);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumns(e):this.handleAddRows(e)}}handleAddColumns(e){let t,i;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),t=e.base-1,i=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),t=e.base,i=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,i)}handleAddRows(e){let t,i;"before"===e.position?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity,{moveFirstTopBorder:!0}),t=e.base-1,i=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity,{moveFirstTopBorder:!1}),t=e.base,i=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,i)}getCellBorder({sheetId:e,col:t,row:i}){var o,n,s,r,a,l,c,h,d,u,g,p;const m={top:null===(s=null===(n=null===(o=this.borders[e])||void 0===o?void 0:o[t])||void 0===n?void 0:n[i])||void 0===s?void 0:s.horizontal,bottom:null===(l=null===(a=null===(r=this.borders[e])||void 0===r?void 0:r[t])||void 0===a?void 0:a[i+1])||void 0===l?void 0:l.horizontal,left:null===(d=null===(h=null===(c=this.borders[e])||void 0===c?void 0:c[t])||void 0===h?void 0:h[i])||void 0===d?void 0:d.vertical,right:null===(p=null===(g=null===(u=this.borders[e])||void 0===u?void 0:u[t+1])||void 0===g?void 0:g[i])||void 0===p?void 0:p.vertical};return m.bottom||m.left||m.right||m.top?m:null}ensureColumnBorderContinuity(e,t,i){const o=Be(t+1,i);for(let n=0;n<this.getters.getNumberRows(e);n++){const s=this.getCellBorder({sheetId:e,col:t,row:n}),r=this.getCellBorder({sheetId:e,col:i,row:n});if(s&&r){const t=this.getCommonSides(s,r);for(let i of o)this.addBorder(e,i,n,t)}}}ensureRowBorderContinuity(e,t,i){const o=Be(t+1,i);for(let n=0;n<this.getters.getNumberCols(e);n++){const s=this.getCellBorder({sheetId:e,col:n,row:t}),r=this.getCellBorder({sheetId:e,col:n,row:i});if(s&&r){const t=this.getCommonSides(s,r);for(let i of o)this.addBorder(e,n,i,t)}}}getCommonSides(e,t){const i={};for(let o of["top","bottom","left","right"])e[o]&&e[o]===t[o]&&(i[o]=e[o]);return i}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsRange(e){return this.borders[e]?Be(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,i,{moveFirstLeftBorder:o}={}){this.borders[e]&&(i<0&&this.moveBordersOfColumn(e,t,i,"vertical",{destructive:!1}),this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>i<0?e-t:t-e)).forEach((n=>{(n===t&&o||n!==t)&&this.moveBordersOfColumn(e,n,i,"vertical"),this.moveBordersOfColumn(e,n,i,"horizontal")})))}shiftBordersVertically(e,t,i,{moveFirstTopBorder:o}={}){this.borders[e]&&(i<0&&this.moveBordersOfRow(e,t,i,"horizontal",{destructive:!1}),this.getRowsRange(e).filter((e=>e>=t)).sort(((e,t)=>i<0?e-t:t-e)).forEach((n=>{(n===t&&o||n!==t)&&this.moveBordersOfRow(e,n,i,"horizontal"),this.moveBordersOfRow(e,n,i,"vertical")})))}moveBordersOfRow(e,t,i,o,{destructive:n}={destructive:!0}){const s=this.borders[e];s&&this.getColumnsWithBorders(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=s[r])||void 0===a?void 0:a[t+i])||void 0===l?void 0:l[o],u=null===(h=null===(c=s[r])||void 0===c?void 0:c[t])||void 0===h?void 0:h[o];this.history.update("borders",e,r,t+i,o,n?u:u||d),this.history.update("borders",e,r,t,o,void 0)}))}moveBordersOfColumn(e,t,i,o,{destructive:n}={destructive:!0}){const s=this.borders[e];s&&this.getRowsRange(e).forEach((r=>{var a,l,c,h;const d=null===(l=null===(a=s[t+i])||void 0===a?void 0:a[r])||void 0===l?void 0:l[o],u=null===(h=null===(c=s[t])||void 0===c?void 0:c[r])||void 0===h?void 0:h[o];this.history.update("borders",e,t+i,r,o,n?u:u||d),this.history.update("borders",e,t,r,o,void 0)}))}setBorder(e,t,i,o,n=!0){var s,r,a,l,c,h,d,u,g,p,m,f,v,b,S,C;!n&&(null===(l=null===(a=null===(r=null===(s=this.borders)||void 0===s?void 0:s[e])||void 0===r?void 0:r[t])||void 0===a?void 0:a[i])||void 0===l?void 0:l.vertical)||this.history.update("borders",e,t,i,"vertical",null==o?void 0:o.left),!n&&(null===(u=null===(d=null===(h=null===(c=this.borders)||void 0===c?void 0:c[e])||void 0===h?void 0:h[t])||void 0===d?void 0:d[i])||void 0===u?void 0:u.horizontal)||this.history.update("borders",e,t,i,"horizontal",null==o?void 0:o.top),!n&&(null===(f=null===(m=null===(p=null===(g=this.borders)||void 0===g?void 0:g[e])||void 0===p?void 0:p[t+1])||void 0===m?void 0:m[i])||void 0===f?void 0:f.vertical)||this.history.update("borders",e,t+1,i,"vertical",null==o?void 0:o.right),!n&&(null===(C=null===(S=null===(b=null===(v=this.borders)||void 0===v?void 0:v[e])||void 0===b?void 0:b[t])||void 0===S?void 0:S[i+1])||void 0===C?void 0:C.horizontal)||this.history.update("borders",e,t,i+1,"horizontal",null==o?void 0:o.bottom)}clearBorders(e,t){for(let i of t){for(let t=i.top;t<=i.bottom;t++){this.history.update("borders",e,i.right+1,t,"vertical",void 0);for(let o=i.left;o<=i.right;o++)this.history.update("borders",e,o,t,void 0)}for(let t=i.left;t<=i.right;t++)this.history.update("borders",e,t,i.bottom+1,"horizontal",void 0)}}addBorder(e,t,i,o){this.setBorder(e,t,i,{...this.getCellBorder({sheetId:e,col:t,row:i}),...o})}setBorders(e,t,i){if("clear"===i)return this.clearBorders(e,t);for(let o of t){if("h"===i||"hv"===i||"all"===i)for(let t=o.top+1;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++)this.addBorder(e,i,t,{top:Z});if("v"===i||"hv"===i||"all"===i)for(let t=o.top;t<=o.bottom;t++)for(let i=o.left+1;i<=o.right;i++)this.addBorder(e,i,t,{left:Z});if("left"===i||"all"===i||"external"===i)for(let t=o.top;t<=o.bottom;t++)this.addBorder(e,o.left,t,{left:Z});if("right"===i||"all"===i||"external"===i)for(let t=o.top;t<=o.bottom;t++)this.addBorder(e,o.right+1,t,{left:Z});if("top"===i||"all"===i||"external"===i)for(let t=o.left;t<=o.right;t++)this.addBorder(e,t,o.top,{top:Z});if("bottom"===i||"all"===i||"external"===i)for(let t=o.left;t<=o.right;t++)this.addBorder(e,t,o.bottom+1,{top:Z})}}addBordersToMerge(e,t){const{left:i,right:o,top:n,bottom:s}=t,r=this.getCellBorder({sheetId:e,col:i,row:n}),a=this.getCellBorder({sheetId:e,col:o,row:s});this.clearBorders(e,[t]),(null==r?void 0:r.top)&&this.setBorders(e,[{...t,bottom:n}],"top"),(null==r?void 0:r.left)&&this.setBorders(e,[{...t,right:i}],"left"),((null==a?void 0:a.bottom)||(null==r?void 0:r.bottom))&&this.setBorders(e,[{...t,top:s}],"bottom"),((null==a?void 0:a.right)||(null==r?void 0:r.right))&&this.setBorders(e,[{...t,left:o}],"right")}import(e){if(e.borders)for(let t of e.sheets)for(let[i,o]of Object.entries(t.cells))if(null==o?void 0:o.border){const n=e.borders[o.border],{col:s,row:r}=Bt(i);this.setBorder(t.id,s,r,n,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Pi(e))}export(e){let t=0;const i={};function o(e){for(let[t,o]of Object.entries(i))if(Ae(o)===Ae(e))return parseInt(t,10);return i[++t]=e,t}for(let t of e.sheets)for(let e=0;e<t.colNumber;e++)for(let i=0;i<t.rowNumber;i++){const n=this.getCellBorder({sheetId:t.id,col:e,row:i});if(n){const s=Ht(e,i),r=t.cells[s],a=o(n);r?r.border=a:t.cells[s]={border:a}}}e.borders=i}exportForExcel(e){this.export(e)}}Iv.getters=["getCellBorder"];class Rv extends xv{constructor(){super(...arguments),this.nextId=1,this.cells={}}adaptRanges(e,t){for(const i of Object.keys(this.cells))for(const o of Object.values(this.cells[i]||{}))if(o.isFormula)for(const n of o.dependencies)if(!t||n.sheetId===t){const t=e(n);"NONE"!==t.changeType&&this.history.update("cells",i,o.id,"dependencies",o.dependencies.indexOf(n),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":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,i){for(let o of t)for(let t=o.top;t<=o.bottom;t++)for(let n=o.left;n<=o.right;n++)this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,format:i})}clearFormatting(e,t){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let o=i.top;o<=i.bottom;o++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,style:null,format:""})}handleAddColumnsRows(e,t){let i,o;"before"===e.position?(i=Be(e.base,e.base+e.quantity),o=e.base+e.quantity):(i=Be(e.base+1,e.base+e.quantity+1),o=e.base),t(e.sheetId,o,i)}import(e){for(let t of e.sheets)for(let i in t.cells){const o=t.cells[i],{col:n,row:s}=Bt(i);if((null==o?void 0:o.content)||(null==o?void 0:o.format)||(null==o?void 0:o.style)){const i=this.importCell(t.id,o,e.styles,e.formats);this.history.update("cells",t.id,i.id,i),this.dispatch("UPDATE_CELL_POSITION",{cellId:i.id,col:n,row:s,sheetId:t.id})}}}export(e){const t={},i={};for(let o of e.sheets){const e={},n=Object.keys(this.cells[o.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const o of n){const n=this.getters.getCell(o);e[Ht(o.col,o.row)]={style:n.style?ot(n.style,t):void 0,format:n.format?ot(n.format,i):void 0,content:n.content||void 0}}o.cells=e}e.styles=t,e.formats=i}importCell(e,t,i,o){const n=t.style&&i[t.style]||void 0,s=t.format&&o[t.format]||void 0,r=this.getNextUid();return this.createCell(r,(null==t?void 0:t.content)||"",s,n,e)}exportForExcel(e){this.export(e)}getCells(e){return this.cells[e]||{}}getCellById(e){for(const t in this.cells){const i=this.cells[t][e];if(i)return i}}buildFormulaContent(e,t,i){const o=i||[...t.dependencies];return nt(t.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=o.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,i=[{colFixed:!1,rowFixed:!1}]){const o=Ht((t=this.getters.expandZone(e,t)).left,t.top,i[0]),n=Ht(t.right,t.bottom,i.length>1?i[1]:i[0]),s=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),r=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=s.col===r.col&&s.row===r.row;return o==n||a?o:o+":"+n}setStyle(e,t,i){for(let o of t)for(let t=o.left;t<=o.right;t++)for(let n=o.top;n<=o.bottom;n++){const o=this.getters.getCell({sheetId:e,col:t,row:n});this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:n,style:i?{...null==o?void 0:o.style,...i}:void 0})}}copyColumnStyle(e,t,i){for(let o=0;o<this.getters.getNumberRows(e);o++){const n=this.getFormat(e,t,o);if(n.style||n.format)for(let t of i)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,...n})}}copyRowStyle(e,t,i){for(let o=0;o<this.getters.getNumberCols(e);o++){const n=this.getFormat(e,o,t);if(n.style||n.format)for(let t of i)this.dispatch("UPDATE_CELL",{sheetId:e,col:o,row:t,...n})}}getFormat(e,t,i){const o={},n=this.getters.getMainCellPosition({sheetId:e,col:t,row:i}),s=this.getters.getCell(n);return s&&(s.style&&(o.style=s.style),s.format&&(o.format=s.format)),o}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,i,o){const n=this.getters.getCell({sheetId:e,col:t,row:i}),s="content"in o||"formula"in o,r=s?pt(null==o?void 0:o.content):(null==n?void 0:n.content)||"";let a;a=void 0!==o.style?o.style||void 0:n?n.style:void 0;let l=("format"in o?o.format:n&&n.format)||wi(r);if((s&&!r&&!o.formula||!s&&(!n||""===n.content))&&!a&&!l)return void(n&&(this.history.update("cells",e,n.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:i,sheetId:e})));const c=(null==n?void 0:n.id)||this.getNextUid(),h=this.createCell(c,r,l,a,e);this.history.update("cells",e,h.id,h),this.dispatch("UPDATE_CELL_POSITION",{cellId:h.id,col:t,row:i,sheetId:e})}createCell(e,t,i,o,n){if(!t.startsWith("="))return this.createLiteralCell(e,t,i,o);try{return this.createFormulaCell(e,t,i,o,n)}catch(n){return this.createErrorFormula(e,t,i,o,n)}}createLiteralCell(e,t,i,o){return{id:e,content:t,style:o,format:i,isFormula:!1}}createFormulaCell(e,t,i,o,n){const s=rf(t);return s.dependencies.length?this.createFormulaCellWithDependencies(e,s,i,o,n):{id:e,content:t,style:o,format:i,isFormula:!0,compiledFormula:s,dependencies:[]}}createFormulaCellWithDependencies(e,t,i,o,n){const s=t.dependencies.map((e=>this.getters.getRangeFromSheetXC(n,e))),r=this.buildFormulaContent.bind(this);return{id:e,get content(){return r(n,{dependencies:this.dependencies,compiledFormula:this.compiledFormula})},style:o,format:i,isFormula:!0,compiledFormula:t,dependencies:s}}createErrorFormula(e,t,i,o,n){return{id:e,content:t,style:o,format:i,isFormula:!0,compiledFormula:{dependencies:[],tokens:wm(t),execute:function(){throw n}},dependencies:[]}}checkCellOutOfSheet(e,t,i){if(!this.getters.tryGetSheet(e))return 27;return ji(t,i,this.getters.getSheetZone(e))?0:18}}Rv.getters=["zoneToXC","getCells","getFormulaCellContent","getCellStyle","buildFormulaContent","getCellById"];class Tv extends xv{constructor(){super(...arguments),this.charts={},this.createChart=function(e){const t=sr.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(i,o,n){const s=t.find((e=>e.match(o.type)));if(!s)throw new Error(`No builder for this chart: ${o.type}`);return s.createChart(o,n,e)}}(this.getters),this.validateChartDefinition=e=>function(e,t){const i=sr.getAll().find((e=>e.match(t.type)));if(!i)throw new Error("Unknown chart type.");return i.validateChartDefinition(e,t)}(this,e.definition)}adaptRanges(e){for(const[t,i]of Object.entries(this.charts))this.history.update("charts",t,null==i?void 0:i.updateRanges(e))}allowDispatch(e){switch(e.type){case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists));default:return 0}}handle(e){var t;switch(e.type){case"CREATE_CHART":this.addFigure(e.id,e.sheetId,e.position,e.size),this.addChart(e.id,e.definition);break;case"UPDATE_CHART":this.addChart(e.id,e.definition);break;case"DUPLICATE_SHEET":{const i=this.getters.getFigures(e.sheetId);for(const o of i)if("chart"===o.tag){const i=o.id.split(J).pop(),n=`${e.sheetIdTo}${J}${i}`,s=null===(t=this.charts[o.id])||void 0===t?void 0:t.copyForSheetId(e.sheetIdTo);s&&this.dispatch("CREATE_CHART",{id:n,position:{x:o.x,y:o.y},size:{width:o.width,height:o.height},definition:s.getDefinition(),sheetId:e.sheetIdTo})}break}case"DELETE_FIGURE":this.history.update("charts",e.id,void 0);break;case"DELETE_SHEET":for(let t of this.getChartIds(e.sheetId))this.history.update("charts",t,void 0)}}getContextCreationChart(e){var t;return null===(t=this.charts[e])||void 0===t?void 0:t.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){var t;const i=null===(t=this.charts[e])||void 0===t?void 0:t.type;if(!i)throw new Error("Chart not defined.");return i}isChartDefined(e){return e in this.charts&&void 0!==this.charts}getChartIds(e){return Object.entries(this.charts).filter((([,t])=>(null==t?void 0:t.sheetId)===e)).map((([e])=>e))}getChartDefinition(e){var t;const i=null===(t=this.charts[e])||void 0===t?void 0:t.getDefinition();if(!i)throw new Error(`There is no chart with the given figureId: ${e}`);return i}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)"chart"===e.tag&&(this.charts[e.id]=this.createChart(e.id,e.data,t.id))}export(e){var t;if(e.sheets)for(let i of e.sheets){const e=this.getters.getFigures(i.id),o=[];for(let i of e){const e=i;if(e&&"chart"===e.tag){const i=null===(t=this.charts[e.id])||void 0===t?void 0:t.getDefinition();i&&(e.data=i,o.push(e))}else o.push(e)}i.figures=o}}exportForExcel(e){var t;for(let i of e.sheets){const e=this.getters.getFigures(i.id),o=[];for(let i of e)if(i&&"chart"===i.tag){const e=null===(t=this.charts[i.id])||void 0===t?void 0:t.getDefinitionForExcel();e&&o.push({...i,data:e})}i.charts=o}}addFigure(e,t,i={x:0,y:0},o={width:536,height:335}){if(this.getters.getFigure(t,e))return;const n={id:e,x:i.x,y:i.y,width:o.width,height:o.height,tag:"chart"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:n})}addChart(e,t){const i=this.getters.getFigureSheetId(e);i&&this.history.update("charts",e,this.createChart(e,t,i))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.id)?84:0}checkChartExists(e){return this.getters.getFigureSheetId(e.id)?0:85}}function Av(e){return""===e?NaN:Number(e)}Tv.getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];class Mv extends xv{constructor(){super(...arguments),this.cfRules={}}loopThroughRangesOfSheet(e,t){for(const i of this.cfRules[e])for(const o of i.ranges){const n=t(o);switch(n.changeType){case"REMOVE":let t=i.ranges.slice();t.splice(i.ranges.indexOf(o),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(i),"ranges",t):this.removeConditionalFormatting(i.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(i),"ranges",i.ranges.indexOf(o),n.range)}}}adaptRanges(e,t){if(t)this.loopThroughRangesOfSheet(t,e);else for(const t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,e)}allowDispatch(e){switch(e.type){case"ADD_CONDITIONAL_FORMAT":return this.checkValidations(e,this.checkCFRule,this.checkEmptyRange);case"MOVE_CONDITIONAL_FORMAT":return this.checkValidReordering(e.cfId,e.direction,e.sheetId)}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const i={...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))};this.addConditionalFormatting(i,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId);break;case"MOVE_CONDITIONAL_FORMAT":this.reorderConditionalFormatting(e.cfId,e.direction,e.sheetId)}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map((e=>this.mapToConditionalFormatInternal(t.id,e)))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map((e=>this.mapToConditionalFormat(t.id,e))))}exportForExcel(e){this.export(e)}getConditionalFormats(e){var t;return(null===(t=this.cfRules[e])||void 0===t?void 0:t.map((t=>this.mapToConditionalFormat(e,t))))||[]}getRulesSelection(e,t){const i=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{i.add(e)}))})),Array.from(i)}getRulesByZone(e,t){const i=new Set;for(let o=t.top;o<=t.bottom;o++)for(let n=t.left;n<=t.right;n++){this.getRulesByCell(e,n,o).forEach((e=>{i.add(e.id)}))}return i}getRulesByCell(e,t,i){const o=[];for(let n of this.cfRules[e])for(let e of n.ranges)ji(t,i,e.zone)&&o.push(n);return new Set(o.map((t=>this.mapToConditionalFormat(e,t))))}mapToConditionalFormat(e,t){return{...t,ranges:t.ranges.map((t=>this.getters.getRangeString(t,e)))}}mapToConditionalFormatInternal(e,t){const i={...t,ranges:t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)))};return i}addConditionalFormatting(e,t){const i=this.cfRules[t].slice(),o=i.findIndex((t=>t.id===e.id)),n=this.mapToConditionalFormatInternal(t,e);o>-1?i.splice(o,1,n):i.push(n),this.history.update("cfRules",t,i)}checkValidReordering(e,t,i){if(!this.cfRules[i])return 27;const o=this.cfRules[i].findIndex((t=>t.id===e));if(-1===o)return 71;const n="up"===t?o-1:o+1;return n<0||n>=this.cfRules[i].length?71:0}checkEmptyRange(e){return e.ranges.length?0:24}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber(2,["Between","NotBetween"]),this.checkOperatorArgsNumber(1,["BeginsWith","ContainsText","EndsWith","GreaterThan","GreaterThanOrEqual","LessThan","LessThanOrEqual","NotContains"]),this.checkOperatorArgsNumber(0,["IsEmpty","IsNotEmpty"]));case"ColorScaleRule":return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case"IconSetRule":return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)))}return 0}checkOperatorArgsNumber(e,t){if(e>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");return i=>{if(t.includes(i.operator)){const t=[],o=e=>void 0===e||""===e;return e>=1&&o(i.values[0])&&t.push(51),e>=2&&o(i.values[1])&&t.push(52),t.length?t:0}return 0}}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return 53;case"max":return 55;case"mid":return 54;case"upperInflectionPoint":return 56;case"lowerInflectionPoint":return 57}return 0}checkFormulaCompilation(e,t){if("formula"!==e.type)return 0;try{rf(e.value||"")}catch(e){switch(t){case"min":return 58;case"max":return 60;case"mid":return 59;case"upperInflectionPoint":return 61;case"lowerInflectionPoint":return 62}}return 0}checkThresholds(e){return this.batchValidations((t=>e(t.minimum,"min")),(t=>e(t.maximum,"max")),(t=>t.midpoint?e(t.midpoint,"mid"):0))}checkInflectionPoints(e){return this.batchValidations((t=>e(t.lowerInflectionPoint,"lowerInflectionPoint")),(t=>e(t.upperInflectionPoint,"upperInflectionPoint")))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,i=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(i)?48:0}checkMinBiggerThanMax(e){const t=e.minimum.value,i=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&Av(t)>=Av(i)?47:0}checkMidBiggerThanMax(e){var t;const i=null===(t=e.midpoint)||void 0===t?void 0:t.value,o=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&Av(i)>=Av(o)?49:0}checkMinBiggerThanMid(e){var t;const i=e.minimum.value,o=null===(t=e.midpoint)||void 0===t?void 0:t.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&Av(i)>=Av(o)?50:0}removeConditionalFormatting(e,t){const i=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==i){const e=this.cfRules[t].slice();e.splice(i,1),this.history.update("cfRules",t,e)}}reorderConditionalFormatting(e,t,i){const o=this.cfRules[i].findIndex((t=>t.id===e)),n="up"===t?o-1:o+1;if(!(n<0||n>=this.cfRules[i].length)&&-1!==o&&-1!==n){const e=[...this.cfRules[i]],t=e[o];e[o]=e[n],e[n]=t,this.history.update("cfRules",i,e)}}}Mv.getters=["getConditionalFormats","getRulesSelection","getRulesByCell"];class Ov extends xv{constructor(){super(...arguments),this.figures={}}allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkFigureDuplicate(e.figure.id);case"UPDATE_FIGURE":case"DELETE_FIGURE":return this.checkFigureExists(e.sheetId,e.id);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":this.addFigure(e.figure,e.sheetId);break;case"UPDATE_FIGURE":const{type:t,sheetId:i,...o}=e,n=o;this.updateFigure(i,n);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId)}}updateFigure(e,t){if("id"in t)for(const[i,o]of Object.entries(t))switch(i){case"x":case"y":void 0!==o&&this.history.update("figures",e,t.id,i,Math.max(o,0));break;case"width":case"height":void 0!==o&&this.history.update("figures",e,t.id,i,o)}}addFigure(e,t){this.history.update("figures",t,e.id,e)}deleteSheet(e){this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){var i;return void 0===(null===(i=this.figures[e])||void 0===i?void 0:i[t])?70:0}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>null==t?void 0:t[e]))?82:0}getFigures(e){return Object.values(this.figures[e]||{}).filter(tt)}getFigure(e,t){var i;return null===(i=this.figures[e])||void 0===i?void 0:i[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>{var i;return void 0!==(null===(i=this.figures[t])||void 0===i?void 0:i[e])}))}import(e){for(let t of e.sheets){const e={};t.figures.forEach((t=>{e[t.id]=t})),this.figures[t.id]=e}}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const i=void 0;t.figures.push({...e,data:i})}}exportForExcel(e){this.export(e)}}Ov.getters=["getFigures","getFigure","getFigureSheetId"];class Nv{constructor(e){this.filters=[],this.zone=e;const t=new ki;this.id=t.uuidv4();for(const i of Be(e.left,e.right+1)){const e={...this.zone,left:i,right:i};this.filters.push(new _v(t.uuidv4(),e))}}get contentZone(){if(this.zone.bottom!==this.zone.top)return{...this.zone,top:this.zone.top+1}}getFilterId(e){var t;return null===(t=this.filters.find((t=>t.col===e)))||void 0===t?void 0:t.id}clone(){return new Nv(this.zone)}}class _v{constructor(e,t){if(t.left!==t.right)throw new Error("Can only define a filter on a single column");this.id=e,this.zoneWithHeaders=t}get col(){return this.zoneWithHeaders.left}get filteredZone(){const e=this.zoneWithHeaders;if(e.bottom!==e.top)return{...e,top:e.top+1}}}class Fv extends xv{constructor(){super(...arguments),this.tables={}}allowDispatch(e){switch(e.type){case"CREATE_FILTER_TABLE":if(!ao(...e.target))return 81;const t=Wi(...e.target),i=()=>this.getFilterTables(e.sheetId).some((e=>Zi(e.zone,t)))?78:0,o=()=>{const i=this.getters.getMergesInZone(e.sheetId,t);for(let e of i)if(Zi(t,e))return 80;return 0};return this.checkValidations(e,i,o);case"ADD_MERGE":for(let t of e.target)for(let i of this.getFilterTables(e.sheetId))if(Zi(i.zone,t))return 80}return 0}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break;case"DUPLICATE_SHEET":const i={};for(const t of Object.values(this.tables[e.sheetId]||{}))if(t){const e=Ne(t);i[e.id]=e}this.history.update("tables",e.sheetIdTo,i);break;case"ADD_COLUMNS_ROWS":this.onAddColumnsRows(e);break;case"REMOVE_COLUMNS_ROWS":this.onDeleteColumnsRows(e);break;case"CREATE_FILTER_TABLE":{const t=Wi(...e.target),i=this.createFilterTable(t);this.history.update("tables",e.sheetId,i.id,i);break}case"REMOVE_FILTER_TABLE":{const t={};for(const i of this.getFilterTables(e.sheetId))e.target.every((e=>!Gi(e,i.zone)))&&(t[i.id]=i);this.history.update("tables",e.sheetId,t);break}case"UPDATE_CELL":{const t=e.sheetId;for(let i of this.getFilterTables(t))this.canUpdateCellCmdExtendTable(e,i)&&this.extendTableDown(t,i);break}}}getFilters(e){return this.getFilterTables(e).map((e=>e.filters)).flat()}getFilterTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(tt):[]}getFilter(e){var t;return null===(t=this.getFilterTable(e))||void 0===t?void 0:t.filters.find((t=>t.col===e.col))}getFilterId(e){var t;return null===(t=this.getFilter(e))||void 0===t?void 0:t.id}getFilterTable({sheetId:e,col:t,row:i}){return this.getFilterTables(e).find((e=>ji(t,i,e.zone)))}getFilterTablesInZone(e,t){return this.getFilterTables(e).filter((e=>Xi(e.zone,t)))}doesZonesContainFilter(e,t){for(const i of t)for(const t of this.getFilterTables(e))if(Gi(i,t.zone))return!0;return!1}onAddColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const i=zi(t.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),o=[];for(const i of t.filters){const t=zi(i.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);o.push(new _v(i.id,t))}if(o.length<Qi(i).numberOfCols){for(let e=i.left;e<=i.right;e++)o.find((t=>t.col===e))||o.push(new _v(this.uuidGenerator.uuidv4(),{...i,left:e,right:e}));o.sort(((e,t)=>e.col-t.col))}this.history.update("tables",e.sheetId,t.id,"zone",i),this.history.update("tables",e.sheetId,t.id,"filters",o)}}onDeleteColumnsRows(e){for(const t of this.getFilterTables(e.sheetId)){const i=$i(t.zone,"COL"===e.dimension?"left":"top",e.elements);if(i){if(Vi(i)!==Vi(t.zone)){const o=[];for(const i of t.filters){const t=$i(i.zoneWithHeaders,"COL"===e.dimension?"left":"top",e.elements);t&&o.push(new _v(i.id,t))}this.history.update("tables",e.sheetId,t.id,"zone",i),this.history.update("tables",e.sheetId,t.id,"filters",o)}}else{const i={...this.tables[e.sheetId]};delete i[t.id],this.history.update("tables",e.sheetId,i)}}}createFilterTable(e){return new Nv(e)}extendTableDown(e,t){const i={...t.zone,bottom:t.zone.bottom+1};this.history.update("tables",e,t.id,"zone",i);for(let i=0;i<t.filters.length;i++){const o=t.filters[i],n={...o.zoneWithHeaders,bottom:o.zoneWithHeaders.bottom+1};this.history.update("tables",e,t.id,"filters",i,"zoneWithHeaders",n)}}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:i,row:o},n){var s;if(!e)return;const r=n.zone;if(!(r.bottom+1===o&&i>=r.left&&i<=r.right))return!1;for(const e of Be(r.left,r.right+1)){const i={sheetId:t,col:e,row:o};if(null===(s=this.getters.getCell(i))||void 0===s?void 0:s.content)return!1;if(this.getters.getFilter(i))return!1;if(this.getters.isInMerge(i))return!1}return!0}import(e){for(const t of e.sheets)for(const e of t.filterTables||[]){const i=this.createFilterTable(Pi(e.range));this.history.update("tables",t.id,i.id,i)}}export(e){for(const t of e.sheets)for(const e of this.getFilterTables(t.id))t.filterTables.push({range:Vi(e.zone)})}exportForExcel(e){this.export(e)}}Fv.getters=["doesZonesContainFilter","getFilter","getFilters","getFilterTable","getFilterTables","getFilterTablesInZone","getFilterId"];class Dv extends xv{constructor(){super(...arguments),this.sizes={}}handle(e){var t,i,o;switch(e.type){case"CREATE_SHEET":{const t=this.computeSheetSizes(e.sheetId),i={COL:t.COL.map((e=>({manualSize:void 0,computedSize:st(e)}))),ROW:t.ROW.map((e=>({manualSize:void 0,computedSize:st(e)})))};this.history.update("sizes",e.sheetId,i);break}case"DUPLICATE_SHEET":for(const t of this.sizes[e.sheetId].ROW)t.computedSize();for(const t of this.sizes[e.sheetId].COL)t.computedSize();this.history.update("sizes",e.sheetIdTo,Ne(this.sizes[e.sheetId]));break;case"DELETE_SHEET":const n={...this.sizes};delete n[e.sheetId],this.history.update("sizes",n);break;case"REMOVE_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];for(let i of[...e.elements].sort(((e,t)=>t-e)))t.splice(i,1);const i=Math.min(...e.elements);t=t.map(((t,o)=>"ROW"===e.dimension&&o>=i?{manualSize:t.manualSize,computedSize:st((()=>this.getRowTallestCellSize(e.sheetId,o)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];const i=at(e.position,e.base),o=t[e.base];t.splice(i,0,...Array(e.quantity).fill(o)),t=t.map(((t,i)=>"ROW"===e.dimension&&i>e.base+e.quantity?{manualSize:t.manualSize,computedSize:st((()=>this.getRowTallestCellSize(e.sheetId,i)))}:t)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"RESIZE_COLUMNS_ROWS":for(let t of e.elements)if("ROW"===e.dimension){const i=this.getRowTallestCellSize(e.sheetId,t);this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:st(i)})}else this.history.update("sizes",e.sheetId,e.dimension,t,{manualSize:e.size||void 0,computedSize:st(e.size||_)});break;case"UPDATE_CELL":if(!(null===(o=null===(i=null===(t=this.sizes[e.sheetId])||void 0===t?void 0:t.ROW)||void 0===i?void 0:i[e.row])||void 0===o?void 0:o.manualSize)){const{sheetId:t,row:i}=e;this.history.update("sizes",t,"ROW",i,"computedSize",st((()=>this.getRowTallestCellSize(t,i))))}break;case"ADD_MERGE":case"REMOVE_MERGE":for(let t of e.target)for(let i of Be(t.top,t.bottom+1)){const t=this.getRowTallestCellSize(e.sheetId,i);t!==this.getRowSize(e.sheetId,i)&&this.history.update("sizes",e.sheetId,"ROW",i,"computedSize",st(t))}}}getColSize(e,t){return this.getHeaderSize(e,"COL",t)}getRowSize(e,t){return this.getHeaderSize(e,"ROW",t)}getHeaderSize(e,t,i){var o,n,s,r;return Math.round((null===(n=null===(o=this.sizes[e])||void 0===o?void 0:o[t][i])||void 0===n?void 0:n.manualSize)||(null===(r=null===(s=this.sizes[e])||void 0===s?void 0:s[t][i])||void 0===r?void 0:r.computedSize())||this.getDefaultHeaderSize(t))}computeSheetSizes(e){var t,i;const o={COL:[],ROW:[]};for(let t of Be(0,this.getters.getNumberCols(e)))o.COL.push(this.getHeaderSize(e,"COL",t));for(let n of Be(0,this.getters.getNumberRows(e))){let s=null===(i=null===(t=this.sizes[e])||void 0===t?void 0:t.ROW)||void 0===i?void 0:i[n].manualSize;if(!s){s=this.getRowTallestCellSize(e,n)}o.ROW.push(s)}return o}getDefaultHeaderSize(e){return"COL"===e?_:F}getCellHeight(e){const t=this.getters.getMerge(e);if(t&&t.bottom!==t.top)return F;return function(e){return e&&e.content?ke(ze(e.style),e.isFormula?1:e.content.split(ce).length)+2*V:F}(this.getters.getCell(e))}getRowTallestCellSize(e,t){const i=this.getters.getRowCells(e,t);let o=0;for(let e=0;e<i.length;e++){const t=this.getters.getCellById(i[e]);if(!t)continue;const n=this.getters.getCellPosition(t.id),s=this.getCellHeight(n);s>o&&s>F&&(o=s)}return o<=F?F:o}import(e){for(let t of e.sheets){const e={COL:[],ROW:[]};for(let[i,o]of Object.entries(t.rows))o.size&&(e.ROW[i]=o.size);for(let[i,o]of Object.entries(t.cols))o.size&&(e.COL[i]=o.size);const i=this.computeSheetSizes(t.id);this.sizes[t.id]={COL:i.COL.map(((t,i)=>({manualSize:e.COL[i],computedSize:st(t)}))),ROW:i.ROW.map(((t,i)=>({manualSize:e.ROW[i],computedSize:st(t)})))}}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){var i,o;for(let n of e.sheets){void 0===n.rows&&(n.rows={});for(let e of Be(0,this.getters.getNumberRows(n.id)))(t||(null===(i=this.sizes[n.id].ROW[e])||void 0===i?void 0:i.manualSize))&&(n.rows[e]={...n.rows[e],size:this.getRowSize(n.id,e)});void 0===n.cols&&(n.cols={});for(let e of Be(0,this.getters.getNumberCols(n.id)))(t||(null===(o=this.sizes[n.id].COL[e])||void 0===o?void 0:o.manualSize))&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}}Dv.getters=["getRowSize","getColSize"];class kv extends xv{constructor(){super(...arguments),this.hiddenHeaders={}}allowDispatch(e){switch(e.type){case"HIDE_COLUMNS_ROWS":{if(!this.getters.tryGetSheet(e.sheetId))return 27;const t="COL"===e.dimension?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),i="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=i?66:Math.min(...e.elements)<0||Math.max(...e.elements)>i?86:0}case"REMOVE_COLUMNS_ROWS":return this.getters.tryGetSheet(e.sheetId)?this.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,Ne(this.hiddenHeaders[e.sheetId]));break;case"DELETE_SHEET":this.history.update("hiddenHeaders",e.sheetId,void 0);break;case"REMOVE_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let i of[...e.elements].sort(((e,t)=>t-e)))t.splice(i,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]],i=at(e.position,e.base);t.splice(i,0,...Array(e.quantity).fill(!1)),this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"HIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!0);break;case"UNHIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!1)}}canRemoveHeaders(e,t,i){const o=this.getAllVisibleHeaders(e,t);return n=i,!o.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=[[]],i=this.hiddenHeaders[e].COL;for(let e=0;e<i.length;e++){i[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getHiddenRowsGroups(e){const t=[[]],i=this.hiddenHeaders[e].ROW;for(let e=0;e<i.length;e++){i[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getAllVisibleHeaders(e,t){return Be(0,this.hiddenHeaders[e][t].length).filter((i=>!this.hiddenHeaders[e][t][i]))}import(e){var t,i;for(let o of e.sheets){this.hiddenHeaders[o.id]={COL:[],ROW:[]};for(let e=0;e<o.rowNumber;e++)this.hiddenHeaders[o.id].ROW[e]=Boolean(null===(t=o.rows[e])||void 0===t?void 0:t.isHidden);for(let e=0;e<o.colNumber;e++)this.hiddenHeaders[o.id].COL[e]=Boolean(null===(i=o.cols[e])||void 0===i?void 0:i.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let i of e.sheets){void 0===i.rows&&(i.rows={});for(let e=0;e<this.getters.getNumberRows(i.id);e++)(t||this.hiddenHeaders[i.id].ROW[e])&&(void 0===i.rows[e]&&(i.rows[e]={}),i.rows[e].isHidden=this.hiddenHeaders[i.id].ROW[e]);void 0===i.cols&&(i.cols={});for(let e=0;e<this.getters.getNumberCols(i.id);e++)(t||this.hiddenHeaders[i.id].COL[e])&&(void 0===i.cols[e]&&(i.cols[e]={}),i.cols[e].isHidden=this.hiddenHeaders[i.id].COL[e])}}}kv.getters=["canRemoveHeaders","getHiddenColsGroups","getHiddenRowsGroups","isRowHiddenByUser","isColHiddenByUser"];class Lv extends xv{constructor(e){super(e),this.images={},this.syncedImages=new Set,this.fileStore=e.external.fileStore}allowDispatch(e){return"CREATE_IMAGE"===e.type&&this.getters.getFigure(e.sheetId,e.figureId)?28:0}handle(e){switch(e.type){case"CREATE_IMAGE":this.addFigure(e.figureId,e.sheetId,e.position,e.size),this.history.update("images",e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const i of t)if("image"===i.tag){const t=i.id.split(J).pop(),o=`${e.sheetIdTo}${J}${t}`,n=this.getImage(i.id);if(n){const t={width:i.width,height:i.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:o,position:{x:i.x,y:i.y},size:t,definition:Ne(n)})}}break}case"DELETE_FIGURE":this.history.update("images",e.sheetId,e.id,void 0);break;case"DELETE_SHEET":this.history.update("images",e.sheetId,void 0)}}garbageCollectExternalResources(){var e;const t=new Set(this.getAllImages().map((e=>e.path)));for(const i of this.syncedImages)t.has(i)||null===(e=this.fileStore)||void 0===e||e.delete(i)}getImage(e){for(const t of Object.values(this.images))if(t&&t[e])return t[e];throw new Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,i,o){const n={id:e,x:i.x,y:i.y,width:o.width,height:o.height,tag:"image"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:n})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter((e=>"image"===e.tag));for(const i of e)this.history.update("images",t.id,i.id,i.data),this.syncedImages.add(i.data.path)}}export(e){var t;for(const i of e.sheets){const e=i.figures.filter((e=>"image"===e.tag));for(const o of e)o.data=null===(t=this.images[i.id])||void 0===t?void 0:t[o.id]}}exportForExcel(e){for(const t of e.sheets){const e=this.getters.getFigures(t.id),i=[];for(const t of e)if("image"===(null==t?void 0:t.tag)){const e=this.getImage(t.id);e&&i.push({...t,data:Ne(e)})}t.images=i}}getAllImages(){const e=[];for(const t in this.images)e.push(...Object.values(this.images[t]||{}).filter(tt));return e}}Lv.getters=["getImage","getImagePath","getImageSize"];class Pv extends xv{constructor(){super(...arguments),this.nextId=1,this.merges={},this.mergeCellMap={}}allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return 0}}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;for(const i of Object.values(t).filter(tt))this.addMerge(e.sheetIdTo,i.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(e.sheetId,t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){const i=t?[t]:Object.keys(this.merges);for(const t of i)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(tt)}getMerge({sheetId:e,col:t,row:i}){var o;const n=this.mergeCellMap[e],s=n?t in n&&(null===(o=n[t])||void 0===o?void 0:o[i]):void 0;return s?this.getMergeById(e,s):void 0}getMergesInZone(e,t){var i;const o=this.mergeCellMap[e];if(!o)return[];const n=new Set;for(const{col:e,row:s}of eo(t)){const t=null===(i=o[e])||void 0===i?void 0:i[s];t&&n.add(t)}return Array.from(n).map((t=>this.getMergeById(e,t))).filter(tt)}doesIntersectMerge(e,t){return eo(t).some((({col:t,row:i})=>void 0!==this.getMerge({sheetId:e,col:t,row:i})))}doesColumnsHaveCommonMerges(e,t,i){const o=this.getters.getSheet(e);for(let n=0;n<this.getters.getNumberRows(e);n++)if(this.isInSameMerge(o.id,t,n,i,n))return!0;return!1}doesRowsHaveCommonMerges(e,t,i){const o=this.getters.getSheet(e);for(let n=0;n<=this.getters.getNumberCols(e);n++)if(this.isInSameMerge(o.id,n,t,n,i))return!0;return!1}expandZone(e,t){let{left:i,right:o,top:n,bottom:s}=t,r={left:i,right:o,top:n,bottom:s};for(let t in this.merges[e]){const i=this.getMergeById(e,parseInt(t));i&&Zi(i,r)&&(r=Wi(i,r))}return qi(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,i,o,n){const s=this.getMerge({sheetId:e,col:t,row:i}),r=this.getMerge({sheetId:e,col:o,row:n});return!(!s||!r)&&qi(s,r)}isInMerge({sheetId:e,col:t,row:i}){var o;const n=this.mergeCellMap[e];return!!n&&(t in n&&Boolean(null===(o=n[t])||void 0===o?void 0:o[i]))}getMainCellPosition(e){if(!this.isInMerge(e))return e;const t=this.getMerge(e).topLeft;return{sheetId:e.sheetId,col:t.col,row:t.row}}getBottomLeftCell(e){if(!this.isInMerge(e))return e;const{bottom:t,left:i}=this.getMerge(e);return{sheetId:e.sheetId,col:i,row:t}}isMergeHidden(e,t){const i=this.getters.getHiddenColsGroups(e),o=this.getters.getHiddenRowsGroups(e);for(let e of i)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of o)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const i=this.getMerge({sheetId:e,col:t.left,row:t.top});if(i)return qi(t,i);const{numberOfCols:o,numberOfRows:n}=Qi(t);return 1===o&&1===n}isMergeDestructive(e,t){let{left:i,right:o,top:n,bottom:s}=t;o=De(o,0,this.getters.getNumberCols(e)-1),s=De(s,0,this.getters.getNumberRows(e)-1);for(let t=n;t<=s;t++)for(let s=i;s<=o;s++)if(s!==i||t!==n){const i=this.getters.getCell({sheetId:e,col:s,row:t});if(i&&""!==i.content)return!0}return!1}getMergeById(e,t){var i;const o=null===(i=this.merges[e])||void 0===i?void 0:i[t];return void 0!==o?Vv(t,o):void 0}checkDestructiveMerge({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;return t.some((t=>this.isMergeDestructive(e,t)))?3:0}checkOverlap({target:e}){for(const t of e)for(const i of e)if(t!==i&&Zi(t,i))return 65;return 0}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return 0;const{xSplit:i,ySplit:o}=this.getters.getPaneDivisions(e);for(const e of t)if(e.left<i&&e.right>=i||e.top<o&&e.bottom>=o)return 75;return 0}checkMergedContentUpdate(e){const{col:t,row:i,content:o}=e;if(void 0===o)return 0;const{col:n,row:s}=this.getMainCellPosition(e);return n===t&&s===i?0:4}checkMergeExists(e){const{sheetId:t,target:i}=e;for(const e of i){const{left:i,top:o}=e,n=this.getMerge({sheetId:t,col:i,row:o});if(void 0===n||!qi(e,n))return 5}return 0}addMerge(e,t){let{left:i,right:o,top:n,bottom:s}=t;o=De(o,0,this.getters.getNumberCols(e)-1),s=De(s,0,this.getters.getNumberRows(e)-1);if(Ht(i,n)===Ht(o,s))return;const r=this.getters.getCell({sheetId:e,col:i,row:n});let a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,Vi({left:i,top:n,right:o,bottom:s})));let l=new Set;for(let t=n;t<=s;t++)for(let s=i;s<=o;s++){s===i&&t===n||this.dispatch("UPDATE_CELL",{sheetId:e,col:s,row:t,style:r?r.style:null,content:""});const o=this.getMerge({sheetId:e,col:s,row:t});o&&l.add(o.id),this.history.update("mergeCellMap",e,s,t,a)}for(let t of l){const{top:i,bottom:o,left:n,right:s}=this.getMergeById(e,t);for(let t=i;t<=o;t++)for(let i=n;i<=s;i++){const o={sheetId:e,col:i,row:t},n=this.getMerge(o);n&&n.id===a||(this.history.update("mergeCellMap",e,i,t,void 0),this.dispatch("CLEAR_CELL",o))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:i,top:o,bottom:n,right:s}=t,r=this.getMerge({sheetId:e,col:i,row:o});if(void 0!==r&&qi(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=o;t<=n;t++)for(let o=i;o<=s;o++)this.history.update("mergeCellMap",e,o,t,void 0)}}applyRangeChangeOnSheet(e,t){const i=Object.entries(this.merges[e]||{});for(const[o,n]of i)if(n){const i=n.zone,s=t(n);switch(s.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,i);break;default:const{numberOfCols:t,numberOfRows:n}=Qi(s.range.zone);1===t&&1===n?this.removeMerge(e,i):this.history.update("merges",e,parseInt(o,10),s.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:i,row:o}of eo(t))this.history.update("mergeCellMap",e,i,o,t.id)}import(e){const t=e.sheets||[];for(let e of t)this.history.update("merges",e.id,{}),this.history.update("mergeCellMap",e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let i of t)this.addMerge(e,Pi(i))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...Uv(e))}}exportForExcel(e){this.export(e)}}function Uv(e){return Object.entries(e).map((([e,t])=>t?Vv(parseInt(e,10),t):void 0)).filter(tt).map((e=>Ht(e.left,e.top)+":"+Ht(e.right,e.bottom)))}function Vv(e,t){return{...t.zone,topLeft:{col:t.zone.left,row:t.zone.top},id:e}}Pv.getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","getBottomLeftCell","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge"];class zv{constructor(e){this.providers=[],this.getters=e}allowDispatch(e){return"MOVE_RANGES"===e.type?1===e.target.length?0:26:0}beforeHandle(e){}handle(e){switch(e.type){case"REMOVE_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",i="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";const n=[...e.elements];n.sort(((e,t)=>t-e));const s=He(n);this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};let r=n,a="NONE";for(let e of s){const s=Math.min(...e),l=Math.max(...e);if(n.zone[t]<=s&&s<=n.zone[i]){const e=Math.min(n.zone[i],l)-s+1;a="RESIZE",r=this.createAdaptedRange(r,o,a,-e)}else if(n.zone[t]>=s&&n.zone[i]<=l)a="REMOVE",r=n.clone({...this.getInvalidRange()});else if(n.zone[t]<=l&&n.zone[i]>=l){const e=l-n.zone[t]+1;a="RESIZE",r=this.createAdaptedRange(r,o,a,-e),r=this.createAdaptedRange(r,o,"MOVE",-(n.zone[t]-s))}else s<n.zone[t]&&(a="MOVE",r=this.createAdaptedRange(r,o,a,-(l-s+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",i="COL"===e.dimension?"right":"bottom",o="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((n=>{if(n.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(n.zone[t]<=e.base&&e.base<n.zone[i])return{changeType:"RESIZE",range:this.createAdaptedRange(n,o,"RESIZE",e.quantity)};if(e.base<n.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(n,o,"MOVE",e.quantity)}}else{if(n.zone[t]<e.base&&e.base<=n.zone[i])return{changeType:"RESIZE",range:this.createAdaptedRange(n,o,"RESIZE",e.quantity)};if(e.base<=n.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(n,o,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId!==e.sheetId)return{changeType:"NONE"};const i=this.getters.getSheetName(e.sheetId);return{changeType:"REMOVE",range:t=t.clone({...this.getInvalidRange(),invalidSheetName:i})}}),e.sheetId);break;case"RENAME_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.name&&t.invalidSheetName===e.name){const i=void 0,o=e.sheetId;return{changeType:"CHANGE",range:t.clone({sheetId:o,invalidSheetName:i})}}return{changeType:"NONE"}}));break;case"MOVE_RANGES":{const t=e.target[0];this.executeOnAllRanges((i=>{if(i.sheetId!==e.sheetId||!Xi(i.zone,t))return{changeType:"NONE"};const o=e.targetSheetId,n=e.col-t.left,s=e.row-t.top,r=this.createAdaptedRange(i,"both","MOVE",[n,s]),a=e.sheetId!==o||r.prefixSheet;return{changeType:"MOVE",range:r.clone({sheetId:o,prefixSheet:a})}}));break}}}finalize(){}verifyRangeRemoved(e){return t=>{const i=e(t);return"NONE"===i.changeType||Ui(i.range.zone)?i:{range:i.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,i,o){const n=to(e.unboundedZone,t,i,o);return e.clone({zone:n})}executeOnAllRanges(e,t){const i=this.verifyRangeRemoved(e);for(const e of this.providers)e(i,t)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,i,o){const n=e.map((e=>Oi.fromRange(e,this.getters)));return n.map((e=>{if(!Ui(e.zone))return e;const n=e.prefixSheet?e.sheetId:o,s={...e.unboundedZone,left:e.isFullRow&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:e.isFullRow?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.isFullCol&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:i),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:i)};return e.clone({sheetId:n,zone:s}).orderZone()}))}getRangeFromSheetXC(e,t){if(!Ft.test(t))return new Oi({sheetId:"",zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let i,o=t,n=!1;t.includes("!")&&(({xc:o,sheetName:i}=Ut(t)),i&&(n=!0));const s=Li(o),r=Oi.getRangeParts(o,s),a=i&&!this.getters.getSheetIdByName(i)?i:void 0,l=this.getters.getSheetIdByName(i)||e;return new Oi({prefixSheet:n,zone:s,sheetId:l,invalidSheetName:a,parts:r},this.getters.getSheetSize).orderZone()}getSelectionRangeString(e,t){const i=Oi.fromRange(e,this.getters),o=this.getters.expandZone(i.sheetId,i.zone),n=i.clone({zone:{...o,bottom:i.isFullCol?void 0:o.bottom,right:i.isFullRow?void 0:o.right}});return this.getRangeString(n,t)}getRangeString(e,t){if(!e)return Y;if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return Y;if(e.zone.left<0||e.zone.top<0)return Y;const i=Oi.fromRange(e,this.getters);let o=i.sheetId!==t||i.invalidSheetName||i.prefixSheet,n="";if(o&&(n=i.invalidSheetName?i.invalidSheetName:Fe(this.getters.getSheetName(i.sheetId))),o&&!n)return Y;let s=this.getRangePartString(i,0);return i.parts&&2===i.parts.length&&(i.zone.top!==i.zone.bottom||i.zone.left!==i.zone.right||i.parts[0].rowFixed||i.parts[0].colFixed||i.parts[1].rowFixed||i.parts[1].colFixed)&&(s+=":",s+=this.getRangePartString(i,1)),`${o?n+"!":""}${s}`}getRangeDataFromXc(e,t){return this.getters.getRangeFromSheetXC(e,t).rangeData}getRangeDataFromZone(e,t){return{_sheetId:e,_zone:t}}getRangeFromRangeData(e){const t={prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]};return new Oi(t,this.getters.getSheetSize)}getRangePartString(e,t){const i=e.parts&&e.parts[t].colFixed?"$":"",o=Vt(0===t?e.zone.left:e.zone.right),n=e.parts&&e.parts[t].rowFixed?"$":"",s=String(0===t?e.zone.top+1:e.zone.bottom+1);let r="";return r=e.isFullCol?0===t&&e.unboundedZone.hasHeader?i+o+n+s:i+o:e.isFullRow?0===t&&e.unboundedZone.hasHeader?i+o+n+s:n+s:i+o+n+s,r}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:Y}}}zv.getters=["getRangeString","getSelectionRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData"];class Bv extends xv{constructor(){super(...arguments),this.sheetIdsMapName={},this.orderedSheetIds=[],this.sheets={},this.cellPosition={}}allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZones)(e);if(0!==t)return t;switch(e.type){case"HIDE_SHEET":return 1===this.getVisibleSheetIds().length?9:0;case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"MOVE_SHEET":try{const t=this.orderedSheetIds.findIndex((t=>t===e.sheetId));return this.findIndexOfTargetSheet(t,e.delta),0}catch(e){return 14}case"RENAME_SHEET":return this.isRenameAllowed(e);case"DELETE_SHEET":return this.orderedSheetIds.length>1?0:9;case"ADD_COLUMNS_ROWS":const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return e.base<0||e.base>t?86:e.quantity<=0?87:0;case"REMOVE_COLUMNS_ROWS":{const t="COL"===e.dimension?this.getNumberCols(e.sheetId):this.getNumberRows(e.sheetId);return Math.min(...e.elements)<0||Math.max(...e.elements)>t?86:0}case"FREEZE_ROWS":return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case"FREEZE_COLUMNS":return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return 0}}handle(e){switch(e.type){case"SET_GRID_LINES_VISIBILITY":this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case"DELETE_CONTENT":this.clearZones(e.sheetId,e.target);break;case"CREATE_SHEET":const t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update("sheetIdsMapName",t.name,t.id);break;case"MOVE_SHEET":this.moveSheet(e.sheetId,e.delta);break;case"RENAME_SHEET":this.renameSheet(this.sheets[e.sheetId],e.name);break;case"HIDE_SHEET":this.hideSheet(e.sheetId);break;case"SHOW_SHEET":this.showSheet(e.sheetId);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case"UPDATE_CELL_POSITION":this.updateCellPosition(e);break;case"FREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,e.quantity,"COL");break;case"FREEZE_ROWS":this.setPaneDivisions(e.sheetId,e.quantity,"ROW");break;case"UNFREEZE_ROWS":this.setPaneDivisions(e.sheetId,0,"ROW");break;case"UNFREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,0,"COL");break;case"UNFREEZE_COLUMNS_ROWS":this.setPaneDivisions(e.sheetId,0,"COL"),this.setPaneDivisions(e.sheetId,0,"ROW")}}import(e){var t,i;for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let o of e.sheets){const e=o.name||n("Sheet")+(Object.keys(this.sheets).length+1),{colNumber:s,rowNumber:r}=this.getImportedSheetSize(o),a={id:o.id,name:e,numberOfCols:s,rows:Di(r),areGridLinesVisible:void 0===o.areGridLinesVisible||o.areGridLinesVisible,isVisible:o.isVisible,panes:{xSplit:(null===(t=o.panes)||void 0===t?void 0:t.xSplit)||0,ySplit:(null===(i=o.panes)||void 0===i?void 0:i.ySplit)||0}};this.orderedSheetIds.push(a.id),this.sheets[a.id]=a}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(tt).map((e=>{const t=this.sheets[e],i={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},conditionalFormats:[],figures:[],filterTables:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible};return(t.panes.xSplit||t.panes.ySplit)&&(i.panes=t.panes),i}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){var t;return null===(t=this.tryGetSheet(e))||void 0===t?void 0:t.name}getSheetIdByName(e){if(e){const t=_e(e);for(const e in this.sheetIdsMapName)if(e.toUpperCase()===t.toUpperCase())return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}getEvaluationSheets(){return this.sheets}doesHeaderExist(e,t,i){return"COL"===t?i>=0&&i<this.getNumberCols(e):i>=0&&i<this.getNumberRows(e)}getRow(e,t){const i=this.getSheet(e).rows[t];if(!i)throw new Error(`Row ${i} not found.`);return i}getCell({sheetId:e,col:t,row:i}){var o;const n=this.tryGetSheet(e),s=null===(o=null==n?void 0:n.rows[i])||void 0===o?void 0:o.cells[t];if(void 0!==s)return this.getters.getCellById(s)}getColsZone(e,t,i){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:i}}getRowCells(e,t){var i;return Object.values(null===(i=this.getSheet(e).rows[t])||void 0===i?void 0:i.cells).filter(tt)}getRowsZone(e,t,i){return{top:t,bottom:i,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){let t=1;const i=this.orderedSheetIds.map(this.getSheetName.bind(this));let o=`${e}${t}`;for(;i.includes(o);)o=`${e}${t}`,t++;return o}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,i){const o={...this.getPaneDivisions(e)};"COL"===i?o.xSplit=t:"ROW"===i&&(o.ySplit=t),this.history.update("sheets",e,"panes",o)}isEmpty(e,t){return eo(t).map((({col:t,row:i})=>this.getCell({sheetId:e,col:t,row:i}))).every((e=>!e||""===e.content))}updateCellPosition(e){const{sheetId:t,cellId:i,col:o,row:n}=e;i?this.setNewPosition(i,t,o,n):this.clearPosition(t,o,n)}setNewPosition(e,t,i,o){const n=this.cellPosition[e];n&&this.clearPosition(t,n.col,n.row),this.history.update("cellPosition",e,{row:o,col:i,sheetId:t}),this.history.update("sheets",t,"rows",o,"cells",i,e)}clearPosition(e,t,i){var o;const n=null===(o=this.sheets[e])||void 0===o?void 0:o.rows[i].cells[t];n&&(this.history.update("cellPosition",n,void 0),this.history.update("sheets",e,"rows",i,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}clearZones(e,t){for(let i of t)for(let t=i.left;t<=i.right;t++)for(let o=i.top;o<=i.bottom;o++){this.sheets[e].rows[o].cells[t]&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:o})}}createSheet(e,t,i,o,n){const s={id:e,name:t,numberOfCols:i,rows:Di(o),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},r=this.orderedSheetIds.slice();r.splice(n,0,s.id);const a=this.sheets;return this.history.update("orderedSheetIds",r),this.history.update("sheets",Object.assign({},a,{[s.id]:s})),s}moveSheet(e,t){const i=this.orderedSheetIds.slice(),o=i.findIndex((t=>t===e)),n=i.splice(o,1);let s=this.findIndexOfTargetSheet(o,t);i.splice(s,0,n[0]),this.history.update("orderedSheetIds",i)}findIndexOfTargetSheet(e,t){for(;0!=t&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(0===t)return e;throw new Error(s("There is not enough visible sheets"))}checkSheetName(e){const{orderedSheetIds:t,sheets:i}=this,o=e.name&&e.name.trim().toLowerCase();return t.find((e=>{var t;return(null===(t=i[e])||void 0===t?void 0:t.name.toLowerCase())===o}))?11:se.test(o)?13:0}checkSheetPosition(e){const{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?15:0}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?0:74}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?0:74}checkRowFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let i of t)if(i.top<e.quantity&&e.quantity<=i.bottom)return 65;return 0}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(let i of t)if(i.left<e.quantity&&e.quantity<=i.right)return 65;return 0}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):10}renameSheet(e,t){const i=e.name;this.history.update("sheets",e.id,"name",t.trim());const o=Object.assign({},this.sheetIdsMapName);o[t]=e.id,delete o[i],this.history.update("sheetIdsMapName",o)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t){const i=this.getSheet(e),o=this.getDuplicateSheetName(i.name),n=Ne(i);n.id=t,n.name=o;for(let e=0;e<=n.numberOfCols;e++)for(let t=0;t<=n.rows.length;t++)n.rows[t]&&(n.rows[t].cells[e]=void 0);const s=this.orderedSheetIds.slice(),r=s.indexOf(e);s.splice(r+1,0,n.id),this.history.update("orderedSheetIds",s),this.history.update("sheets",Object.assign({},this.sheets,{[n.id]:n}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:i}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:n.id,col:e,row:i,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIdsMapName);a[n.name]=n.id,this.history.update("sheetIdsMapName",a)}getDuplicateSheetName(e){let t=1;const i=this.orderedSheetIds.map(this.getSheetName.bind(this)),o=s("Copy of %s",e);let n=o.toString();for(;i.includes(n);)n=`${o} (${t})`,t++;return n}deleteSheet(e){const t=e.name,i=Object.assign({},this.sheets);delete i[e.id],this.history.update("sheets",i);const o=this.orderedSheetIds.slice(),n=o.indexOf(e.id);o.splice(n,1),this.history.update("orderedSheetIds",o);const s=Object.assign({},this.sheetIdsMapName);delete s[t],this.history.update("sheetIdsMapName",s)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(let i of t)this.moveCellOnColumnsDeletion(e,i);const i=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",i-t.length);const o=t.filter((t=>t<e.panes.xSplit)).length;o&&this.setPaneDivisions(e.id,e.panes.xSplit-o,"COL")}removeRows(e,t){t.sort(((e,t)=>t-e));for(let i of He(t))this.moveCellOnRowsDeletion(e,i[i.length-1],i[0]),i.map((t=>this.updateRowsStructureOnDeletion(t,e)));const i=t.filter((t=>t<e.panes.ySplit)).length;i&&this.setPaneDivisions(e.id,e.panes.ySplit-i,"ROW")}addColumns(e,t,i,o){const n="before"===i?t:t+1;this.moveCellsOnAddition(e,n,o,"columns");const s=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",s+o),n<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+o,"COL")}addRows(e,t,i,o){const n="before"===i?t:t+1;this.addEmptyRows(e,o),this.moveCellsOnAddition(e,n,o,"rows"),this.updateRowsStructureOnAddition(e,t,o),n<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+o,"ROW")}moveCellOnColumnsDeletion(e,t){for(let i=0;i<e.rows.length;i++){const o=e.rows[i];for(let n in o.cells){const s=Number(n),r=o.cells[n];r&&(s===t&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:s,row:i}),s>t&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r,col:s-1,row:i}))}}}moveCellsOnAddition(e,t,i,o){const n=[];for(let s=0;s<e.rows.length;s++){const r=e.rows[s];if("rows"!==o||s>=t)for(let a in r.cells){const l=Number(a),c=r.cells[a];c&&("rows"===o||l>=t)&&n.push({type:"UPDATE_CELL_POSITION",sheetId:e.id,cellId:c,col:l+("columns"===o?i:0),row:s+("rows"===o?i:0)})}}for(let e of n.reverse())this.dispatch(e.type,e)}moveCellOnRowsDeletion(e,t,i){const o=i-t+1;for(let n=0;n<e.rows.length;n++){const s=e.rows[n];if(n>=t&&n<=i)for(let t in s.cells){const i=Number(t);s.cells[t]&&this.dispatch("CLEAR_CELL",{sheetId:e.id,col:i,row:n})}if(n>i)for(let t in s.cells){const i=Number(t),r=s.cells[t];r&&this.dispatch("UPDATE_CELL_POSITION",{sheetId:e.id,cellId:r,col:i,row:n-o})}}}updateRowsStructureOnDeletion(e,t){const i=[],o=t.rows.map((e=>e.cells));for(let n in t.rows)Number(n)!==e&&i.push({cells:o.shift()});this.history.update("sheets",t.id,"rows",i)}updateRowsStructureOnAddition(e,t,i){const o=[],n=e.rows.map((e=>e.cells));e.rows.forEach((()=>o.push({cells:n.shift()}))),this.history.update("sheets",e.id,"rows",o)}addEmptyRows(e,t){const i=e.rows.slice();for(let e=0;e<t;e++)i.push({cells:{}});this.history.update("sheets",e.id,"rows",i)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(Bt);let i=e.rowNumber,o=e.colNumber;for(let{col:e,row:n}of t)i=Math.max(i,n+1),o=Math.max(o,e+1);return{rowNumber:i,colNumber:o}}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?27:"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?12:0}checkZones(e){const t=[];if("zone"in e&&t.push(e.zone),"target"in e&&Array.isArray(e.target)&&t.push(...e.target),"ranges"in e&&Array.isArray(e.ranges)&&t.push(...e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone))),!t.every(Ui))return 25;if(t.length&&"sheetId"in e){const i=this.getSheetZone(e.sheetId);return t.every((e=>Xi(e,i)))?0:18}return 0}}Bv.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 Hv extends yv{constructor({getters:e,stateObserver:t,dispatch:i,uiActions:o,selection:n}){super(t,i),this.getters=e,this.ui=o,this.selection=n}drawGrid(e,t){}}Hv.layers=[];class $v extends Hv{constructor(){super(...arguments),this.customColors=new Set,this.shouldUpdateColors=!1}handle(e){switch(e.type){case"UPDATE_CELL":case"UPDATE_CHART":case"CREATE_CHART":case"ADD_CONDITIONAL_FORMAT":this.shouldUpdateColors=!0}}finalize(){if(this.shouldUpdateColors){this.shouldUpdateColors=!1;for(const e of this.getCustomColors())this.tryToAddColor(e)}}getCustomColors(){let e=[];for(const t of this.getters.getSheetIds()){const i=Object.values(this.getters.getCells(t));e=e.concat(this.getColorsFromCells(i),this.getFormattingColors(t),this.getChartColors(t))}return function(e){const t=[{leadColor:wt(255,0,0),colors:[]},{leadColor:wt(255,128,0),colors:[]},{leadColor:wt(128,128,0),colors:[]},{leadColor:wt(128,255,0),colors:[]},{leadColor:wt(0,255,0),colors:[]},{leadColor:wt(0,255,128),colors:[]},{leadColor:wt(0,255,255),colors:[]},{leadColor:wt(0,127,255),colors:[]},{leadColor:wt(0,0,255),colors:[]},{leadColor:wt(127,0,255),colors:[]},{leadColor:wt(128,0,128),colors:[]},{leadColor:wt(255,0,128),colors:[]}];for(const i of e.map(It)){let e=500,o=0;t.forEach(((t,n)=>{const s=(r=i,a=t.leadColor,Math.sqrt(Math.pow(r.r-a.r,2)+Math.pow(r.g-a.g,2)+Math.pow(r.b-a.b,2)));var r,a;e>s&&(e=s,o=n)})),t[o].colors.push(i)}return t.map((e=>e.colors.sort(((e,t)=>Tt(e).s-Tt(t).s)))).flat().map(xt)}([...new Set([...new Set([...e,...this.customColors])].filter(Ct).map(St))]).filter((e=>!M.includes(e)))}getColorsFromCells(e){var t,i;const o=new Set;for(const n of e)(null===(t=n.style)||void 0===t?void 0:t.textColor)&&o.add(n.style.textColor),(null===(i=n.style)||void 0===i?void 0:i.fillColor)&&o.add(n.style.fillColor);return[...o]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),i=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(i.push(t.style.textColor),i.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(i.push(bt(t.minimum.color)),i.push(t.midpoint?bt(t.midpoint.color):void 0),i.push(bt(t.maximum.color)))}return i.filter(tt)}getChartColors(e){const t=this.getters.getChartIds(e).map((e=>this.getters.getChart(e)));let i=new Set;for(let e of t){if(void 0===e)continue;const t=e.getDefinition().background;switch(void 0!==t&&i.add(t),e.type){case"gauge":const t=e.sectionRule.colors;i.add(t.lowerColor),i.add(t.middleColor),i.add(t.upperColor);break;case"scorecard":const o=e;i.add(o.baselineColorDown),i.add(o.baselineColorUp)}}return[...i]}tryToAddColor(e){const t=St(e);e&&!M.includes(t)&&this.customColors.add(t)}}$v.getters=["getCustomColors"];const Wv=Gu.mapping;class Gv extends Hv{constructor(e){super(e),this.isUpToDate=!1,this.evaluatedCells={},this.evalContext=e.custom,this.lazyEvaluation=e.lazyEvaluation}handle(e){switch(sn.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 i=rf(e),o=this.getCompilationParameters((e=>this.getEvaluatedCell(this.getters.getCellPosition(e.id)))),n=[];for(let e of i.dependencies)n.push(this.getters.getRangeFromSheetXC(t,e));return i.execute(n,...o).value}getRangeFormattedValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.formattedValue))}getRangeValues(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.value))}getRangeFormats(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.format))}getEvaluatedCell({sheetId:e,col:t,row:i}){var o,n,s;return void 0===this.getters.getCell({sheetId:e,col:t,row:i})?fn(""):(null===(s=null===(n=null===(o=this.evaluatedCells[e])||void 0===o?void 0:o[t])||void 0===n?void 0:n[i])||void 0===s?void 0:s.call(n))||fn("")}getEvaluatedCells(e){const t=this.getters.getCells(e)||{},i={};for(let e of Object.keys(t)){const t=this.getters.getCellPosition(e);i[e]=this.getEvaluatedCell(t)}return i}getColEvaluatedCells(e,t){var i;return Object.values((null===(i=this.evaluatedCells[e])||void 0===i?void 0:i[t])||[]).filter(tt).map((e=>e()))}getEvaluatedCellsInZone(e,t){return eo(t).map((({col:t,row:i})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:i})))}setEvaluatedCell(e,t){const{col:i,row:o,sheetId:n}=this.getters.getCellPosition(e);this.evaluatedCells[n]||(this.evaluatedCells[n]={}),this.evaluatedCells[n][i]||(this.evaluatedCells[n][i]={}),this.evaluatedCells[n][i][o]=t,this.lazyEvaluation||this.evaluatedCells[n][i][o]()}*getAllCells(){for(const e of this.getters.getSheetIds()){const t=this.getters.getCells(e);for(const e in t)yield t[e]}}evaluate(){this.evaluatedCells={};const e=new Set,t=e=>{var t,n;const s=e.id,{col:r,row:a,sheetId:l}=this.getters.getCellPosition(s),c=null===(n=null===(t=this.evaluatedCells[l])||void 0===t?void 0:t[r])||void 0===n?void 0:n[a];return c||st((()=>{try{switch(e.isFormula){case!0:return o(e);case!1:return pn(e.content,e.format)}}catch(t){return i(t,e)}}))},i=(e,t)=>{e instanceof Error||(e=new Error(e));const i=(null==e?void 0:e.errorType)||a.GenericError,o=n[2].__lastFnCalled||"",s=new c(i,e.message.replace("[[FUNCTION_NAME]]",o),void 0!==e.logLevel?e.logLevel:l.error);return Cn(t.content,s)},o=t=>{const i=t.id;if(e.has(i))throw new d;n[2].__originCellXC=()=>{const e=n[2].getters.getCellPosition(i);return Ht(e.col,e.row)},e.add(i);const o=t.compiledFormula.execute(t.dependencies,...n);if(e.delete(i),Array.isArray(o.value))throw new Error(s("This formula depends on invalid values"));return fn(o.value,t.format||o.format)},n=this.getCompilationParameters((e=>t(e)()));for(const e of this.getAllCells())this.setEvaluatedCell(e.id,t(e))}getCompilationParameters(e){const t=Object.assign(Object.create(Wv),this.evalContext,{getters:this.getters}),i=this.getters;const o=t=>{const i=e(t);if(i.type===on.error)throw i.error;return i};return[function(e,t,n,r){if(t)return{value:Vi(e.zone)};if(!Ui(e.zone))throw new u;if(e.zone.bottom!==e.zone.top||e.zone.left!==e.zone.right)throw new Error(r?s("Function %s expects the parameter %s to be a single value or a single cell reference, not a range.",n.toString(),r.toString()):s("Function %s expects its parameters to be single values or single cell references, not ranges.",n.toString()));if(e.invalidSheetName)throw new Error(s("Invalid sheet name: %s",e.invalidSheetName));return function(e){let t;if(!i.tryGetSheet(e.sheetId))throw new Error(s("Invalid sheet name"));return t=i.getCell({sheetId:e.sheetId,col:e.zone.left,row:e.zone.top}),t&&""!==t.content?o(t):{value:null,format:null==t?void 0:t.format}}(e)},function(e){const n=e.sheetId;if(!Ui(e.zone))throw new u;const s=i.getSheetZone(n),r=[],a=Gi(e.zone,s);if(!a)return r.push([]),r;for(let i=a.left;i<=a.right;i++){const n=[];for(let s=a.top;s<=a.bottom;s++){const r=t.getters.getCell({sheetId:e.sheetId,col:i,row:s});n.push(r?o(r):void 0)}r.push(n)}return r},t]}exportForExcel(e){for(let t of e.sheets)for(const e in t.cells){const i={sheetId:t.id,...Bt(e)},o=this.getters.getCell(i);if(o){const n=t.cells[e],s=this.getEvaluatedCell(i);n.value=s.value,n.isFormula=o.isFormula&&!this.isBadExpression(o.content),o.format!==s.format&&(n.computedFormat=s.format)}}}isBadExpression(e){try{return rf(e),!1}catch(e){return!0}}}Gv.getters=["evaluateFormula","getRangeFormattedValues","getRangeValues","getRangeFormats","getEvaluatedCell","getEvaluatedCells","getColEvaluatedCells","getEvaluatedCellsInZone"];class qv extends Hv{constructor(){super(...arguments),this.charts={},this.createRuntimeChart=function(e){const t=sr.getAll().sort(((e,t)=>e.sequence-t.sequence));return function(i){const o=t.find((e=>e.match(i.type)));if(!o)throw new Error("No runtime builder for this chart.");return o.getChartRuntime(i,e)}}(this.getters)}handle(e){if(sn.has(e.type)||rn.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 i=t.zone.left,o=t.zone.top,n=t.sheetId;return this.getters.getCellComputedStyle({sheetId:n,col:i,row:o}).fillColor||w}}qv.getters=["getChartRuntime","getBackgroundOfSingleCellChart"];class Zv extends Hv{constructor(){super(...arguments),this.isStale=!0,this.computedStyles={},this.computedIcons={},this.rulePredicate={CellIsRule:(e,t)=>{if(e.type===on.error)return!1;const i=t.values.map(mn);switch(t.operator){case"IsEmpty":return""===e.value.toString().trim();case"IsNotEmpty":return""!==e.value.toString().trim();case"BeginsWith":return""!==i[0]&&e.value.toString().startsWith(i[0].toString());case"EndsWith":return""!==i[0]&&e.value.toString().endsWith(i[0].toString());case"Between":return e.value>=i[0]&&e.value<=i[1];case"NotBetween":return!(e.value>=i[0]&&e.value<=i[1]);case"ContainsText":return e.value.toString().indexOf(i[0].toString())>-1;case"NotContains":return!e.value||-1==e.value.toString().indexOf(i[0].toString());case"GreaterThan":return e.value>i[0];case"GreaterThanOrEqual":return e.value>=i[0];case"LessThan":return e.value<i[0];case"LessThanOrEqual":return e.value<=i[0];case"NotEqual":return""!==i[0]&&e.value!==i[0];case"Equal":return""===i[0]||e.value===i[0];default:console.warn(s("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}}}handle(e){switch((rn.has(e.type)||"UPDATE_CELL"===e.type&&"content"in e)&&(this.isStale=!0),e.type){case"ACTIVATE_SHEET":const t=e.sheetIdTo;this.computedStyles[t]=this.computedStyles[t]||{},this.computedIcons[t]=this.computedIcons[t]||{},this.isStale=!0;break;case"AUTOFILL_CELL":const i=this.getters.getActiveSheetId(),o=this.getters.getRulesByCell(i,e.originCol,e.originRow);for(const t of o)this.adaptRules(i,t,[Ht(e.col,e.row)],[]);break;case"PASTE_CONDITIONAL_FORMAT":this.pasteCf(e.origin,e.target,e.operation)}}finalize(){this.isStale&&(this.computeStyles(),this.isStale=!1)}getCellComputedStyle(e){var t;const{sheetId:i,col:o,row:n}=e,s=this.getters.getCell(e),r=this.computedStyles[i],a=r&&(null===(t=r[o])||void 0===t?void 0:t[n]),l={...null==s?void 0:s.style,...a};return this.getters.getEvaluatedCell(e).link&&!l.textColor&&(l.textColor=x),this.getters.isFilterHeader(e)&&(l.bold=!0),l}getConditionalIcon({col:e,row:t}){var i;const o=this.getters.getActiveSheetId(),n=this.computedIcons[o];return n&&(null===(i=n[e])||void 0===i?void 0:i[t])}computeStyles(){var e;const t=this.getters.getActiveSheetId();this.computedStyles[t]={},this.computedIcons[t]={};const i=this.computedStyles[t];for(let o of this.getters.getConditionalFormats(t).reverse())try{switch(o.rule.type){case"ColorScaleRule":for(let e of o.ranges)this.applyColorScale(e,o.rule);break;case"IconSetRule":for(let e of o.ranges)this.applyIcon(e,o.rule);break;default:for(let n of o.ranges){const s=this.getters.getRangeFromSheetXC(t,n).zone;for(let n=s.top;n<=s.bottom;n++)for(let r=s.left;r<=s.right;r++){const s=this.rulePredicate[o.rule.type];let a=this.getters.getEvaluatedCell({sheetId:t,col:r,row:n});s&&s(a,o.rule)&&(i[r]||(i[r]=[]),i[r][n]=Object.assign((null===(e=i[r])||void 0===e?void 0:e[n])||{},o.rule.style))}}}}catch(e){}}parsePoint(e,t,i){const o=this.getters.getActiveSheetId(),n=this.getters.getEvaluatedCellsInZone(o,this.getters.getRangeFromSheetXC(o,e).zone).filter((e=>e.type===on.number)).map((e=>e.value));switch(t.type){case"value":return"max"===i?Math.max(...n):Math.min(...n);case"number":return Number(t.value);case"percentage":const e=Math.min(...n);return e+(Math.max(...n)-e)*Number(t.value)/100;case"percentile":return ii(n,Number(t.value)/100,!0);case"formula":const o=t.value&&this.getters.evaluateFormula(t.value);return o instanceof Promise?null:o;default:return null}}applyIcon(e,t){const i=this.parsePoint(e,t.lowerInflectionPoint),o=this.parsePoint(e,t.upperInflectionPoint);if(null===i||null===o||i>o)return;const n=this.getters.getActiveSheetId(),s=this.getters.getRangeFromSheetXC(n,e).zone,r=this.computedIcons[n],a=[t.icons.upper,t.icons.middle,t.icons.lower];for(let e=s.top;e<=s.bottom;e++)for(let l=s.left;l<=s.right;l++){const s=this.getters.getEvaluatedCell({sheetId:n,col:l,row:e});if(s.type!==on.number)continue;const c=this.computeIcon(s.value,o,t.upperInflectionPoint.operator,i,t.lowerInflectionPoint.operator,a);r[l]||(r[l]=[]),r[l][e]=c}}computeIcon(e,t,i,o,n,s){return"ge"===i&&e>=t||"gt"===i&&e>t?s[0]:"ge"===n&&e>=o||"gt"===n&&e>o?s[1]:s[2]}applyColorScale(e,t){var i;const o=this.parsePoint(e,t.minimum,"min"),n=t.midpoint?this.parsePoint(e,t.midpoint):null,s=this.parsePoint(e,t.maximum,"max");if(null===o||null===s||o>=s||n&&(o>=n||n>=s))return;const r=this.getters.getActiveSheetId(),a=this.getters.getRangeFromSheetXC(r,e).zone,l=this.computedStyles[r],c=[];t.midpoint&&n?(c.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,n,t.minimum.color,t.midpoint.color)}),c.push({minValue:n,minColor:t.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(n,s,t.midpoint.color,t.maximum.color)})):c.push({minValue:o,minColor:t.minimum.color,colorDiffUnit:this.computeColorDiffUnits(o,s,t.minimum.color,t.maximum.color)});for(let e=a.top;e<=a.bottom;e++)for(let t=a.left;t<=a.right;t++){const a=this.getters.getEvaluatedCell({sheetId:r,col:t,row:e});if(a.type===on.number){const r=De(a.value,o,s);let h;h=2===c.length&&n?r<=n?this.colorCell(r,c[0].minValue,c[0].minColor,c[0].colorDiffUnit):this.colorCell(r,c[1].minValue,c[1].minColor,c[1].colorDiffUnit):this.colorCell(r,c[0].minValue,c[0].minColor,c[0].colorDiffUnit),l[t]||(l[t]=[]),l[t][e]=(null===(i=l[t])||void 0===i?void 0:i[e])||{},l[t][e].fillColor=bt(h)}}}computeColorDiffUnits(e,t,i,o){const n=t-e;return[((i>>16)%256-(o>>16)%256)/n,((i>>8)%256-(o>>8)%256)/n,(i%256-o%256)/n]}colorCell(e,t,i,o){const[n,s,r]=o;return Math.round((i>>16)%256-n*(e-t))<<16|Math.round((i>>8)%256-s*(e-t))<<8|Math.round(i%256-r*(e-t))}adaptRules(e,t,i,o){if(0===i.length&&0===o.length)return;const n=this.getters.getConditionalFormats(e),s=n.findIndex((e=>e.id===t.id));let r=[];s>-1&&(r=n[s].ranges),r=r.concat(i);const a=Yi(r,o);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,i){const o=Ht(t.col,t.row);for(let n of this.getters.getConditionalFormats(e.sheetId))for(let s of n.ranges)if(ji(e.col,e.row,this.getters.getRangeFromSheetXC(e.sheetId,s).zone)){const s=n,r=[];"CUT"===i&&r.push(Ht(e.col,e.row)),e.sheetId===t.sheetId?this.adaptRules(e.sheetId,s,[o],r):(this.adaptRules(t.sheetId,s,[o],[]),this.adaptRules(e.sheetId,s,[],r))}}}Zv.getters=["getConditionalIcon","getCellComputedStyle"];class jv extends Hv{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 i of this.getters.getFilters(e.sheetIdTo)){const o=i.zoneWithHeaders;t[i.id]=this.getFilterValues({sheetId:e.sheetId,col:o.left,row:o.top})}this.filterValues[e.sheetIdTo]=t}}finalize(){this.isEvaluationDirty&&(this.updateHiddenRows(),this.isEvaluationDirty=!1)}isRowFiltered(e,t){return e===this.getters.getActiveSheetId()&&this.hiddenRows.has(t)}getCellBorderWithFilterBorder(e){const{sheetId:t,col:i,row:o}=e;let n;for(let e of this.getters.getFilterTables(t)){const s=e.zone;if(ji(i,o,s)){const e=this.intersectZoneWithViewport(t,s);n={top:o===e.top?j:void 0,bottom:o===e.bottom?j:void 0,left:i===e.left?j:void 0,right:i===e.right?j:void 0}}}const s=this.getters.getCellBorder(e),r={...n,...ct(s||{})};return it(r)?null:r}getFilterHeaders(e){const t=[];for(let i of this.getters.getFilterTables(e)){const o=i.zone;if(!o)continue;const n=o.top;for(let i=o.left;i<=o.right;i++)this.getters.isColHidden(e,i)||this.getters.isRowHidden(e,n)||t.push({col:i,row:n})}return t}getFilterValues(e){const t=this.getters.getFilterId(e),i=e.sheetId;return t&&this.filterValues[i]&&this.filterValues[i][t]||[]}isFilterHeader({sheetId:e,col:t,row:i}){return this.getFilterHeaders(e).some((e=>e.col===t&&e.row===i))}isFilterActive(e){var t,i;const o=this.getters.getFilterId(e),n=e.sheetId;return Boolean(o&&(null===(i=null===(t=this.filterValues[n])||void 0===t?void 0:t[o])||void 0===i?void 0:i.length))}intersectZoneWithViewport(e,t){return{left:this.getters.findVisibleHeader(e,"COL",t.left,t.right),right:this.getters.findVisibleHeader(e,"COL",t.right,t.left),top:this.getters.findVisibleHeader(e,"ROW",t.top,t.bottom),bottom:this.getters.findVisibleHeader(e,"ROW",t.bottom,t.top)}}updateFilter({col:e,row:t,values:i,sheetId:o}){const n=this.getters.getFilterId({sheetId:o,col:e,row:t});n&&(this.filterValues[o]||(this.filterValues[o]={}),this.filterValues[o][n]=i)}updateHiddenRows(){var e,t;const i=this.getters.getActiveSheetId(),o=this.getters.getFilters(i).sort(((e,t)=>e.zoneWithHeaders.top-t.zoneWithHeaders.top)),n=new Set;for(let s of o){if(this.getters.isRowHiddenByUser(i,s.zoneWithHeaders.top))continue;if(n.has(s.zoneWithHeaders.top))continue;const o=null===(t=null===(e=this.filterValues[i])||void 0===e?void 0:e[s.id])||void 0===t?void 0:t.map(ht);if(o&&s.filteredZone)for(let e=s.filteredZone.top;e<=s.filteredZone.bottom;e++){const t=this.getCellValueAsString(i,s.col,e);o.includes(t)&&n.add(e)}}this.hiddenRows=n}getCellValueAsString(e,t,i){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:i}).formattedValue.toLowerCase()}exportForExcel(e){for(const t of e.sheets){const e=t.id;for(const i of t.filterTables){const o=Pi(i.range),n=[],s=[];for(const i of Be(0,Qi(o).numberOfCols)){const r={sheetId:t.id,col:o.left+i,row:o.top},a=this.getFilterValues(r),l=this.getters.getFilter(r);if(!l)continue;const c=l.filteredZone?eo(l.filteredZone).map((t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue)):[];if(a.length){const e=c.filter((e=>e)).filter((e=>!a.includes(e)));n.push({colId:i,displayedValues:[...new Set(e)],displayBlanks:!a.includes("")&&c.some((e=>!e))})}const h={col:l.col,row:l.zoneWithHeaders.top,sheetId:e},d=this.getters.getEvaluatedCell(h).formattedValue,u=this.getUniqueColNameForExcel(i,d,s);s.push(u),t.cells[Ht(h.col,h.row)]={...t.cells[Ht(h.col,h.row)],content:u,value:u,isFormula:!1}}i.filters=n}}}getUniqueColNameForExcel(e,t,i){t||(t=`Column${e}`);let o=t,n=2;for(;i.includes(o);)o=t+String(n),n++;return o}}jv.getters=["getCellBorderWithFilterBorder","getFilterHeaders","getFilterValues","isFilterHeader","isRowFiltered","isFilterActive"];class Xv{constructor(e,t,i,o,n,s){this.getters=e,this.sheetId=t,this.boundaries=i,this.viewportWidth=o.width,this.viewportHeight=o.height,this.offsetScrollbarX=s.x,this.offsetScrollbarY=s.y,this.canScrollVertically=n.canScrollVertically,this.canScrollHorizontally=n.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){const e=this.getters.findLastVisibleColRowIndex(this.sheetId,"COL",{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,"ROW",{first:this.boundaries.top,last:this.boundaries.bottom}),{end:i,size:o}=this.getters.getColDimensions(this.sheetId,e),{end:n,size:s}=this.getters.getRowDimensions(this.sheetId,t),r=this.searchHeaderIndex("COL",i-this.viewportWidth,0),a=this.getters.getColSize(this.sheetId,r),l=this.searchHeaderIndex("ROW",n-this.viewportHeight,0),c=this.getters.getRowSize(this.sheetId,l);let h=i-this.offsetCorrectionX;this.canScrollHorizontally&&(h+=Math.max(_,Math.min(a,this.viewportWidth-o)),h=Math.max(h,this.viewportWidth));let d=n-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(F+5,Math.min(c,this.viewportHeight-s)),d=Math.max(d,this.viewportHeight)),{width:h,height:d}}getColIndex(e,t=!1){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex("COL",e-this.offsetCorrectionX,this.left,t)}getRowIndex(e,t=!1){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex("ROW",e-this.offsetCorrectionY,this.top,t)}adjustPosition(e){const t=this.sheetId;e||(e=this.getters.getSheetPosition(t));const i=this.getters.getMainCellPosition({sheetId:t,...e}),{col:o,row:n}=this.getters.getNextVisibleCellPosition(i);ji(o,this.boundaries.top,this.boundaries)&&this.adjustPositionX(o),ji(this.boundaries.left,n,this.boundaries)&&this.adjustPositionY(n)}adjustPositionX(e){const t=this.sheetId,{end:i}=this.getters.getColDimensions(t,e),o=this.getters.getNumberCols(t);if(this.offsetX+this.offsetCorrectionX+this.viewportWidth<i)for(let e=this.left;this.offsetX+this.offsetCorrectionX+this.viewportWidth<i&&!(e>o);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 i=this.left;i>=e&&!(i<0);i--)this.getters.isColHidden(t,i)||(this.offsetX=this.getters.getColDimensions(t,i).start-this.offsetCorrectionX,this.offsetScrollbarX=this.offsetX,this.adjustViewportZoneX())}adjustPositionY(e){const t=this.sheetId,{end:i}=this.getters.getRowDimensions(t,e),o=this.getters.getNumberRows(t);if(this.offsetY+this.viewportHeight+this.offsetCorrectionY<i)for(let e=this.top;this.offsetY+this.viewportHeight+this.offsetCorrectionY<i&&!(e>o);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 i=this.top;i>=e&&!(i<0);i--)this.getters.isRowHidden(t,i)||(this.offsetY=this.getters.getRowDimensions(t,i).start-this.offsetCorrectionY,this.offsetScrollbarY=this.offsetY,this.adjustViewportZoneY())}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getRect(e){const t=Gi(e,this.zone);if(t){return{x:this.getters.getColRowOffset("COL",this.zone.left,t.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset("ROW",this.zone.top,t.top)+this.offsetCorrectionY,width:Math.min(this.getters.getColRowOffset("COL",t.left,t.right+1),this.viewportWidth),height:Math.min(this.getters.getColRowOffset("ROW",t.top,t.bottom+1),this.viewportHeight)}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,i=0,o=!1){let n=0;const s=this.sheetId,r=this.getters.getNumberHeaders(s,e);for(let a=i;a<=r-1;a++){const i=o||"COL"!==e?a<this.top&&a>this.bottom:a<this.left&&a>this.right;if(!this.getters.isHeaderHidden(s,e,a)&&!i&&(n+="COL"===e?this.getters.getColSize(s,a):this.getters.getRowSize(s,a),n>t))return a}return-1}get zone(){return{left:this.left,right:this.right,top:this.top,bottom:this.bottom}}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetScrollbarX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetScrollbarY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){const{width:e}=this.getMaxSize();this.viewportWidth+this.offsetScrollbarX>e&&(this.offsetScrollbarX=Math.max(0,e-this.viewportWidth))}this.left=this.getColIndex(this.offsetScrollbarX,!0),this.right=this.getColIndex(this.offsetScrollbarX+this.viewportWidth,!0),-1===this.right&&(this.right=this.boundaries.right),this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){const{height:e}=this.getMaxSize();this.viewportHeight+this.offsetScrollbarY>e&&(this.offsetScrollbarY=Math.max(0,e-this.viewportHeight))}this.top=this.getRowIndex(this.offsetScrollbarY,!0),this.bottom=this.getRowIndex(this.offsetScrollbarY+this.viewportWidth,!0),-1===this.bottom&&(this.bottom=this.boundaries.bottom),this.adjustViewportZoneY()}adjustViewportZoneX(){const e=this.sheetId;this.left=this.searchHeaderIndex("COL",this.offsetScrollbarX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex("COL",this.viewportWidth,this.left)),-1===this.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 Yv extends Hv{constructor(){super(...arguments),this.viewports={},this.sheetViewWidth=1e3,this.sheetViewHeight=1e3,this.gridOffsetX=0,this.gridOffsetY=0,this.sheetsWithDirtyViewports=new Set}allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.checkScrollingDirection(e);case"RESIZE_SHEETVIEW":return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return 0}}handleEvent(e){switch(e.type){case"HeadersSelected":case"AlterZone":break;case"ZonesSelected":let{col:t,row:i}=io(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const o=e.previousAnchor.zone,n=e.anchor.zone,{top:s,bottom:r,left:a,right:l}=this.getters.getActiveMainViewport();o.left===n.left&&o.right===n.right&&(t=a>t||t>l?a:t),o.top===n.top&&o.bottom===n.bottom&&(i=s>i||i>r?s:i)}const o=this.getters.getActiveSheetId();t=Math.min(t,this.getters.getNumberCols(o)-1),i=Math.min(i,this.getters.getNumberRows(o)-1),this.refreshViewport(this.getters.getActiveSheetId(),{col:t,row:i})}}handle(e){var t;switch(this.cleanViewports(),e.type){case"START":this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case"UNDO":case"REDO":this.resetSheetViews();break;case"RESIZE_SHEETVIEW":this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case"SET_VIEWPORT_OFFSET":this.setSheetViewOffset(e.offsetX,e.offsetY);break;case"SHIFT_VIEWPORT_DOWN":const{top:i}=this.getActiveMainViewport(),o=this.getters.getActiveSheetId(),n=this.clipOffsetY(this.getters.getRowDimensions(o,i).start+this.sheetViewHeight);this.shiftVertically(n);break;case"SHIFT_VIEWPORT_UP":{const{top:e}=this.getActiveMainViewport(),t=this.getters.getActiveSheetId(),i=this.clipOffsetY(this.getters.getRowDimensions(t,e).end-this.sheetViewHeight);this.shiftVertically(i);break}case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"UPDATE_FILTER":this.resetViewports(e.sheetId);break;case"UPDATE_CELL":("content"in e||"format"in e||void 0!==(null===(t=e.style)||void 0===t?void 0:t.fontSize))&&this.sheetsWithDirtyViewports.add(e.sheetId);break;case"ACTIVATE_SHEET":this.setViewports(),this.refreshViewport(e.sheetIdTo);break;case"UNFREEZE_ROWS":case"UNFREEZE_COLUMNS":case"FREEZE_COLUMNS":case"FREEZE_ROWS":case"UNFREEZE_COLUMNS_ROWS":this.resetViewports(this.getters.getActiveSheetId());break;case"DELETE_SHEET":this.sheetsWithDirtyViewports.delete(e.sheetId);break;case"START_EDITION":const{col:s,row:r}=this.getters.getActivePosition();this.refreshViewport(this.getters.getActiveSheetId(),{col:s,row:r})}}finalize(){for(const e of this.sheetsWithDirtyViewports)this.resetViewports(e);this.sheetsWithDirtyViewports=new Set,this.setViewports()}setViewports(){var e;const t=this.getters.getSheetIds();for(const i of t)(null===(e=this.viewports[i])||void 0===e?void 0:e.bottomRight)||this.resetViewports(i)}getColIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getColIndex(e))))}getRowIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getRowIndex(e))))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getActiveMainViewport(){const e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getActiveSheetDOMScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetScrollbarX,scrollY:t.offsetScrollbarY}}getSheetViewVisibleCols(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>Be(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=>Be(e.top,e.bottom+1))).flat())].filter((t=>!this.getters.isHeaderHidden(e,"ROW",t)))}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:i,ySplit:o}=this.getters.getPaneDivisions(e);let{width:n,height:s}=t.getMaxSize();return{x:this.getters.getColDimensions(e,i).start,y:this.getters.getRowDimensions(e,o).start,width:n,height:s}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:i}=this.getMainViewportRect(),o=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-o.viewportWidth+1),maxOffsetY:Math.max(0,i-o.viewportHeight+1)}}getColRowOffsetInViewport(e,t,i){const o=this.getters.getActiveSheetId(),n=this.getters.getSheetViewVisibleCols(),s=this.getters.getSheetViewVisibleRows();if(i<t)return-this.getColRowOffsetInViewport(e,i,t);let r=0;const a="COL"===e?n:s;for(let n=t;n<i;n++)a.includes(n)&&(r+="COL"===e?this.getters.getColSize(o,n):this.getters.getRowSize(o,n));return r}isVisibleInViewport({sheetId:e,col:t,row:i}){return this.getSubViewports(e).some((e=>e.isVisible(t,i)))}getEdgeScrollCol(e,t,i){let o=!1,n=0,s=0;const{xSplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(o=!0,s=qt(e-a),n=1):e<l&&i>=l&&c>0?(o=!0,s=qt(l-e),n=-1):r&&t<l&&e>l&&(o=!0,s=qt(e),n="reset"),{canEdgeScroll:o,direction:n,delay:s}}getEdgeScrollRow(e,t,i){let o=!1,n=0,s=0;const{ySplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(o=!0,s=qt(e-a),n=1):e<l&&i>=l&&c>0?(o=!0,s=qt(l-e),n=-1):r&&t<l&&e>l&&(o=!0,s=qt(e),n="reset"),{canEdgeScroll:o,direction:n,delay:s}}getVisibleRect(e){const t=this.getters.getActiveSheetId(),i=this.getSubViewports(t).map((t=>t.getRect(e))).filter(tt);if(0===i.length)return{x:0,y:0,width:0,height:0};const o=Math.min(...i.map((e=>e.x))),n=Math.min(...i.map((e=>e.y))),s=Math.max(...i.map((e=>e.x+e.width)))-o,r=Math.max(...i.map((e=>e.y+e.height)))-n;return{x:o+this.gridOffsetX,y:n+this.gridOffsetY,width:s,height:r}}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,i).start}}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(tt)}checkPositiveDimension(e){return e.width<0||e.height<0?68:0}checkValuesAreDifferent(e){const{height:t,width:i}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===i&&e.height===t?76:0}checkScrollingDirection({offsetX:e,offsetY:t}){const i=this.getMainInternalViewport(this.getters.getActiveSheetId());return!i.canScrollHorizontally&&e>0||!i.canScrollVertically&&t>0?69:0}getMainViewport(e){const t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){const e=this.getters.getSheetIds();for(let t of Object.keys(this.viewports))e.includes(t)||delete this.viewports[t]}resetSheetViews(){for(let e of Object.keys(this.viewports)){const t=this.getters.getSheetPosition(e);this.resetViewports(e);const i=this.getSubViewports(e);Object.values(i).forEach((e=>{e.adjustPosition(t)}))}}resizeSheetView(e,t,i=0,o=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=i,this.gridOffsetY=o,this.recomputeViewports()}recomputeViewports(){for(let e of Object.keys(this.viewports))this.resetViewports(e)}setSheetViewOffset(e,t){const i=this.getters.getActiveSheetId(),{maxOffsetX:o,maxOffsetY:n}=this.getMaximumSheetOffset();Object.values(this.getSubViewports(i)).forEach((i=>i.setViewportOffset(De(e,0,o),De(t,0,n))))}clipOffsetY(e){const{height:t}=this.getMainViewportRect(),i=t-this.sheetViewHeight;return e=Math.min(e,i),e=Math.max(e,0)}getViewportOffset(e){var t,i;return{x:(null===(t=this.viewports[e])||void 0===t?void 0:t.bottomRight.offsetScrollbarX)||0,y:(null===(i=this.viewports[e])||void 0===i?void 0:i.bottomRight.offsetScrollbarY)||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e),o=this.getters.getNumberCols(e),n=this.getters.getNumberRows(e),s=this.getters.getColRowOffset("COL",0,t,e),r=this.getters.getColRowOffset("ROW",0,i,e),{xRatio:a,yRatio:l}=this.getFrozenSheetViewRatio(e),c=a<1,h=l<1,d=this.getViewportOffset(e),u={topLeft:i&&t&&new Xv(this.getters,e,{left:0,right:t-1,top:0,bottom:i-1},{width:s,height:r},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:i&&new Xv(this.getters,e,{left:t,right:o-1,top:0,bottom:i-1},{width:this.sheetViewWidth-s,height:r},{canScrollHorizontally:c,canScrollVertically:!1},{x:c?d.x:0,y:0})||void 0,bottomLeft:t&&new Xv(this.getters,e,{left:0,right:t-1,top:i,bottom:n-1},{width:s,height:this.sheetViewHeight-r},{canScrollHorizontally:!1,canScrollVertically:h},{x:0,y:h?d.y:0})||void 0,bottomRight:new Xv(this.getters,e,{left:t,right:o-1,top:i,bottom:n-1},{width:this.sheetViewWidth-s,height:this.sheetViewHeight-r},{canScrollHorizontally:c,canScrollVertically:h},{x:c?d.x:0,y:h?d.y:0})};this.viewports[e]=u}refreshViewport(e,t){Object.values(this.getSubViewports(e)).forEach((e=>{e.adjustViewportZone(),e.adjustPosition(t)}))}shiftVertically(e){const{top:t}=this.getActiveMainViewport(),{scrollX:i}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(i,e);const{anchor:o}=this.getters.getSelection(),n=this.getActiveMainViewport().top-t;this.selection.selectCell(o.cell.col,o.cell.row+n)}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],i=this.getters.getFigures(e),{scrollX:o,scrollY:n}=this.getActiveSheetScrollInfo(),{x:s,y:r}=this.getters.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const e of i)e.x>=s&&(e.x+e.width<=s+o||e.x>=a+o+s)||e.y>=r&&(e.y+e.height<=r+n||e.y>=l+n+r)||t.push(e);return t}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:i}=this.getters.getPaneDivisions(e),o=this.getters.getColDimensions(e,t).start,n=this.getters.getRowDimensions(e,i).start;return{xRatio:o/(this.sheetViewWidth+this.gridOffsetX),yRatio:n/(this.sheetViewHeight+this.gridOffsetY)}}}Yv.getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getActiveSheetDOMScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio"];class Kv{constructor(e,t,i){this.index=0,this.cells=e,this.getters=t,this.direction=i}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:i,tooltip:o}=wn.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:i,tooltip:o,origin:{col:e.data.col,row:e.data.row}}}}class Qv extends Hv{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:De(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:De(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?0:45;case"AUTOFILL_AUTO":const i=this.getters.getSelectedZone();return i.top===i.bottom?0:1}return 0}handle(e){switch(e.type){case"AUTOFILL":this.autofill(!0);break;case"AUTOFILL_SELECT":this.select(e.col,e.row);break;case"AUTOFILL_AUTO":this.autofillAuto();break;case"AUTOFILL_CELL":this.autoFillMerge(e.originCol,e.originRow,e.col,e.row);const t=this.getters.getActiveSheetId();this.dispatch("UPDATE_CELL",{sheetId:t,col:e.col,row:e.row,style:e.style||null,content:e.content||"",format:e.format||""}),this.dispatch("SET_BORDER",{sheetId:t,col:e.col,row:e.row,border:e.border})}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),i=this.autofillZone;switch(this.direction){case"down":for(let o=t.left;o<=t.right;o++){const n=[];for(let e=t.top;e<=t.bottom;e++)n.push(Ht(o,e));const s=this.createGenerator(n);for(let t=i.top;t<=i.bottom;t++)this.computeNewCell(s,o,t,e)}break;case"up":for(let o=t.left;o<=t.right;o++){const n=[];for(let e=t.bottom;e>=t.top;e--)n.push(Ht(o,e));const s=this.createGenerator(n);for(let t=i.bottom;t>=i.top;t--)this.computeNewCell(s,o,t,e)}break;case"left":for(let o=t.top;o<=t.bottom;o++){const n=[];for(let e=t.right;e>=t.left;e--)n.push(Ht(e,o));const s=this.createGenerator(n);for(let t=i.right;t>=i.left;t--)this.computeNewCell(s,t,o,e)}break;case"right":for(let o=t.top;o<=t.bottom;o++){const n=[];for(let e=t.left;e<=t.right;e++)n.push(Ht(e,o));const s=this.createGenerator(n);for(let t=i.left;t<=i.right;t++)this.computeNewCell(s,t,o,e)}}e&&(this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0)}select(e,t){const i=this.getters.getSelectedZone();if(ji(e,t,i))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,i.top-1,i.left,i.right),this.steps=i.top-t;break;case"down":this.saveZone(i.bottom+1,t,i.left,i.right),this.steps=t-i.bottom;break;case"left":this.saveZone(i.top,i.bottom,e,i.left-1),this.steps=i.left-e;break;case"right":this.saveZone(i.top,i.bottom,i.right+1,e),this.steps=e-i.right}this.autofill(!1)}}autofillAuto(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let i=e.left,o=e.bottom;if(i>0){let e=this.getters.getEvaluatedCell({sheetId:t,col:i-1,row:o});for(;e.type!==on.empty;)o+=1,e=this.getters.getEvaluatedCell({sheetId:t,col:i-1,row:o})}if(o===e.bottom&&(i=e.right,i<=this.getters.getNumberCols(t))){let e=this.getters.getEvaluatedCell({sheetId:t,col:i+1,row:o});for(;e.type!==on.empty;)o+=1,e=this.getters.getEvaluatedCell({sheetId:t,col:i+1,row:o})}o!==e.bottom&&(this.select(e.left,o-1),this.autofill(!0))}computeNewCell(e,t,i,o){const{cellData:n,tooltip:s,origin:r}=e.next(),{content:a,style:l,border:c,format:h}=n;this.tooltip=s,o&&this.dispatch("AUTOFILL_CELL",{originCol:r.col,originRow:r.row,col:t,row:i,content:a,style:l,border:c,format:h})}getRule(e,t){const i=yn.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((i=>i.condition(e,t)));return i&&i.generateRule(e,t)}createGenerator(e){const t=[],i=[],o=this.getters.getActiveSheetId();for(let t of e){const{col:e,row:n}=Bt(t),s=this.getters.getCell({sheetId:o,col:e,row:n});i.push({col:e,row:n,cell:s,sheetId:o})}const n=i.map((e=>e.cell));for(let e of i){let i={type:"COPY_MODIFIER"};if(e&&e.cell){i=this.getRule(e.cell,n)||i}const o=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:o},rule:i})}return new Kv(t,this.getters,this.direction)}saveZone(e,t,i,o){this.autofillZone={top:e,bottom:t,left:i,right:o}}getDirection(e,t){const i=this.getters.getSelectedZone(),o={up:{number:i.top-t,value:"up"},down:{number:t-i.bottom,value:"down"},left:{number:i.left-e,value:"left"},right:{number:e-i.right,value:"right"}};if(1===Object.values(o).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(o).find((e=>e.number>0?1:0)).value;const n=o.up.number>0?"up":"down",s=o.left.number>0?"left":"right";return Math.abs(o[n].number)>=Math.abs(o[s].number)?o[n].value:o[s].value}autoFillMerge(e,t,i,o){const n=this.getters.getActiveSheetId(),s={sheetId:n,col:i,row:o},r={sheetId:n,col:e,row:t};if(this.getters.isInMerge(s)&&!this.getters.isInMerge(r)){const e=this.getters.getMerge(s);e&&this.dispatch("REMOVE_MERGE",{sheetId:n,target:[e]})}const a=this.getters.getMerge(r);(null==a?void 0:a.topLeft.col)===e&&(null==a?void 0:a.topLeft.row)===t&&this.dispatch("ADD_MERGE",{sheetId:n,target:[{top:o,bottom:o+a.bottom-a.top,left:i,right:i+a.right-a.left}]})}drawGrid(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:i}=e,{x:o,y:n,width:s,height:r}=this.getters.getVisibleRect(this.autofillZone);s>0&&r>0&&(t.strokeStyle="black",t.lineWidth=i,t.setLineDash([3]),t.strokeRect(o,n,s,r),t.setLineDash([]))}}Qv.layers=[5],Qv.getters=["getAutofillTooltip"];class Jv extends Hv{handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:i}=this.getters.getSelection();for(const o of t){const t=this.getAutomaticSums(e,o,i.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,i){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,i):this.sumData(e,t)}sumData(e,t){const i=this.dimensionsToSum(e,t),o=this.sumDimensions(e,t,i).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return i.has("ROW")&&i.has("COL")&&o.push(this.sumTotal(t)),o}sumAdjacentData(e,t,i){const{col:o,row:n}=ji(i.col,i.row,t)?i:{col:t.left,row:t.top},s=this.findAdjacentData(e,o,n);return s?this.getters.isSingleCellOrMerge(e,t)||Ji(Wi(s,t))?[{position:{col:o,row:n},zone:s}]:this.sumDimensions(e,Wi(s,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,i){const o=this.getters.getSheet(e),n=this.getters.getMainCellPosition({sheetId:e,col:t,row:i}),s=this.findSuitableZoneToSum(o,n.col,n.row);if(s)return this.getters.expandZone(e,s)}findSuitableZoneToSum(e,t,i){const o=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:i-1}),n=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:i});if(this.isNumber(n)&&!this.isNumber(o))return this.findHorizontalZone(e,t,i);const s=this.findVerticalZone(e,t,i);if(this.isZoneValid(s))return s;const r=this.findHorizontalZone(e,t,i);return this.isZoneValid(r)?r:void 0}findVerticalZone(e,t,i){const o={top:0,bottom:i-1,left:t,right:t},n=this.reduceZoneStart(e,o,o.bottom);return{...o,top:n}}findHorizontalZone(e,t,i){const o={top:i,bottom:i,left:0,right:t-1},n=this.reduceZoneStart(e,o,o.right);return{...o,left:n}}reduceZoneStart(e,t,i){const o=this.getters.getEvaluatedCellsInZone(e.id,t),n=Be(i,-1,-1),s=n.filter((e=>o[e]&&!o[e].isAutoSummable)),r=Math.max(...s),a=He(n.filter((e=>this.isNumber(o[e]))))[0]||[];return Math.max(...a)<r?1/0:Math.min(...a)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){var t;return e.type===on.number&&!(null===(t=e.format)||void 0===t?void 0:t.match(X))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){const i=new Set;return Ji(t)?(i.add(1===Qi(t).numberOfCols?"COL":"ROW"),i):(this.lastColIsEmpty(e,t)&&i.add("ROW"),this.lastRowIsEmpty(e,t)&&i.add("COL"),0===i.size&&i.add("COL"),i)}sumDimensions(e,t,i){return[...i.has("COL")?this.sumColumns(t,e):[],...i.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:i}=e;return{position:{col:i,row:t},zone:{...e,top:t,right:i-1}}}sumColumns(e,t){const i=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,i.bottom-1)},eo(i).map((t=>({position:t,zone:{...e,right:t.col,left:t.col}})))}sumRows(e,t){const i=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,i.right-1)},eo(i).map((t=>({position:t,zone:{...e,top:t.row,bottom:t.row}})))}dispatchCellUpdates(e,t){for(const i of t){const{col:t,row:o}=i.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,content:`=SUM(${this.getters.zoneToXC(e,i.zone)})`})}}nextEmptyRow(e,t){let i=t.bottom+1;const{left:o,right:n}=t;for(;!this.getters.isEmpty(e,{bottom:i,top:i,left:o,right:n});)i++;return{...t,top:i,bottom:i}}nextEmptyCol(e,t){let i=t.right+1;const{top:o,bottom:n}=t;for(;!this.getters.isEmpty(e,{left:i,right:i,top:o,bottom:n});)i++;return{...t,left:i,right:i}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}Jv.getters=["getAutomaticSums"];class eb extends Hv{allowDispatch(e){if("OPEN_CELL_POPOVER"===e.type){try{os.get(e.popoverType)}catch(e){return 72}return 0}return 0}handle(e){switch(e.type){case"ACTIVATE_SHEET":case"CLOSE_CELL_POPOVER":this.persistentPopover=void 0;break;case"OPEN_CELL_POPOVER":this.persistentPopover={col:e.col,row:e.row,sheetId:this.getters.getActiveSheetId(),type:e.popoverType}}}getCellPopover({col:e,row:t}){var i,o;const n=this.getters.getActiveSheetId();if(this.persistentPopover&&this.getters.isVisibleInViewport(this.persistentPopover)){const e=this.getters.getMainCellPosition(this.persistentPopover),t=null===(o=(i=os.get(this.persistentPopover.type)).onOpen)||void 0===o?void 0:o.call(i,e,this.getters);return(null==t?void 0:t.isOpen)?{...t,anchorRect:this.computePopoverAnchorRect(this.persistentPopover)}:{isOpen:!1}}if(void 0===e||void 0===t||!this.getters.isVisibleInViewport({sheetId:n,col:e,row:t}))return{isOpen:!1};const s=this.getters.getMainCellPosition({sheetId:n,col:e,row:t}),r=os.getAll().map((e=>{var t;return null===(t=e.onHover)||void 0===t?void 0:t.call(e,s,this.getters)})).find((e=>null==e?void 0:e.isOpen));return(null==r?void 0:r.isOpen)?{...r,anchorRect:this.computePopoverAnchorRect(s)}:{isOpen:!1}}hasOpenedPopover(){return void 0!==this.persistentPopover}getPersistentPopoverTypeAtPosition({col:e,row:t}){if(this.persistentPopover&&this.persistentPopover.col===e&&this.persistentPopover.row===t)return this.persistentPopover.type}computePopoverAnchorRect({col:e,row:t}){const i=this.getters.getActiveSheetId(),o=this.getters.getMerge({sheetId:i,col:e,row:t});return o?this.getters.getVisibleRect(o):this.getters.getVisibleRect(no({col:e,row:t}))}}eb.getters=["getCellPopover","getPersistentPopoverTypeAtPosition","hasOpenedPopover"];var tb;!function(e){e[e.previous=-1]="previous",e[e.current=0]="current",e[e.next=1]="next"}(tb||(tb={}));class ib extends Hv{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(tb.previous);break;case"SELECT_SEARCH_NEXT_MATCH":this.selectNextCell(tb.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(tb.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),i=[];if(this.toSearch)for(const o of Object.values(t)){const{col:t,row:n}=this.getters.getCellPosition(o.id);if(o&&this.currentSearchRegex&&this.currentSearchRegex.test(this.getSearchableString({sheetId:e,col:t,row:n}))){const e={col:t,row:n,selected:!1};i.push(e)}}return i.sort(this.sortByRowThenColumn)}sortByRowThenColumn(e,t){return e.row===t.row?e.col-t.col:e.row>t.row?1:-1}selectNextCell(e){const t=this.searchMatches;if(!t.length)return void(this.selectedMatchIndex=null);let i;i=null===this.selectedMatchIndex?0:this.selectedMatchIndex+e,i=(i%t.length+t.length)%t.length,this.selectedMatchIndex=i,this.selection.selectCell(t[i].col,t[i].row);for(let e=0;e<this.searchMatches.length;e++)this.searchMatches[e].selected=e===this.selectedMatchIndex}clearSearch(){this.toSearch="",this.searchMatches=[],this.selectedMatchIndex=null,this.currentSearchRegex=null,this.searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1}}replace(e){if(null===this.selectedMatchIndex||!this.currentSearchRegex)return;const t=this.searchMatches[this.selectedMatchIndex],i=this.getters.getActiveSheetId(),o=this.getters.getCell({sheetId:i,...t});if((null==o?void 0:o.isFormula)&&!this.searchOptions.searchFormulas)this.selectNextCell(tb.next);else{const o=new RegExp(this.currentSearchRegex.source,this.currentSearchRegex.flags+"g"),n=this.getSearchableString({sheetId:i,col:t.col,row:t.row}).replace(o,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(tb.current)}}replaceAll(e){const t=this.searchMatches.length;for(let i=0;i<t;i++)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,i=this.getters.getActiveSheetId();for(const e of this.searchMatches){const o=this.getters.getMerge({sheetId:i,col:e.col,row:e.row}),n=o?o.left:e.col,s=o?o.right:e.col,r=o?o.top:e.row,a=o?o.bottom:e.row,{x:l,y:c,width:h,height:d}=this.getters.getVisibleRect({top:r,left:n,right:s,bottom:a});h>0&&d>0&&(t.fillStyle="#8B008B33",t.fillRect(l,c,h,d),e.selected&&(t.strokeStyle="#8B008B",t.strokeRect(l,c,h,d)))}}}ib.layers=[3],ib.getters=["getSearchMatches","getCurrentSelectedMatchIndex"];class ob extends Hv{isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,i){return"COL"===t?this.isColHidden(e,i):this.isRowHidden(e,i)}getNextVisibleCellPosition({sheetId:e,col:t,row:i}){return{sheetId:e,col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",i,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,i,o){if(i<=o)for(let n=i;n<=o;n++)if(this.getters.doesHeaderExist(e,t,n)&&!this.isHeaderHidden(e,t,n))return n;if(i>o)for(let n=i;n>=o;n--)if(this.getters.doesHeaderExist(e,t,n)&&!this.isHeaderHidden(e,t,n))return n}findLastVisibleColRowIndex(e,t,{last:i,first:o}){return Be(i,o,-1).find((i=>!this.isHeaderHidden(e,t,i)))||o}findFirstVisibleColRowIndex(e,t){const i=this.getters.getNumberHeaders(e,t);for(let o=0;o<i;o++){if("COL"===t&&!this.isColHidden(e,o))return o;if("ROW"===t&&!this.isRowHidden(e,o))return o}}exportForExcel(e){for(const t of e.sheets)for(const[e,i]of Object.entries(t.rows)){const o=this.isRowHidden(t.id,Number(e));i.isHidden=o}}}ob.getters=["getNextVisibleCellPosition","findVisibleHeader","findLastVisibleColRowIndex","findFirstVisibleColRowIndex","isRowHidden","isColHidden","isHeaderHidden"];class nb extends Hv{getHighlights(){return this.prepareHighlights(this.getters.getComposerHighlights().concat(this.getters.getSelectionInputHighlights()))}prepareHighlights(e){return e.filter((e=>e.zone.top>=0&&e.zone.left>=0&&e.zone.bottom<this.getters.getNumberRows(e.sheetId)&&e.zone.right<this.getters.getNumberCols(e.sheetId))).map((e=>{const{numberOfRows:t,numberOfCols:i}=Qi(e.zone),o=t*i==1?this.getters.expandZone(e.sheetId,e.zone):e.zone;return{...e,zone:o}}))}drawGrid(e){const{ctx:t,thinLineWidth:i}=e,o=this.getters.getActiveSheetId(),n=3*i;t.lineWidth=n;const s=this.getHighlights();for(let e of s.filter(((e,t)=>s.findIndex((t=>qi(t.zone,e.zone)&&t.sheetId===o))===t))){const{x:i,y:o,width:s,height:r}=this.getters.getVisibleRect(e.zone);s>0&&r>0&&(t.strokeStyle=e.color,t.strokeRect(i+n/2,o+n/2,s-n,r-n),t.globalCompositeOperation="source-over",t.fillStyle=e.color+"20",t.fillRect(i+n,o+n,s-2*n,r-2*n))}}}nb.layers=[1],nb.getters=["getHighlights"];class sb extends Hv{constructor(){super(...arguments),this.boxes=[]}getColDimensionsInViewport(e,t){const i=Math.min(...this.getters.getSheetViewVisibleCols()),o=this.getters.getColRowOffsetInViewport("COL",i,t),n=this.getters.getColSize(e,t);return{start:o,size:n,end:o+(this.getters.isColHidden(e,t)?0:n)}}getRowDimensionsInViewport(e,t){const i=Math.min(...this.getters.getSheetViewVisibleRows()),o=this.getters.getColRowOffsetInViewport("ROW",i,t),n=this.getters.getRowSize(e,t);return{start:o,size:n,end:o+(this.getters.isRowHidden(e,t)?0:n)}}getHeaderOffset(e,t,i){let o=this.getters.getColRowOffsetInViewport(e,t,i);return this.getters.isDashboard()||(o+="ROW"===e?O:N),o}drawGrid(e,t){switch(t){case 0:this.boxes=this.getGridBoxes(),this.drawBackground(e),this.drawOverflowingCellBackground(e),this.drawCellBackground(e),this.drawBorders(e),this.drawTexts(e),this.drawIcon(e),this.drawFrozenPanes(e);break;case 7:this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e))}}drawBackground(e){const{ctx:t,thinLineWidth:i}=e,{width:o,height:n}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle="#ffffff",t.fillRect(0,0,o+m,n+m);const s=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),r=s?.1*i:0;if(s)for(const e of this.boxes)t.strokeStyle="#E2E3E3",t.lineWidth=i,t.strokeRect(e.x+r,e.y+r,e.width-2*r,e.height-2*r)}drawCellBackground(e){const{ctx:t}=e;for(const e of this.boxes){let i=e.style;i.fillColor&&"#ffffff"!==i.fillColor&&(t.fillStyle=i.fillColor||"#ffffff",t.fillRect(e.x,e.y,e.width,e.height)),e.error&&(t.fillStyle="red",t.beginPath(),t.moveTo(e.x+e.width-5,e.y),t.lineTo(e.x+e.width,e.y),t.lineTo(e.x+e.width,e.y+5),t.fill())}}drawOverflowingCellBackground(e){var t,i;const{ctx:o,thinLineWidth:n}=e;for(const e of this.boxes)if(e.content&&e.isOverflow){const s=e.content.align||"left";let r,a;const l=e.y+n/2,c=e.height-n,h=Math.min((null===(t=e.clipRect)||void 0===t?void 0:t.width)||1/0,e.content.width);"left"===s?(r=e.x+n/2,a=h-2*n):"right"===s?(r=e.x+e.width-n/2,a=2*n-h):(r=((null===(i=e.clipRect)||void 0===i?void 0:i.x)||e.x+e.width/2-e.content.width/2)+n/2,a=h-2*n),o.fillStyle="#ffffff",o.fillRect(r,l,a,c)}}drawBorders(e){const{ctx:t,thinLineWidth:i}=e;for(let e of this.boxes){const t=e.border;if(t){const{x:i,y:n,width:s,height:r}=e;t.left&&o(t.left,i,n,i,n+r),t.top&&o(t.top,i,n,i+s,n),t.right&&o(t.right,i+s,n,i+s,n+r),t.bottom&&o(t.bottom,i,n+r,i+s,n+r)}}function o([e,o],n,s,r,a){t.strokeStyle=o,t.lineWidth=("thin"===e?2:3)*i,t.beginPath(),t.moveTo(n,s),t.lineTo(r,a),t.stroke()}}drawTexts(e){const{ctx:t,thinLineWidth:i}=e;let o;t.textBaseline="top";for(let e of this.boxes)if(e.content){const n=e.style||{},s=e.content.align||"left",r=Ve(n);r!==o&&(o=r,t.font=r),t.fillStyle=n.textColor||"#000";let a=e.x;if(a+="left"===s?U+(e.image?e.image.size+P:0):"right"===s?e.width-U-(e.isFilterHeader?20:0):e.width/2,t.textAlign=s,e.clipRect){t.save(),t.beginPath();const{x:i,y:o,width:n,height:s}=e.clipRect;t.rect(i,o,n,s),t.clip()}const l=ze(n),c=e.content.textLines.length;let h=this.computeTextYCoordinate(e,l,c);for(let o of e.content.textLines){if(t.fillText(o,Math.round(a),Math.round(h)),n.strikethrough||n.underline){const e=Le(t,o,n);let r=a;"right"===s?r-=e:"center"===s&&(r-=e/2),n.strikethrough&&t.fillRect(r,h+l/2,e,2.6*i),n.underline&&t.fillRect(r,h+l+1,e,1.3*i)}h+=U+l}e.clipRect&&t.restore()}}drawIcon(e){const{ctx:t}=e;for(const e of this.boxes)if(e.image){const i=e.image.image;if(e.image.clipIcon){t.save(),t.beginPath();const{x:i,y:o,width:n,height:s}=e.image.clipIcon;t.rect(i,o,n,s),t.clip()}const o=e.image.size,n=this.computeTextYCoordinate(e,o);t.drawImage(i,e.x+P,n,o,o),e.image.clipIcon&&t.restore()}}computeTextYCoordinate(e,t,i=1){const o=e.y+1,n=ke(t,i),s=e.height>n+2*U,r=e.verticalAlign||"middle";if(s){if("middle"===r)return o+(e.height-n)/2;if("bottom"===r)return o+e.height-n-U}return o+U}drawHeaders(e){const{ctx:t,thinLineWidth:i}=e,o=this.getters.getSheetViewVisibleCols(),n=o[0],s=o[o.length-1],r=this.getters.getSheetViewVisibleRows(),a=r[0],l=r[r.length-1],{width:c,height:h}=this.getters.getSheetViewDimensionWithHeaders(),d=this.getters.getSelectedZones(),u=function(e){const t=new Set;for(let i of e)for(let e of Be(i.left,i.right+1))t.add(e);return t}(d),g=function(e){const t=new Set;for(let i of e)for(let e of Be(i.top,i.bottom+1))t.add(e);return t}(d),p=this.getters.getActiveSheetId(),m=this.getters.getNumberCols(p),f=this.getters.getNumberRows(p),E=this.getters.getActiveCols(),w=this.getters.getActiveRows();t.font=`400 11px ${q}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=i,t.strokeStyle="#333";for(let e=n;e<=s;e++){const i={left:e,right:e,top:0,bottom:f-1},{x:o,width:n}=this.getters.getVisibleRect(i),s=this.getters.doesZonesContainFilter(p,[i]),r=E.has(e),a=u.has(e);t.fillStyle=r?s?I:S:a?s?T:b:s?R:v,t.fillRect(o,0,n,O)}for(let e=a;e<=l;e++){const i={top:e,bottom:e,left:0,right:m-1},{y:o,height:n}=this.getters.getVisibleRect(i),s=this.getters.doesZonesContainFilter(p,[i]),r=w.has(e),a=g.has(e);t.fillStyle=r?s?I:S:a?s?T:b:s?R:v,t.fillRect(0,o,N,n)}t.beginPath(),t.moveTo(N,0),t.lineTo(N,h),t.moveTo(0,O),t.lineTo(c,O),t.strokeStyle="#C0C0C0",t.stroke(),t.beginPath();for(const e of o){const i=this.getters.getColSize(p,e),o=Vt(e);t.fillStyle=E.has(e)?"#fff":C;let s=this.getHeaderOffset("COL",n,e);t.fillText(o,s+i/2,13),t.moveTo(s+i,0),t.lineTo(s+i,O)}for(const e of r){const i=this.getters.getRowSize(p,e);t.fillStyle=w.has(e)?"#fff":C;let o=this.getHeaderOffset("ROW",a,e);t.fillText(String(e+1),24,o+i/2),t.moveTo(0,o+i),t.lineTo(N,o+i)}t.stroke()}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:i}=e,{x:o,y:n}=this.getters.getMainViewportCoordinates(),s=this.getters.isDashboard()?0:N,r=this.getters.isDashboard()?0:O;t.lineWidth=6*i,t.strokeStyle="#BCBCBC",t.beginPath(),o&&(t.moveTo(s+o,0),t.lineTo(s+o,r)),n&&(t.moveTo(0,r+n),t.lineTo(s,r+n)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:i}=e,{x:o,y:n}=this.getters.getMainViewportCoordinates(),s=this.getters.getSheetViewVisibleCols(),r=s[0],a=s[s.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:r,right:a,top:l[0],bottom:l[l.length-1]},h=this.getters.getVisibleRect(c),d=this.getters.isDashboard()?0:N,u=this.getters.isDashboard()?0:O;t.lineWidth=6*i,t.strokeStyle="#DADFE8",t.beginPath(),o&&(t.moveTo(d+o,u),t.lineTo(d+o,h.height+u)),n&&(t.moveTo(d,u+n),t.lineTo(h.width+d,u+n)),t.stroke()}findNextEmptyCol(e,t,i){const o=this.getters.getActiveSheetId();let n=e;for(;n<t;){const e={sheetId:o,col:n+1,row:i},t=this.getters.getEvaluatedCell(e),s=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==on.empty||this.getters.isInMerge(e)||(null==s?void 0:s.left))return n;n++}return n}findPreviousEmptyCol(e,t,i){const o=this.getters.getActiveSheetId();let n=e;for(;n>t;){const e={sheetId:o,col:n-1,row:i},t=this.getters.getEvaluatedCell(e),s=this.getters.getCellBorderWithFilterBorder(e);if(t.type!==on.empty||this.getters.isInMerge(e)||(null==s?void 0:s.right))return n;n--}return n}computeCellAlignment(e,t){const i=this.getters.getCell(e);if((null==i?void 0:i.isFormula)&&this.getters.shouldShowFormulas())return"left";const{align:o}=this.getters.getCellStyle(e),n=this.getters.getEvaluatedCell(e);return t&&n.type===on.number?"center"!==o?"left":o:o||n.defaultAlign}createZoneBox(e,t,i){const{left:o,right:n}=i,s=t.left,r=t.top,a={sheetId:e,col:s,row:r},c=this.getters.getEvaluatedCell(a),h=this.getters.shouldShowFormulas(),{x:d,y:u,width:g,height:p}=this.getters.getVisibleRect(t),{verticalAlign:m}=this.getters.getCellStyle(a),f={x:d,y:u,width:g,height:p,border:this.getters.getCellBorderWithFilterBorder(a)||void 0,style:this.getters.getCellComputedStyle(a),verticalAlign:m};if(c.type===on.empty)return f;const v=this.getters.getConditionalIcon(a),b=ze(f.style),S=v?P+b:0;v&&(f.image={type:"icon",size:b,clipIcon:{x:f.x,y:f.y,width:Math.min(S,g),height:p},image:bg[v].img}),f.isFilterHeader=this.getters.isFilterHeader(a);const C=f.isFilterHeader?19:0,E=this.getters.getCellComputedStyle(a),w=E.wrapping||"overflow",y="wrap"!==w||h?void 0:g-2*U,x=this.getters.getCellMultiLineText(a,y),I=Math.max(...x.map((e=>this.getters.getTextWidth(e,E)+U))),R=S+I+C,T=this.computeCellAlignment(a,R>g);f.content={textLines:x,width:"overflow"===w?I:g,align:T},c.type===on.error&&c.error.logLevel>l.silent&&(f.error=c.error.message);const A=R>g||b>p;if(v||f.isFilterHeader)f.clipRect={x:f.x+S,y:f.y,width:Math.max(0,g-S-C),height:p};else if(A&&"overflow"===w){let e,i;switch(this.getters.isInMerge(a)?(e=this.getters.getMerge(a).right,i=s):(e=this.findNextEmptyCol(s,n,r),i=this.findPreviousEmptyCol(s,o,r),f.isOverflow=!0),T){case"left":{const i=no({col:e,row:r}),{x:o,y:n,width:s,height:a}=this.getters.getVisibleRect(Wi(t,i));(s<R||b>a||x.length>1)&&(f.clipRect={x:o,y:n,width:s,height:a});break}case"right":{const e=no({col:i,row:r}),{x:o,y:n,width:s,height:a}=this.getters.getVisibleRect(Wi(t,e));(s<R||b>a||x.length>1)&&(f.clipRect={x:o,y:n,width:s,height:a});break}case"center":{const o={...t,left:i,right:e},{x:n,y:s,height:r,width:a}=this.getters.getVisibleRect(o),l=R/2,c=f.x+f.width/2;if(n+a<c+l||n>c-l||b>r||x.length>1){const e=n>c-l?n:c-l,t=n+a-e;f.clipRect={x:e,y:s,width:t,height:r}}break}}}else("clip"===w||"wrap"===w||x.length>1)&&(f.clipRect={x:f.x,y:f.y,width:g,height:p});return f}getGridBoxes(){const e=[],t=this.getters.getSheetViewVisibleCols(),i=t[0],o=t[t.length-1],n=this.getters.getSheetViewVisibleRows(),s={left:i,right:o,top:n[0],bottom:n[n.length-1]},r=this.getters.getActiveSheetId();for(const i of n)for(const o of t){const t={sheetId:r,col:o,row:i};this.getters.isInMerge(t)||e.push(this.createZoneBox(r,no(t),s))}for(const t of this.getters.getMerges(r))if(!this.getters.isMergeHidden(r,t)&&Zi(t,s)){const i=this.createZoneBox(r,t,s),o=this.getters.getCellBorder({sheetId:r,col:t.right,row:t.bottom});i.border={...i.border,bottom:o?o.bottom:void 0,right:o?o.right:void 0},i.isMerge=!0,e.push(i)}return e}}sb.layers=[0,7],sb.getters=["getColDimensionsInViewport","getRowDimensionsInViewport"];class rb extends Hv{constructor(e,t,i){if(i&&t.length>1)throw new Error("Input with a single range cannot be instantiated with several range references.");super(e),this.inputHasSingleRange=i,this.ranges=[],this.focusedRangeIndex=null,this.willAddNewRange=!1,this.insertNewRange(0,t),this.activeSheet=this.getters.getActiveSheetId(),0===this.ranges.length&&(this.insertNewRange(this.ranges.length,[""]),this.focusLast())}allowDispatch(e){switch(e.type){case"ADD_EMPTY_RANGE":if(this.inputHasSingleRange&&1===this.ranges.length)return 30;break;case"CHANGE_RANGE":if(this.inputHasSingleRange&&e.value.split(",").length>1)return 30}return 0}handleEvent(e){const t=Vi(e.anchor.zone),i=this.activeSheet,o=this.getters.getActiveSheetId(),n=this.getters.getSheetName(o);this.add([o===i?t:`${Fe(n)}!${t}`])}handle(e){switch(e.type){case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"FOCUS_RANGE":this.focus(this.getIndex(e.rangeId));break;case"CHANGE_RANGE":{const t=this.getIndex(e.rangeId);if(null!==t&&this.focusedRangeIndex!==t&&this.focus(t),null!==t){const i=e.value.replace(/^,+/,"").split(",").map((e=>e.trim()));this.setRange(t,i)}break}case"ADD_EMPTY_RANGE":this.insertNewRange(this.ranges.length,[""]),this.focusLast();break;case"REMOVE_RANGE":const t=this.getIndex(e.rangeId);null!==t&&this.removeRange(t);break;case"STOP_SELECTION_INPUT":this.willAddNewRange=!1;break;case"PREPARE_SELECTION_INPUT_EXPANSION":{const e=this.focusedRangeIndex;null===e||this.inputHasSingleRange||(this.willAddNewRange=""!==this.ranges[e].xc.trim());break}case"ACTIVATE_SHEET":if(e.sheetIdFrom!==e.sheetIdTo){const{col:t,row:i}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),o=this.getters.expandZone(e.sheetIdTo,no({col:t,row:i}));this.selection.resetAnchor(this,{cell:{col:t,row:i},zone:o})}}}getSelectionInputValue(){return this.cleanInputs(this.ranges.map((e=>e.xc?e.xc:"")))}getSelectionInputHighlights(){return this.ranges.map((e=>this.inputToHighlights(e))).flat()}focus(e){this.focusedRangeIndex=e}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null}add(e){null!==this.focusedRangeIndex&&0!==e.length&&(this.willAddNewRange?(this.insertNewRange(this.ranges.length,e),this.focusLast(),this.willAddNewRange=!1):this.setRange(this.focusedRangeIndex,e))}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){const i=Math.max(0,...this.ranges.map((e=>Number(e.id))));this.ranges.splice(e,0,...t.map(((e,t)=>({xc:e,id:i+t+1,color:vt[(i+t)%vt.length]}))))}setRange(e,t){const[,...i]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,i),i.length&&this.focus(e+i.length)}removeRange(e){this.ranges.splice(e,1),null!==this.focusedRangeIndex&&this.focusLast()}inputToHighlights({xc:e,color:t}){const i=this.cleanInputs([e]).filter((e=>this.getters.isRangeValid(e))).filter((e=>this.shouldBeHighlighted(this.activeSheet,e)));return i.map((e=>{const{sheetName:i}=Ut(e);return{zone:this.getters.getRangeFromSheetXC(this.activeSheet,e).zone,sheetId:i&&this.getters.getSheetIdByName(i)||this.activeSheet,color:t}}))}cleanInputs(e){return e.map((e=>e.split(","))).flat().map((e=>e.trim())).filter((e=>""!==e))}shouldBeHighlighted(e,t){const{sheetName:i}=Ut(t),o=this.getters.getSheetIdByName(i),n=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(o===n||void 0===o&&n===e)}getIndex(e){const t=this.ranges.findIndex((t=>t.id===e));return t>=0?t:null}}rb.layers=[1],rb.getters=[];class ab extends Hv{get currentInput(){return this.focusedInputId?this.inputs[this.focusedInputId]:null}constructor(e){super(e),this.config=e,this.inputs={},this.focusedInputId=null}allowDispatch(e){var t,i;if("FOCUS_RANGE"===e.type){const o=null===(t=this.currentInput)||void 0===t?void 0:t.getIndex(e.rangeId);if(this.focusedInputId===e.id&&(null===(i=this.currentInput)||void 0===i?void 0:i.focusedRangeIndex)===o)return 29}return this.currentInput?this.currentInput.allowDispatch(e):0}handle(e){var t;switch(e.type){case"ENABLE_NEW_SELECTION_INPUT":this.initInput(e.id,e.initialRanges||[],e.hasSingleRange);break;case"DISABLE_SELECTION_INPUT":this.focusedInputId===e.id&&this.unfocus(),delete this.inputs[e.id];break;case"UNFOCUS_SELECTION_INPUT":this.unfocus();break;case"ADD_EMPTY_RANGE":case"REMOVE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id];this.selection.capture(t,{cell:{col:0,row:0},zone:no({col:0,row:0})},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}break;case"FOCUS_RANGE":case"CHANGE_RANGE":if(e.id!==this.focusedInputId){const t=this.inputs[e.id],i=t.ranges.find((t=>t.id===e.rangeId)),o=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(o,(null==i?void 0:i.xc)||"A1").zone;this.selection.capture(t,{cell:{col:n.left,row:n.top},zone:n},{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e.id}}null===(t=this.currentInput)||void 0===t||t.handle(e)}getSelectionInput(e){return this.inputs[e]?this.inputs[e].ranges.map(((t,i)=>Object.assign({},t,{color:this.focusedInputId===e&&null!==this.inputs[e].focusedRangeIndex&&this.isRangeValid(t.xc)?t.color:null,isFocused:this.focusedInputId===e&&this.inputs[e].focusedRangeIndex===i}))):[]}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:i}=Ut(e);return null!==t.match(Ft)&&(!i||void 0!==this.getters.getSheetIdByName(i))}getSelectionInputValue(e){return this.inputs[e].getSelectionInputValue()}getSelectionInputHighlights(){return this.focusedInputId?this.inputs[this.focusedInputId].getSelectionInputHighlights():[]}initInput(e,t,i=!1){if(this.inputs[e]=new rb(this.config,t,i),0===t.length){const t=this.inputs[e],i={zone:no({col:0,row:0}),cell:{col:0,row:0}};this.selection.capture(t,i,{handleEvent:t.handleEvent.bind(t)}),this.focusedInputId=e}}unfocus(){this.selection.release(this.currentInput),this.focusedInputId=null}}ab.layers=[1],ab.getters=["getSelectionInput","getSelectionInputValue","isRangeValid","getSelectionInputHighlights"];class lb{constructor(){this.subscriptions={}}on(e,t,i){if(!i)throw new Error("Missing callback");this.subscriptions[e]||(this.subscriptions[e]=[]),this.subscriptions[e].push({owner:t,callback:i})}trigger(e,t){const i=this.subscriptions[e]||[];for(let e=0,o=i.length;e<o;e++){const o=i[e];o.callback.call(o.owner,t)}}off(e,t){const i=this.subscriptions[e];i&&(this.subscriptions[e]=i.filter((e=>e.owner!==t)))}clear(){this.subscriptions={}}}function cb(e,t){return{...e,definition:vr(e.definition,t)}}function hb(e,t){if(e.sheetId!==t.sheetId)return e;if(("FREEZE_COLUMNS"===e.type?"COL":"ROW")!==t.dimension)return e;let i=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));for(let t of e)i>t&&i--}if("ADD_COLUMNS_ROWS"===t.type){i=i>("before"===t.position?t.base-1:t.base)?i+t.quantity:i}return i>0?{...e,quantity:i}:void 0}Xu.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],cb),Xu.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],cb),Xu.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const i=t.sheetId;if(e.targetSheetId===i||e.sheetId===i)return;return e})),Xu.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),Xu.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){var i;if(e.name===t.name)return{...e,name:(null===(i=e.name)||void 0===i?void 0:i.match(/\d+/))?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),Xu.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE","CREATE_FILTER_TABLE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const i=[];for(const o of e.target)for(const e of t.target)Zi(o,e)||i.push({...o});if(i.length)return{...e,target:i};return})),Xu.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],hb),Xu.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],hb),Xu.addTransformation("CREATE_FILTER_TABLE",["CREATE_FILTER_TABLE","ADD_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;for(const i of e.target)for(const e of t.target)if(Zi(e,i))return;return e}));const db=[{match:function(e){return"sheetId"in e},fn:pb},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const i=pb(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;const o=[];for(const i of e.target){const e=rs(i,t);e&&o.push(e)}if(!o.length)return"IGNORE_COMMAND";return{...e,target:o}}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const i=pb(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const i="COL"===t.dimension?"col":"row";let o=e[i];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(o))return"IGNORE_COMMAND";for(let t of e)o>=t&&o--}"ADD_COLUMNS_ROWS"===t.type&&(o>t.base||o===t.base&&"before"===t.position)&&(o+=t.quantity);return{...e,[i]:o}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const i of t.target){if(!(e.col===i.left&&e.row===i.top)&&ji(e.col,e.row,i))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e&&"sheetId"in e},fn:function(e,t){const i=pb(e,t);if("SKIP_TRANSFORMATION"!==i)return"IGNORE_COMMAND"===i?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type){if(t.dimension!==e.dimension)return e;const i="ADD_COLUMNS_ROWS"===e.type,o=i?"base":"elements";let n=i?[e[o]]:e[o];if("REMOVE_COLUMNS_ROWS"===t.type&&(n=n.map((e=>{if(t.elements.includes(e))return;const i=t.elements.sort(((e,t)=>t-e));for(let t of i)e>t&&e--;return e})).filter(tt)),"ADD_COLUMNS_ROWS"===t.type){const e="before"===t.position?t.base-1:t.base;n=n.map((i=>i>e?i+t.quantity:i))}if(n.length){let t=n;return i&&(t=n[0]),{...e,[o]:t}}return"IGNORE_COMMAND"}return"SKIP_TRANSFORMATION"}},{match:function(e){return"ranges"in e},fn:function(e,t){const i=[],o="DELETE_SHEET"===t.type&&t.sheetId;for(const n of e.ranges)if(n._sheetId!==t.sheetId)i.push({...n,_zone:n._zone});else{const e=rs(n._zone,t);e&&o!==n._sheetId&&i.push({...n,_zone:e})}if(!i.length)return"IGNORE_COMMAND";return{...e,ranges:i}}}];function ub(e,t){const i=Xu.getTransformation(e.type,t.type);return i?i(e,t):function(e,t){for(const{match:i,fn:o}of db)if(i(e)){const i=o(e,t);if("SKIP_TRANSFORMATION"===i)continue;if("IGNORE_COMMAND"===i)return;e=i}return e}(e,t)}function gb(e,t){let i=[...e];for(const e of t)i=i.map((t=>ub(t,e))).filter(tt);return i}function pb(e,t){const i="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===i?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class mb{constructor(e,t,i,o){this._commands=[],this._changes=[],this.id=e,this.clientId=t,this._commands=[...i],this._changes=o?[...o]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class fb extends Error{}class vb extends lb{constructor(e,t,i=K){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=i,this.clients={},this.clientId="local",this.pendingMessages=[],this.waitingAck=!1,this.waitingUndoRedoAck=!1,this.isReplayingInitialRevisions=!1,this.processedRevisions=new Set,this.uuidGenerator=new ki,this.debouncedMove=function(e,t,i){let o;return function(){const n=this,s=arguments,r=i&&!o;clearTimeout(o),o=setTimeout((function(){o=null,i||e.apply(n,s)}),t),r&&e.apply(n,s)}}(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t){if(!e.length||!t.length||!this.canApplyOptimisticUpdate())return;const i=new mb(this.uuidGenerator.uuidv4(),this.clientId,e,t);this.revisions.append(i.id,i),this.trigger("new-local-state-update",{id:i.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:i.id,clientId:i.clientId,commands:i.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_UNDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_REDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:"local",name:"local"},this.clientId="local"),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this))}loadInitialMessages(e){this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1}leave(){delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}snapshot(e){const t=this.uuidGenerator.uuidv4();this.transportService.sendMessage({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){const e=this.clients[this.clientId];if(!e)throw new fb("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(tt))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}_move(e){var t;if(!this.clients[this.clientId])return;const i=null===(t=this.clients[this.clientId])||void 0===t?void 0:t.position;if((null==i?void 0:i.col)===e.col&&i.row===e.row&&i.sheetId===e.sheetId)return;const o=i?"CLIENT_MOVED":"CLIENT_JOINED",n=this.getClient();this.clients[this.clientId]={...n,position:e},this.transportService.sendMessage({type:o,version:1,client:{...n,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:i}=e,o=new mb(e.nextRevisionId,t,i);if(o.clientId!==this.clientId){this.revisions.insert(o.id,o,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:gb(i,t)})}break;case"SNAPSHOT_CREATED":{const t=new mb(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 bb=["#ff851b","#0074d9","#7fdbff","#b10dc9","#39cccc","#f012be","#3d9970","#111111","#ff4136","#aaaaaa","#85144b","#001f3f"];class Sb extends Hv{constructor(){super(...arguments),this.availableColors=new Set(bb),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(bb));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 fb)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const i of this.getters.getConnectedClients())if(i.id!==this.getters.getClient().id&&i.position&&i.position.sheetId===e&&this.isPositionValid(i.position)){const e=i.position;this.colors[i.id]||(this.colors[i.id]=this.chooseNewColor());const o=this.colors[i.id];t.push({...i,position:e,color:o})}return t}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:i}=e,o=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:n,col:s}=e.position,r=this.getters.expandZone(o,{top:n,bottom:n,left:s,right:s}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);if(c<=0||h<=0)continue;const d=e.color,u=`${d}10`;t.fillStyle=u,t.lineWidth=4*i,t.strokeStyle=d,t.globalCompositeOperation="multiply",t.fillRect(a,l,c,h),t.globalCompositeOperation="source-over",t.strokeRect(a,l,c,h),t.font=`bold ${G+1}px ${q}`}}}Sb.getters=["getClientsToDisplay"],Sb.layers=[6];class Cb extends Hv{allowDispatch(e){if("SORT_CELLS"===e.type){if(!ji(e.col,e.row,e.zone))throw new Error(s("The anchor must be part of the provided zone"));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return 0}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{})}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;return eo(t).some((({col:t,row:i})=>!this.getters.isInMerge({sheetId:e,col:t,row:i})))?63:0}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return 0;const i=this.getters.getMerges(e).filter((e=>Zi(e,t))),o=Qi(i[0]);let[n,s]=[o.numberOfCols,o.numberOfRows];return i.every((e=>{let[t,i]=[e.right-e.left+1,e.bottom-e.top+1];return t===n&&i===s}))?0:63}expand(e,t){const{left:i,right:o,top:n,bottom:s}=this.getters.expandZone(e,t);return{left:Math.max(0,i),right:Math.min(this.getters.getNumberCols(e)-1,o),top:Math.max(0,n),bottom:Math.min(this.getters.getNumberRows(e)-1,s)}}checkExpandedValues(e,t){const i=this.expand(e,t);let o;if(this.getters.doesIntersectMerge(e,i)){const{left:t,right:n,top:s,bottom:r}=i;for(let i=t;i<=n;i++)for(let t=s;t<=r;t++){const{col:n,row:s}=this.getters.getMainCellPosition({sheetId:e,col:i,row:t});if(o=this.getters.getEvaluatedCell({sheetId:e,col:n,row:s}),o.formattedValue)return!0}}else for(let t of this.getters.getEvaluatedCellsInZone(e,i))if(t.formattedValue)return!0;return!1}getContiguousZone(e,t){let i,{top:o,bottom:n,left:s,right:r}=t,a=!1;for(;!a;)a=!0,o>0&&(i=this.checkExpandedValues(e,{left:s-1,right:r+1,top:o-1,bottom:o-1}),i&&(a=!1,o--)),s>0&&(i=this.checkExpandedValues(e,{left:s-1,right:s-1,top:o-1,bottom:n+1}),i&&(a=!1,s--)),r<this.getters.getNumberCols(e)-1&&(i=this.checkExpandedValues(e,{left:r+1,right:r+1,top:o-1,bottom:n+1}),i&&(a=!1,r++)),n<this.getters.getNumberRows(e)-1&&(i=this.checkExpandedValues(e,{left:s-1,right:r+1,top:n+1,bottom:n+1}),i&&(a=!1,n++));return{left:s,right:r,top:o,bottom:n}}hasHeader(e,t){if(1===t[0].length)return!1;let i=t.map((t=>t.map((({col:t,row:i})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:i}).type))));return i[0][0]===on.empty&&(i=i.slice(1)),!i.some((e=>e[0]===on.empty))&&!!i.some((e=>e[1]!==on.empty&&e[0]!==e[1]))}sortZone(e,t,i,o,n){const[s,r]=this.mainCellsSteps(e,i);let a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},i),c=this.mainCells(e,i);!n.sortHeaders&&this.hasHeader(e,c)&&(l.top+=r),c=this.mainCells(e,l);const h=function(e,t,i){const o=e.map(((e,t)=>({index:t,type:e.type,value:e.value})));let n=o.filter((e=>e.type===on.empty)),s=o.filter((e=>e.type!==on.empty));i&&(s.push(...n.map((e=>({...e,type:on.number,value:0})))),n=[]);const r="descending"===t?-1:1;return s.sort(((e,t)=>{let i=Sr.indexOf(e.type)-Sr.indexOf(t.type);return 0===i&&(i=e.type===on.text||e.type===on.error?e.value.localeCompare(t.value):e.value-t.value),r*i})).concat(n)}(c[a-l.left].map((e=>this.getters.getEvaluatedCell(e))),o,Boolean(n.emptyCellAsZero)),d=h.map((e=>e.index)),[u,g]=[c.length,c[0].length],p=[];for(let e=0;e<u;e++){for(let t=0;t<g;t++){let{col:i,row:o,sheetId:n}=c[e][d[t]];const a=this.getters.getCell({sheetId:n,col:i,row:o});let h=l.left+e*s,u=l.top+t*r,g={sheetId:n,col:h,row:u,content:""};if(a){let e=a.content;if(a.isFormula){const t=u-this.getters.getCellPosition(a.id).row,i=this.getters.createAdaptedRanges(a.dependencies,0,t,n);e=this.getters.buildFormulaContent(n,a,i)}g.style=a.style,g.content=e,g.format=a.format}p.push(g)}for(const e of p)this.dispatch("UPDATE_CELL",e)}}mainCellsSteps(e,t){const i=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[i?i.right-i.left+1:1,i?i.bottom-i.top+1:1]}mainCells(e,t){const[i,o]=this.mainCellsSteps(e,t),n=[],s=Be(t.left,t.right+1,i),r=Be(t.top,t.bottom+1,o);for(const t of s){const i=[];n.push(i);for(const o of r)i.push({sheetId:e,col:t,row:o})}return n}}Cb.getters=["getContiguousZone"];class Eb extends Hv{constructor(){super(...arguments),this.showFormulas=!1}handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}Eb.getters=["shouldShowFormulas"];class wb extends Hv{constructor(){super(...arguments),this.ctx=document.createElement("canvas").getContext("2d")}allowDispatch(e){switch(e.type){case"AUTORESIZE_ROWS":case"AUTORESIZE_COLUMNS":try{this.getters.getSheet(e.sheetId);break}catch(e){return 27}}return 0}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(let t of e.cols){const i=this.getColMaxWidth(e.sheetId,t);0!==i&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:i,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":for(let t of e.rows)this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"ROW",size:null,sheetId:e.sheetId})}}getCellWidth(e){const t=this.getCellText(e),i=this.getters.getCellComputedStyle(e),o=t.split(ce);let n=Math.max(...o.map((e=>this.getTextWidth(e,i))));this.getters.getConditionalIcon(e)&&(n+=function(e){return ze(e)+2*P}(this.getters.getCellStyle(e)));if(this.getters.isFilterHeader(e)&&(n+=20),n>0&&(n+=2*z,"wrap"===this.getters.getCellStyle(e).wrapping)){const t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,n)}return n}getTextWidth(e,t){return Le(this.ctx,e,t)}getCellText(e,t=!1){const i=this.getters.getCell(e);return t&&(null==i?void 0:i.isFormula)?i.content:this.getters.getEvaluatedCell(e).formattedValue}getCellMultiLineText(e,t){const i=this.getters.getCellStyle(e),o=this.getters.getCellText(e,this.getters.shouldShowFormulas()),n=[];for(const e of o.split("\n")){const o=e.split(" ");if(!t){n.push(e);continue}let s="",r=t;for(let e of o){const o=this.splitWordToSpecificWidth(this.ctx,e,t,i),a=o.pop(),l=Le(this.ctx,a,i);if(o.length)""!==s&&(n.push(s),s="",r=t),o.forEach((e=>{n.push(e)})),s=a,r=t-l;else{const e=""===s?a:" "+a,o=Le(this.ctx,e,i);o<=r?(s+=e,r-=o):(n.push(s),s=a,r=t-l)}}""!==s&&n.push(s)}return n}getColDimensions(e,t){const i=this.getColRowOffset("COL",0,t,e),o=this.getters.getColSize(e,t);return{start:i,size:o,end:i+(this.getters.isColHidden(e,t)?0:o)}}getRowDimensions(e,t){const i=this.getColRowOffset("ROW",0,t,e),o=this.getters.getRowSize(e,t);return{start:i,size:o,end:i+(this.getters.isRowHidden(e,t)?0:o)}}getColRowOffset(e,t,i,o=this.getters.getActiveSheetId()){if(i<t)return-this.getColRowOffset(e,i,t);let n=0;for(let s=t;s<i;s++)this.getters.isHeaderHidden(o,e,s)||(n+="COL"===e?this.getters.getColSize(o,s):this.getters.getRowSize(o,s));return n}getColMaxWidth(e,t){const i=eo(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,...i)}splitWordToSpecificWidth(e,t,i,o){if(Le(e,t,o)<=i)return[t];const n=[];let s="";for(let r of t){Le(e,s+r,o)>i?(n.push(s),s=r):s+=r}return n.push(s),n}}wb.getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getColDimensions","getRowDimensions","getColRowOffset"];class yb{constructor(e,t,i,o){this.getters=t,this.dispatch=i,this.selection=o,this.operation=e,this.sheetId=t.getActiveSheetId()}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0}addMissingDimensions(e,t,i,o){const n=this.getters.getActiveSheetId(),s=t+o-this.getters.getNumberRows(n);s>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(n)-1,sheetId:n,quantity:s,position:"after"});const r=e+i-this.getters.getNumberCols(n);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(n)-1,sheetId:n,quantity:r,position:"after"})}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class xb extends yb{constructor(e,t,i,o,n){if(super(t,i,o,n),!e.length)return this.cells=[[]],this.zones=[],void(this.copiedTables=[]);const s=new Set(e.map((e=>e.left))),r=new Set(e.map((e=>e.right))),a=new Set(e.map((e=>e.top))),l=new Set(e.map((e=>e.bottom))),c=1===a.size&&1===l.size||1===s.size&&1===r.size?function(e){return e.reduce(((e,t)=>{const i=e.length;for(let o=0;o<i;o++)if(Zi(e[o],t))return e[o]=Wi(e[o],t),e;return e[i]=t,e}),[])}(e):[e[e.length-1]],h=c.map((e=>eo(e))).flat(),d=[...new Set(h.map((e=>e.col)))].sort(((e,t)=>e-t)),u=[...new Set(h.map((e=>e.row)))].sort(((e,t)=>e-t)),g=[],p=i.getActiveSheetId();for(let e of u){let t=[];for(let o of d){const n={col:o,row:e,sheetId:p};t.push({cell:i.getCell(n),style:i.getCellComputedStyle(n),evaluatedCell:i.getEvaluatedCell(n),border:i.getCellBorder(n)||void 0,position:n})}g.push(t)}const m=[];for(const t of e)for(const e of this.getters.getFilterTablesInZone(p,t)){const t=[];for(const i of Be(e.zone.left,e.zone.right+1))t.push(this.getters.getFilterValues({sheetId:p,col:i,row:e.zone.top}));m.push({filtersValues:t,zone:e.zone})}this.cells=g,this.zones=c,this.copiedTables=m}isCutAllowed(e){return 1!==e.length?19:0}isPasteAllowed(e,t){const i=this.getters.getActiveSheetId();if("CUT"===this.operation&&void 0!==(null==t?void 0:t.pasteOption))return 21;if(e.length>1&&(this.cells.length>1||this.cells[0].length>1))return 20;const o=this.cells.length,n=this.cells[0].length;for(let t of this.getPasteZones(e))if(this.getters.doesIntersectMerge(i,t)&&(e.length>1||!this.getters.isSingleCellOrMerge(i,e[0])||o*n!=1))return 2;const{xSplit:s,ySplit:r}=this.getters.getPaneDivisions(i);for(const t of this.getPasteZones(e))if(t.left<s&&t.right>=s||t.top<r&&t.bottom>=r)return 75;return 0}paste(e,t){"COPY"===this.operation?this.pasteFromCopy(e,t):this.pasteFromCut(e,t);const i=this.cells.length,o=this.cells[0].length,n="CUT"===this.operation;(null==t?void 0:t.selectTarget)&&this.selectPastedZone(o,i,n,e)}pasteFromCopy(e,t){if(1===e.length){const i=this.cells.length,o=this.cells[0].length,n=this.pastedZones(e,o,i);for(const e of n)this.pasteZone(e.left,e.top,t)}else for(const i of e)for(let e=i.left;e<=i.right;e++)for(let o=i.top;o<=i.bottom;o++)this.pasteZone(e,o,t);void 0===(null==t?void 0:t.pasteOption)&&this.pasteCopiedTables(e)}pasteFromCut(e,t){this.clearClippedZones();const i=e[0];this.pasteZone(i.left,i.top,t),this.dispatch("MOVE_RANGES",{target:this.zones,sheetId:this.sheetId,targetSheetId:this.getters.getActiveSheetId(),col:i.left,row:i.top});for(const e of this.copiedTables)this.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.getters.getActiveSheetId(),target:[e.zone]});this.pasteCopiedTables(e)}pastedZones(e,t,i){const o=e[0],n=Math.max(1,Math.floor((o.right+1-o.left)/t)),s=Math.max(1,Math.floor((o.bottom+1-o.top)/i)),r=[];for(let e=0;e<n;e++)for(let n=0;n<s;n++){const s=o.top+n*i,a=o.left+e*t;r.push({left:a,top:s,bottom:s+i-1,right:a+t-1})}return r}getPasteZones(e){const t=this.cells;if(!t.length||!t[0].length)return e;const i=[],o=t.length,n=t[0].length,s=e[e.length-1],r=s.left,a=s.top,l=Math.max(1,Math.floor((s.right+1-r)/n)),c=Math.max(1,Math.floor((s.bottom+1-a)/o));for(let e=1;e<=l;e++)for(let t=1;t<=c;t++)i.push({left:r,top:a,right:r-1+e*n,bottom:a-1+t*o});return i}selectPastedZone(e,t,i,o){const n=o[0],s=n.left,r=n.top;if(t>1||e>1||i){const n=this.pastedZones(o,e,t),a=i?n[0]:Wi(...n);this.selection.selectZone({cell:{col:s,row:r},zone:a})}}clearClippedZones(){for(const e of this.cells)for(const t of e)t.cell&&this.dispatch("CLEAR_CELL",t.position);this.dispatch("CLEAR_FORMATTING",{sheetId:this.sheetId,target:this.zones})}pasteZone(e,t,i){const o=this.cells.length,n=this.cells[0].length,s="onlyValue"!==(null==i?void 0:i.pasteOption)&&(null==i?void 0:i.shouldPasteCF),r=this.getters.getActiveSheetId();this.addMissingDimensions(n,o,e,t);for(let a=0;a<o;a++){const o=this.cells[a];for(let l=0;l<n;l++){const n=o[l],c={col:e+l,row:t+a,sheetId:r};"CUT"!==this.operation&&this.pasteMergeIfExist(n.position,c),this.pasteCell(n,c,this.operation,i),s&&this.dispatch("PASTE_CONDITIONAL_FORMAT",{origin:n.position,target:c,operation:this.operation})}}}pasteCell(e,t,i,o){const{sheetId:n,col:s,row:r}=t,a=this.getters.getEvaluatedCell(t);if("onlyValue"!==(null==o?void 0:o.pasteOption)){const i=this.getters.getCellBorder(t),o=e.border,a={top:(null==i?void 0:i.top)||(null==o?void 0:o.top),bottom:(null==i?void 0:i.bottom)||(null==o?void 0:o.bottom),left:(null==i?void 0:i.left)||(null==o?void 0:o.left),right:(null==i?void 0:i.right)||(null==o?void 0:o.right)};this.dispatch("SET_BORDER",{sheetId:n,col:s,row:r,border:a})}if(e.cell){if("onlyFormat"===(null==o?void 0:o.pasteOption))return void this.dispatch("UPDATE_CELL",{...t,style:e.cell.style,format:e.evaluatedCell.format});if("onlyValue"===(null==o?void 0:o.pasteOption)){const i=di(e.evaluatedCell.value);return void this.dispatch("UPDATE_CELL",{...t,content:i})}let a=e.cell.content;if(e.cell.isFormula&&"COPY"===i){const t=s-e.position.col,o=r-e.position.row;a=this.getUpdatedContent(n,e.cell,t,o,i)}this.dispatch("UPDATE_CELL",{...t,content:a,style:e.cell.style||null,format:e.cell.format})}else a&&("onlyValue"===(null==o?void 0:o.pasteOption)?this.dispatch("UPDATE_CELL",{...t,content:""}):"onlyFormat"===(null==o?void 0:o.pasteOption)?this.dispatch("UPDATE_CELL",{...t,style:null,format:""}):this.dispatch("CLEAR_CELL",t))}getUpdatedContent(e,t,i,o,n){const s=this.getters.createAdaptedRanges(t.dependencies,i,o,e);return this.getters.buildFormulaContent(e,t,s)}pasteMergeIfExist(e,t){let{sheetId:i,col:o,row:n}=e;const{col:s,row:r}=this.getters.getMainCellPosition(e);if(s===o&&r===n){const s=this.getters.getMerge(e);if(!s)return;({sheetId:i,col:o,row:n}=t),this.dispatch("ADD_MERGE",{sheetId:i,force:!0,target:[{left:o,top:n,right:o+s.right-s.left,bottom:n+s.bottom-s.top}]})}}pasteCopiedTables(e){const t=this.getters.getActiveSheetId(),i=e[0],o=this.zones[0],n=[i.left-o.left,i.top-o.top];for(const e of this.copiedTables){const i=to(e.zone,"both","MOVE",n);this.dispatch("CREATE_FILTER_TABLE",{sheetId:t,target:[i]});for(const o of Be(0,e.filtersValues.length))this.dispatch("UPDATE_FILTER",{sheetId:t,col:i.left+o,row:i.top,values:e.filtersValues[o]})}}getClipboardContent(){return{[nn.PlainText]:this.getPlainTextContent(),[nn.Html]:this.getHTMLContent()}}getPlainTextContent(){return this.cells.map((e=>e.map((e=>e.cell?this.getters.getCellText(e.position,this.getters.shouldShowFormulas()):"")).join("\t"))).join("\n")||"\t"}getHTMLContent(){if(1==this.cells.length&&1==this.cells[0].length)return this.getters.getCellText(this.cells[0][0].position);let e='<table border="1" style="border-collapse:collapse">';for(const t of this.cells){e+="<tr>";for(const i of t){e+=`<td style="${fo(po(i.style))}">`+Gf(this.getters.getCellText(i.position))+"</td>"}e+="</tr>"}return e+="</table>",e}isColRowDirtyingClipboard(e,t){if(!this.zones)return!1;for(let i of this.zones){if("COL"===t&&e<=i.right)return!0;if("ROW"===t&&e<=i.bottom)return!0}return!1}drawClipboard(e){const{ctx:t,thinLineWidth:i}=e;if(this.sheetId===this.getters.getActiveSheetId()&&this.zones&&this.zones.length){t.setLineDash([8,5]),t.strokeStyle=E,t.lineWidth=3.3*i;for(const e of this.zones){const{x:i,y:o,width:n,height:s}=this.getters.getVisibleRect(e);n>0&&s>0&&t.strokeRect(i,o,n,s)}}}}class Ib{constructor(e,t,i){this.operation=e,this.getters=t,this.dispatch=i,this.sheetId=t.getActiveSheetId();const o=t.getSelectedFigureId();if(!o)throw new Error("No figure selected");const n=t.getFigure(this.sheetId,o);if(!n)throw new Error(`No figure for the given id: ${o}`);switch(this.copiedFigure={...n},n.tag){case"chart":this.copiedFigureContent=new Rb(i,t,this.sheetId,o);break;case"image":this.copiedFigureContent=new Tb(i,t,this.sheetId,o);break;default:throw new Error(`Unknow tag '${n.tag}' for the given figure id: ${o}`)}}isCutAllowed(e){return 0}isPasteAllowed(e,t){return 0===e.length?73:void 0!==(null==t?void 0:t.pasteOption)?22:0}paste(e){const t=this.getters.getActiveSheetId(),i={x:this.getters.getColDimensions(t,e[0].left).start,y:this.getters.getRowDimensions(t,e[0].top).start},o={height:this.copiedFigure.height,width:this.copiedFigure.width},n=(new ki).uuidv4();this.copiedFigureContent.paste(t,n,i,o),"CUT"===this.operation&&this.dispatch("DELETE_FIGURE",{sheetId:this.copiedFigureContent.sheetId,id:this.copiedFigure.id}),this.dispatch("SELECT_FIGURE",{id:n})}getClipboardContent(){return{[nn.PlainText]:"\t"}}isColRowDirtyingClipboard(e,t){return!1}drawClipboard(e){}}class Rb{constructor(e,t,i,o){this.dispatch=e,this.sheetId=i;const n=t.getChart(o);if(!n)throw new Error(`No chart for the given id: ${o}`);this.copiedChart=n.copyInSheetId(i)}paste(e,t,i,o){const n=this.copiedChart.copyInSheetId(e);this.dispatch("CREATE_CHART",{id:t,sheetId:e,position:i,size:o,definition:n.getDefinition()})}}class Tb{constructor(e,t,i,o){this.dispatch=e,this.sheetId=i;const n=t.getImage(o);this.copiedImage=Ne(n)}paste(e,t,i,o){const n=Ne(this.copiedImage);this.dispatch("CREATE_IMAGE",{figureId:t,sheetId:e,position:i,size:o,definition:n})}}class Ab extends yb{constructor(e,t,i,o){super("COPY",t,i,o),this.values=e.replace(/\r/g,"").split("\n").map((e=>e.split("\t")))}isPasteAllowed(e,t){const i=this.getters.getActiveSheetId(),o=this.getPasteZone(e);return this.getters.doesIntersectMerge(i,o)?2:0}paste(e){const t=this.values,i=this.getPasteZone(e),{left:o,top:n}=i,{numberOfCols:s,numberOfRows:r}=Qi(i),a=this.getters.getActiveSheetId();this.addMissingDimensions(s,r,o,n);for(let e=0;e<t.length;e++)for(let i=0;i<t[e].length;i++)this.dispatch("UPDATE_CELL",{row:n+e,col:o+i,content:t[e][i],sheetId:a});const l={left:o,top:n,right:o+s-1,bottom:n+r-1};this.selection.selectZone({cell:{col:o,row:n},zone:l})}getClipboardContent(){return{[nn.PlainText]:this.values.map((e=>e.join("\t"))).join("\n")}}getPasteZone(e){const t=this.values.length,i=Math.max(...this.values.map((e=>e.length))),{left:o,top:n}=e[0];return{top:n,left:o,bottom:n+t-1,right:o+i-1}}}class Mb extends Hv{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 i=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);return this.state.isPasteAllowed(e.target,{pasteOption:i});case"PASTE_FROM_OS_CLIPBOARD":return new Ab(e.text,this.getters,this.dispatch,this.selection).isPasteAllowed(e.target);case"INSERT_CELL":{const{cut:t,paste:i}=this.getInsertCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(i)}case"DELETE_CELL":{const{cut:t,paste:i}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);return this.getClipboardStateForCopyCells(t,"CUT").isPasteAllowed(i)}}return 0}handle(e){var t,i;switch(e.type){case"COPY":case"CUT":const o="target"in e&&e.target||this.getters.getSelectedZones();this.state=this.getClipboardState(o,e.type),this.status="visible";break;case"PASTE":if(!this.state)break;const n=e.pasteOption||(this._isPaintingFormat?"onlyFormat":void 0);this._isPaintingFormat=!1,this.state.paste(e.target,{pasteOption:n,shouldPasteCF:!0,selectTarget:!0}),"CUT"===this.state.operation&&(this.state=void 0),this.status="invisible";break;case"CLEAN_CLIPBOARD_HIGHLIGHT":this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:i}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!Ui(t[0])){for(const{col:t,row:i}of eo(e.zone))this.dispatch("CLEAR_CELL",{col:t,row:i,sheetId:this.getters.getActiveSheetId()});break}this.getClipboardStateForCopyCells(t,"CUT").paste(i);break}case"INSERT_CELL":{const{cut:t,paste:i}=this.getInsertCellsTargets(e.zone,e.shiftDimension);this.getClipboardStateForCopyCells(t,"CUT").paste(i);break}case"ADD_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(t=this.state)||void 0===t?void 0:t.operation))return;this.state.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.state=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible","CUT"!==(null===(i=this.state)||void 0===i?void 0:i.operation))return;for(let t of e.elements){if(this.state.isColRowDirtyingClipboard(t,e.dimension)){this.state=void 0;break}}this.status="invisible";break;case"PASTE_FROM_OS_CLIPBOARD":new Ab(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:cn(e)&&(this.status="invisible")}}getClipboardContent(){var e;return(null===(e=this.state)||void 0===e?void 0:e.getClipboardContent())||{[nn.PlainText]:"\t"}}getClipboardTextContent(){var e;return(null===(e=this.state)||void 0===e?void 0:e.getClipboardContent()[nn.PlainText])||"\t"}isCutOperation(){return!!this.state&&"CUT"===this.state.operation}isPaintingFormat(){return this._isPaintingFormat}getDeleteCellsTargets(e,t){const i=this.getters.getActiveSheetId();let o;return o="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(i)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(i)-1},{cut:[o],paste:[e]}}getInsertCellsTargets(e,t){const i=this.getters.getActiveSheetId();let o,n;return"COL"===t?(o={...e,right:this.getters.getNumberCols(i)-1},n={...e,left:e.right+1,right:e.right+1}):(o={...e,bottom:this.getters.getNumberRows(i)-1},n={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(i)-1}),{cut:[o],paste:[n]}}getClipboardStateForCopyCells(e,t){return new xb(e,t,this.getters,this.dispatch,this.selection)}getClipboardState(e,t){return this.getters.getSelectedFigureId()?new Ib(t,this.getters,this.dispatch):new xb(e,t,this.getters,this.dispatch,this.selection)}drawGrid(e){"visible"===this.status&&this.state&&this.state.drawClipboard(e)}}function Ob(e){if("REFERENCE"!==e.type)return e;const{xc:t,sheetName:i}=Ut(e.value),[o,n]=t.split(":"),s=i?`${Fe(i)}!`:"",r=Nb(o),a=n?`:${Nb(n)}`:"";return{...e,value:s+r+a}}function Nb(e){switch(function(e){if(function(e){return e.startsWith("$")&&e.length>1&&e.slice(1).includes("$")}(e))return"colrow";if(function(e){return e.startsWith("$")}(e))return"col";if(function(e){return e.includes("$",1)}(e))return"row";return"none"}(e)){case"none":e=_b(e,"colrow");break;case"colrow":e=_b(e,"row");break;case"row":e=_b(e,"col");break;case"col":e=_b(e,"none")}return e}function _b(e,t){let i;switch(e=e.replace(/\$/g,""),t){case"col":return"$"+e;case"row":return i=e.search(/[0-9]/),e.slice(0,i)+"$"+e.slice(i);case"colrow":return i=e.search(/[0-9]/),"$"+(e=e.slice(0,i)+"$"+e.slice(i));case"none":return e}}Mb.layers=[2],Mb.getters=["getClipboardContent","getClipboardTextContent","isCutOperation","isPaintingFormat"];const Fb=s("The cell you are trying to edit has been deleted.");class Db extends Hv{constructor(){super(...arguments),this.col=0,this.row=0,this.mode="inactive",this.sheetId="",this.currentContent="",this.currentTokens=[],this.selectionStart=0,this.selectionEnd=0,this.selectionInitialStart=0,this.initialContent="",this.previousRef="",this.previousRange=void 0,this.colorIndexByRange={}}allowDispatch(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":return this.validateSelection(this.currentContent.length,e.start,e.end);case"SET_CURRENT_CONTENT":return e.selection?this.validateSelection(e.content.length,e.selection.start,e.selection.end):0;case"START_EDITION":if(e.selection){const t=e.text||this.getComposerContent(this.getters.getActivePosition());return this.validateSelection(t.length,e.selection.start,e.selection.end)}return 0;default:return 0}}handleEvent(e){if("selecting"===this.mode)if("newAnchor"===e.mode)this.insertSelectedRange(e.anchor.zone);else this.replaceSelectedRanges(e.anchor.zone)}handle(e){switch(e.type){case"CHANGE_COMPOSER_CURSOR_SELECTION":this.selectionStart=e.start,this.selectionEnd=e.end;break;case"STOP_COMPOSER_RANGE_SELECTION":this.isSelectingForComposer()&&(this.mode="editing");break;case"START_EDITION":"inactive"!==this.mode&&e.text?this.setContent(e.text,e.selection):this.startEdition(e.text,e.selection),this.updateRangeColor();break;case"STOP_EDITION":e.cancel?(this.cancelEditionAndActivateSheet(),this.resetContent()):this.stopEdition(),this.colorIndexByRange={};break;case"SET_CURRENT_CONTENT":this.setContent(e.content,e.selection,!0),this.updateRangeColor();break;case"REPLACE_COMPOSER_CURSOR_SELECTION":this.replaceSelection(e.text);break;case"SELECT_FIGURE":this.cancelEditionAndActivateSheet(),this.resetContent();break;case"ADD_COLUMNS_ROWS":this.onAddElements(e);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case"START_CHANGE_HIGHLIGHT":this.dispatch("STOP_COMPOSER_RANGE_SELECTION");const t=this.getters.getRangeFromRangeData(e.range),i=this.currentTokens.filter((e=>"REFERENCE"===e.type)).find((e=>{const{xc:i,sheetName:o}=Ut(e.value),n=o||this.getters.getSheetName(this.sheetId),s=this.getters.getActiveSheetId();if(this.getters.getSheetName(s)!==n)return!1;const r=this.getters.getRangeFromSheetXC(s,i);return qi(this.getters.expandZone(s,r.zone),t.zone)}));this.previousRef=i.value,this.previousRange=this.getters.getRangeFromSheetXC(this.getters.getActiveSheetId(),this.previousRef),this.selectionInitialStart=i.start;break;case"CHANGE_HIGHLIGHT":const o=this.getters.getRangeFromRangeData(e.range),n=this.getRangeReference(o,this.previousRange.parts);this.selectionStart=this.selectionInitialStart,this.selectionEnd=this.selectionInitialStart+this.previousRef.length,this.replaceSelection(n),this.previousRef=n,this.selectionStart=this.currentContent.length,this.selectionEnd=this.currentContent.length;break;case"ACTIVATE_SHEET":if(this.currentContent.startsWith("=")||(this.cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){const t=this.getters.getActivePosition(),{col:i,row:o}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),n=this.getters.expandZone(e.sheetIdTo,no({col:i,row:o}));this.selection.resetAnchor(this,{cell:{col:i,row:o},zone:n})}break;case"DELETE_SHEET":case"UNDO":case"REDO":!!this.getters.tryGetSheet(this.sheetId)||"inactive"===this.mode||(this.sheetId=this.getters.getActiveSheetId(),this.cancelEditionAndActivateSheet(),this.resetContent(),this.ui.notifyUI({type:"ERROR",text:Fb}));break;case"CYCLE_EDITION_REFERENCES":this.cycleReferences()}}getEditionMode(){return this.mode}getCurrentContent(){return"inactive"===this.mode?this.getComposerContent(this.getters.getActivePosition()):this.currentContent}getEditionSheet(){return this.sheetId}getComposerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}getCurrentEditedCell(){return{sheetId:this.sheetId,col:this.col,row:this.row}}isSelectingForComposer(){return"selecting"===this.mode}showSelectionIndicator(){return this.isSelectingForComposer()&&this.canStartComposerRangeSelection()}getCurrentTokens(){return this.currentTokens}getTokenAtCursor(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return e===t&&0===t?void 0:this.currentTokens.find((i=>i.start<=e&&i.end>=t))}cycleReferences(){const e=this.getTokensInSelection(),t=e.filter((e=>"REFERENCE"===e.type));if(0===t.length)return;const i=e.map(Ob).map((e=>e.value)).join(""),o=this.currentContent,n=e[0].start,s=e[e.length-1].end,r=o.slice(0,n)+i+o.slice(s),a=r.length-o.length,l={start:t[0].start,end:t[t.length-1].end+a};1===t.length&&this.selectionStart===this.selectionEnd&&(l.start=l.end),this.dispatch("SET_CURRENT_CONTENT",{content:r,selection:l})}validateSelection(e,t,i){return t>=0&&t<=e&&i>=0&&i<=e?0:46}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:Fb});const{top:t,left:i}=Hi({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",[...e.elements]);this.col=i,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.mode)return this.dispatch("STOP_EDITION",{cancel:!0}),void this.ui.notifyUI({type:"ERROR",text:Fb});const{top:t,left:i}=Hi({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",[...e.elements]);this.col=i,this.row=t}onAddElements(e){const{top:t,left:i}=Bi({left:this.col,right:this.col,top:this.row,bottom:this.row},"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.col=i,this.row=t}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){const e=no({col:this.col,row:this.row});this.selection.resetAnchor(this,{cell:{col:this.col,row:this.row},zone:e})}this.mode="selecting",this.selectionInitialStart=this.selectionStart}startEdition(e,t){var i;const o=this.getters.getActiveCell();e&&(null===(i=o.format)||void 0===i?void 0:i.includes("%"))&&Jt(e)&&(t=t||{start:e.length,end:e.length},e=`${e}%`);const{col:n,row:s,sheetId:r}=this.getters.getActivePosition();this.col=n,this.sheetId=r,this.row=s,this.initialContent=this.getComposerContent({sheetId:r,col:n,row:s}),this.mode="editing",this.setContent(e||this.initialContent,t),this.colorIndexByRange={};const a=no({col:this.col,row:this.row});this.selection.capture(this,{cell:{col:this.col,row:this.row},zone:a},{handleEvent:this.handleEvent.bind(this),release:()=>{this.stopEdition()}})}stopEdition(){if("inactive"!==this.mode){this.cancelEditionAndActivateSheet();const e=this.col,t=this.row;let i=this.currentContent;if(!(this.initialContent!==i))return;if(i){const o=this.getters.getActiveSheetId(),n=this.getters.getEvaluatedCell({sheetId:o,col:this.col,row:this.row});if(i.startsWith("=")){const e=this.currentTokens.filter((e=>"LEFT_PAREN"===e.type)).length,t=this.currentTokens.filter((e=>"RIGHT_PAREN"===e.type)).length,o=e-t;o>0&&(i+=nt(new Array(o).fill(")")))}else n.link&&(i=Xe(i,n.link.url));this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,col:e,row:t,content:i})}else this.dispatch("UPDATE_CELL",{sheetId:this.sheetId,content:"",col:e,row:t});this.setContent("")}}cancelEditionAndActivateSheet(){if("inactive"===this.mode)return;this.cancelEdition();this.getters.getActiveSheetId()!==this.sheetId&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheetId})}getComposerContent(e){const t=this.getters.getCell(e);if(null==t?void 0:t.isFormula)return t.content;const{format:i,value:o,type:n,formattedValue:s}=this.getters.getEvaluatedCell(e);switch(n){case on.text:case on.empty:return o;case on.boolean:return s;case on.error:return(null==t?void 0:t.content)||"";case on.number:return i&&vi(i)?s:this.numberComposerContent(o,i)}}numberComposerContent(e,t){return(null==t?void 0:t.includes("%"))?100*e+"%":function(e){const{integerDigits:t,decimalDigits:i}=pi(e,20);return i?`${t}.${i}`:t}(e)}cancelEdition(){"inactive"!==this.mode&&(this.mode="inactive",this.selection.release(this))}resetContent(){this.setContent(this.initialContent||"")}setContent(e,t,i){const o=this.currentContent!==e;this.currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,(o||"inactive"!==this.mode)&&(this.currentTokens=e.startsWith("=")?af(e):[],this.currentTokens.length>100&&i&&this.ui.notifyUI({type:"ERROR",text:s("This formula has over 100 parts. It can't be processed properly, consider splitting it into multiple cells")})),this.canStartComposerRangeSelection()&&this.startComposerRangeSelection()}insertSelectedRange(e){const t=Math.min(this.selectionStart,this.selectionEnd),i=this.getZoneReference(e);this.canStartComposerRangeSelection()?(this.insertText(i,t),this.selectionInitialStart=t):(this.insertText(","+i,t),this.selectionInitialStart=t+1)}replaceSelectedRanges(e){const t=this.getZoneReference(e);this.replaceText(t,this.selectionInitialStart,this.selectionEnd)}getZoneReference(e,t=[{colFixed:!1,rowFixed:!1}]){const i=this.getters.getActiveSheetId();let o=this.getters.zoneToXC(i,e,t);if(this.getters.getEditionSheet()!==this.getters.getActiveSheetId()){o=`${Fe(this.getters.getSheetName(this.getters.getActiveSheetId()))}!${o}`}return o}getRangeReference(e,t=[{colFixed:!1,rowFixed:!1}]){let i=[...t];1===t.length&&ro(e.zone)>1?i.push({...t[0]}):2===t.length&&1===ro(e.zone)&&i.pop();const o=e.clone({parts:i});return this.getters.getSelectionRangeString(o,this.getters.getEditionSheet())}replaceSelection(e){const t=Math.min(this.selectionStart,this.selectionEnd),i=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,i)}replaceText(e,t,i){this.currentContent=this.currentContent.slice(0,t)+this.currentContent.slice(i,this.currentContent.length),this.insertText(e,t)}insertText(e,t){const i=this.currentContent.slice(0,t)+e+this.currentContent.slice(t),o=t+e.length;this.dispatch("SET_CURRENT_CONTENT",{content:i,selection:{start:o,end:o}})}updateRangeColor(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return;const e=this.getters.getEditionSheet(),t=this.getReferencedRanges().map((t=>this.getters.getRangeString(t,e))),i={};for(const e of t)void 0!==this.colorIndexByRange[e]&&(i[e]=this.colorIndexByRange[e]);const o=new Set(Object.values(i));let n=0;const s=()=>{for(;o.has(n);)n++;return o.add(n),n};for(const e of t){const t=e in i?i[e]:s();i[e]=t}this.colorIndexByRange=i}getComposerHighlights(){if(!this.currentContent.startsWith("=")||"inactive"===this.mode)return[];const e=this.getters.getEditionSheet(),t=e=>{const t=this.colorIndexByRange[e];return vt[t%vt.length]};return this.getReferencedRanges().map((i=>{const o=this.getters.getRangeString(i,e);return{zone:i.zone,color:t(o),sheetId:i.sheetId}}))}getReferencedRanges(){const e=this.getters.getEditionSheet();return this.currentTokens.filter((e=>"REFERENCE"===e.type)).map((t=>this.getters.getRangeFromSheetXC(e,t.value)))}canStartComposerRangeSelection(){if(this.currentContent.startsWith("=")){const e=this.getTokenAtCursor();if(!e)return!1;const t=this.currentTokens.map((e=>e.start)).indexOf(e.start);let i=t,o=e;for(;!["COMMA","LEFT_PAREN","OPERATOR"].includes(o.type)||Cm.includes(o.value);){if("SPACE"!==o.type||i<1)return!1;i--,o=this.currentTokens[i]}for(i=t+1,o=this.currentTokens[i];o&&!["COMMA","RIGHT_PAREN","OPERATOR"].includes(o.type);){if("SPACE"!==o.type)return!1;i++,o=this.currentTokens[i]}return!0}return!1}getTokensInSelection(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return this.currentTokens.filter((i=>i.start<=e&&i.end>=e||i.start>=e&&i.start<t))}}Db.getters=["getEditionMode","isSelectingForComposer","showSelectionIndicator","getCurrentContent","getEditionSheet","getComposerSelection","getCurrentTokens","getTokenAtCursor","getComposerHighlights","getCurrentEditedCell"];const kb=[{name:s("Sum"),types:[on.number],compute:e=>ll.compute([e])},{name:s("Avg"),types:[on.number],compute:e=>Sl.compute([e])},{name:s("Min"),types:[on.number],compute:e=>Ll.compute([e])},{name:s("Max"),types:[on.number],compute:e=>_l.compute([e])},{name:s("Count"),types:[on.number,on.text,on.boolean,on.error],compute:e=>Tl.compute([e])},{name:s("Count Numbers"),types:[on.number,on.text,on.boolean,on.error],compute:e=>Rl.compute([e])}];class Lb extends Hv{constructor(e){super(e),this.gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]},this.selectedFigureId=null,this.sheetsData={},this.activeSheet=null,this.moveClient=e.moveClient}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{this.getters.getSheet(e.sheetIdTo);break}catch(e){return 27}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return 0}handleEvent(e){const t=e.anchor;let i=[];switch(e.mode){case"overrideSelection":i=[t.zone];break;case"updateAnchor":i=[...this.gridSelection.zones];const o=i.findIndex((t=>qi(t,e.previousAnchor.zone)));o>=0&&(i[o]=t.zone);break;case"newAnchor":i=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,i),this.selection.resetDefaultAnchor(this,Ne(this.gridSelection.anchor));const{col:o,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:o,row:n}),this.selectedFigureId=null}handle(e){switch(e.type){case"START_EDITION":case"ACTIVATE_SHEET":this.selectedFigureId=null;break;case"DELETE_FIGURE":this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;case"DELETE_SHEET":this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null)}switch(e.type){case"START":const t=this.getters.getVisibleSheetIds()[0];this.dispatch("ACTIVATE_SHEET",{sheetIdTo:t,sheetIdFrom:t});const{col:i,row:o}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(i,o),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case"ACTIVATE_SHEET":if(this.getters.isSheetVisible(e.sheetIdTo)||this.dispatch("SHOW_SHEET",{sheetId:e.sheetIdTo}),this.setActiveSheet(e.sheetIdTo),this.sheetsData[e.sheetIdFrom]={gridSelection:Ne(this.gridSelection)},e.sheetIdTo in this.sheetsData)Object.assign(this,this.sheetsData[e.sheetIdTo]),this.selection.resetDefaultAnchor(this,Ne(this.gridSelection.anchor));else{const{col:t,row:i}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0});this.selectCell(t,i)}break;case"REMOVE_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);const{col:i,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:i,row:o})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:i,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:i,row:o})}break}case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"SELECT_FIGURE":this.selectedFigureId=e.id;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left");break;case"HIDE_SHEET":e.sheetId===this.getActiveSheetId()&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case"UNDO":case"REDO":case"DELETE_SHEET":const n=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of n)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:Ne(t)}}if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){const e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){const{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);const{col:t,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:i})}const s=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map((e=>this.getters.expandZone(s,e))),this.gridSelection.anchor.zone=this.getters.expandZone(s,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones)}this.selection.resetDefaultAnchor(this,Ne(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 i=t.left;i<=t.right;i++)e.add(i);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(let i of this.gridSelection.zones)if(0===i.left&&i.right===this.getters.getNumberCols(t)-1)for(let t=i.top;t<=i.bottom;t++)e.add(t);return e}getCurrentStyle(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return Ne(this.gridSelection.zones)}getSelectedZone(){return Ne(this.gridSelection.anchor.zone)}getSelection(){return Ne(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!==on.empty)));let t=new Set,i=[];for(let o of e)t.add(o.type),i.push(o.value);let o={};for(let e of kb){let n;e.types.some((e=>t.has(e)))&&(n=e.compute(i)),o[e.name]=n}return o}getAggregate(){let e=0,t=0;const i=this.getters.getActiveSheetId(),o=this.gridSelection.zones.map(eo).flat();for(const{col:n,row:s}of o){const o=this.getters.getEvaluatedCell({sheetId:i,col:n,row:s});o.type===on.number&&(t++,e+=o.value)}return t<2?null:di(e)}isSelected(e){return!!this.getters.getSelectedZones().find((t=>qi(t,e)))}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let i=[];const o="COL"===e?"left":"top",n="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[n]-e[o]+1},((t,i)=>e[o]+i));i=i.concat(t)}return[...new Set(i)].sort()}setSelectionMixin(e,t){const{anchor:i,zones:o}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=i,this.gridSelection.zones=function(e){return e.reverse().filter(((e,t,i)=>t===i.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}(o)}selectCell(e,t){const i=this.getters.getActiveSheetId(),o=this.getters.expandZone(i,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:o,cell:{col:e,row:t}},[o])}setActiveSheet(e){const t=this.getters.getSheet(e);this.activeSheet=t}activateNextSheet(e){const t=this.getters.getSheetIds(),i=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[i]})}onColumnsRemoved(e){const{cell:t,zone:i}=this.gridSelection.anchor,o=Hi(i,"left",[...e.elements]);let n={left:t.col,right:t.col,top:t.row,bottom:t.row};n=Hi(n,"left",[...e.elements]);const s={cell:{col:n.left,row:n.top},zone:o};this.setSelectionMixin(s,[o])}onRowsRemoved(e){const{cell:t,zone:i}=this.gridSelection.anchor,o=Hi(i,"top",[...e.elements]);let n={left:t.col,right:t.col,top:t.row,bottom:t.row};n=Hi(n,"top",[...e.elements]);const s={cell:{col:n.left,row:n.top},zone:o};this.setSelectionMixin(s,[o])}onAddElements(e){const t=Bi(this.gridSelection.anchor.zone,"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity),i={cell:{col:t.left,row:t.top},zone:t};this.setSelectionMixin(i,[t])}onMoveElements(e){const t=e.elements.length;this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:"before"});const i="COL"===e.dimension,o=e.elements[0],n=e.elements[t-1],s=e.base<o,r=s&&i?t:0,a=s&&!i?t:0;this.dispatch("CUT",{target:[{left:i?o+r:0,right:i?n+r:this.getters.getNumberCols(e.sheetId)-1,top:i?0:o+a,bottom:i?this.getters.getNumberRows(e.sheetId)-1:n+a}]}),this.dispatch("PASTE",{target:[{left:i?e.base:0,right:i?e.base+t-1:this.getters.getNumberCols(e.sheetId)-1,top:i?0:e.base,bottom:i?this.getters.getNumberRows(e.sheetId)-1:e.base+t-1}]});const l=s?e.elements.map((e=>e+t)):e.elements;let c=e.base;for(const t of l){const i="COL"===e.dimension?this.getters.getColSize(e.sheetId,t):this.getters.getRowSize(e.sheetId,t);this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:i,elements:[c]}),c+=1}this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,elements:l})}isMoveElementAllowed(e){const t="COL"===e.dimension,i=e.elements[0],o=e.elements[e.elements.length-1],n=e.sheetId,s=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;return s(n,i-1,i)||s(n,o,o+1)||s(n,e.base-1,e.base)?2:0}clipSelection(e,t){const i=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;return{zones:t.zones.map((e=>({left:De(e.left,0,i),right:De(e.right,0,i),top:De(e.top,0,o),bottom:De(e.bottom,0,o)}))),anchor:{cell:{col:De(t.anchor.cell.col,0,i),row:De(t.anchor.cell.row,0,o)},zone:{left:De(t.anchor.zone.left,0,i),right:De(t.anchor.zone.right,0,i),top:De(t.anchor.zone.top,0,o),bottom:De(t.anchor.zone.bottom,0,o)}}}}drawGrid(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:i}=e,o=this.getSelectedZones();t.fillStyle="#f3f7fe";const n=1===o.length&&o[0].left===o[0].right&&o[0].top===o[0].bottom;t.fillStyle=n?"#f3f7fe":"#e9f0ff",t.strokeStyle=E,t.lineWidth=1.5*i;for(const e of o){const{x:i,y:o,width:n,height:s}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(i,o,n,s),t.globalCompositeOperation="source-over",t.strokeRect(i,o,n,s)}t.globalCompositeOperation="source-over";const s=this.getActivePosition();let r;t.strokeStyle=E,t.lineWidth=3*i,r=this.getters.isInMerge(s)?this.getters.getMerge(s):no(s);const{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);c>0&&h>0&&t.strokeRect(a,l,c,h)}}Lb.layers=[6],Lb.getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getStatisticFnResults","getAggregate","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSelected","getElementsFromSelection"];const Pb=(new Eo).add("sheet",Bv).add("header visibility",kv).add("filters",Fv).add("cell",Rv).add("merge",Pv).add("headerSize",Dv).add("borders",Iv).add("conditional formatting",Mv).add("figures",Ov).add("chart",Tv).add("image",Lv),Ub=(new Eo).add("ui_sheet",wb).add("header_visibility_ui",ob).add("ui_options",Eb).add("selectionInputManager",ab).add("highlight",nb).add("grid renderer",sb).add("autofill",Qv).add("find_and_replace",ib).add("sort",Cb).add("automatic_sum",Jv).add("format",class extends Hv{handle(e){if("SET_DECIMAL"===e.type)this.setDecimal(e.sheetId,e.target,e.step)}setDecimal(e,t,i){for(const o of t)for(const t of eo(o)){const o=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==o){const n=xi(o,i);this.dispatch("SET_FORMATTING",{sheetId:e,target:[no(t)],format:n})}}}getCellNumberFormat(e){var t;for(const i of[e]){const e=this.getters.getEvaluatedCell(i);if(e.type===on.number&&!(null===(t=e.format)||void 0===t?void 0:t.match(X)))return e.format||Ei(e.value)}}}).add("cell_popovers",eb).add("selection_multiuser",Sb),Vb=(new Eo).add("selection",Lb).add("clipboard",Mb).add("edition",Db),zb=(new Eo).add("evaluation",Gv).add("evaluation_filter",jv).add("evaluation_chart",qv).add("evaluation_cf",Zv).add("viewport",Yv).add("custom_colors",$v),Bb=new Eo;Bb.add("link",{condition:(e,t)=>!!t.model.getters.getEvaluatedCell(e).link,action:(e,t)=>Ao(t.model.getters.getEvaluatedCell(e).link,t),sequence:5});class Hb{constructor(e){this.fileStore=e}async requestImage(){const e=await this.getImageFromUser(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageSize(t),mimetype:e.type}}getImageFromUser(){return new Promise(((e,t)=>{const i=document.createElement("input");i.setAttribute("type","file"),i.setAttribute("accept","image/*"),i.addEventListener("change",(async()=>{null===i.files||1!=i.files.length?t():e(i.files[0])})),i.click()}))}getImageSize(e){return new Promise(((t,i)=>{const o=new Image;o.src=e,o.addEventListener("load",(()=>{const e={width:o.width,height:o.height};t(e)})),o.addEventListener("error",i)}))}}const $b=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];uo`
1400
1400
  .o-ripple {
1401
1401
  z-index: 1;
1402
1402
  }
1403
- `;class $b extends t.Component{constructor(){super(...arguments),this.rippleRef=t.useRef("ripple")}setup(){let e;t.onMounted((()=>{const t=this.rippleRef.el;t&&t.animate&&(e=t.animate(Hb,{duration:this.props.duration,easing:"ease-out"}),e.addEventListener("finish",this.props.onAnimationEnd))})),t.onWillUnmount((()=>{null==e||e.removeEventListener("finish",this.props.onAnimationEnd)}))}get rippleStyle(){const{x:e,y:t,width:i,height:o}=this.props;return mo({transform:"scale(0)",left:e,top:t,"margin-left":`${-i/2+(this.props.offsetX||0)}px`,"margin-top":`${-o/2+(this.props.offsetY||0)}px`,width:`${i}px`,height:`${o}px`,background:this.props.color,"border-radius":"100%",opacity:`${this.props.opacity}`})}}$b.template="o-spreadsheet-RippleEffect",$b.props={x:String,y:String,color:String,opacity:Number,duration:Number,width:Number,height:Number,offsetY:Number,offsetX:Number,allowOverflow:Boolean,onAnimationEnd:Function,style:String};class Wb extends t.Component{constructor(){super(...arguments),this.childContainer=t.useRef("childContainer"),this.state=t.useState({ripples:[]}),this.currentId=1}onClick(e){if(!this.props.enabled)return;if(!this.childContainer.el)return;const t=this.getRippleChildRectInfo(),{x:i,y:o,width:n,height:s}=t,r=Math.max(n,s),a={x:e.clientX-i,y:e.clientY-o,width:this.props.width||2.85*r,height:this.props.height||2.85*r};this.state.ripples.push({rippleRect:a,id:this.currentId++})}getRippleStyle(){const e=this.childContainer.el;if(!e||1!==e.childElementCount||!e.firstElementChild)return"";const t=this.getRippleChildRectInfo();return mo({top:t.marginTop+"px",left:t.marginLeft+"px",width:t.width+"px",height:t.height+"px"})}getRippleChildRectInfo(){const e=this.childContainer.el;if(!e)throw new Error("No child container element found");if(1!==e.childElementCount||!e.firstElementChild){return{...Ln(e),marginLeft:0,marginTop:0}}const t=e.firstElementChild,i=function(e){const t=window.getComputedStyle(e);return{top:parseInt(t.marginTop,10)||0,bottom:parseInt(t.marginBottom,10)||0,left:parseInt(t.marginLeft,10)||0,right:parseInt(t.marginRight,10)||0}}(t);return{...Ln(t),marginLeft:i.left,marginTop:i.top}}removeRipple(e){const t=this.state.ripples.findIndex((t=>t.id===e));-1!==t&&this.state.ripples.splice(t,1)}getRippleEffectProps(e){var t;const i=null===(t=this.state.ripples.find((t=>t.id===e)))||void 0===t?void 0:t.rippleRect;if(!i)throw new Error("Cannot find a ripple with the id "+e);return{color:this.props.color,opacity:this.props.opacity,duration:this.props.duration,x:this.props.ignoreClickPosition?"50%":i.x+"px",y:this.props.ignoreClickPosition?"50%":i.y+"px",width:i.width,height:i.height,offsetX:this.props.offsetX||0,offsetY:this.props.offsetY||0,allowOverflow:this.props.allowOverflow||!1,style:this.getRippleStyle(),onAnimationEnd:()=>this.removeRipple(e)}}}Wb.template="o-spreadsheet-Ripple",Wb.components={RippleEffect:$b},Wb.defaultProps={color:"#aaaaaa",opacity:.4,duration:800,enabled:!0,onAnimationEnd:()=>{},class:""},Wb.props={color:{type:String,optional:!0},opacity:{type:Number,optional:!0},duration:{type:Number,optional:!0},ignoreClickPosition:{type:Boolean,optional:!0},width:{type:Number,optional:!0},height:{type:Number,optional:!0},offsetY:{type:Number,optional:!0},offsetX:{type:Number,optional:!0},allowOverflow:{type:Boolean,optional:!0},enabled:{type:Boolean,optional:!0},onAnimationEnd:{type:Function,optional:!0},slots:Object,class:{type:String,optional:!0}},ho`
1403
+ `;class Wb extends t.Component{constructor(){super(...arguments),this.rippleRef=t.useRef("ripple")}setup(){let e;t.onMounted((()=>{const t=this.rippleRef.el;t&&t.animate&&(e=t.animate($b,{duration:this.props.duration,easing:"ease-out"}),e.addEventListener("finish",this.props.onAnimationEnd))})),t.onWillUnmount((()=>{null==e||e.removeEventListener("finish",this.props.onAnimationEnd)}))}get rippleStyle(){const{x:e,y:t,width:i,height:o}=this.props;return fo({transform:"scale(0)",left:e,top:t,"margin-left":`${-i/2+(this.props.offsetX||0)}px`,"margin-top":`${-o/2+(this.props.offsetY||0)}px`,width:`${i}px`,height:`${o}px`,background:this.props.color,"border-radius":"100%",opacity:`${this.props.opacity}`})}}Wb.template="o-spreadsheet-RippleEffect",Wb.props={x:String,y:String,color:String,opacity:Number,duration:Number,width:Number,height:Number,offsetY:Number,offsetX:Number,allowOverflow:Boolean,onAnimationEnd:Function,style:String};class Gb extends t.Component{constructor(){super(...arguments),this.childContainer=t.useRef("childContainer"),this.state=t.useState({ripples:[]}),this.currentId=1}onClick(e){if(!this.props.enabled)return;if(!this.childContainer.el)return;const t=this.getRippleChildRectInfo(),{x:i,y:o,width:n,height:s}=t,r=Math.max(n,s),a={x:e.clientX-i,y:e.clientY-o,width:this.props.width||2.85*r,height:this.props.height||2.85*r};this.state.ripples.push({rippleRect:a,id:this.currentId++})}getRippleStyle(){const e=this.childContainer.el;if(!e||1!==e.childElementCount||!e.firstElementChild)return"";const t=this.getRippleChildRectInfo();return fo({top:t.marginTop+"px",left:t.marginLeft+"px",width:t.width+"px",height:t.height+"px"})}getRippleChildRectInfo(){const e=this.childContainer.el;if(!e)throw new Error("No child container element found");if(1!==e.childElementCount||!e.firstElementChild){return{...Pn(e),marginLeft:0,marginTop:0}}const t=e.firstElementChild,i=function(e){const t=window.getComputedStyle(e);return{top:parseInt(t.marginTop,10)||0,bottom:parseInt(t.marginBottom,10)||0,left:parseInt(t.marginLeft,10)||0,right:parseInt(t.marginRight,10)||0}}(t);return{...Pn(t),marginLeft:i.left,marginTop:i.top}}removeRipple(e){const t=this.state.ripples.findIndex((t=>t.id===e));-1!==t&&this.state.ripples.splice(t,1)}getRippleEffectProps(e){var t;const i=null===(t=this.state.ripples.find((t=>t.id===e)))||void 0===t?void 0:t.rippleRect;if(!i)throw new Error("Cannot find a ripple with the id "+e);return{color:this.props.color,opacity:this.props.opacity,duration:this.props.duration,x:this.props.ignoreClickPosition?"50%":i.x+"px",y:this.props.ignoreClickPosition?"50%":i.y+"px",width:i.width,height:i.height,offsetX:this.props.offsetX||0,offsetY:this.props.offsetY||0,allowOverflow:this.props.allowOverflow||!1,style:this.getRippleStyle(),onAnimationEnd:()=>this.removeRipple(e)}}}Gb.template="o-spreadsheet-Ripple",Gb.components={RippleEffect:Wb},Gb.defaultProps={color:"#aaaaaa",opacity:.4,duration:800,enabled:!0,onAnimationEnd:()=>{},class:""},Gb.props={color:{type:String,optional:!0},opacity:{type:Number,optional:!0},duration:{type:Number,optional:!0},ignoreClickPosition:{type:Boolean,optional:!0},width:{type:Number,optional:!0},height:{type:Number,optional:!0},offsetY:{type:Number,optional:!0},offsetX:{type:Number,optional:!0},allowOverflow:{type:Boolean,optional:!0},enabled:{type:Boolean,optional:!0},onAnimationEnd:{type:Function,optional:!0},slots:Object,class:{type:String,optional:!0}},uo`
1404
1404
  .o-sheet {
1405
1405
  color: #666;
1406
1406
  padding: 0 15px;
@@ -1441,7 +1441,7 @@
1441
1441
  }
1442
1442
  }
1443
1443
  }
1444
- `;class Gb extends t.Component{constructor(){super(...arguments),this.state=t.useState({isEditing:!1}),this.sheetDivRef=t.useRef("sheetDiv"),this.sheetNameRef=t.useRef("sheetNameSpan"),this.editionState="initializing"}setup(){t.onMounted((()=>{this.isSheetActive&&this.scrollToSheet()})),t.onPatched((()=>{this.sheetNameRef.el&&this.state.isEditing&&"initializing"===this.editionState&&(this.editionState="editing",this.focusInputAndSelectContent())}))}focusInputAndSelectContent(){var e;if(!this.state.isEditing||!this.sheetNameRef.el)return;this.sheetNameRef.el.focus();const t=window.getSelection();t&&this.sheetNameRef.el.firstChild&&t.setBaseAndExtent(this.sheetNameRef.el.firstChild,0,this.sheetNameRef.el.firstChild,(null===(e=this.sheetNameRef.el.textContent)||void 0===e?void 0:e.length)||0)}scrollToSheet(){var e,t;null===(t=null===(e=this.sheetDivRef.el)||void 0===e?void 0:e.scrollIntoView)||void 0===t||t.call(e)}onFocusOut(){this.state.isEditing&&"initializing"!==this.editionState&&this.stopEdition()}onMouseDown(e){this.activateSheet(),this.props.onMouseDown(e)}activateSheet(){this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:this.props.sheetId}),this.scrollToSheet()}onDblClick(){this.startEdition()}onKeyDown(e){this.state.isEditing&&("Enter"===e.key&&(e.preventDefault(),this.stopEdition()),"Escape"===e.key&&this.cancelEdition())}onClickSheetName(e){this.state.isEditing&&e.stopPropagation()}startEdition(){this.state.isEditing=!0,this.editionState="initializing"}stopEdition(){var e;if(!this.state.isEditing)return;this.state.isEditing=!1,this.editionState="initializing",null===(e=this.sheetNameRef.el)||void 0===e||e.blur();const t=this.getInputContent()||"";!function(e,t,i,o){const n=e.model.getters.getSheetName(t);if(null===i||i===n)return;const r=e.model.dispatch("RENAME_SHEET",{sheetId:t,name:i});r.reasons.includes(10)?e.raiseError(s("The sheet name cannot be empty."),o):r.reasons.includes(11)?e.raiseError(s("A sheet with the name %s already exists. Please select another name.",i),o):r.reasons.includes(13)&&e.raiseError(s("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",ne.join(" ")),o)}(this.env,this.props.sheetId,t,(()=>this.startEdition()))}cancelEdition(){var e;this.state.isEditing=!1,this.editionState="initializing",null===(e=this.sheetNameRef.el)||void 0===e||e.blur(),this.setInputContent(this.sheetName)}onIconClick(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}onContextMenu(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}getInputContent(){var e;return null===(e=this.sheetNameRef.el)||void 0===e?void 0:e.textContent}setInputContent(e){this.sheetNameRef.el&&(this.sheetNameRef.el.textContent=e)}get contextMenuRegistry(){return function(e){const t=new Qn;return t.add("delete",{name:s("Delete"),sequence:10,isVisible:e=>e.model.getters.getSheetIds().length>1,action:e=>e.askConfirmation(s("Are you sure you want to delete this sheet ?"),(()=>{e.model.dispatch("DELETE_SHEET",{sheetId:e.model.getters.getActiveSheetId()})}))}).add("duplicate",{name:s("Duplicate"),sequence:20,action:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.uuidGenerator.uuidv4();e.model.dispatch("DUPLICATE_SHEET",{sheetId:t,sheetIdTo:i}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:i})}}).add("rename",{name:s("Rename"),sequence:30,action:()=>e.renameSheetCallback()}).add("move_right",{name:s("Move right"),sequence:40,isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getVisibleSheetIds();return i.indexOf(t)!==i.length-1},action:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),delta:1})}).add("move_left",{name:s("Move left"),sequence:50,isVisible:e=>{const t=e.model.getters.getActiveSheetId();return e.model.getters.getVisibleSheetIds()[0]!==t},action:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),delta:-1})}).add("hide_sheet",{name:s("Hide sheet"),sequence:60,isVisible:e=>1!==e.model.getters.getVisibleSheetIds().length,action:e=>e.model.dispatch("HIDE_SHEET",{sheetId:e.model.getters.getActiveSheetId()})}),t}({renameSheetCallback:()=>{this.scrollToSheet(),this.startEdition()}})}get isSheetActive(){return this.env.model.getters.getActiveSheetId()===this.props.sheetId}get sheetName(){return this.env.model.getters.getSheetName(this.props.sheetId)}}Gb.template="o-spreadsheet-BottomBarSheet",Gb.components={Ripple:Wb},Gb.defaultProps={onMouseDown:()=>{},style:""},Gb.props={sheetId:String,openContextMenu:Function,style:{type:String,optional:!0},onMouseDown:{type:Function,optional:!0}},ho`
1444
+ `;class qb extends t.Component{constructor(){super(...arguments),this.state=t.useState({isEditing:!1}),this.sheetDivRef=t.useRef("sheetDiv"),this.sheetNameRef=t.useRef("sheetNameSpan"),this.editionState="initializing"}setup(){t.onMounted((()=>{this.isSheetActive&&this.scrollToSheet()})),t.onPatched((()=>{this.sheetNameRef.el&&this.state.isEditing&&"initializing"===this.editionState&&(this.editionState="editing",this.focusInputAndSelectContent())}))}focusInputAndSelectContent(){var e;if(!this.state.isEditing||!this.sheetNameRef.el)return;this.sheetNameRef.el.focus();const t=window.getSelection();t&&this.sheetNameRef.el.firstChild&&t.setBaseAndExtent(this.sheetNameRef.el.firstChild,0,this.sheetNameRef.el.firstChild,(null===(e=this.sheetNameRef.el.textContent)||void 0===e?void 0:e.length)||0)}scrollToSheet(){var e,t;null===(t=null===(e=this.sheetDivRef.el)||void 0===e?void 0:e.scrollIntoView)||void 0===t||t.call(e)}onFocusOut(){this.state.isEditing&&"initializing"!==this.editionState&&this.stopEdition()}onMouseDown(e){this.activateSheet(),this.props.onMouseDown(e)}activateSheet(){this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:this.props.sheetId}),this.scrollToSheet()}onDblClick(){this.startEdition()}onKeyDown(e){this.state.isEditing&&("Enter"===e.key&&(e.preventDefault(),this.stopEdition()),"Escape"===e.key&&this.cancelEdition())}onClickSheetName(e){this.state.isEditing&&e.stopPropagation()}startEdition(){this.state.isEditing=!0,this.editionState="initializing"}stopEdition(){var e;if(!this.state.isEditing)return;this.state.isEditing=!1,this.editionState="initializing",null===(e=this.sheetNameRef.el)||void 0===e||e.blur();const t=this.getInputContent()||"";!function(e,t,i,o){const n=e.model.getters.getSheetName(t);if(null===i||i===n)return;const r=e.model.dispatch("RENAME_SHEET",{sheetId:t,name:i});r.reasons.includes(10)?e.raiseError(s("The sheet name cannot be empty."),o):r.reasons.includes(11)?e.raiseError(s("A sheet with the name %s already exists. Please select another name.",i),o):r.reasons.includes(13)&&e.raiseError(s("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",ne.join(" ")),o)}(this.env,this.props.sheetId,t,(()=>this.startEdition()))}cancelEdition(){var e;this.state.isEditing=!1,this.editionState="initializing",null===(e=this.sheetNameRef.el)||void 0===e||e.blur(),this.setInputContent(this.sheetName)}onIconClick(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}onContextMenu(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}getInputContent(){var e;return null===(e=this.sheetNameRef.el)||void 0===e?void 0:e.textContent}setInputContent(e){this.sheetNameRef.el&&(this.sheetNameRef.el.textContent=e)}get contextMenuRegistry(){return function(e){const t=new Jn;return t.add("delete",{name:s("Delete"),sequence:10,isVisible:e=>e.model.getters.getSheetIds().length>1,action:e=>e.askConfirmation(s("Are you sure you want to delete this sheet ?"),(()=>{e.model.dispatch("DELETE_SHEET",{sheetId:e.model.getters.getActiveSheetId()})}))}).add("duplicate",{name:s("Duplicate"),sequence:20,action:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.uuidGenerator.uuidv4();e.model.dispatch("DUPLICATE_SHEET",{sheetId:t,sheetIdTo:i}),e.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:i})}}).add("rename",{name:s("Rename"),sequence:30,action:()=>e.renameSheetCallback()}).add("move_right",{name:s("Move right"),sequence:40,isVisible:e=>{const t=e.model.getters.getActiveSheetId(),i=e.model.getters.getVisibleSheetIds();return i.indexOf(t)!==i.length-1},action:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),delta:1})}).add("move_left",{name:s("Move left"),sequence:50,isVisible:e=>{const t=e.model.getters.getActiveSheetId();return e.model.getters.getVisibleSheetIds()[0]!==t},action:e=>e.model.dispatch("MOVE_SHEET",{sheetId:e.model.getters.getActiveSheetId(),delta:-1})}).add("hide_sheet",{name:s("Hide sheet"),sequence:60,isVisible:e=>1!==e.model.getters.getVisibleSheetIds().length,action:e=>e.model.dispatch("HIDE_SHEET",{sheetId:e.model.getters.getActiveSheetId()})}),t}({renameSheetCallback:()=>{this.scrollToSheet(),this.startEdition()}})}get isSheetActive(){return this.env.model.getters.getActiveSheetId()===this.props.sheetId}get sheetName(){return this.env.model.getters.getSheetName(this.props.sheetId)}}qb.template="o-spreadsheet-BottomBarSheet",qb.components={Ripple:Gb},qb.defaultProps={onMouseDown:()=>{},style:""},qb.props={sheetId:String,openContextMenu:Function,style:{type:String,optional:!0},onMouseDown:{type:Function,optional:!0}},uo`
1445
1445
  .o-selection-statistic {
1446
1446
  margin-right: 20px;
1447
1447
  padding: 4px 4px 4px 8px;
@@ -1451,7 +1451,7 @@
1451
1451
  background-color: rgba(0, 0, 0, 0.08) !important;
1452
1452
  }
1453
1453
  }
1454
- `;class qb extends t.Component{constructor(){super(...arguments),this.selectedStatisticFn="",this.statisticFnResults={}}setup(){this.statisticFnResults=this.env.model.getters.getStatisticFnResults(),t.onWillUpdateProps((()=>{const e=this.env.model.getters.getStatisticFnResults();at(e,this.statisticFnResults)||this.props.closeContextMenu(),this.statisticFnResults=e}))}getSelectedStatistic(){if(!Object.values(this.statisticFnResults).every((e=>void 0===e)))return""===this.selectedStatisticFn&&(this.selectedStatisticFn=Object.keys(this.statisticFnResults)[0]),this.getComposedFnName(this.selectedStatisticFn,this.statisticFnResults[this.selectedStatisticFn])}listSelectionStatistics(e){const t=new Qn;let i=0;for(let[e,o]of Object.entries(this.statisticFnResults))t.add(e,{name:this.getComposedFnName(e,o),sequence:i,isReadonlyAllowed:!0,action:()=>{this.selectedStatisticFn=e}}),i++;const o=e.currentTarget,{top:n,left:s,width:r}=o.getBoundingClientRect();this.props.openContextMenu(s+r,n,t)}getComposedFnName(e,t){return e+": "+(void 0!==t?hi(t):"__")}}qb.template="o-spreadsheet-BottomBarStatisic",qb.components={Ripple:Wb},qb.props={openContextMenu:Function,closeContextMenu:Function};class Zb{constructor(e){this.edgeScrollOffset=0,this.items=e.items.map((e=>({...e,positionAtStart:e.position}))),this.draggedItemId=e.draggedItemId,this.containerEl=e.containerEl,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onDragEnd=e.onDragEnd,this.initialMousePosition=e.mouseX,this.currentMousePosition=e.mouseX,this.minPosition=this.items[0].position,this.maxPosition=this.items[this.items.length-1].position+this.items[this.items.length-1].size,Rg(this.onMouseMove.bind(this),this.onMouseUp.bind(this))}onMouseMove(e){if(0!==e.button)return void this.onCancel();const t=e.clientX;t<this.containerRect.left||t>this.containerRect.right?this.startEdgeScroll(t<this.containerRect.left?-1:1):(this.stopEdgeScroll(),this.moveDraggedItemToPosition(t+this.edgeScrollOffset))}moveDraggedItemToPosition(e){this.currentMousePosition=e;const t=this.getHoveredItemIndex(e,this.items),i=this.items.findIndex((e=>e.id===this.draggedItemId)),o=this.items[i];if(this.deadZone&&this.isInZone(e,this.deadZone))return void this.onChange(this.getItemsPositions());if(this.isInZone(e,{start:o.position,end:o.position+o.size})&&(this.deadZone=void 0),i===t)return void this.onChange(this.getItemsPositions());const n=Math.min(i,t),s=Math.max(i,t),r=Math.sign(t-i);let a=0;for(let e=n;e<=s;e++)e!==i&&(this.items[e].position-=r*o.size,a+=this.items[e].size);o.position+=r*a,this.items.sort(((e,t)=>e.position-t.position)),this.deadZone=r>0?{start:e,end:o.position}:{start:o.position+o.size,end:e},this.onChange(this.getItemsPositions())}onMouseUp(e){0!==e.button&&this.onCancel();const t=this.items.findIndex((e=>e.id===this.draggedItemId));this.onDragEnd(this.draggedItemId,t),this.stopEdgeScroll()}startEdgeScroll(e){this.edgeScrollIntervalId||(this.edgeScrollIntervalId=window.setInterval((()=>{const t=3*e;let i=this.currentMousePosition+t;i<this.minPosition?i=this.minPosition:i>this.maxPosition&&(i=this.maxPosition),this.edgeScrollOffset+=i-this.currentMousePosition,this.moveDraggedItemToPosition(i),this.containerEl.scrollLeft+=t}),5))}stopEdgeScroll(){window.clearInterval(this.edgeScrollIntervalId),this.edgeScrollIntervalId=void 0}getHoveredItemIndex(e,t){return e<=this.minPosition?0:e>=this.maxPosition?t.length-1:t.findIndex((t=>t.position+t.size>=e))}getItemsPositions(){const e={};for(let t of this.items){if(t.id!==this.draggedItemId){e[t.id]=t.position-t.positionAtStart;continue}let i=this.currentMousePosition-this.initialMousePosition;i=Math.max(this.minPosition-t.positionAtStart,i),i=Math.min(this.maxPosition-t.positionAtStart-t.size,i),e[t.id]=i}return e}get containerRect(){return this.containerEl.getBoundingClientRect()}isInZone(e,t){return e>=t.start&&e<=t.end}destroy(){this.stopEdgeScroll()}}ho`
1454
+ `;class Zb extends t.Component{constructor(){super(...arguments),this.selectedStatisticFn="",this.statisticFnResults={}}setup(){this.statisticFnResults=this.env.model.getters.getStatisticFnResults(),t.onWillUpdateProps((()=>{const e=this.env.model.getters.getStatisticFnResults();lt(e,this.statisticFnResults)||this.props.closeContextMenu(),this.statisticFnResults=e}))}getSelectedStatistic(){if(!Object.values(this.statisticFnResults).every((e=>void 0===e)))return""===this.selectedStatisticFn&&(this.selectedStatisticFn=Object.keys(this.statisticFnResults)[0]),this.getComposedFnName(this.selectedStatisticFn,this.statisticFnResults[this.selectedStatisticFn])}listSelectionStatistics(e){const t=new Jn;let i=0;for(let[e,o]of Object.entries(this.statisticFnResults))t.add(e,{name:this.getComposedFnName(e,o),sequence:i,isReadonlyAllowed:!0,action:()=>{this.selectedStatisticFn=e}}),i++;const o=e.currentTarget,{top:n,left:s,width:r}=o.getBoundingClientRect();this.props.openContextMenu(s+r,n,t)}getComposedFnName(e,t){return e+": "+(void 0!==t?di(t):"__")}}Zb.template="o-spreadsheet-BottomBarStatisic",Zb.components={Ripple:Gb},Zb.props={openContextMenu:Function,closeContextMenu:Function};class jb{constructor(e){this.edgeScrollOffset=0,this.items=e.items.map((e=>({...e,positionAtStart:e.position}))),this.draggedItemId=e.draggedItemId,this.containerEl=e.containerEl,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onDragEnd=e.onDragEnd,this.initialMousePosition=e.mouseX,this.currentMousePosition=e.mouseX,this.minPosition=this.items[0].position,this.maxPosition=this.items[this.items.length-1].position+this.items[this.items.length-1].size,Tg(this.onMouseMove.bind(this),this.onMouseUp.bind(this))}onMouseMove(e){if(0!==e.button)return void this.onCancel();const t=e.clientX;t<this.containerRect.left||t>this.containerRect.right?this.startEdgeScroll(t<this.containerRect.left?-1:1):(this.stopEdgeScroll(),this.moveDraggedItemToPosition(t+this.edgeScrollOffset))}moveDraggedItemToPosition(e){this.currentMousePosition=e;const t=this.getHoveredItemIndex(e,this.items),i=this.items.findIndex((e=>e.id===this.draggedItemId)),o=this.items[i];if(this.deadZone&&this.isInZone(e,this.deadZone))return void this.onChange(this.getItemsPositions());if(this.isInZone(e,{start:o.position,end:o.position+o.size})&&(this.deadZone=void 0),i===t)return void this.onChange(this.getItemsPositions());const n=Math.min(i,t),s=Math.max(i,t),r=Math.sign(t-i);let a=0;for(let e=n;e<=s;e++)e!==i&&(this.items[e].position-=r*o.size,a+=this.items[e].size);o.position+=r*a,this.items.sort(((e,t)=>e.position-t.position)),this.deadZone=r>0?{start:e,end:o.position}:{start:o.position+o.size,end:e},this.onChange(this.getItemsPositions())}onMouseUp(e){0!==e.button&&this.onCancel();const t=this.items.findIndex((e=>e.id===this.draggedItemId));this.onDragEnd(this.draggedItemId,t),this.stopEdgeScroll()}startEdgeScroll(e){this.edgeScrollIntervalId||(this.edgeScrollIntervalId=window.setInterval((()=>{const t=3*e;let i=this.currentMousePosition+t;i<this.minPosition?i=this.minPosition:i>this.maxPosition&&(i=this.maxPosition),this.edgeScrollOffset+=i-this.currentMousePosition,this.moveDraggedItemToPosition(i),this.containerEl.scrollLeft+=t}),5))}stopEdgeScroll(){window.clearInterval(this.edgeScrollIntervalId),this.edgeScrollIntervalId=void 0}getHoveredItemIndex(e,t){return e<=this.minPosition?0:e>=this.maxPosition?t.length-1:t.findIndex((t=>t.position+t.size>=e))}getItemsPositions(){const e={};for(let t of this.items){if(t.id!==this.draggedItemId){e[t.id]=t.position-t.positionAtStart;continue}let i=this.currentMousePosition-this.initialMousePosition;i=Math.max(this.minPosition-t.positionAtStart,i),i=Math.min(this.maxPosition-t.positionAtStart-t.size,i),e[t.id]=i}return e}get containerRect(){return this.containerEl.getBoundingClientRect()}isInZone(e,t){return e>=t.start&&e<=t.end}destroy(){this.stopEdgeScroll()}}uo`
1455
1455
  .o-spreadsheet-bottom-bar {
1456
1456
  background-color: ${f};
1457
1457
  padding-left: ${N}px;
@@ -1500,12 +1500,12 @@
1500
1500
  }
1501
1501
  }
1502
1502
  }
1503
- `;class jb extends t.Component{constructor(){super(...arguments),this.bottomBarRef=t.useRef("bottomBar"),this.sheetListRef=t.useRef("sheetList"),this.targetScroll=void 0,this.state=t.useState({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1}),this.menuMaxHeight=250,this.menuState=t.useState({isOpen:!1,menuId:void 0,position:null,menuItems:[]}),this.sheetState=t.useState({sheetList:this.getVisibleSheets(),isDnd:!1,sheetDndPositions:void 0})}setup(){t.onWillUpdateProps((()=>{this.updateScrollState();const e=this.getVisibleSheets();this.sheetState.isDnd&&!at(this.sheetState.sheetList,e)&&this.stopDragging(),this.sheetState.sheetList=e})),t.onWillUnmount((()=>{var e;null===(e=this.dndHelper)||void 0===e||e.destroy()}))}isDragged(e){var t;return this.sheetState.isDnd&&(null===(t=this.dndHelper)||void 0===t?void 0:t.draggedItemId)===e}clickAddSheet(e){const t=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getSheetIds().findIndex((e=>e===t))+1,o=this.env.model.uuidGenerator.uuidv4(),n=this.env.model.getters.getNextSheetName(this.env._t("Sheet"));this.env.model.dispatch("CREATE_SHEET",{sheetId:o,position:i,name:n}),this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map((e=>{const t=this.env.model.getters.getSheet(e);return{id:t.id,name:t.name}}))}getSheets(){return this.sheetState.sheetList}clickListSheets(e){const t=new Qn,i=this.env.model.getters.getActiveSheetId();let o=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:o,isReadonlyAllowed:!0,textColor:n.isVisible?void 0:"grey",action:t=>{t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:i,sheetIdTo:e})}}),o++}const n=e.currentTarget,{left:s}=n.getBoundingClientRect(),r=this.bottomBarRef.el.getBoundingClientRect().top;this.openContextMenu(s,r,"listSheets",t)}openContextMenu(e,t,i,o){this.menuState.isOpen=!0,this.menuState.menuId=i,this.menuState.menuItems=o.getMenuItems(),this.menuState.position={x:e,y:t}}onSheetContextMenu(e,t,i){const o=i.currentTarget,{top:n,left:s}=o.getBoundingClientRect();i.closedMenuId!==e?this.openContextMenu(s,n,e,t):this.closeMenu()}closeMenu(){this.menuState.isOpen=!1,this.menuState.menuId=void 0,this.menuState.menuItems=[],this.menuState.position=null}closeContextMenuWithId(e){this.menuState.menuId===e&&this.closeMenu()}onWheel(e){this.targetScroll=void 0;e.currentTarget.scrollLeft+=.5*e.deltaY}onScroll(){this.updateScrollState(),this.targetScroll===this.sheetListCurrentScroll&&(this.targetScroll=void 0)}onArrowLeft(e){if(!this.state.isSheetListScrollableLeft)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll-this.sheetListWidth;this.scrollSheetListTo(Math.max(0,t))}onArrowRight(e){if(!this.state.isSheetListScrollableRight)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll+this.sheetListWidth;this.scrollSheetListTo(Math.min(this.sheetListMaxScroll,t))}updateScrollState(){this.state.isSheetListScrollableLeft=this.sheetListCurrentScroll>0,this.state.isSheetListScrollableRight=this.sheetListCurrentScroll<this.sheetListMaxScroll}scrollSheetListTo(e){this.sheetListRef.el&&(this.targetScroll=e,this.sheetListRef.el.scrollTo({top:0,left:e,behavior:"smooth"}))}onSheetMouseDown(e,t){if(0!==t.button)return;this.closeMenu();const i=t.clientX;document.body.style.cursor="move";const o=this.getVisibleSheets(),n=this.getSheetItemRects(),s=o.map(((e,t)=>({id:e.id,size:n[t].width,position:n[t].x})));this.dndHelper=new Zb({draggedItemId:e,mouseX:i,items:s,containerEl:this.sheetListRef.el,onChange:e=>{this.sheetState.isDnd=!0,this.sheetState.sheetDndPositions=e},onCancel:()=>this.stopDragging(),onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){const i=t-this.sheetState.sheetList.findIndex((t=>t.id===e));e&&0!==i&&this.env.model.dispatch("MOVE_SHEET",{sheetId:e,delta:i}),this.stopDragging()}getSheetStyle(e){var t;const i={};return this.sheetState.isDnd&&(i.position="relative",i.left=((null===(t=this.sheetState.sheetDndPositions)||void 0===t?void 0:t[e])||0)+"px",i.transition="left 0.5s",i.cursor="move"),this.isDragged(e)&&(i.transition="left 0s",i["z-index"]="1000"),mo(i)}stopDragging(){document.body.style.cursor="",this.sheetState.sheetList=this.getVisibleSheets(),this.sheetState.isDnd=!1,this.sheetState.sheetDndPositions=void 0,this.dndHelper=void 0}getSheetItemRects(){return Array.from(this.bottomBarRef.el.querySelectorAll(".o-sheet")).map((e=>e.getBoundingClientRect())).map((e=>({x:e.x,width:e.width-1,y:e.y,height:e.height})))}getSheetClasses(e){let t="";return this.isDragged(e)&&(t+="dragged "),this.sheetState.isDnd&&(t+="dragging "),t}get sheetListCurrentScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollLeft:0}get sheetListWidth(){return this.sheetListRef.el?this.sheetListRef.el.clientWidth:0}get sheetListMaxScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollWidth-this.sheetListRef.el.clientWidth:0}}jb.template="o-spreadsheet-BottomBar",jb.components={Menu:qn,Ripple:Wb,BottomBarSheet:Gb,BottomBarStatistic:qb},jb.props={onClick:Function},ho`
1503
+ `;class Xb extends t.Component{constructor(){super(...arguments),this.bottomBarRef=t.useRef("bottomBar"),this.sheetListRef=t.useRef("sheetList"),this.targetScroll=void 0,this.state=t.useState({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1}),this.menuMaxHeight=250,this.menuState=t.useState({isOpen:!1,menuId:void 0,position:null,menuItems:[]}),this.sheetState=t.useState({sheetList:this.getVisibleSheets(),isDnd:!1,sheetDndPositions:void 0})}setup(){t.onWillUpdateProps((()=>{this.updateScrollState();const e=this.getVisibleSheets();this.sheetState.isDnd&&!lt(this.sheetState.sheetList,e)&&this.stopDragging(),this.sheetState.sheetList=e})),t.onWillUnmount((()=>{var e;null===(e=this.dndHelper)||void 0===e||e.destroy()}))}isDragged(e){var t;return this.sheetState.isDnd&&(null===(t=this.dndHelper)||void 0===t?void 0:t.draggedItemId)===e}clickAddSheet(e){const t=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getSheetIds().findIndex((e=>e===t))+1,o=this.env.model.uuidGenerator.uuidv4(),n=this.env.model.getters.getNextSheetName(this.env._t("Sheet"));this.env.model.dispatch("CREATE_SHEET",{sheetId:o,position:i,name:n}),this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:o})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map((e=>{const t=this.env.model.getters.getSheet(e);return{id:t.id,name:t.name}}))}getSheets(){return this.sheetState.sheetList}clickListSheets(e){const t=new Jn,i=this.env.model.getters.getActiveSheetId();let o=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:o,isReadonlyAllowed:!0,textColor:n.isVisible?void 0:"grey",action:t=>{t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:i,sheetIdTo:e})}}),o++}const n=e.currentTarget,{left:s}=n.getBoundingClientRect(),r=this.bottomBarRef.el.getBoundingClientRect().top;this.openContextMenu(s,r,"listSheets",t)}openContextMenu(e,t,i,o){this.menuState.isOpen=!0,this.menuState.menuId=i,this.menuState.menuItems=o.getMenuItems(),this.menuState.position={x:e,y:t}}onSheetContextMenu(e,t,i){const o=i.currentTarget,{top:n,left:s}=o.getBoundingClientRect();i.closedMenuId!==e?this.openContextMenu(s,n,e,t):this.closeMenu()}closeMenu(){this.menuState.isOpen=!1,this.menuState.menuId=void 0,this.menuState.menuItems=[],this.menuState.position=null}closeContextMenuWithId(e){this.menuState.menuId===e&&this.closeMenu()}onWheel(e){this.targetScroll=void 0;e.currentTarget.scrollLeft+=.5*e.deltaY}onScroll(){this.updateScrollState(),this.targetScroll===this.sheetListCurrentScroll&&(this.targetScroll=void 0)}onArrowLeft(e){if(!this.state.isSheetListScrollableLeft)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll-this.sheetListWidth;this.scrollSheetListTo(Math.max(0,t))}onArrowRight(e){if(!this.state.isSheetListScrollableRight)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll+this.sheetListWidth;this.scrollSheetListTo(Math.min(this.sheetListMaxScroll,t))}updateScrollState(){this.state.isSheetListScrollableLeft=this.sheetListCurrentScroll>0,this.state.isSheetListScrollableRight=this.sheetListCurrentScroll<this.sheetListMaxScroll}scrollSheetListTo(e){this.sheetListRef.el&&(this.targetScroll=e,this.sheetListRef.el.scrollTo({top:0,left:e,behavior:"smooth"}))}onSheetMouseDown(e,t){if(0!==t.button)return;this.closeMenu();const i=t.clientX;document.body.style.cursor="move";const o=this.getVisibleSheets(),n=this.getSheetItemRects(),s=o.map(((e,t)=>({id:e.id,size:n[t].width,position:n[t].x})));this.dndHelper=new jb({draggedItemId:e,mouseX:i,items:s,containerEl:this.sheetListRef.el,onChange:e=>{this.sheetState.isDnd=!0,this.sheetState.sheetDndPositions=e},onCancel:()=>this.stopDragging(),onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){const i=t-this.sheetState.sheetList.findIndex((t=>t.id===e));e&&0!==i&&this.env.model.dispatch("MOVE_SHEET",{sheetId:e,delta:i}),this.stopDragging()}getSheetStyle(e){var t;const i={};return this.sheetState.isDnd&&(i.position="relative",i.left=((null===(t=this.sheetState.sheetDndPositions)||void 0===t?void 0:t[e])||0)+"px",i.transition="left 0.5s",i.cursor="move"),this.isDragged(e)&&(i.transition="left 0s",i["z-index"]="1000"),fo(i)}stopDragging(){document.body.style.cursor="",this.sheetState.sheetList=this.getVisibleSheets(),this.sheetState.isDnd=!1,this.sheetState.sheetDndPositions=void 0,this.dndHelper=void 0}getSheetItemRects(){return Array.from(this.bottomBarRef.el.querySelectorAll(".o-sheet")).map((e=>e.getBoundingClientRect())).map((e=>({x:e.x,width:e.width-1,y:e.y,height:e.height})))}getSheetClasses(e){let t="";return this.isDragged(e)&&(t+="dragged "),this.sheetState.isDnd&&(t+="dragging "),t}get sheetListCurrentScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollLeft:0}get sheetListWidth(){return this.sheetListRef.el?this.sheetListRef.el.clientWidth:0}get sheetListMaxScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollWidth-this.sheetListRef.el.clientWidth:0}}Xb.template="o-spreadsheet-BottomBar",Xb.components={Menu:Zn,Ripple:Gb,BottomBarSheet:qb,BottomBarStatistic:Zb},Xb.props={onClick:Function},uo`
1504
1504
  .o-dashboard-clickable-cell {
1505
1505
  position: absolute;
1506
1506
  cursor: pointer;
1507
1507
  }
1508
- `;let Xb=1;class Yb extends t.Component{setup(){const e=t.useRef("grid");this.canvasPosition=Vn(e),this.hoveredCell=t.useState({col:void 0,row:void 0}),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),ep("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimension())),this.onMouseWheel=tp(((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.col=void 0,this.hoveredCell.row=void 0}))}onCellHovered({col:e,row:t}){this.hoveredCell.col=e,this.hoveredCell.row=t}get gridContainer(){const e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e),{end:i}=this.env.model.getters.getColDimensions(e,t);return mo({"max-width":`${i}px`})}get gridOverlayDimensions(){return mo({height:"100%",width:"100%"})}getCellClickableStyle(e){return mo({top:`${e.y}px`,left:`${e.x}px`,width:`${e.width}px`,height:`${e.height}px`})}getClickableCells(){const e=[],t=this.env.model.getters.getActiveSheetId();for(const i of this.env.model.getters.getSheetViewVisibleCols())for(const o of this.env.model.getters.getSheetViewVisibleRows()){const n={sheetId:t,col:i,row:o},s=this.getClickableAction(n);if(!s)continue;let r;r=this.env.model.getters.isInMerge(n)?this.env.model.getters.getMerge(n):oo({col:i,row:o});const a=this.env.model.getters.getVisibleRect(r);e.push({coordinates:a,position:{col:i,row:o},action:s,tKey:`${Xb}-${i}-${o}`})}return Xb++,e}getClickableAction(e){for(const t of zb.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:i}=e;i({...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:i,scrollY:o}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:i+e,offsetY:o+t})}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}}Yb.template="o-spreadsheet-SpreadsheetDashboard",Yb.components={GridOverlay:jg,GridPopover:Xg,Popover:Hn,VerticalScrollBar:lp,HorizontalScrollBar:ap,FilterIconsOverlay:Gg},Yb.props={},ho`
1508
+ `;let Yb=1;class Kb extends t.Component{setup(){const e=t.useRef("grid");this.canvasPosition=zn(e),this.hoveredCell=t.useState({col:void 0,row:void 0}),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),tp("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimension())),this.onMouseWheel=ip(((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.col=void 0,this.hoveredCell.row=void 0}))}onCellHovered({col:e,row:t}){this.hoveredCell.col=e,this.hoveredCell.row=t}get gridContainer(){const e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e),{end:i}=this.env.model.getters.getColDimensions(e,t);return fo({"max-width":`${i}px`})}get gridOverlayDimensions(){return fo({height:"100%",width:"100%"})}getCellClickableStyle(e){return fo({top:`${e.y}px`,left:`${e.x}px`,width:`${e.width}px`,height:`${e.height}px`})}getClickableCells(){const e=[],t=this.env.model.getters.getActiveSheetId();for(const i of this.env.model.getters.getSheetViewVisibleCols())for(const o of this.env.model.getters.getSheetViewVisibleRows()){const n={sheetId:t,col:i,row:o},s=this.getClickableAction(n);if(!s)continue;let r;r=this.env.model.getters.isInMerge(n)?this.env.model.getters.getMerge(n):no({col:i,row:o});const a=this.env.model.getters.getVisibleRect(r);e.push({coordinates:a,position:{col:i,row:o},action:s,tKey:`${Yb}-${i}-${o}`})}return Yb++,e}getClickableAction(e){for(const t of Bb.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:i}=e;i({...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:i,scrollY:o}=this.env.model.getters.getActiveSheetDOMScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:i+e,offsetY:o+t})}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}}Kb.template="o-spreadsheet-SpreadsheetDashboard",Kb.components={GridOverlay:Xg,GridPopover:Yg,Popover:$n,VerticalScrollBar:cp,HorizontalScrollBar:lp,FilterIconsOverlay:qg},Kb.props={},uo`
1509
1509
  .o-sidePanel {
1510
1510
  display: flex;
1511
1511
  flex-direction: column;
@@ -1669,15 +1669,16 @@
1669
1669
  }
1670
1670
  }
1671
1671
  }
1672
- `;class Kb extends t.Component{setup(){this.state=t.useState({panel:yg.get(this.props.component)}),t.onWillUpdateProps((e=>this.state.panel=yg.get(e.component)))}getTitle(){return"function"==typeof this.state.panel.title?this.state.panel.title(this.env):this.state.panel.title}}Kb.template="o-spreadsheet-SidePanel",Kb.props={component:String,panelProps:{type:Object,optional:!0},onCloseSidePanel:Function};const Qb={MergeIsDestructive:s("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),MergeInFilter:s("You can't merge cells inside of an existing filter.")};ho`
1672
+ `;class Qb extends t.Component{setup(){this.state=t.useState({panel:xg.get(this.props.component)}),t.onWillUpdateProps((e=>this.state.panel=xg.get(e.component)))}getTitle(){return"function"==typeof this.state.panel.title?this.state.panel.title(this.env):this.state.panel.title}}Qb.template="o-spreadsheet-SidePanel",Qb.props={component:String,panelProps:{type:Object,optional:!0},onCloseSidePanel:Function};const Jb={MergeIsDestructive:s("Merging these cells will only preserve the top-leftmost value. Merge anyway?"),MergeInFilter:s("You can't merge cells inside of an existing filter.")};uo`
1673
1673
  .o-topbar-composer {
1674
1674
  height: fit-content;
1675
1675
  margin-top: -1px;
1676
1676
  border: 1px solid;
1677
1677
  z-index: ${le.TopBarComposer};
1678
1678
  }
1679
- `;class Jb extends t.Component{get composerStyle(){const e={padding:"5px 0px 5px 8px","max-height":"100px","line-height":"24px"};return e.height="inactive"===this.props.focus?"34px":"fit-content",mo(e)}get containerStyle(){return"inactive"===this.props.focus?mo({"border-color":A,"border-right":"none"}):mo({"border-color":E})}}Jb.template="o-spreadsheet-TopBarComposer",Jb.components={Composer:Vg},Jb.props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerContentFocused:Function},ho`
1679
+ `;class eS extends t.Component{get composerStyle(){const e={padding:"5px 0px 5px 8px","max-height":"100px","line-height":"24px"};return e.height="inactive"===this.props.focus?"34px":"fit-content",fo(e)}get containerStyle(){return"inactive"===this.props.focus?fo({"border-color":A,"border-right":"none"}):fo({"border-color":E})}}eS.template="o-spreadsheet-TopBarComposer",eS.components={Composer:zg},eS.props={focus:{validate:e=>["inactive","cellFocus","contentFocus"].includes(e)},onComposerContentFocused:Function},uo`
1680
1680
  .o-font-size-editor {
1681
+ height: calc(100% - 4px);
1681
1682
  input.o-font-size {
1682
1683
  height: 20px;
1683
1684
  width: 23px;
@@ -1690,7 +1691,7 @@
1690
1691
  -webkit-appearance: none;
1691
1692
  }
1692
1693
  }
1693
- `;class eS extends t.Component{constructor(){super(...arguments),this.fontSizes=he,this.dropdown=t.useState({isOpen:!1}),this.inputRef=t.useRef("inputFontSize"),this.rootEditorRef=t.useRef("FontSizeEditor")}setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}onExternalClick(e){Dn(this.rootEditorRef.el,e)||this.closeFontList()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||G}toggleFontList(){this.dropdown.isOpen?this.closeFontList():(this.props.onToggle(),this.inputRef.el.focus())}closeFontList(){this.dropdown.isOpen=!1}setSize(e){const t=De(Math.floor(parseFloat(e)),1,400);Or(this.env,{fontSize:t}),this.closeFontList()}setSizeFromInput(e){this.setSize(e.target.value)}setSizeFromList(e){this.setSize(e)}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if("Enter"===e.key||"Escape"===e.key){this.closeFontList();const t=e.target;"Escape"===e.key&&(t.value=`${this.currentFontSize}`),this.props.onToggle()}}}eS.template="o-spreadsheet-FontSizeEditor",eS.components={},eS.props={onToggle:Function,dropdownStyle:String};const tS=[{name:"automatic",text:Is.Automatic},{name:"number",text:Is.Number,description:"1,000.12",value:"#,##0.00"},{name:"percent",text:Is.Percent,description:"10.12%",value:"0.00%"},{name:"currency",text:Is.Currency,description:"$1,000.12",value:"[$$]#,##0.00"},{name:"currency_rounded",text:Is.CurrencyRounded,description:"$1,000",value:"[$$]#,##0"},{name:"date",text:Is.Date,description:"9/26/2008",value:"m/d/yyyy"},{name:"time",text:Is.Time,description:"10:43:00 PM",value:"hh:mm:ss a"},{name:"datetime",text:Is.DateTime,description:"9/26/2008 22:43:00",value:"m/d/yyyy hh:mm:ss"},{name:"duration",text:Is.Duration,description:"27:51:38",value:"hhhh:mm:ss"}],iS=[{name:"custom_currency",text:Is.CustomCurrency,sidePanel:"CustomCurrency"}],oS="#4a4f59";ho`
1694
+ `;class tS extends t.Component{constructor(){super(...arguments),this.fontSizes=he,this.dropdown=t.useState({isOpen:!1}),this.inputRef=t.useRef("inputFontSize"),this.rootEditorRef=t.useRef("FontSizeEditor")}setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}onExternalClick(e){kn(this.rootEditorRef.el,e)||this.closeFontList()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||G}toggleFontList(){this.dropdown.isOpen?this.closeFontList():(this.props.onToggle(),this.inputRef.el.focus())}closeFontList(){this.dropdown.isOpen=!1}setSize(e){const t=De(Math.floor(parseFloat(e)),1,400);Nr(this.env,{fontSize:t}),this.closeFontList()}setSizeFromInput(e){this.setSize(e.target.value)}setSizeFromList(e){this.setSize(e)}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if("Enter"===e.key||"Escape"===e.key){this.closeFontList();const t=e.target;"Escape"===e.key&&(t.value=`${this.currentFontSize}`),this.props.onToggle()}}}tS.template="o-spreadsheet-FontSizeEditor",tS.components={},tS.props={onToggle:Function,dropdownStyle:String,class:String};const iS=[{name:"automatic",text:Rs.Automatic},{name:"number",text:Rs.Number,description:"1,000.12",value:"#,##0.00"},{name:"percent",text:Rs.Percent,description:"10.12%",value:"0.00%"},{name:"currency",text:Rs.Currency,description:"$1,000.12",value:"[$$]#,##0.00"},{name:"currency_rounded",text:Rs.CurrencyRounded,description:"$1,000",value:"[$$]#,##0"},{name:"date",text:Rs.Date,description:"9/26/2008",value:"m/d/yyyy"},{name:"time",text:Rs.Time,description:"10:43:00 PM",value:"hh:mm:ss a"},{name:"datetime",text:Rs.DateTime,description:"9/26/2008 22:43:00",value:"m/d/yyyy hh:mm:ss"},{name:"duration",text:Rs.Duration,description:"27:51:38",value:"hhhh:mm:ss"}],oS=[{name:"custom_currency",text:Rs.CustomCurrency,sidePanel:"CustomCurrency"}],nS="#4a4f59";uo`
1694
1695
  .o-spreadsheet-topbar {
1695
1696
  background-color: white;
1696
1697
  line-height: 1.2;
@@ -1700,7 +1701,7 @@
1700
1701
  line-height: 1.2;
1701
1702
  user-select: none;
1702
1703
  font-weight: 500;
1703
- color: ${oS};
1704
+ color: ${nS};
1704
1705
 
1705
1706
  .o-topbar-top {
1706
1707
  border-bottom: 1px solid ${A};
@@ -1767,7 +1768,7 @@
1767
1768
  svg path,
1768
1769
  polygon,
1769
1770
  rect {
1770
- fill: ${oS};
1771
+ fill: ${nS};
1771
1772
  }
1772
1773
  }
1773
1774
 
@@ -1892,7 +1893,7 @@
1892
1893
  }
1893
1894
  }
1894
1895
  }
1895
- `;class nS extends t.Component{constructor(){super(...arguments),this.commonFormats=tS,this.customFormats=iS,this.currentFormatName="automatic",this.style={},this.state=t.useState({menuState:{isOpen:!1,position:null,menuItems:[]},activeTool:""}),this.isSelectingMenu=!1,this.openedEl=null,this.inMerge=!1,this.cannotMerge=!1,this.undoTool=!1,this.redoTool=!1,this.paintFormatTool=!1,this.fillColor="#ffffff",this.textColor="#000000",this.menus=[]}get dropdownStyle(){return`max-height:${this.props.dropdownMaxHeight}px`}setup(){t.useExternalListener(window,"click",this.onExternalClick),t.onWillStart((()=>this.updateCellState())),t.onWillUpdateProps((()=>this.updateCellState()))}get topbarComponents(){return xg.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){Or(this.env,{[e]:!this.style[e]})}toggleFormat(e){const t=tS.find((t=>t.name===e)),i=t&&t.value||"";Mr(this.env,i)}toggleHorizontalAlign(e){Or(this.env,{align:e}),this.onClick()}toggleVerticalAlign(e){Or(this.env,{verticalAlign:e}),this.onClick()}toggleTextWrapping(e){Or(this.env,{wrapping:e}),this.onClick()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.openMenu(e,t)}toggleDropdownTool(e,t){const i=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=i?"":e,this.openedEl=i?null:t.target}toggleContextMenu(e,t){this.state.menuState.isOpen?this.closeMenus():this.openMenu(e,t)}openMenu(e,t){const{left:i,top:o,height:n}=t.target.getBoundingClientRect();this.state.menuState.isOpen=!0,this.state.menuState.position={x:i,y:o+n},this.state.menuState.menuItems=e.children(this.env),this.state.menuState.parentMenu=e,this.isSelectingMenu=!0,this.openedEl=t.target,this.env.model.dispatch("STOP_EDITION")}closeMenus(){this.state.activeTool="",this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){const e=this.env.model.getters.getSelectedZones(),{col:t,row:i,sheetId:o}=this.env.model.getters.getActivePosition();this.inMerge=!1;const{top:n,left:s,right:r,bottom:a}=this.env.model.getters.getSelectedZone(),{xSplit:l,ySplit:c}=this.env.model.getters.getPaneDivisions(o);if(this.cannotMerge=e.length>1||n===a&&s===r||s<l&&l<=r||n<c&&c<=a,!this.cannotMerge){const n=this.env.model.getters.expandZone(o,oo({col:t,row:i}));this.inMerge=Gi(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=qu.getMenuItems()}getMenuName(e){return e.name(this.env)}toggleMerge(){if(this.cannotMerge)return;const e=this.env.model.getters.getSelectedZones(),t=[e[e.length-1]],i=this.env.model.getters.getActiveSheetId();this.inMerge?this.env.model.dispatch("REMOVE_MERGE",{sheetId:i,target:t}):function(e,t,i){const o=e.model.dispatch("ADD_MERGE",{sheetId:t,target:i});o.isCancelledBecause(80)?e.raiseError(Qb.MergeInFilter):o.isCancelledBecause(3)&&e.askConfirmation(Qb.MergeIsDestructive,(()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:i,force:!0})}))}(this.env,i,t)}setColor(e,t){Or(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=iS.find((t=>t.name===e)),i=t&&t.sidePanel||"";this.env.openSidePanel(i)}setDecimal(e){this.env.model.dispatch("SET_DECIMAL",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),step:e})}paintFormat(){this.env.model.dispatch("ACTIVATE_PAINT_FORMAT",{target:this.env.model.getters.getSelectedZones()})}clearFormatting(){this.env.model.dispatch("CLEAR_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}doAction(e){e(this.env),this.closeMenus()}undo(){this.env.model.dispatch("REQUEST_UNDO")}redo(){this.env.model.dispatch("REQUEST_REDO")}get selectionContainsFilter(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones();return this.env.model.getters.doesZonesContainFilter(e,t)}get cannotCreateFilter(){return!ro(...this.env.model.getters.getSelectedZones())}createFilter(){if(this.cannotCreateFilter)return;this.env.model.selection.selectTableAroundSelection();const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones();wr(this.env,e,t)}removeFilter(){this.env.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}}nS.template="o-spreadsheet-TopBar",nS.components={ColorPickerWidget:sg,Menu:qn,TopBarComposer:Jb,FontSizeEditor:eS},nS.props={onClick:Function,focusComposer:String,onComposerContentFocused:Function,dropdownMaxHeight:Number};class sS{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({[on.PlainText]:this.getBlob(e,on.PlainText),[on.Html]:this.getBlob(e,on.Html)})]}getBlob(e,t){return new Blob([e[t]||""],{type:t})}}ho`
1896
+ `;class sS extends t.Component{constructor(){super(...arguments),this.commonFormats=iS,this.customFormats=oS,this.currentFormatName="automatic",this.style={},this.state=t.useState({menuState:{isOpen:!1,position:null,menuItems:[]},activeTool:""}),this.isSelectingMenu=!1,this.openedEl=null,this.inMerge=!1,this.cannotMerge=!1,this.undoTool=!1,this.redoTool=!1,this.paintFormatTool=!1,this.fillColor="#ffffff",this.textColor="#000000",this.menus=[]}get dropdownStyle(){return`max-height:${this.props.dropdownMaxHeight}px`}setup(){t.useExternalListener(window,"click",this.onExternalClick),t.onWillStart((()=>this.updateCellState())),t.onWillUpdateProps((()=>this.updateCellState()))}get topbarComponents(){return Ig.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){Nr(this.env,{[e]:!this.style[e]})}toggleFormat(e){const t=iS.find((t=>t.name===e)),i=t&&t.value||"";Or(this.env,i)}toggleHorizontalAlign(e){Nr(this.env,{align:e}),this.onClick()}toggleVerticalAlign(e){Nr(this.env,{verticalAlign:e}),this.onClick()}toggleTextWrapping(e){Nr(this.env,{wrapping:e}),this.onClick()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.openMenu(e,t)}toggleDropdownTool(e,t){const i=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=i?"":e,this.openedEl=i?null:t.target}toggleContextMenu(e,t){this.state.menuState.isOpen?this.closeMenus():this.openMenu(e,t)}openMenu(e,t){const{left:i,top:o,height:n}=t.target.getBoundingClientRect();this.state.menuState.isOpen=!0,this.state.menuState.position={x:i,y:o+n},this.state.menuState.menuItems=e.children(this.env),this.state.menuState.parentMenu=e,this.isSelectingMenu=!0,this.openedEl=t.target,this.env.model.dispatch("STOP_EDITION")}closeMenus(){this.state.activeTool="",this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){const e=this.env.model.getters.getSelectedZones(),{col:t,row:i,sheetId:o}=this.env.model.getters.getActivePosition();this.inMerge=!1;const{top:n,left:s,right:r,bottom:a}=this.env.model.getters.getSelectedZone(),{xSplit:l,ySplit:c}=this.env.model.getters.getPaneDivisions(o);if(this.cannotMerge=e.length>1||n===a&&s===r||s<l&&l<=r||n<c&&c<=a,!this.cannotMerge){const n=this.env.model.getters.expandZone(o,no({col:t,row:i}));this.inMerge=qi(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=Zu.getMenuItems()}getMenuName(e){return e.name(this.env)}toggleMerge(){if(this.cannotMerge)return;const e=this.env.model.getters.getSelectedZones(),t=[e[e.length-1]],i=this.env.model.getters.getActiveSheetId();this.inMerge?this.env.model.dispatch("REMOVE_MERGE",{sheetId:i,target:t}):function(e,t,i){const o=e.model.dispatch("ADD_MERGE",{sheetId:t,target:i});o.isCancelledBecause(80)?e.raiseError(Jb.MergeInFilter):o.isCancelledBecause(3)&&e.askConfirmation(Jb.MergeIsDestructive,(()=>{e.model.dispatch("ADD_MERGE",{sheetId:t,target:i,force:!0})}))}(this.env,i,t)}setColor(e,t){Nr(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=oS.find((t=>t.name===e)),i=t&&t.sidePanel||"";this.env.openSidePanel(i)}setDecimal(e){this.env.model.dispatch("SET_DECIMAL",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),step:e})}paintFormat(){this.env.model.dispatch("ACTIVATE_PAINT_FORMAT",{target:this.env.model.getters.getSelectedZones()})}clearFormatting(){this.env.model.dispatch("CLEAR_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}doAction(e){e(this.env),this.closeMenus()}undo(){this.env.model.dispatch("REQUEST_UNDO")}redo(){this.env.model.dispatch("REQUEST_REDO")}get selectionContainsFilter(){const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones();return this.env.model.getters.doesZonesContainFilter(e,t)}get cannotCreateFilter(){return!ao(...this.env.model.getters.getSelectedZones())}createFilter(){if(this.cannotCreateFilter)return;this.env.model.selection.selectTableAroundSelection();const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones();yr(this.env,e,t)}removeFilter(){this.env.model.dispatch("REMOVE_FILTER_TABLE",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}}sS.template="o-spreadsheet-TopBar",sS.components={ColorPickerWidget:rg,Menu:Zn,TopBarComposer:eS,FontSizeEditor:tS},sS.props={onClick:Function,focusComposer:String,onComposerContentFocused:Function,dropdownMaxHeight:Number};class rS{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({[nn.PlainText]:this.getBlob(e,nn.PlainText),[nn.Html]:this.getBlob(e,nn.Html)})]}getBlob(e,t){return new Blob([e[t]||""],{type:t})}}uo`
1896
1897
  .o-spreadsheet {
1897
1898
  position: relative;
1898
1899
  display: grid;
@@ -1936,7 +1937,7 @@
1936
1937
  height: ${15}px;
1937
1938
  vertical-align: sub;
1938
1939
  }
1939
- `,ho`
1940
+ `,uo`
1940
1941
  .o-grid {
1941
1942
  position: relative;
1942
1943
  overflow: hidden;
@@ -1965,23 +1966,23 @@
1965
1966
  outline: none;
1966
1967
  }
1967
1968
  }
1968
- `;class rS 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 Bb(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:rS._t,clipboard:this.env.clipboard||new sS(navigator.clipboard),startCellEdition:e=>this.onGridComposerCellFocused(e)}),t.useExternalListener(window,"resize",(()=>this.render(!0))),t.useExternalListener(window,"beforeunload",this.unbindModelEvents.bind(this)),this.bindModelEvents(),t.onMounted((()=>{this.checkViewportSize()})),t.onWillUnmount((()=>this.unbindModelEvents())),t.onPatched((()=>{this.checkViewportSize()}))}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}bindModelEvents(){this.model.on("update",this,(()=>this.render(!0))),this.model.on("notify-ui",this,this.onNotifyUI)}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.env.notifyUser({text:s("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),tag:"viewportTooSmall"}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}onNotifyUI(e){if("ERROR"===e.type)this.env.raiseError(e.text)}openSidePanel(e,t){this.sidePanel.component=e,this.sidePanel.panelProps=t,this.sidePanel.isOpen=!0}closeSidePanel(){this.sidePanel.isOpen=!1,this.focusGrid()}toggleSidePanel(e,t){this.sidePanel.isOpen&&e===this.sidePanel.component?(this.sidePanel.isOpen=!1,this.focusGrid()):this.openSidePanel(e,t)}focusGrid(){if(!this._focusGrid)throw new Error("_focusGrid should be exposed by the grid component");this._focusGrid()}onKeydown(e){let t="";(e.ctrlKey||e.metaKey)&&(t+="CTRL+"),t+=e.key.toUpperCase();let i=this.keyDownMapping[t];if(i)return e.preventDefault(),e.stopPropagation(),void i()}onTopBarComposerFocused(e){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="contentFocus",this.composer.gridFocusMode="inactive",this.setComposerContent({selection:e}||{}))}onGridComposerContentFocused(){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="contentFocus",this.setComposerContent({}))}onGridComposerCellFocused(e,t){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="cellFocus",this.setComposerContent({content:e,selection:t}||{}))}setComposerContent({content:e,selection:t}){"inactive"===this.model.getters.getEditionMode()?this.model.dispatch("START_EDITION",{text:e,selection:t}):e&&this.model.dispatch("SET_CURRENT_CONTENT",{content:e,selection:t})}get gridHeight(){const{height:e}=this.env.model.getters.getSheetViewDimension();return e}}rS.template="o-spreadsheet-Spreadsheet",rS.components={TopBar:nS,Grid:hp,BottomBar:jb,SidePanel:Kb,SpreadsheetDashboard:Yb},rS._t=e=>e,rS.props={model:Object};class aS{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 lS(e){return pr.get(e.type)(e)}function cS(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class hS{constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find((t=>t.id===e));if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){var e;return null===(e=this.operations[this.operations.length-1])||void 0===e?void 0:e.id}getFirstOperationAmong(e,t){for(const i of this.operations){if(i.id===e)return e;if(i.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const i=this.buildTransformation.with(e.data),{before:o,operation:n,after:s}=this.locateOperation(t);this.operations=[...o,n,e,...s.map((e=>e.transformed(i)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new hS(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:i}=this.locateOperation(e);this.operations=t.concat([i])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class dS{constructor(e,t){this.id=e,this.data=t}transformed(e){return new uS(this.id,nt((()=>e(this.data))))}}class uS{constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new uS(this.id,this.lazyData.map(e))}}class gS{constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new gS(function*(e,t){for(const i of e)if(yield i,i.operation.id===t)return}(this.operations,e))}stopBefore(e){return new gS(function*(e,t){for(const i of e){if(i.operation.id===t)return;yield i}}(this.operations,e))}startAfter(e){return new gS(function*(e,t){let i=!0;for(const o of e)i||(yield o),o.operation.id===t&&(i=!1)}(this.operations,e))}}class pS{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 gS(He(this._execution(e),this._execution(e)))}revertedExecution(e){return new gS(He(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){var i;const o=e.getLastOperationId()||(null===(i=this.previousBranch(e))||void 0===i?void 0:i.getLastOperationId());e.append(t),o&&this.insertPrevious(e,t,o)}insertOperationAfter(e,t,i){e.insert(t,i),this.updateNextWith(e,t,i),this.insertPrevious(e,t,i)}undo(e,t){const i=this.buildTransformation.without(t.data),o=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const n=e.fork(t.id);o&&this.branchingOperationIds.set(n,o),this.insertBranchAfter(e,n),this.transform(n,i)}redo(e){const t=this.nextBranch(e);if(!t)return;const i=this.nextBranch(t);this.removeBranchFromTree(t);const o=this.branchingOperationIds.get(t);o?this.branchingOperationIds.set(e,o):this.branchingOperationIds.delete(e),i&&this.rebaseUp(i)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const i of this.revertedExecution(e))if(i.operation.id===t)return i;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!t||!i)return;const o=this.buildTransformation.without(i.data),n=t.fork(i.id);this.branchingOperationIds.set(n,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,n),n.transform(o);const s=this.nextBranch(n);s&&this.rebaseUp(s)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const i=this.branches.findIndex((t=>t===e));this.branches.splice(i+1,0,t)}updateNextWith(e,t,i){const o=this.branchingOperationIds.get(e),n=this.nextBranch(e);if(o&&n)if(e.getFirstOperationAmong(i,o)===o){const s=this.addToNextBranch(e,n,o,t,i);this.updateNextWith(n,s,i)}else{const e=this.buildTransformation.with(t.data);this.transform(n,e)}}addToNextBranch(e,t,i,o,n){let s=o;return n===i?(s=this.getTransformedOperation(e,i,o),t.prepend(s)):t.contains(n)?(s=this.getTransformedOperation(e,i,o),t.insert(s,n)):t.append(o),s}getTransformedOperation(e,t,i){const o=e.getOperation(t),n=this.buildTransformation.without(o.data);return i.transformed(n)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const i=this.nextBranch(e);i&&this.transform(i,t)}insertPrevious(e,t,i){const{previousBranch:o,branchingOperation:n}=this.findPreviousBranchingOperation(e);if(!o||!n)return;const s=this.buildTransformation.with(n.data),r=e.fork(i);r.transform(s),o.cutAfter(i),o.appendBranch(r);const a=t.transformed(s);this.insertPrevious(o,a,i)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const i=this.branchingOperationIds.get(t);return i?{previousBranch:t,branchingOperation:t.getOperation(i)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let i=!!t;const o=e.getOperations();for(let n=o.length-1;n>=0;n--){const s=o[n];s.id===t&&(i=!1),i||(yield{operation:s,branch:e,isCancelled:!this.shouldExecute(e,s)})}const n=this.previousBranch(e);yield*n?this._revertedExecution(n):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class mS{constructor(e,t,i,o,n){this.applyOperation=t,this.revertOperation=i,this.buildEmpty=o,this.buildTransformation=n,this.HEAD_BRANCH=new hS(this.buildTransformation),this.tree=new pS(n,this.HEAD_BRANCH);const s=new dS(e,o(e));this.tree.insertOperationLast(this.HEAD_BRANCH,s),this.HEAD_OPERATION=s}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const i=new dS(e,t),o=this.tree.getLastBranch();this.tree.insertOperationLast(o,i),this.HEAD_BRANCH=o,this.HEAD_OPERATION=i}insert(e,t,i){const o=new dS(e,t);this.revertTo(i),this.tree.insertOperationAfter(this.HEAD_BRANCH,o,i),this.fastForward()}undo(e,t,i){const{branch:o,operation:n}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(o,n),this.fastForward(),this.insert(t,this.buildEmpty(t),i)}redo(e,t,i){const{branch:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(o),this.fastForward(),this.insert(t,this.buildEmpty(t),i)}drop(e){this.revertBefore(e),this.tree.drop(e)}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:i,isCancelled:o}of e)o||this.revertOperation(i.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:i,isCancelled:o}of e)o||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=i}}function fS(e,t,i){return new mS(e,(e=>{const o=e.commands.slice(),{changes:n}=t((()=>{for(const e of o)i(e)}));e.setChanges(n)}),(e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){vS(t.changes[e],"before")}}([e])),(e=>new pb(e,"empty",[],[])),{with:e=>t=>new pb(t.id,t.clientId,ub(t.commands,e.commands)),without:e=>t=>new pb(t.id,t.clientId,ub(t.commands,e.commands.map(lS).flat()))})}function vS(e,t){let i=e.root,o=e.path[e.path.length-1];for(let t=0;t<e.path.slice(0,-1).length;t++){const o=e.path[t];if(void 0===i[o]){const n=e.path[t+1];i[o]=cS(n)}i=i[o]}void 0===e[t]?delete i[o]:i[o]=e[t]}class bS 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 SS{constructor(){this.observers=[]}registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||(this.mainSubscription=this.defaultSubscription)}observe(e,t){this.observers.push({owner:e,callbacks:t})}capture(e,t){var i,o,n;if(this.observers.find((t=>t.owner===e)))throw new Error("You are already subscribed forever");(null===(i=this.mainSubscription)||void 0===i?void 0:i.owner)&&this.mainSubscription.owner!==e&&(null===(n=(o=this.mainSubscription.callbacks).release)||void 0===n||n.call(o)),this.mainSubscription={owner:e,callbacks:t}}release(e){var t;(null===(t=this.mainSubscription)||void 0===t?void 0:t.owner)!==e||this.observers.find((t=>t.owner===e))||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){var e,t,i;this.mainSubscription!==this.defaultSubscription&&(null===(i=null===(e=this.mainSubscription)||void 0===e?void 0:(t=e.callbacks).release)||void 0===i||i.call(t),this.mainSubscription=this.defaultSubscription)}isListening(e){var t;return(null===(t=this.mainSubscription)||void 0===t?void 0:t.owner)===e}send(e){var t;null===(t=this.mainSubscription)||void 0===t||t.callbacks.handleEvent(e),[...this.observers].forEach((t=>t.callbacks.handleEvent(e)))}}class CS{constructor(e){this.getters=e,this.stream=new SS,this.anchor={cell:{col:0,row:0},zone:oo({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,i){this.stream.capture(e,i),this.anchor=t}registerAsDefault(e,t,i){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,i),this.defaultAnchor=t,this.capture(e,t,i)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}selectZone(e){return this.modifyAnchor(e,"overrideSelection","ZonesSelected")}modifyAnchor(e,t,i){const o=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(o,e.zone)},this.processEvent({type:i,anchor:e,mode:t})}selectCell(e,t){const i=oo({col:e,row:t});return this.selectZone({zone:i,cell:{col:e,row:t}})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new cn(83);const{col:i,row:o}=this.getNextAvailablePosition(e,t);return this.selectCell(i,o)}setAnchorCorner(e,t){const i=this.getters.getActiveSheetId(),{col:o,row:n}=this.anchor.cell,s={left:Math.min(o,e),top:Math.min(n,t),right:Math.max(o,e),bottom:Math.max(n,t)},r={zone:this.getters.expandZone(i,s),cell:{col:o,row:n}};return this.processEvent({type:"AlterZone",mode:"updateAnchor",anchor:r})}addCellToSelection(e,t){const i=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:i,col:e,row:t}));const o=this.getters.expandZone(i,oo({col:e,row:t}));return this.processEvent({type:"ZonesSelected",anchor:{zone:o,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new cn(83);const i=this.getters.getActiveSheetId(),o=this.anchor,{col:n,row:s}=o.cell,{left:r,right:a,top:l,bottom:c}=o.zone,h=this.getStartingPosition(e);let[d,u]=this.deltaToTarget(h,e,t);if(0===d&&0===u)return cn.Success;let g=o.zone;const p=e=>{e=io(e);const{left:t,right:o,top:n,bottom:s}=this.getters.expandZone(i,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(i)-1,o),top:Math.max(0,n),bottom:Math.min(this.getters.getNumberRows(i)-1,s)}},{col:m,row:f}=this.getReferencePosition();let v=0;for(;null!==g;){if(v++,d<0){const e=this.getNextAvailableCol(d,a-(v-1),f);g=m<=a-v?p({top:l,left:r,bottom:c,right:e}):null}if(d>0){const e=this.getNextAvailableCol(d,r+(v-1),f);g=r+v<=m?p({top:l,left:e,bottom:c,right:a}):null}if(u<0){const e=this.getNextAvailableRow(u,m,c-(v-1));g=f<=c-v?p({top:l,left:r,bottom:e,right:a}):null}if(u>0){const e=this.getNextAvailableRow(u,m,l+(v-1));g=l+v<=f?p({top:e,left:r,bottom:c,right:a}):null}if(g=g?io(g):g,g&&!Gi(g,o.zone))return this.processEvent({type:"ZonesSelected",mode:"updateAnchor",anchor:{zone:g,cell:{col:n,row:s}}})}g=p($i({top:s,bottom:s,left:n,right:n},io({top:this.getNextAvailableRow(u,m,l),left:this.getNextAvailableCol(d,r,f),bottom:this.getNextAvailableRow(u,m,c),right:this.getNextAvailableCol(d,a,f)})));const b={zone:g,cell:{col:n,row:s}};return this.processEvent({type:"ZonesSelected",anchor:b,mode:"updateAnchor"})}selectColumn(e,t){const i=this.getters.getActiveSheetId(),o=this.getters.getNumberRows(i)-1;let n={left:e,right:e,top:0,bottom:o};const s=this.getters.findFirstVisibleColRowIndex(i,"ROW");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=e,a=s;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),n=$i(n,{left:r,right:r,top:s,bottom:o})}return this.processEvent({type:"HeadersSelected",anchor:{zone:n,cell:{col:r,row:a}},mode:t})}selectRow(e,t){const i=this.getters.getActiveSheetId(),o=this.getters.getNumberCols(i)-1;let n={top:e,bottom:e,left:0,right:o};const s=this.getters.findFirstVisibleColRowIndex(i,"COL");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=s,a=e;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),n=$i(n,{left:s,right:o,top:a,bottom:a})}return this.processEvent({type:"HeadersSelected",anchor:{zone:n,cell:{col:r,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(Gi(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:oo(t.cell)},"updateAnchor","AlterZone");const i=this.expandZoneToTable(t.zone);return at(i,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:i},"updateAnchor","AlterZone")}selectTableAroundSelection(){const e=this.expandZoneToTable(this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:e},"updateAnchor","AlterZone")}selectAll(){const e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({type:"HeadersSelected",mode:"overrideSelection",anchor:{zone:t,cell:this.anchor.cell}})}processEvent(e){const t={...e,previousAnchor:Ne(this.anchor)},i=this.checkEventAnchorZone(t);return 0!==i?new cn(i):(this.anchor=t.anchor,this.stream.send(t),cn.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:i}=e;if(!Zi(t.col,t.row,i))return 16;const{left:o,right:n,top:s,bottom:r}=i,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",o,n);return void 0===this.getters.findVisibleHeader(a,"ROW",s,r)||void 0===l?17:0}checkAnchorZoneOrThrow(e){if(16===this.checkAnchorZone(e))throw new Error(n("The provided anchor is invalid. The cell must be part of the zone."))}getNextAvailablePosition(e,t=1){const{col:i,row:o}=this.anchor.cell,n=this.deltaToTarget({col:i,row:o},e,t);return{col:this.getNextAvailableCol(n[0],i,o),row:this.getNextAvailableRow(n[1],i,o)}}getNextAvailableCol(e,t,i){const o=this.getters.getActiveSheetId(),n={col:t,row:i};return this.getNextAvailableHeader(e,"COL",t,n,(e=>this.getters.isInSameMerge(o,t,i,e,i)))}getNextAvailableRow(e,t,i){const o=this.getters.getActiveSheetId(),n={col:t,row:i};return this.getNextAvailableHeader(e,"ROW",i,n,(e=>this.getters.isInSameMerge(o,t,i,t,e)))}getNextAvailableHeader(e,t,i,o,n){const s=this.getters.getActiveSheetId();if(0===e)return i;const r=Math.sign(e);let a=i+e;for(;n(a);)a+=r;for(;this.getters.isHeaderHidden(s,t,a);)a+=r;return a<0||a>this.getters.getNumberHeaders(s,t)-1?this.getters.isHeaderHidden(s,t,i)?this.getNextAvailableHeader(-r,t,i,o,n):i:a}getReferencePosition(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:i,right:o,top:n,bottom:s}=t.zone,{col:r,row:a}=t.cell;return{col:this.getters.isColHidden(e,r)&&this.getters.findVisibleHeader(e,"COL",i,o)||r,row:this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",n,s)||a}}deltaToTarget(e,t,i){switch(t){case"up":return"end"!==i?[0,-i]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==i?[0,i]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==i?[-i,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==i?[i,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:i}=this.getPosition();const o=this.anchor.zone;switch(e){case"down":case"up":i=i===o.top?o.bottom:o.top;break;case"left":case"right":t=t===o.right?o.left:o.right}return{col:t,row:i}}getEndOfCluster(e,t,i){const o=this.getters.getActiveSheet();let n=e;const s=this.getNextCellPosition(e,t,i);let r=this.isCellEmpty(n,o.id)||this.isCellEmpty(s,o.id)?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(n,t,i);if(n.col===e.col&&n.row===e.row)break;const s=this.isCellEmpty(e,o.id);if("endOfCluster"===r&&s)break;if("nextCluster"===r&&!s){n=e;break}n=e}return"cols"===t?n.col:n.row}isCellEmpty({col:e,row:t},i=this.getters.getActiveSheetId()){const o=this.getters.getMainCellPosition({sheetId:i,col:e,row:t});return this.getters.getEvaluatedCell(o).type===tn.empty}getNextCellPosition(e,t,i){const o="cols"===t?"col":"row",n={...e},s="cols"===t?this.getNextAvailableCol(i,n.col,n.row):this.getNextAvailableRow(i,n.col,n.row);return n[o]=s,{col:n.col,row:n.row}}getPosition(){return{...this.anchor.cell}}expandZoneToTable(e){const t=e=>{for(const t of ze(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 ze(e.top,e.bottom+1)){if(!this.isCellEmpty({col:e.left-1,row:t}))return{...e,left:e.left-1};if(!this.isCellEmpty({col:e.right+1,row:t}))return{...e,right:e.right+1}}return e};let i=!1,o=e;do{i=!1;const e=t(o);Gi(o,e)||(i=!0,o=e)}while(i);return o}}class ES{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(),[i,...o]=e;let n=i,s=o[o.length-1];for(let e=0;e<=o.length-2;e++){const t=o[e];if(void 0===n[t]){const i=o[e+1];n[t]=cS(i)}n=n[t]}n[s]!==t&&(this.changes.push({root:i,path:o,before:n[s],after:t}),void 0===t?delete n[s]:n[s]=t)}}const wS=17781237,yS=88853993;function xS(e,t,i){const o=[["xmlns:r",Cp],["xmlns:a",fp],["xmlns:c",vp]],n=IS({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let s=Xf``;e.data.title&&(s=Xf`
1969
+ `;class aS 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 Hb(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:aS._t,clipboard:this.env.clipboard||new rS(navigator.clipboard),startCellEdition:e=>this.onGridComposerCellFocused(e)}),t.useExternalListener(window,"resize",(()=>this.render(!0))),t.useExternalListener(window,"beforeunload",this.unbindModelEvents.bind(this)),this.bindModelEvents(),t.onMounted((()=>{this.checkViewportSize()})),t.onWillUnmount((()=>this.unbindModelEvents())),t.onPatched((()=>{this.checkViewportSize()}))}get focusTopBarComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.topBarFocus}get focusGridComposer(){return"inactive"===this.model.getters.getEditionMode()?"inactive":this.composer.gridFocusMode}bindModelEvents(){this.model.on("update",this,(()=>this.render(!0))),this.model.on("notify-ui",this,this.onNotifyUI)}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.env.notifyUser({text:s("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),tag:"viewportTooSmall"}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}onNotifyUI(e){if("ERROR"===e.type)this.env.raiseError(e.text)}openSidePanel(e,t){this.sidePanel.component=e,this.sidePanel.panelProps=t,this.sidePanel.isOpen=!0}closeSidePanel(){this.sidePanel.isOpen=!1,this.focusGrid()}toggleSidePanel(e,t){this.sidePanel.isOpen&&e===this.sidePanel.component?(this.sidePanel.isOpen=!1,this.focusGrid()):this.openSidePanel(e,t)}focusGrid(){if(!this._focusGrid)throw new Error("_focusGrid should be exposed by the grid component");this._focusGrid()}onKeydown(e){let t="";(e.ctrlKey||e.metaKey)&&(t+="CTRL+"),t+=e.key.toUpperCase();let i=this.keyDownMapping[t];if(i)return e.preventDefault(),e.stopPropagation(),void i()}onTopBarComposerFocused(e){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="contentFocus",this.composer.gridFocusMode="inactive",this.setComposerContent({selection:e}||{}))}onGridComposerContentFocused(){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="contentFocus",this.setComposerContent({}))}onGridComposerCellFocused(e,t){this.model.getters.isReadonly()||(this.model.dispatch("UNFOCUS_SELECTION_INPUT"),this.composer.topBarFocus="inactive",this.composer.gridFocusMode="cellFocus",this.setComposerContent({content:e,selection:t}||{}))}setComposerContent({content:e,selection:t}){"inactive"===this.model.getters.getEditionMode()?this.model.dispatch("START_EDITION",{text:e,selection:t}):e&&this.model.dispatch("SET_CURRENT_CONTENT",{content:e,selection:t})}get gridHeight(){const{height:e}=this.env.model.getters.getSheetViewDimension();return e}}aS.template="o-spreadsheet-Spreadsheet",aS.components={TopBar:sS,Grid:dp,BottomBar:Xb,SidePanel:Qb,SpreadsheetDashboard:Kb},aS._t=e=>e,aS.props={model:Object};class lS{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 cS(e){return mr.get(e.type)(e)}function hS(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class dS{constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find((t=>t.id===e));if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){var e;return null===(e=this.operations[this.operations.length-1])||void 0===e?void 0:e.id}getFirstOperationAmong(e,t){for(const i of this.operations){if(i.id===e)return e;if(i.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const i=this.buildTransformation.with(e.data),{before:o,operation:n,after:s}=this.locateOperation(t);this.operations=[...o,n,e,...s.map((e=>e.transformed(i)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new dS(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:i}=this.locateOperation(e);this.operations=t.concat([i])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class uS{constructor(e,t){this.id=e,this.data=t}transformed(e){return new gS(this.id,st((()=>e(this.data))))}}class gS{constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new gS(this.id,this.lazyData.map(e))}}class pS{constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new pS(function*(e,t){for(const i of e)if(yield i,i.operation.id===t)return}(this.operations,e))}stopBefore(e){return new pS(function*(e,t){for(const i of e){if(i.operation.id===t)return;yield i}}(this.operations,e))}startAfter(e){return new pS(function*(e,t){let i=!0;for(const o of e)i||(yield o),o.operation.id===t&&(i=!1)}(this.operations,e))}}class mS{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 pS($e(this._execution(e),this._execution(e)))}revertedExecution(e){return new pS($e(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){var i;const o=e.getLastOperationId()||(null===(i=this.previousBranch(e))||void 0===i?void 0:i.getLastOperationId());e.append(t),o&&this.insertPrevious(e,t,o)}insertOperationAfter(e,t,i){e.insert(t,i),this.updateNextWith(e,t,i),this.insertPrevious(e,t,i)}undo(e,t){const i=this.buildTransformation.without(t.data),o=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const n=e.fork(t.id);o&&this.branchingOperationIds.set(n,o),this.insertBranchAfter(e,n),this.transform(n,i)}redo(e){const t=this.nextBranch(e);if(!t)return;const i=this.nextBranch(t);this.removeBranchFromTree(t);const o=this.branchingOperationIds.get(t);o?this.branchingOperationIds.set(e,o):this.branchingOperationIds.delete(e),i&&this.rebaseUp(i)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const i of this.revertedExecution(e))if(i.operation.id===t)return i;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!t||!i)return;const o=this.buildTransformation.without(i.data),n=t.fork(i.id);this.branchingOperationIds.set(n,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,n),n.transform(o);const s=this.nextBranch(n);s&&this.rebaseUp(s)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const i=this.branches.findIndex((t=>t===e));this.branches.splice(i+1,0,t)}updateNextWith(e,t,i){const o=this.branchingOperationIds.get(e),n=this.nextBranch(e);if(o&&n)if(e.getFirstOperationAmong(i,o)===o){const s=this.addToNextBranch(e,n,o,t,i);this.updateNextWith(n,s,i)}else{const e=this.buildTransformation.with(t.data);this.transform(n,e)}}addToNextBranch(e,t,i,o,n){let s=o;return n===i?(s=this.getTransformedOperation(e,i,o),t.prepend(s)):t.contains(n)?(s=this.getTransformedOperation(e,i,o),t.insert(s,n)):t.append(o),s}getTransformedOperation(e,t,i){const o=e.getOperation(t),n=this.buildTransformation.without(o.data);return i.transformed(n)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const i=this.nextBranch(e);i&&this.transform(i,t)}insertPrevious(e,t,i){const{previousBranch:o,branchingOperation:n}=this.findPreviousBranchingOperation(e);if(!o||!n)return;const s=this.buildTransformation.with(n.data),r=e.fork(i);r.transform(s),o.cutAfter(i),o.appendBranch(r);const a=t.transformed(s);this.insertPrevious(o,a,i)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const i=this.branchingOperationIds.get(t);return i?{previousBranch:t,branchingOperation:t.getOperation(i)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let i=!!t;const o=e.getOperations();for(let n=o.length-1;n>=0;n--){const s=o[n];s.id===t&&(i=!1),i||(yield{operation:s,branch:e,isCancelled:!this.shouldExecute(e,s)})}const n=this.previousBranch(e);yield*n?this._revertedExecution(n):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class fS{constructor(e,t,i,o,n){this.applyOperation=t,this.revertOperation=i,this.buildEmpty=o,this.buildTransformation=n,this.HEAD_BRANCH=new dS(this.buildTransformation),this.tree=new mS(n,this.HEAD_BRANCH);const s=new uS(e,o(e));this.tree.insertOperationLast(this.HEAD_BRANCH,s),this.HEAD_OPERATION=s}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const i=new uS(e,t),o=this.tree.getLastBranch();this.tree.insertOperationLast(o,i),this.HEAD_BRANCH=o,this.HEAD_OPERATION=i}insert(e,t,i){const o=new uS(e,t);this.revertTo(i),this.tree.insertOperationAfter(this.HEAD_BRANCH,o,i),this.fastForward()}undo(e,t,i){const{branch:o,operation:n}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(o,n),this.fastForward(),this.insert(t,this.buildEmpty(t),i)}redo(e,t,i){const{branch:o}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(o),this.fastForward(),this.insert(t,this.buildEmpty(t),i)}drop(e){this.revertBefore(e),this.tree.drop(e)}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:i,isCancelled:o}of e)o||this.revertOperation(i.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:i,isCancelled:o}of e)o||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=i}}function vS(e,t,i){return new fS(e,(e=>{const o=e.commands.slice(),{changes:n}=t((()=>{for(const e of o)i(e)}));e.setChanges(n)}),(e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){bS(t.changes[e],"before")}}([e])),(e=>new mb(e,"empty",[],[])),{with:e=>t=>new mb(t.id,t.clientId,gb(t.commands,e.commands)),without:e=>t=>new mb(t.id,t.clientId,gb(t.commands,e.commands.map(cS).flat()))})}function bS(e,t){let i=e.root,o=e.path[e.path.length-1];for(let t=0;t<e.path.slice(0,-1).length;t++){const o=e.path[t];if(void 0===i[o]){const n=e.path[t+1];i[o]=hS(n)}i=i[o]}void 0===e[t]?delete i[o]:i[o]=e[t]}class SS 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 CS{constructor(){this.observers=[]}registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||(this.mainSubscription=this.defaultSubscription)}observe(e,t){this.observers.push({owner:e,callbacks:t})}capture(e,t){var i,o,n;if(this.observers.find((t=>t.owner===e)))throw new Error("You are already subscribed forever");(null===(i=this.mainSubscription)||void 0===i?void 0:i.owner)&&this.mainSubscription.owner!==e&&(null===(n=(o=this.mainSubscription.callbacks).release)||void 0===n||n.call(o)),this.mainSubscription={owner:e,callbacks:t}}release(e){var t;(null===(t=this.mainSubscription)||void 0===t?void 0:t.owner)!==e||this.observers.find((t=>t.owner===e))||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){var e,t,i;this.mainSubscription!==this.defaultSubscription&&(null===(i=null===(e=this.mainSubscription)||void 0===e?void 0:(t=e.callbacks).release)||void 0===i||i.call(t),this.mainSubscription=this.defaultSubscription)}isListening(e){var t;return(null===(t=this.mainSubscription)||void 0===t?void 0:t.owner)===e}send(e){var t;null===(t=this.mainSubscription)||void 0===t||t.callbacks.handleEvent(e),[...this.observers].forEach((t=>t.callbacks.handleEvent(e)))}}class ES{constructor(e){this.getters=e,this.stream=new CS,this.anchor={cell:{col:0,row:0},zone:no({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,i){this.stream.capture(e,i),this.anchor=t}registerAsDefault(e,t,i){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,i),this.defaultAnchor=t,this.capture(e,t,i)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}selectZone(e){return this.modifyAnchor(e,"overrideSelection","ZonesSelected")}modifyAnchor(e,t,i){const o=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(o,e.zone)},this.processEvent({type:i,anchor:e,mode:t})}selectCell(e,t){const i=no({col:e,row:t});return this.selectZone({zone:i,cell:{col:e,row:t}})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new hn(83);const{col:i,row:o}=this.getNextAvailablePosition(e,t);return this.selectCell(i,o)}setAnchorCorner(e,t){const i=this.getters.getActiveSheetId(),{col:o,row:n}=this.anchor.cell,s={left:Math.min(o,e),top:Math.min(n,t),right:Math.max(o,e),bottom:Math.max(n,t)},r={zone:this.getters.expandZone(i,s),cell:{col:o,row:n}};return this.processEvent({type:"AlterZone",mode:"updateAnchor",anchor:r})}addCellToSelection(e,t){const i=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:i,col:e,row:t}));const o=this.getters.expandZone(i,no({col:e,row:t}));return this.processEvent({type:"ZonesSelected",anchor:{zone:o,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new hn(83);const i=this.getters.getActiveSheetId(),o=this.anchor,{col:n,row:s}=o.cell,{left:r,right:a,top:l,bottom:c}=o.zone,h=this.getStartingPosition(e);let[d,u]=this.deltaToTarget(h,e,t);if(0===d&&0===u)return hn.Success;let g=o.zone;const p=e=>{e=oo(e);const{left:t,right:o,top:n,bottom:s}=this.getters.expandZone(i,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(i)-1,o),top:Math.max(0,n),bottom:Math.min(this.getters.getNumberRows(i)-1,s)}},{col:m,row:f}=this.getReferencePosition();let v=0;for(;null!==g;){if(v++,d<0){const e=this.getNextAvailableCol(d,a-(v-1),f);g=m<=a-v?p({top:l,left:r,bottom:c,right:e}):null}if(d>0){const e=this.getNextAvailableCol(d,r+(v-1),f);g=r+v<=m?p({top:l,left:e,bottom:c,right:a}):null}if(u<0){const e=this.getNextAvailableRow(u,m,c-(v-1));g=f<=c-v?p({top:l,left:r,bottom:e,right:a}):null}if(u>0){const e=this.getNextAvailableRow(u,m,l+(v-1));g=l+v<=f?p({top:e,left:r,bottom:c,right:a}):null}if(g=g?oo(g):g,g&&!qi(g,o.zone))return this.processEvent({type:"ZonesSelected",mode:"updateAnchor",anchor:{zone:g,cell:{col:n,row:s}}})}g=p(Wi({top:s,bottom:s,left:n,right:n},oo({top:this.getNextAvailableRow(u,m,l),left:this.getNextAvailableCol(d,r,f),bottom:this.getNextAvailableRow(u,m,c),right:this.getNextAvailableCol(d,a,f)})));const b={zone:g,cell:{col:n,row:s}};return this.processEvent({type:"ZonesSelected",anchor:b,mode:"updateAnchor"})}selectColumn(e,t){const i=this.getters.getActiveSheetId(),o=this.getters.getNumberRows(i)-1;let n={left:e,right:e,top:0,bottom:o};const s=this.getters.findFirstVisibleColRowIndex(i,"ROW");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=e,a=s;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),n=Wi(n,{left:r,right:r,top:s,bottom:o})}return this.processEvent({type:"HeadersSelected",anchor:{zone:n,cell:{col:r,row:a}},mode:t})}selectRow(e,t){const i=this.getters.getActiveSheetId(),o=this.getters.getNumberCols(i)-1;let n={top:e,bottom:e,left:0,right:o};const s=this.getters.findFirstVisibleColRowIndex(i,"COL");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=s,a=e;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),n=Wi(n,{left:s,right:o,top:a,bottom:a})}return this.processEvent({type:"HeadersSelected",anchor:{zone:n,cell:{col:r,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(qi(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:no(t.cell)},"updateAnchor","AlterZone");const i=this.expandZoneToTable(t.zone);return lt(i,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:i},"updateAnchor","AlterZone")}selectTableAroundSelection(){const e=this.expandZoneToTable(this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:e},"updateAnchor","AlterZone")}selectAll(){const e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({type:"HeadersSelected",mode:"overrideSelection",anchor:{zone:t,cell:this.anchor.cell}})}processEvent(e){const t={...e,previousAnchor:Ne(this.anchor)},i=this.checkEventAnchorZone(t);return 0!==i?new hn(i):(this.anchor=t.anchor,this.stream.send(t),hn.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:i}=e;if(!ji(t.col,t.row,i))return 16;const{left:o,right:n,top:s,bottom:r}=i,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",o,n);return void 0===this.getters.findVisibleHeader(a,"ROW",s,r)||void 0===l?17:0}checkAnchorZoneOrThrow(e){if(16===this.checkAnchorZone(e))throw new Error(n("The provided anchor is invalid. The cell must be part of the zone."))}getNextAvailablePosition(e,t=1){const{col:i,row:o}=this.anchor.cell,n=this.deltaToTarget({col:i,row:o},e,t);return{col:this.getNextAvailableCol(n[0],i,o),row:this.getNextAvailableRow(n[1],i,o)}}getNextAvailableCol(e,t,i){const o=this.getters.getActiveSheetId(),n={col:t,row:i};return this.getNextAvailableHeader(e,"COL",t,n,(e=>this.getters.isInSameMerge(o,t,i,e,i)))}getNextAvailableRow(e,t,i){const o=this.getters.getActiveSheetId(),n={col:t,row:i};return this.getNextAvailableHeader(e,"ROW",i,n,(e=>this.getters.isInSameMerge(o,t,i,t,e)))}getNextAvailableHeader(e,t,i,o,n){const s=this.getters.getActiveSheetId();if(0===e)return i;const r=Math.sign(e);let a=i+e;for(;n(a);)a+=r;for(;this.getters.isHeaderHidden(s,t,a);)a+=r;return a<0||a>this.getters.getNumberHeaders(s,t)-1?this.getters.isHeaderHidden(s,t,i)?this.getNextAvailableHeader(-r,t,i,o,n):i:a}getReferencePosition(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:i,right:o,top:n,bottom:s}=t.zone,{col:r,row:a}=t.cell;return{col:this.getters.isColHidden(e,r)&&this.getters.findVisibleHeader(e,"COL",i,o)||r,row:this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",n,s)||a}}deltaToTarget(e,t,i){switch(t){case"up":return"end"!==i?[0,-i]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==i?[0,i]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==i?[-i,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==i?[i,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:i}=this.getPosition();const o=this.anchor.zone;switch(e){case"down":case"up":i=i===o.top?o.bottom:o.top;break;case"left":case"right":t=t===o.right?o.left:o.right}return{col:t,row:i}}getEndOfCluster(e,t,i){const o=this.getters.getActiveSheet();let n=e;const s=this.getNextCellPosition(e,t,i);let r=this.isCellEmpty(n,o.id)||this.isCellEmpty(s,o.id)?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(n,t,i);if(n.col===e.col&&n.row===e.row)break;const s=this.isCellEmpty(e,o.id);if("endOfCluster"===r&&s)break;if("nextCluster"===r&&!s){n=e;break}n=e}return"cols"===t?n.col:n.row}isCellEmpty({col:e,row:t},i=this.getters.getActiveSheetId()){const o=this.getters.getMainCellPosition({sheetId:i,col:e,row:t});return this.getters.getEvaluatedCell(o).type===on.empty}getNextCellPosition(e,t,i){const o="cols"===t?"col":"row",n={...e},s="cols"===t?this.getNextAvailableCol(i,n.col,n.row):this.getNextAvailableRow(i,n.col,n.row);return n[o]=s,{col:n.col,row:n.row}}getPosition(){return{...this.anchor.cell}}expandZoneToTable(e){const t=e=>{for(const t of Be(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 Be(e.top,e.bottom+1)){if(!this.isCellEmpty({col:e.left-1,row:t}))return{...e,left:e.left-1};if(!this.isCellEmpty({col:e.right+1,row:t}))return{...e,right:e.right+1}}return e};let i=!1,o=e;do{i=!1;const e=t(o);qi(o,e)||(i=!0,o=e)}while(i);return o}}class wS{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(),[i,...o]=e;let n=i,s=o[o.length-1];for(let e=0;e<=o.length-2;e++){const t=o[e];if(void 0===n[t]){const i=o[e+1];n[t]=hS(i)}n=n[t]}n[s]!==t&&(this.changes.push({root:i,path:o,before:n[s],after:t}),void 0===t?delete n[s]:n[s]=t)}}const yS=17781237,xS=88853993;function IS(e,t,i){const o=[["xmlns:r",Ep],["xmlns:a",vp],["xmlns:c",bp]],n=RS({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let s=Yf``;e.data.title&&(s=Yf`
1969
1970
  <c:title>
1970
- ${TS(e.data.title,e.data.fontColor)}
1971
+ ${AS(e.data.title,e.data.fontColor)}
1971
1972
  <c:overlay val="0" />
1972
1973
  </c:title>
1973
- `);let r=Xf``;switch(e.data.type){case"bar":r=function(e){const t=new ms,i=[];for(const[o,n]of Object.entries(e.dataSets)){const s=os(t.next()),r=IS({backgroundColor:s,line:{color:s}});i.push(Xf`
1974
+ `);let r=Yf``;switch(e.data.type){case"bar":r=function(e){const t=new fs,i=[];for(const[o,n]of Object.entries(e.dataSets)){const s=ns(t.next()),r=RS({backgroundColor:s,line:{color:s}});i.push(Yf`
1974
1975
  <c:ser>
1975
1976
  <c:idx val="${o}"/>
1976
1977
  <c:order val="${o}"/>
1977
- ${n.label?Xf`<c:tx>${NS(n.label)}</c:tx>`:""}
1978
+ ${n.label?Yf`<c:tx>${_S(n.label)}</c:tx>`:""}
1978
1979
  ${r}
1979
- ${e.labelRange?Xf`<c:cat>${NS(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
1980
+ ${e.labelRange?Yf`<c:cat>${_S(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
1980
1981
  <c:val> <!-- x-coordinate values -->
1981
- ${_S(n.range)}
1982
+ ${FS(n.range)}
1982
1983
  </c:val>
1983
1984
  </c:ser>
1984
- `)}const o="left"===e.verticalAxisPosition?"l":"r",n=e.stacked?"stacked":"clustered",s=e.stacked?100:-20;return Xf`
1985
+ `)}const o="left"===e.verticalAxisPosition?"l":"r",n=e.stacked?"stacked":"clustered",s=e.stacked?100:-20;return Yf`
1985
1986
  <c:barChart>
1986
1987
  <c:barDir val="col"/>
1987
1988
  <c:grouping val="${n}"/>
@@ -1989,13 +1990,13 @@
1989
1990
  <c:gapWidth val="70"/>
1990
1991
  <!-- each data marker in the series does not have a different color -->
1991
1992
  <c:varyColors val="0"/>
1992
- ${jf(i)}
1993
- <c:axId val="${wS}" />
1993
+ ${Xf(i)}
1994
1994
  <c:axId val="${yS}" />
1995
+ <c:axId val="${xS}" />
1995
1996
  </c:barChart>
1996
- ${OS("b","c:catAx",wS,yS,{fontColor:e.fontColor})}
1997
- ${OS(o,"c:valAx",yS,wS,{fontColor:e.fontColor})}
1998
- `}(e.data);break;case"line":r=function(e){const t=new ms,i=[];for(const[o,n]of Object.entries(e.dataSets)){const s=IS({line:{width:2.5,style:"solid",color:os(t.next())}});i.push(Xf`
1997
+ ${NS("b","c:catAx",yS,xS,{fontColor:e.fontColor})}
1998
+ ${NS(o,"c:valAx",xS,yS,{fontColor:e.fontColor})}
1999
+ `}(e.data);break;case"line":r=function(e){const t=new fs,i=[];for(const[o,n]of Object.entries(e.dataSets)){const s=RS({line:{width:2.5,style:"solid",color:ns(t.next())}});i.push(Yf`
1999
2000
  <c:ser>
2000
2001
  <c:idx val="${o}"/>
2001
2002
  <c:order val="${o}"/>
@@ -2004,50 +2005,50 @@
2004
2005
  <c:symbol val="circle" />
2005
2006
  <c:size val="5"/>
2006
2007
  </c:marker>
2007
- ${n.label?Xf`<c:tx>${NS(n.label)}</c:tx>`:""}
2008
+ ${n.label?Yf`<c:tx>${_S(n.label)}</c:tx>`:""}
2008
2009
  ${s}
2009
- ${e.labelRange?Xf`<c:cat>${NS(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
2010
+ ${e.labelRange?Yf`<c:cat>${_S(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
2010
2011
  <c:val> <!-- x-coordinate values -->
2011
- ${_S(n.range)}
2012
+ ${FS(n.range)}
2012
2013
  </c:val>
2013
2014
  </c:ser>
2014
- `)}const o="left"===e.verticalAxisPosition?"l":"r",n=e.stacked?"stacked":"standard";return Xf`
2015
+ `)}const o="left"===e.verticalAxisPosition?"l":"r",n=e.stacked?"stacked":"standard";return Yf`
2015
2016
  <c:lineChart>
2016
2017
  <c:grouping val="${n}"/>
2017
2018
  <!-- each data marker in the series does not have a different color -->
2018
2019
  <c:varyColors val="0"/>
2019
- ${jf(i)}
2020
- <c:axId val="${wS}" />
2020
+ ${Xf(i)}
2021
2021
  <c:axId val="${yS}" />
2022
+ <c:axId val="${xS}" />
2022
2023
  </c:lineChart>
2023
- ${OS("b","c:catAx",wS,yS,{fontColor:e.fontColor})}
2024
- ${OS(o,"c:valAx",yS,wS,{fontColor:e.fontColor})}
2025
- `}(e.data);break;case"pie":r=function(e,t,i,{holeSize:o}={holeSize:50}){const n=new ms,s=Math.max(...e.dataSets.map((e=>Cf(e.range,t,i)))),r=ze(0,s).map((()=>os(n.next()))),a=[];for(const[o,n]of Object.entries(e.dataSets).reverse()){const s=Cf(n.range,t,i),l=[];for(const e of ze(0,s)){const t=IS({backgroundColor:r[e],line:{color:"FFFFFF",width:1.5}});l.push(Xf`
2024
+ ${NS("b","c:catAx",yS,xS,{fontColor:e.fontColor})}
2025
+ ${NS(o,"c:valAx",xS,yS,{fontColor:e.fontColor})}
2026
+ `}(e.data);break;case"pie":r=function(e,t,i,{holeSize:o}={holeSize:50}){const n=new fs,s=Math.max(...e.dataSets.map((e=>Ef(e.range,t,i)))),r=Be(0,s).map((()=>ns(n.next()))),a=[];for(const[o,n]of Object.entries(e.dataSets).reverse()){const s=Ef(n.range,t,i),l=[];for(const e of Be(0,s)){const t=RS({backgroundColor:r[e],line:{color:"FFFFFF",width:1.5}});l.push(Yf`
2026
2027
  <c:dPt>
2027
2028
  <c:idx val="${e}"/>
2028
2029
  ${t}
2029
2030
  </c:dPt>
2030
- `)}a.push(Xf`
2031
+ `)}a.push(Yf`
2031
2032
  <c:ser>
2032
2033
  <c:idx val="${o}"/>
2033
2034
  <c:order val="${o}"/>
2034
- ${n.label?Xf`<c:tx>${NS(n.label)}</c:tx>`:""}
2035
- ${jf(l)}
2036
- ${MS({showLeaderLines:!0})}
2037
- ${e.labelRange?Xf`<c:cat>${NS(e.labelRange)}</c:cat>`:""}
2035
+ ${n.label?Yf`<c:tx>${_S(n.label)}</c:tx>`:""}
2036
+ ${Xf(l)}
2037
+ ${OS({showLeaderLines:!0})}
2038
+ ${e.labelRange?Yf`<c:cat>${_S(e.labelRange)}</c:cat>`:""}
2038
2039
  <c:val>
2039
- ${_S(n.range)}
2040
+ ${FS(n.range)}
2040
2041
  </c:val>
2041
2042
  </c:ser>
2042
- `)}return Xf`
2043
+ `)}return Yf`
2043
2044
  <c:doughnutChart>
2044
2045
  <c:varyColors val="1" />
2045
2046
  <c:holeSize val="${o}" />
2046
- ${MS()}
2047
- ${jf(a)}
2047
+ ${OS()}
2048
+ ${Xf(a)}
2048
2049
  </c:doughnutChart>
2049
- `}(e.data,t,i,{holeSize:0})}let a="t";switch(e.data.legendPosition){case"bottom":a="b";break;case"left":a="l";break;case"right":a="r";break;case"top":a="t"}const l=e.data.fontColor,c=Xf`
2050
- <c:chartSpace ${Gf(o)}>
2050
+ `}(e.data,t,i,{holeSize:0})}let a="t";switch(e.data.legendPosition){case"bottom":a="b";break;case"left":a="l";break;case"right":a="r";break;case"top":a="t"}const l=e.data.fontColor,c=Yf`
2051
+ <c:chartSpace ${qf(o)}>
2051
2052
  <c:roundedCorners val="0" />
2052
2053
  <!-- <manualLayout/> to manually position the chart in the figure container -->
2053
2054
  ${n}
@@ -2058,32 +2059,32 @@
2058
2059
  <!-- how the chart element is placed on the chart -->
2059
2060
  <c:layout />
2060
2061
  ${r}
2061
- ${IS({backgroundColor:e.data.backgroundColor})}
2062
+ ${RS({backgroundColor:e.data.backgroundColor})}
2062
2063
  </c:plotArea>
2063
- ${function(e,t){return Xf`
2064
+ ${function(e,t){return Yf`
2064
2065
  <c:legend>
2065
2066
  <c:legendPos val="${e}"/>
2066
2067
  <c:overlay val="0"/>
2067
- ${AS(10,t)}
2068
+ ${MS(10,t)}
2068
2069
  </c:legend>
2069
2070
  `}(a,l)}
2070
2071
  </c:chart>
2071
2072
  </c:chartSpace>
2072
- `;return qf(c)}function IS(e){return Xf`
2073
+ `;return Zf(c)}function RS(e){return Yf`
2073
2074
  <c:spPr>
2074
- ${e.backgroundColor?RS(e.backgroundColor):""}
2075
- ${e.line?function(e){const t=[["cmpd","sng"]];e.width&&t.push(["w",Sf(e.width)]);const i=e.style?Xf`<a:prstDash val="${e.style}"/>`:"";return Xf`
2076
- <a:ln ${Gf(t)}>
2077
- ${RS(e.color)}
2075
+ ${e.backgroundColor?TS(e.backgroundColor):""}
2076
+ ${e.line?function(e){const t=[["cmpd","sng"]];e.width&&t.push(["w",Cf(e.width)]);const i=e.style?Yf`<a:prstDash val="${e.style}"/>`:"";return Yf`
2077
+ <a:ln ${qf(t)}>
2078
+ ${TS(e.color)}
2078
2079
  ${i}
2079
2080
  </a:ln>
2080
2081
  `}(e.line):""}
2081
2082
  </c:spPr>
2082
- `}function RS(e){return Xf`
2083
+ `}function TS(e){return Yf`
2083
2084
  <a:solidFill>
2084
2085
  <a:srgbClr val="${e}"/>
2085
2086
  </a:solidFill>
2086
- `}function TS(e,t="000000",i=22){return Xf`
2087
+ `}function AS(e,t="000000",i=22){return Yf`
2087
2088
  <c:tx>
2088
2089
  <c:rich>
2089
2090
  <a:bodyPr />
@@ -2091,7 +2092,7 @@
2091
2092
  <a:p>
2092
2093
  <a:pPr lvl="0">
2093
2094
  <a:defRPr b="0">
2094
- ${RS(t)}
2095
+ ${TS(t)}
2095
2096
  <a:latin typeface="+mn-lt"/>
2096
2097
  </a:defRPr>
2097
2098
  </a:pPr>
@@ -2102,20 +2103,20 @@
2102
2103
  </a:p>
2103
2104
  </c:rich>
2104
2105
  </c:tx>
2105
- `}function AS(e=12,t="000000",i=!1,o=!1){return Xf`
2106
+ `}function MS(e=12,t="000000",i=!1,o=!1){return Yf`
2106
2107
  <c:txPr>
2107
2108
  <a:bodyPr/>
2108
2109
  <a:lstStyle/>
2109
2110
  <a:p>
2110
2111
  <a:pPr lvl="0">
2111
- <a:defRPr ${Gf([["b",i?"1":"0"],["i",o?"1":"0"],["sz",100*e]])}>
2112
- ${RS(t)}
2112
+ <a:defRPr ${qf([["b",i?"1":"0"],["i",o?"1":"0"],["sz",100*e]])}>
2113
+ ${TS(t)}
2113
2114
  <a:latin typeface="+mn-lt"/>
2114
2115
  </a:defRPr>
2115
2116
  </a:pPr>
2116
2117
  </a:p>
2117
2118
  </c:txPr>
2118
- `}function MS({showLeaderLines:e}={showLeaderLines:!1}){return Xf`
2119
+ `}function OS({showLeaderLines:e}={showLeaderLines:!1}){return Yf`
2119
2120
  <dLbls>
2120
2121
  <c:showLegendKey val="0"/>
2121
2122
  <c:showVal val="0"/>
@@ -2125,7 +2126,7 @@
2125
2126
  <c:showBubbleSize val="0"/>
2126
2127
  <c:showLeaderLines val="${e?"1":"0"}"/>
2127
2128
  </dLbls>
2128
- `}function OS(e,t,i,o,{fontColor:n}){return Xf`
2129
+ `}function NS(e,t,i,o,{fontColor:n}){return Yf`
2129
2130
  <${t}>
2130
2131
  <c:axId val="${i}"/>
2131
2132
  <c:crossAx val="${o}"/> <!-- reference to the other axe of the chart -->
@@ -2134,62 +2135,62 @@
2134
2135
  <c:orientation val="minMax" />
2135
2136
  </c:scaling>
2136
2137
  <c:axPos val="${e}" />
2137
- ${function(e="B7B7B7"){return Xf`
2138
+ ${function(e="B7B7B7"){return Yf`
2138
2139
  <c:majorGridlines>
2139
- ${IS({line:{color:e}})}
2140
+ ${RS({line:{color:e}})}
2140
2141
  </c:majorGridlines>
2141
2142
  `}()}
2142
2143
  <c:majorTickMark val="out" />
2143
2144
  <c:minorTickMark val="none" />
2144
2145
  <c:numFmt formatCode="General" sourceLinked="1" />
2145
2146
  <c:title>
2146
- ${TS("")}
2147
+ ${AS("")}
2147
2148
  </c:title>
2148
- ${AS(10,n)}
2149
+ ${MS(10,n)}
2149
2150
  </${t}>
2150
2151
  <!-- <tickLblPos/> omitted -->
2151
- `}function NS(e){return Xf`
2152
+ `}function _S(e){return Yf`
2152
2153
  <c:strRef>
2153
2154
  <c:f>${e}</c:f>
2154
2155
  </c:strRef>
2155
- `}function _S(e){return Xf`
2156
+ `}function FS(e){return Yf`
2156
2157
  <c:numRef>
2157
2158
  <c:f>${e}</c:f>
2158
2159
  <c:numCache />
2159
2160
  </c:numRef>
2160
- `}function FS(e){const t=e.content,i=Wu.content,o=[];let n=Xf``;if(Em(t).filter((e=>"FUNCTION"===e.type)).every((e=>i[e.value.toUpperCase()].isExported))){let i=Xf``;const s=kS(t);return e.value===a.CircularDependency&&(o.push(["t","str"]),i=Xf`<v>${e.value}</v>`),n=Xf`
2161
+ `}function DS(e){const t=e.content,i=Gu.content,o=[];let n=Yf``;if(wm(t).filter((e=>"FUNCTION"===e.type)).every((e=>i[e.value.toUpperCase()].isExported))){let i=Yf``;const s=LS(t);return e.value===a.CircularDependency&&(o.push(["t","str"]),i=Yf`<v>${e.value}</v>`),n=Yf`
2161
2162
  <f>
2162
2163
  ${s}
2163
2164
  </f>
2164
2165
  ${i}
2165
- `,{attrs:o,node:n}}{const t=e.value,i=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n"}}(t);return o.push(["t",i]),n=Xf`<v>${t}</v>`,{attrs:o,node:n}}}function DS(e,t,i=!1){let o=e;const n=[];if(!i&&["TRUE","FALSE"].includes(o.trim()))o="TRUE"===o?"1":"0",n.push(["t","b"]);else if(i||!Qt(o)){const{id:i}=pf(e,t);o=i.toString(),n.push(["t","s"])}return{attrs:n,node:Xf`<v>${o}</v>`}}function kS(e){let t;"="===e[0]&&(e=e.slice(1));try{t=Hm(e)}catch(t){return e}return t=Wm(t,"STRING",LS),t=Wm(t,"FUNCALL",(e=>e=function(e){const t=e.value.toUpperCase(),i=e.args,o=Ap[t];if(o){const n=Wu.content[t].args.filter((e=>!e.optional)),s=n.length-e.args.length;if(s)for(let t=e.args.length;t<n.length;t++){const e=o[t-s];i.push({type:e.type,value:e.value})}}return{...e,args:i}}(e=function(e){const t=e.value.toUpperCase();return{...e,value:Mp.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()})))),t?Gm(t):e}function LS(e){const t=e.value.replace(new RegExp('"',"g"),""),i=Se(t);if(i){let o=[];return(t.match(fe)||t.match(ve))&&o.push("yyyy-mm-dd"),t.match(be)&&o.push("hh:mm:ss"),{...e,value:hi(i.value,o.join(" "))}}return{...e,value:e.value.replace(/\\"/g,'""')}}function PS(e,t){const i=[];for(const o of t)switch(o.rule.type){case"CellIsRule":i.push(US(o,o.rule,e));break;case"ColorScaleRule":i.push(VS(o,o.rule));break;case"IconSetRule":i.push(zS(o,o.rule));break;default:console.warn(`Conditional formatting ${o.rule.type} not implemented`)}return i}function US(e,t,i){const o=BS(e),n=af(t.operator);o.push(...function(e){const t=af(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 s=function(e,t){const i=e[0].split(":")[0],o=t.values;switch(t.operator){case"ContainsText":return[`NOT(ISERROR(SEARCH("${o[0]}",${i})))`];case"NotContains":return[`ISERROR(SEARCH("${o[0]}",${i}))`];case"BeginsWith":return[`LEFT(${i},LEN("${o[0]}"))="${o[0]}"`];case"EndsWith":return[`RIGHT(${i},LEN("${o[0]}"))="${o[0]}"`];case"IsEmpty":return[`LEN(TRIM(${i}))=0`];case"IsNotEmpty":return[`LEN(TRIM(${i}))>0`];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":return[o[0]];case"Between":case"NotBetween":return[o[0],o[1]]}}(e.ranges,t).map((e=>Xf`<formula>${e}</formula>`)),r={font:{color:{rgb:t.style.textColor},bold:t.style.bold,italic:t.style.italic,strike:t.style.strikethrough,underline:t.style.underline}};t.style.fillColor&&(r.fill={fgColor:{rgb:t.style.fillColor}});const{id:a}=pf(r,i);return o.push(["dxfId",a]),Xf`
2166
+ `,{attrs:o,node:n}}{const t=e.value,i=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n"}}(t);return o.push(["t",i]),n=Yf`<v>${t}</v>`,{attrs:o,node:n}}}function kS(e,t,i=!1){let o=e;const n=[];if(!i&&["TRUE","FALSE"].includes(o.trim()))o="TRUE"===o?"1":"0",n.push(["t","b"]);else if(i||!Jt(o)){const{id:i}=mf(e,t);o=i.toString(),n.push(["t","s"])}return{attrs:n,node:Yf`<v>${o}</v>`}}function LS(e){let t;"="===e[0]&&(e=e.slice(1));try{t=$m(e)}catch(t){return e}return t=Gm(t,"STRING",PS),t=Gm(t,"FUNCALL",(e=>e=function(e){const t=e.value.toUpperCase(),i=e.args,o=Mp[t];if(o){const n=Gu.content[t].args.filter((e=>!e.optional)),s=n.length-e.args.length;if(s)for(let t=e.args.length;t<n.length;t++){const e=o[t-s];i.push({type:e.type,value:e.value})}}return{...e,args:i}}(e=function(e){const t=e.value.toUpperCase();return{...e,value:Op.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()})))),t?qm(t):e}function PS(e){const t=e.value.replace(new RegExp('"',"g"),""),i=Se(t);if(i){let o=[];return(t.match(fe)||t.match(ve))&&o.push("yyyy-mm-dd"),t.match(be)&&o.push("hh:mm:ss"),{...e,value:di(i.value,o.join(" "))}}return{...e,value:e.value.replace(/\\"/g,'""')}}function US(e,t){const i=[];for(const o of t)switch(o.rule.type){case"CellIsRule":i.push(VS(o,o.rule,e));break;case"ColorScaleRule":i.push(zS(o,o.rule));break;case"IconSetRule":i.push(BS(o,o.rule));break;default:console.warn(`Conditional formatting ${o.rule.type} not implemented`)}return i}function VS(e,t,i){const o=HS(e),n=lf(t.operator);o.push(...function(e){const t=lf(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 s=function(e,t){const i=e[0].split(":")[0],o=t.values;switch(t.operator){case"ContainsText":return[`NOT(ISERROR(SEARCH("${o[0]}",${i})))`];case"NotContains":return[`ISERROR(SEARCH("${o[0]}",${i}))`];case"BeginsWith":return[`LEFT(${i},LEN("${o[0]}"))="${o[0]}"`];case"EndsWith":return[`RIGHT(${i},LEN("${o[0]}"))="${o[0]}"`];case"IsEmpty":return[`LEN(TRIM(${i}))=0`];case"IsNotEmpty":return[`LEN(TRIM(${i}))>0`];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":return[o[0]];case"Between":case"NotBetween":return[o[0],o[1]]}}(e.ranges,t).map((e=>Yf`<formula>${e}</formula>`)),r={font:{color:{rgb:t.style.textColor},bold:t.style.bold,italic:t.style.italic,strike:t.style.strikethrough,underline:t.style.underline}};t.style.fillColor&&(r.fill={fgColor:{rgb:t.style.fillColor}});const{id:a}=mf(r,i);return o.push(["dxfId",a]),Yf`
2166
2167
  <conditionalFormatting sqref="${e.ranges.join(" ")}">
2167
- <cfRule ${Gf(o)}>
2168
- ${jf(s)}
2168
+ <cfRule ${qf(o)}>
2169
+ ${Xf(s)}
2169
2170
  </cfRule>
2170
2171
  </conditionalFormatting>
2171
- `}function VS(e,t){const i=BS(e);i.push(["type","colorScale"]);const o=[];for(const n of e.ranges){const e=[],s=[];let r=!0;for(let i of["minimum","midpoint","maximum"]){const o=t[i];o&&("formula"!==o.type?(e.push($S(o,i)),s.push([["rgb",os(vt(o.color))]])):r=!1)}if(!r){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const a=e.map((e=>Xf`<cfvo ${Gf(e)}/>`)),l=s.map((e=>Xf`<color ${Gf(e)}/>`));o.push(Xf`
2172
+ `}function zS(e,t){const i=HS(e);i.push(["type","colorScale"]);const o=[];for(const n of e.ranges){const e=[],s=[];let r=!0;for(let i of["minimum","midpoint","maximum"]){const o=t[i];o&&("formula"!==o.type?(e.push(WS(o,i)),s.push([["rgb",ns(bt(o.color))]])):r=!1)}if(!r){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const a=e.map((e=>Yf`<cfvo ${qf(e)}/>`)),l=s.map((e=>Yf`<color ${qf(e)}/>`));o.push(Yf`
2172
2173
  <conditionalFormatting sqref="${n}">
2173
- <cfRule ${Gf(i)}>
2174
+ <cfRule ${qf(i)}>
2174
2175
  <colorScale>
2175
- ${jf(a)}
2176
- ${jf(l)}
2176
+ ${Xf(a)}
2177
+ ${Xf(l)}
2177
2178
  </colorScale>
2178
2179
  </cfRule>
2179
2180
  </conditionalFormatting>
2180
- `)}return jf(o)}function zS(e,t){const i=BS(e);i.push(["type","iconSet"]);const o=[];for(const n of e.ranges){const e=[[["type","percent"],["val",0]]];let s=!0;for(let i of["lowerInflectionPoint","upperInflectionPoint"]){if("formula"===t[i].type){s=!1;continue}const o=t[i];e.push([...$S(o,i),["gte","ge"===o.operator?"1":"0"]])}if(!s){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const r=e.map((e=>Xf`<cfvo ${Gf(e)} />`));o.push(Xf`
2181
+ `)}return Xf(o)}function BS(e,t){const i=HS(e);i.push(["type","iconSet"]);const o=[];for(const n of e.ranges){const e=[[["type","percent"],["val",0]]];let s=!0;for(let i of["lowerInflectionPoint","upperInflectionPoint"]){if("formula"===t[i].type){s=!1;continue}const o=t[i];e.push([...WS(o,i),["gte","ge"===o.operator?"1":"0"]])}if(!s){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const r=e.map((e=>Yf`<cfvo ${qf(e)} />`));o.push(Yf`
2181
2182
  <conditionalFormatting sqref="${n}">
2182
- <cfRule ${Gf(i)}>
2183
- <iconSet iconSet="${HS(t.icons)}">
2184
- ${jf(r)}
2183
+ <cfRule ${qf(i)}>
2184
+ <iconSet iconSet="${$S(t.icons)}">
2185
+ ${Xf(r)}
2185
2186
  </iconSet>
2186
2187
  </cfRule>
2187
2188
  </conditionalFormatting>
2188
- `)}return jf(o)}function BS(e){return[["priority",1],["stopIfTrue",e.stopIfTrue?1:0]]}function HS(e){return pp[Object.keys(pp).find((t=>e.upper.toLowerCase().startsWith(t)))||"dots"]}function $S(e,t){const i=function(e,t){switch(e){case"value":return"minimum"===t?"min":"max";case"number":return"num";case"percentage":return"percent";default:return e}}(e.type,t),o=[["type",i]];if("min"!==i&&"max"!==i){let t=e.value;if("formula"===i)try{t=kS(e.value)}catch(i){t=e.value}o.push(["val",t])}return o}function WS(e,t,i){const o=[["xmlns:xdr",mp.drawing],["xmlns:r",Cp],["xmlns:a",fp],["xmlns:c",vp]],n=[];for(const[o,s]of Object.entries(i))switch(null==s?void 0:s.tag){case"chart":n.push(ZS(s,t,e[o]));break;case"image":n.push(jS(s,t,e[o]))}return qf(Xf`
2189
- <xdr:wsDr ${Gf(o)}>
2190
- ${jf(n)}
2189
+ `)}return Xf(o)}function HS(e){return[["priority",1],["stopIfTrue",e.stopIfTrue?1:0]]}function $S(e){return mp[Object.keys(mp).find((t=>e.upper.toLowerCase().startsWith(t)))||"dots"]}function WS(e,t){const i=function(e,t){switch(e){case"value":return"minimum"===t?"min":"max";case"number":return"num";case"percentage":return"percent";default:return e}}(e.type,t),o=[["type",i]];if("min"!==i&&"max"!==i){let t=e.value;if("formula"===i)try{t=LS(e.value)}catch(i){t=e.value}o.push(["val",t])}return o}function GS(e,t,i){const o=[["xmlns:xdr",fp.drawing],["xmlns:r",Ep],["xmlns:a",vp],["xmlns:c",bp]],n=[];for(const[o,s]of Object.entries(i))switch(null==s?void 0:s.tag){case"chart":n.push(jS(s,t,e[o]));break;case"image":n.push(XS(s,t,e[o]))}return Zf(Yf`
2190
+ <xdr:wsDr ${qf(o)}>
2191
+ ${Xf(n)}
2191
2192
  </xdr:wsDr>
2192
- `)}function GS(e,t){const{x:i,y:o,height:n,width:s}=e,r=Object.values(t.cols),a=Object.values(t.rows),{index:l,offset:c}=qS(r,i),{index:h,offset:d}=qS(r,i+s),{index:u,offset:g}=qS(a,o),{index:p,offset:m}=qS(a,o+n);return{from:{col:l,colOff:c,row:u,rowOff:g},to:{col:h,colOff:d,row:p,rowOff:m}}}function qS(e,t){let i=0;for(const[o,n]of Object.entries(e)){if(i<=t&&t<i+n.size)return{index:parseInt(o),offset:Sf(t-i+$)};i+=n.size}return{index:e.length-1,offset:Sf(t-i+$)}}function ZS(e,t,i){const{from:o,to:n}=GS(e,t),s=ff(e.id),r=[["id",s],["name",`Chart ${s}`],["title","Chart"]];return Xf`
2193
+ `)}function qS(e,t){const{x:i,y:o,height:n,width:s}=e,r=Object.values(t.cols),a=Object.values(t.rows),{index:l,offset:c}=ZS(r,i),{index:h,offset:d}=ZS(r,i+s),{index:u,offset:g}=ZS(a,o),{index:p,offset:m}=ZS(a,o+n);return{from:{col:l,colOff:c,row:u,rowOff:g},to:{col:h,colOff:d,row:p,rowOff:m}}}function ZS(e,t){let i=0;for(const[o,n]of Object.entries(e)){if(i<=t&&t<i+n.size)return{index:parseInt(o),offset:Cf(t-i+$)};i+=n.size}return{index:e.length-1,offset:Cf(t-i+$)}}function jS(e,t,i){const{from:o,to:n}=qS(e,t),s=vf(e.id),r=[["id",s],["name",`Chart ${s}`],["title","Chart"]];return Yf`
2193
2194
  <xdr:twoCellAnchor>
2194
2195
  <xdr:from>
2195
2196
  <xdr:col>${o.col}</xdr:col>
@@ -2205,7 +2206,7 @@
2205
2206
  </xdr:to>
2206
2207
  <xdr:graphicFrame>
2207
2208
  <xdr:nvGraphicFramePr>
2208
- <xdr:cNvPr ${Gf(r)} />
2209
+ <xdr:cNvPr ${qf(r)} />
2209
2210
  <xdr:cNvGraphicFramePr />
2210
2211
  </xdr:nvGraphicFramePr>
2211
2212
  <xdr:xfrm>
@@ -2213,14 +2214,14 @@
2213
2214
  <a:ext cx="0" cy="0"/>
2214
2215
  </xdr:xfrm>
2215
2216
  <a:graphic>
2216
- <a:graphicData uri="${vp}">
2217
+ <a:graphicData uri="${bp}">
2217
2218
  <c:chart r:id="${i}" />
2218
2219
  </a:graphicData>
2219
2220
  </a:graphic>
2220
2221
  </xdr:graphicFrame>
2221
2222
  <xdr:clientData fLocksWithSheet="0"/>
2222
2223
  </xdr:twoCellAnchor>
2223
- `}function jS(e,t,i){const{from:o,to:n}=GS(e,t),s=bf(e.id),r=[["id",s],["name",`Image ${s}`],["title","Image"]];return Xf`
2224
+ `}function XS(e,t,i){const{from:o,to:n}=qS(e,t),s=Sf(e.id),r=[["id",s],["name",`Image ${s}`],["title","Image"]];return Yf`
2224
2225
  <xdr:twoCellAnchor editAs="oneCell">
2225
2226
  <xdr:from>
2226
2227
  <xdr:col>${o.col}</xdr:col>
@@ -2236,7 +2237,7 @@
2236
2237
  </xdr:to>
2237
2238
  <xdr:pic>
2238
2239
  <xdr:nvPicPr>
2239
- <xdr:cNvPr ${Gf(r)}/>
2240
+ <xdr:cNvPr ${qf(r)}/>
2240
2241
  <xdr:cNvPicPr preferRelativeResize="0"/>
2241
2242
  </xdr:nvPicPr>
2242
2243
  <xdr:blipFill>
@@ -2254,69 +2255,69 @@
2254
2255
  </xdr:pic>
2255
2256
  <xdr:clientData fLocksWithSheet="0"/>
2256
2257
  </xdr:twoCellAnchor>
2257
- `}function XS(e){return tt(e)?Xf``:Xf`
2258
+ `}function YS(e){return it(e)?Yf``:Yf`
2258
2259
  <font>
2259
- ${e.bold?Xf`<b />`:""}
2260
- ${e.italic?Xf`<i />`:""}
2261
- ${e.underline?Xf`<u />`:""}
2262
- ${e.strike?Xf`<strike />`:""}
2263
- ${e.size?Xf`<sz val="${e.size}" />`:""}
2264
- ${e.color&&e.color.rgb?Xf`<color rgb="${os(e.color.rgb)}" />`:""}
2265
- ${e.name?Xf`<name val="${e.name}" />`:""}
2260
+ ${e.bold?Yf`<b />`:""}
2261
+ ${e.italic?Yf`<i />`:""}
2262
+ ${e.underline?Yf`<u />`:""}
2263
+ ${e.strike?Yf`<strike />`:""}
2264
+ ${e.size?Yf`<sz val="${e.size}" />`:""}
2265
+ ${e.color&&e.color.rgb?Yf`<color rgb="${ns(e.color.rgb)}" />`:""}
2266
+ ${e.name?Yf`<name val="${e.name}" />`:""}
2266
2267
  </font>
2267
- `}function YS(e){return e?Gf([["style",e.style],["color",os(e.color.rgb)]]):Xf``}const KS=Xf`<tableStyleInfo name="TableStyleLight8" showFirstColumn="0" showLastColumn="0" showRowStripes="0" showColumnStripes="0"/>`;function QS(e,t,i){const o=Xf`
2268
- <table ${Gf([["id",t],["name",`Table${t}`],["displayName",`Table${t}`],["ref",e.range],["xmlns",mp.table],["xmlns:xr",mp.revision],["xmlns:xr3",mp.revision3],["xmlns:mc",mp.markupCompatibility]])}>
2269
- ${function(e){const t=[["ref",e.range]];return Xf`
2270
- <autoFilter ${Gf(t)}>
2271
- ${jf(function(e){const t=Li(e.range),i=[];for(const o of ze(0,Ki(t).numberOfCols)){const t=e.filters[o];if(!t||!t.filteredValues.length)continue;const n=Xf`
2272
- <filterColumn ${Gf([["colId",o]])}>
2273
- ${JS(t)}
2268
+ `}function KS(e){return e?qf([["style",e.style],["color",ns(e.color.rgb)]]):Yf``}const QS=Yf`<tableStyleInfo name="TableStyleLight8" showFirstColumn="0" showLastColumn="0" showRowStripes="0" showColumnStripes="0"/>`;function JS(e,t,i){const o=Yf`
2269
+ <table ${qf([["id",t],["name",`Table${t}`],["displayName",`Table${t}`],["ref",e.range],["xmlns",fp.table],["xmlns:xr",fp.revision],["xmlns:xr3",fp.revision3],["xmlns:mc",fp.markupCompatibility]])}>
2270
+ ${function(e){const t=[["ref",e.range]];return Yf`
2271
+ <autoFilter ${qf(t)}>
2272
+ ${Xf(function(e){const t=[];for(const i of e.filters){const e=Yf`
2273
+ <filterColumn ${qf([["colId",i.colId]])}>
2274
+ ${eC(i)}
2274
2275
  </filterColumn>
2275
- `;i.push(n)}return i}(e))}
2276
+ `;t.push(e)}return t}(e))}
2276
2277
  </autoFilter>
2277
2278
  `}(e)}
2278
- ${function(e,t){var i;const o=Li(e.range),n=[];for(const e of ze(0,Ki(o).numberOfCols)){const s=Bt(o.left+e,o.top),r=[["id",e+1],["name",(null===(i=t.cells[s])||void 0===i?void 0:i.content)||`col${e}`]];n.push(Xf`<tableColumn ${Gf(r)}/>`)}return Xf`
2279
- <tableColumns ${Gf([["count",n.length]])}>
2280
- ${jf(n)}
2279
+ ${function(e,t){var i;const o=Pi(e.range),n=[];for(const e of Be(0,Qi(o).numberOfCols)){const s=Ht(o.left+e,o.top),r=[["id",e+1],["name",(null===(i=t.cells[s])||void 0===i?void 0:i.content)||`col${e}`]];n.push(Yf`<tableColumn ${qf(r)}/>`)}return Yf`
2280
+ <tableColumns ${qf([["count",n.length]])}>
2281
+ ${Xf(n)}
2281
2282
  </tableColumns>
2282
2283
  `}(e,i)}
2283
- ${KS}
2284
+ ${QS}
2284
2285
  </table>
2285
- `;return qf(o)}function JS(e){return Xf`
2286
- <filters>
2287
- ${jf(e.filteredValues.map((e=>Xf`<filter ${Gf([["val",e]])}/>`)))}
2286
+ `;return Zf(o)}function eC(e){const t=e.displayedValues.map((e=>Yf`<filter ${qf([["val",e]])}/>`));return Yf`
2287
+ <filters ${qf(e.displayBlanks?[["blank",1]]:[])}>
2288
+ ${Xf(t)}
2288
2289
  </filters>
2289
- `}function eC(e){if(!Object.values(e).length)return Xf``;const t=[];for(let[i,o]of Object.entries(e)){const e=[["min",parseInt(i)+1],["max",parseInt(i)+1],["width",cf(o.size||_)],["customWidth",1],["hidden",o.isHidden?1:0]];t.push(Xf`
2290
- <col ${Gf(e)}/>
2291
- `)}return Xf`
2290
+ `}function tC(e){if(!Object.values(e).length)return Yf``;const t=[];for(let[i,o]of Object.entries(e)){const e=[["min",parseInt(i)+1],["max",parseInt(i)+1],["width",hf(o.size||_)],["customWidth",1],["hidden",o.isHidden?1:0]];t.push(Yf`
2291
+ <col ${qf(e)}/>
2292
+ `)}return Yf`
2292
2293
  <cols>
2293
- ${jf(t)}
2294
+ ${Xf(t)}
2294
2295
  </cols>
2295
- `}function tC(e,t,i){const o=[];for(let n=0;n<i.rowNumber;n++){const s=[["r",n+1]],r=i.rows[n]||{};s.push(["ht",lf(r.size||F)],["customHeight",1],["hidden",r.isHidden?1:0]);const a=[];for(let o=0;o<i.colNumber;o++){const s=Bt(o,n),r=i.cells[s];if(r){const l=[["r",s]],c=uf(e,df(r,t));l.push(["s",c]);let h=[],d=Xf``;if(r.isFormula)({attrs:h,node:d}=FS(r));else if(r.content&&qe(r.content)){const{label:t}=Xe(r.content);({attrs:h,node:d}=DS(t,e.sharedStrings))}else if(r.content&&""!==r.content){const t=iC(o,n,i);({attrs:h,node:d}=DS(r.content,e.sharedStrings,t))}l.push(...h),a.push(Xf`
2296
- <c ${Gf(l)}>
2296
+ `}function iC(e,t,i){const o=[];for(let n=0;n<i.rowNumber;n++){const s=[["r",n+1]],r=i.rows[n]||{};s.push(["ht",cf(r.size||F)],["customHeight",1],["hidden",r.isHidden?1:0]);const a=[];for(let o=0;o<i.colNumber;o++){const s=Ht(o,n),r=i.cells[s];if(r){const l=[["r",s]],c=gf(e,uf(r,t));l.push(["s",c]);let h=[],d=Yf``;if(r.isFormula)({attrs:h,node:d}=DS(r));else if(r.content&&Ze(r.content)){const{label:t}=Ye(r.content);({attrs:h,node:d}=kS(t,e.sharedStrings))}else if(r.content&&""!==r.content){const t=oC(o,n,i);({attrs:h,node:d}=kS(r.content,e.sharedStrings,t))}l.push(...h),a.push(Yf`
2297
+ <c ${qf(l)}>
2297
2298
  ${d}
2298
2299
  </c>
2299
- `)}}(a.length||r.size!==F||r.isHidden)&&o.push(Xf`
2300
- <row ${Gf(s)}>
2301
- ${jf(a)}
2300
+ `)}}(a.length||r.size!==F||r.isHidden)&&o.push(Yf`
2301
+ <row ${qf(s)}>
2302
+ ${Xf(a)}
2302
2303
  </row>
2303
- `)}return Xf`
2304
+ `)}return Yf`
2304
2305
  <sheetData>
2305
- ${jf(o)}
2306
+ ${Xf(o)}
2306
2307
  </sheetData>
2307
- `}function iC(e,t,i){return i.filterTables.some((i=>{const o=Li(i.range),n={...o,bottom:o.top};return Zi(e,t,n)}))}function oC(e,t,i){var o;const n=t.sheets[i].cells,s=[];for(const r in n){const a=null===(o=n[r])||void 0===o?void 0:o.content;if(a&&qe(a)){const{label:o,url:n}=Xe(a);if(Ke(n)){const e=Je(n),i=t.sheets.find((t=>t.id===e)),a=i?`${i.name}!A1`:Y;s.push(Xf`
2308
+ `}function oC(e,t,i){return i.filterTables.some((i=>{const o=Pi(i.range),n={...o,bottom:o.top};return ji(e,t,n)}))}function nC(e,t,i){var o;const n=t.sheets[i].cells,s=[];for(const r in n){const a=null===(o=n[r])||void 0===o?void 0:o.content;if(a&&Ze(a)){const{label:o,url:n}=Ye(a);if(Qe(n)){const e=et(n),i=t.sheets.find((t=>t.id===e)),a=i?`${i.name}!A1`:Y;s.push(Yf`
2308
2309
  <hyperlink display="${o}" location="${a}" ref="${r}"/>
2309
- `)}else{const t=gf(e.relsFiles,`xl/worksheets/_rels/sheet${i}.xml.rels`,{target:Eo(n),type:Sp.hyperlink,targetMode:"External"});s.push(Xf`
2310
+ `)}else{const t=pf(e.relsFiles,`xl/worksheets/_rels/sheet${i}.xml.rels`,{target:wo(n),type:Cp.hyperlink,targetMode:"External"});s.push(Yf`
2310
2311
  <hyperlink r:id="${t}" ref="${r}"/>
2311
- `)}}}return s.length?Xf`
2312
+ `)}}}return s.length?Yf`
2312
2313
  <hyperlinks>
2313
- ${jf(s)}
2314
+ ${Xf(s)}
2314
2315
  </hyperlinks>
2315
- `:Xf``}function nC(e){if(e.length){const t=e.map((e=>Xf`<mergeCell ref="${e}" />`));return Xf`
2316
+ `:Yf``}function sC(e){if(e.length){const t=e.map((e=>Yf`<mergeCell ref="${e}" />`));return Yf`
2316
2317
  <mergeCells count="${e.length}">
2317
- ${jf(t)}
2318
+ ${Xf(t)}
2318
2319
  </mergeCells>
2319
- `}return Xf``}function sC(e){const t=e.panes;let i=Xf``;if(t&&(t.xSplit||t.ySplit)){const e=Bt(t.xSplit,t.ySplit),o=t.xSplit?Xf`xSplit="${t.xSplit}"`:"",n=t.ySplit?Xf`ySplit="${t.ySplit}"`:"",s=t.xSplit?Xf`<selection pane="topRight"/>`:"",r=t.ySplit?Xf`<selection pane="bottomLeft"/>`:"",a=t.xSplit&&t.ySplit?Xf`<selection pane="bottomRight"/>`:"";i=Xf`
2320
+ `}return Yf``}function rC(e){const t=e.panes;let i=Yf``;if(t&&(t.xSplit||t.ySplit)){const e=Ht(t.xSplit,t.ySplit),o=t.xSplit?Yf`xSplit="${t.xSplit}"`:"",n=t.ySplit?Yf`ySplit="${t.ySplit}"`:"",s=t.xSplit?Yf`<selection pane="topRight"/>`:"",r=t.ySplit?Yf`<selection pane="bottomLeft"/>`:"",a=t.xSplit&&t.ySplit?Yf`<selection pane="bottomRight"/>`:"";i=Yf`
2320
2321
  <pane
2321
2322
  ${o}
2322
2323
  ${n}
@@ -2326,126 +2327,126 @@
2326
2327
  ${s}
2327
2328
  ${r}
2328
2329
  ${a}
2329
- `}return Xf`
2330
+ `}return Yf`
2330
2331
  <sheetViews>
2331
2332
  <sheetView showGridLines="${e.areGridLinesVisible?1:0}" workbookViewId="0">
2332
2333
  ${i}
2333
2334
  </sheetView>
2334
2335
  </sheetViews>
2335
- `}function rC(e){const t=[],i={relsFiles:[],sharedStrings:[],styles:[{fontId:0,fillId:0,numFmtId:0,borderId:0,alignment:{vertical:"center"}}],fonts:[{size:G,family:2,color:{rgb:"000000"},name:"Calibri"}],fills:[{reservedAttribute:"none"},{reservedAttribute:"gray125"}],borders:[{}],numFmts:[],dxfs:[]};return t.push(function(e,t){const i=[["xmlns",mp.workbook],["xmlns:r",Cp]],o=[];for(const[i,n]of Object.entries(e.sheets)){const e=[["state",n.isVisible?"visible":"hidden"],["name",n.name],["sheetId",parseInt(i)+1],["r:id",`rId${parseInt(i)+1}`]];o.push(Xf`
2336
- <sheet ${Gf(e)} />
2337
- `),gf(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Sp.sheet,target:`worksheets/sheet${i}.xml`})}return $f(qf(Xf`
2338
- <workbook ${Gf(i)}>
2336
+ `}function aC(e){const t=[],i={relsFiles:[],sharedStrings:[],styles:[{fontId:0,fillId:0,numFmtId:0,borderId:0,alignment:{vertical:"center"}}],fonts:[{size:G,family:2,color:{rgb:"000000"},name:"Calibri"}],fills:[{reservedAttribute:"none"},{reservedAttribute:"gray125"}],borders:[{}],numFmts:[],dxfs:[]};return t.push(function(e,t){const i=[["xmlns",fp.workbook],["xmlns:r",Ep]],o=[];for(const[i,n]of Object.entries(e.sheets)){const e=[["state",n.isVisible?"visible":"hidden"],["name",n.name],["sheetId",parseInt(i)+1],["r:id",`rId${parseInt(i)+1}`]];o.push(Yf`
2337
+ <sheet ${qf(e)} />
2338
+ `),pf(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Cp.sheet,target:`worksheets/sheet${i}.xml`})}return Wf(Zf(Yf`
2339
+ <workbook ${qf(i)}>
2339
2340
  <sheets>
2340
- ${jf(o)}
2341
+ ${Xf(o)}
2341
2342
  </sheets>
2342
2343
  </workbook>
2343
- `),"xl/workbook.xml","workbook")}(e,i)),t.push(...function(e,t){const i=[];let o=1;for(const[n,s]of Object.entries(e.sheets)){const r=[["xmlns",mp.worksheet],["xmlns:r",Cp]],a=[["defaultRowHeight",lf(F)],["defaultColWidth",cf(_)]],l=aC(s,n,o,t,i);o+=s.filterTables.length;let c=Xf``;const h=[];for(const o of s.charts){const s=ff(o.id),r=gf(t.relsFiles,`xl/drawings/_rels/drawing${n}.xml.rels`,{target:`../charts/chart${s}.xml`,type:Sp.chart});h.push(r),i.push($f(xS(o,n,e),`xl/charts/chart${s}.xml`,"chart"))}for(const e of s.images){const o=e.data.mimetype;if(void 0===o)continue;const s=Yp[o];if(void 0===s)continue;let r=`image${bf(e.id)}.${s}`;const a=gf(t.relsFiles,`xl/drawings/_rels/drawing${n}.xml.rels`,{target:`../media/${r}`,type:Sp.image});h.push(a),i.push({path:`xl/media/${r}`,imageSrc:e.data.path})}const d=[...s.charts,...s.images];if(d.length){const e=gf(t.relsFiles,`xl/worksheets/_rels/sheet${n}.xml.rels`,{target:`../drawings/drawing${n}.xml`,type:Sp.drawing});i.push($f(WS(h,s,d),`xl/drawings/drawing${n}.xml`,"drawing")),c=Xf`<drawing r:id="${e}" />`}const u=Xf`
2344
- <worksheet ${Gf(r)}>
2345
- ${sC(s)}
2346
- <sheetFormatPr ${Gf(a)} />
2347
- ${eC(s.cols)}
2348
- ${tC(t,e,s)}
2349
- ${nC(s.merges)}
2350
- ${jf(PS(t.dxfs,s.conditionalFormats))}
2351
- ${oC(t,e,n)}
2344
+ `),"xl/workbook.xml","workbook")}(e,i)),t.push(...function(e,t){const i=[];let o=1;for(const[n,s]of Object.entries(e.sheets)){const r=[["xmlns",fp.worksheet],["xmlns:r",Ep]],a=[["defaultRowHeight",cf(F)],["defaultColWidth",hf(_)]],l=lC(s,n,o,t,i);o+=s.filterTables.length;let c=Yf``;const h=[];for(const o of s.charts){const s=vf(o.id),r=pf(t.relsFiles,`xl/drawings/_rels/drawing${n}.xml.rels`,{target:`../charts/chart${s}.xml`,type:Cp.chart});h.push(r),i.push(Wf(IS(o,n,e),`xl/charts/chart${s}.xml`,"chart"))}for(const e of s.images){const o=e.data.mimetype;if(void 0===o)continue;const s=Kp[o];if(void 0===s)continue;let r=`image${Sf(e.id)}.${s}`;const a=pf(t.relsFiles,`xl/drawings/_rels/drawing${n}.xml.rels`,{target:`../media/${r}`,type:Cp.image});h.push(a),i.push({path:`xl/media/${r}`,imageSrc:e.data.path})}const d=[...s.charts,...s.images];if(d.length){const e=pf(t.relsFiles,`xl/worksheets/_rels/sheet${n}.xml.rels`,{target:`../drawings/drawing${n}.xml`,type:Cp.drawing});i.push(Wf(GS(h,s,d),`xl/drawings/drawing${n}.xml`,"drawing")),c=Yf`<drawing r:id="${e}" />`}const u=Yf`
2345
+ <worksheet ${qf(r)}>
2346
+ ${rC(s)}
2347
+ <sheetFormatPr ${qf(a)} />
2348
+ ${tC(s.cols)}
2349
+ ${iC(t,e,s)}
2350
+ ${sC(s.merges)}
2351
+ ${Xf(US(t.dxfs,s.conditionalFormats))}
2352
+ ${nC(t,e,n)}
2352
2353
  ${c}
2353
2354
  ${l}
2354
2355
  </worksheet>
2355
- `;i.push($f(qf(u),`xl/worksheets/sheet${n}.xml`,"sheet"))}return gf(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Sp.sharedStrings,target:"sharedStrings.xml"}),gf(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Sp.styles,target:"styles.xml"}),i}(e,i)),t.push(function(e){const t=Xf`
2356
- <styleSheet ${Gf([["xmlns",mp.styleSheet],["xmlns:r",Cp]])}>
2357
- ${function(e){const t=[];for(let[i,o]of Object.entries(e)){const e=[["numFmtId",parseInt(i)+Tp],["formatCode",o.format]];t.push(Xf`
2358
- <numFmt ${Gf(e)}/>
2359
- `)}return Xf`
2356
+ `;i.push(Wf(Zf(u),`xl/worksheets/sheet${n}.xml`,"sheet"))}return pf(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Cp.sharedStrings,target:"sharedStrings.xml"}),pf(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:Cp.styles,target:"styles.xml"}),i}(e,i)),t.push(function(e){const t=Yf`
2357
+ <styleSheet ${qf([["xmlns",fp.styleSheet],["xmlns:r",Ep]])}>
2358
+ ${function(e){const t=[];for(let[i,o]of Object.entries(e)){const e=[["numFmtId",parseInt(i)+Ap],["formatCode",o.format]];t.push(Yf`
2359
+ <numFmt ${qf(e)}/>
2360
+ `)}return Yf`
2360
2361
  <numFmts count="${e.length}">
2361
- ${jf(t)}
2362
+ ${Xf(t)}
2362
2363
  </numFmts>
2363
2364
  `}(e.numFmts)}
2364
- ${i=e.fonts,Xf`
2365
+ ${i=e.fonts,Yf`
2365
2366
  <fonts count="${i.length}">
2366
- ${jf(Object.values(i).map(XS))}
2367
+ ${Xf(Object.values(i).map(YS))}
2367
2368
  </fonts>
2368
2369
  `}
2369
- ${function(e){const t=[];for(let i of Object.values(e))void 0!==i.reservedAttribute?t.push(Xf`
2370
+ ${function(e){const t=[];for(let i of Object.values(e))void 0!==i.reservedAttribute?t.push(Yf`
2370
2371
  <fill>
2371
2372
  <patternFill patternType="${i.reservedAttribute}" />
2372
2373
  </fill>
2373
- `):t.push(Xf`
2374
+ `):t.push(Yf`
2374
2375
  <fill>
2375
2376
  <patternFill patternType="solid">
2376
- <fgColor rgb="${os(i.fgColor.rgb)}" />
2377
+ <fgColor rgb="${ns(i.fgColor.rgb)}" />
2377
2378
  <bgColor indexed="64" />
2378
2379
  </patternFill>
2379
2380
  </fill>
2380
- `);return Xf`
2381
+ `);return Yf`
2381
2382
  <fills count="${e.length}">
2382
- ${jf(t)}
2383
+ ${Xf(t)}
2383
2384
  </fills>
2384
2385
  `}(e.fills)}
2385
- ${function(e){const t=[];for(let i of Object.values(e))t.push(Xf`
2386
+ ${function(e){const t=[];for(let i of Object.values(e))t.push(Yf`
2386
2387
  <border>
2387
- <left ${YS(i.left)} />
2388
- <right ${YS(i.right)} />
2389
- <top ${YS(i.top)} />
2390
- <bottom ${YS(i.bottom)} />
2391
- <diagonal ${YS(i.diagonal)} />
2388
+ <left ${KS(i.left)} />
2389
+ <right ${KS(i.right)} />
2390
+ <top ${KS(i.top)} />
2391
+ <bottom ${KS(i.bottom)} />
2392
+ <diagonal ${KS(i.diagonal)} />
2392
2393
  </border>
2393
- `);return Xf`
2394
+ `);return Yf`
2394
2395
  <borders count="${e.length}">
2395
- ${jf(t)}
2396
+ ${Xf(t)}
2396
2397
  </borders>
2397
2398
  `}(e.borders)}
2398
- ${function(e){const t=[];for(let i of e){const e=[["numFmtId",i.numFmtId],["fillId",i.fillId],["fontId",i.fontId],["borderId",i.borderId]],o=[];i.alignment&&i.alignment.vertical&&o.push(["vertical",i.alignment.vertical]),i.alignment&&i.alignment.horizontal&&o.push(["horizontal",i.alignment.horizontal]),t.push(Xf`
2399
- <xf ${Gf(e)}>
2400
- ${o?Xf`<alignment ${Gf(o)} />`:""}
2399
+ ${function(e){const t=[];for(let i of e){const e=[["numFmtId",i.numFmtId],["fillId",i.fillId],["fontId",i.fontId],["borderId",i.borderId]],o=[];i.alignment&&i.alignment.vertical&&o.push(["vertical",i.alignment.vertical]),i.alignment&&i.alignment.horizontal&&o.push(["horizontal",i.alignment.horizontal]),t.push(Yf`
2400
+ <xf ${qf(e)}>
2401
+ ${o?Yf`<alignment ${qf(o)} />`:""}
2401
2402
  </xf>
2402
- `)}return Xf`
2403
+ `)}return Yf`
2403
2404
  <cellXfs count="${e.length}">
2404
- ${jf(t)}
2405
+ ${Xf(t)}
2405
2406
  </cellXfs>
2406
2407
  `}(e.styles)}
2407
- ${function(e){const t=[];for(const i of e){let e=Xf``;i.font&&(e=XS(i.font));let o=Xf``;i.fill&&(o=Xf`
2408
+ ${function(e){const t=[];for(const i of e){let e=Yf``;i.font&&(e=YS(i.font));let o=Yf``;i.fill&&(o=Yf`
2408
2409
  <fill>
2409
2410
  <patternFill>
2410
- <bgColor rgb="${os(i.fill.fgColor.rgb)}" />
2411
+ <bgColor rgb="${ns(i.fill.fgColor.rgb)}" />
2411
2412
  </patternFill>
2412
2413
  </fill>
2413
- `),t.push(Xf`
2414
+ `),t.push(Yf`
2414
2415
  <dxf>
2415
2416
  ${e}
2416
2417
  ${o}
2417
2418
  </dxf>
2418
- `)}return Xf`
2419
+ `)}return Yf`
2419
2420
  <dxfs count="${e.length}">
2420
- ${jf(t)}
2421
+ ${Xf(t)}
2421
2422
  </dxfs>
2422
2423
  `}(e.dxfs)}
2423
2424
  </styleSheet>
2424
- `;var i;return $f(qf(t),"xl/styles.xml","styles")}(i)),t.push(function(e){const t=[["xmlns",mp.sst],["count",e.length],["uniqueCount",e.length]],i=e.map((e=>Xf`<si><t>${e}</t></si>`));return $f(qf(Xf`
2425
- <sst ${Gf(t)}>
2426
- ${jf(i)}
2425
+ `;var i;return Wf(Zf(t),"xl/styles.xml","styles")}(i)),t.push(function(e){const t=[["xmlns",fp.sst],["count",e.length],["uniqueCount",e.length]],i=e.map((e=>Yf`<si><t>${e}</t></si>`));return Wf(Zf(Yf`
2426
+ <sst ${qf(t)}>
2427
+ ${Xf(i)}
2427
2428
  </sst>
2428
- `),"xl/sharedStrings.xml","sharedStrings")}(i.sharedStrings)),t.push(...function(e){const t=[];for(const i of e){const e=[];for(const t of i.rels){const i=[["Id",t.id],["Target",t.target],["Type",t.type]];t.targetMode&&i.push(["TargetMode",t.targetMode]),e.push(Xf`
2429
- <Relationship ${Gf(i)} />
2430
- `)}const o=Xf`
2431
- <Relationships xmlns="${mp.Relationships}">
2432
- ${jf(e)}
2429
+ `),"xl/sharedStrings.xml","sharedStrings")}(i.sharedStrings)),t.push(...function(e){const t=[];for(const i of e){const e=[];for(const t of i.rels){const i=[["Id",t.id],["Target",t.target],["Type",t.type]];t.targetMode&&i.push(["TargetMode",t.targetMode]),e.push(Yf`
2430
+ <Relationship ${qf(i)} />
2431
+ `)}const o=Yf`
2432
+ <Relationships xmlns="${fp.Relationships}">
2433
+ ${Xf(e)}
2433
2434
  </Relationships>
2434
- `;t.push($f(qf(o),i.path))}return t}(i.relsFiles)),t.push(function(e){const t=[],i=Object.entries(Yp).map((([e,t])=>function(e,t){return Xf`
2435
+ `;t.push(Wf(Zf(o),i.path))}return t}(i.relsFiles)),t.push(function(e){const t=[],i=Object.entries(Kp).map((([e,t])=>function(e,t){return Yf`
2435
2436
  <Default Extension="${e}" ContentType="${t}" />
2436
- `}(t,e)));for(const i of e)"contentType"in i&&i.contentType&&t.push(Zf("/"+i.path,bp[i.contentType]));return $f(qf(Xf`
2437
- <Types xmlns="${mp.Types}">
2438
- ${jf(Object.values(i))}
2437
+ `}(t,e)));for(const i of e)"contentType"in i&&i.contentType&&t.push(jf("/"+i.path,Sp[i.contentType]));return Wf(Zf(Yf`
2438
+ <Types xmlns="${fp.Types}">
2439
+ ${Xf(Object.values(i))}
2439
2440
  <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />
2440
2441
  <Default Extension="xml" ContentType="application/xml" />
2441
- ${jf(t)}
2442
+ ${Xf(t)}
2442
2443
  </Types>
2443
- `),"[Content_Types].xml")}(t)),t.push(function(){const e=[["Id","rId1"],["Type",Sp.document],["Target","xl/workbook.xml"]];return $f(qf(Xf`
2444
- <Relationships xmlns="${mp.Relationships}">
2445
- <Relationship ${Gf(e)} />
2444
+ `),"[Content_Types].xml")}(t)),t.push(function(){const e=[["Id","rId1"],["Type",Cp.document],["Target","xl/workbook.xml"]];return Wf(Zf(Yf`
2445
+ <Relationships xmlns="${fp.Relationships}">
2446
+ <Relationship ${qf(e)} />
2446
2447
  </Relationships>
2447
- `),"_rels/.rels")}()),{name:"my_spreadsheet.xlsx",files:t}}function aC(e,t,i,o,n){let s=i;if(!e.filterTables.length)return new dp("");const r=`xl/worksheets/_rels/sheet${t}.xml.rels`,a=[];for(const t of e.filterTables){const i=gf(o.relsFiles,r,{target:`../tables/table${s}.xml`,type:Sp.table});n.push($f(QS(t,s,e),`xl/tables/table${s}.xml`,"table")),a.push(Xf`<tablePart r:id="${i}" />`),s++}return Xf`
2448
+ `),"_rels/.rels")}()),{name:"my_spreadsheet.xlsx",files:t}}function lC(e,t,i,o,n){let s=i;if(!e.filterTables.length)return new up("");const r=`xl/worksheets/_rels/sheet${t}.xml.rels`,a=[];for(const t of e.filterTables){const i=pf(o.relsFiles,r,{target:`../tables/table${s}.xml`,type:Cp.table});n.push(Wf(JS(t,s,e),`xl/tables/table${s}.xml`,"table")),a.push(Yf`<tablePart r:id="${i}" />`),s++}return Yf`
2448
2449
  <tableParts count="${e.filterTables.length}">
2449
- ${jf(a)}
2450
+ ${Xf(a)}
2450
2451
  </tableParts>
2451
- `}var lC;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(lC||(lC={}));const cC={},hC={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:O,HEADER_WIDTH:N,TOPBAR_HEIGHT:63,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:_,DEFAULT_CELL_HEIGHT:F,SCROLLBAR_WIDTH:D},dC={autofillModifiersRegistry:En,autofillRulesRegistry:wn,cellMenuRegistry:ia,colMenuRegistry:oa,linkMenuRegistry:Jn,functionRegistry:Wu,featurePluginRegistry:Pb,statefulUIPluginRegistry:Ub,coreViewsPluginRegistry:Vb,corePluginRegistry:Lb,rowMenuRegistry:na,sidePanelRegistry:yg,figureRegistry:hr,chartSidePanelComponentRegistry:pg,chartComponentRegistry:sr,chartRegistry:nr,topbarMenuRegistry:qu,topbarComponentRegistry:xg,clickableCellRegistry:zb,otRegistry:ju,inverseCommandRegistry:pr,urlRegistry:wo,cellPopoverRegistry:is},uC={arg:aa,toBoolean:Po,toJsDate:Uo,toNumber:_o,toString:Do,toXC:Bt,toZone:Li,toCartesian:zt,numberToLetters:Ut,UuidGenerator:Di,formatValue:hi,computeTextWidth:Le,createEmptyWorkbookData:Cv,createEmptySheet:Sv,createEmptyExcelSheet:Ev,getDefaultChartJsRuntime:_s,chartFontColor:fs,ChartColors:ms,EvaluationError:c,CellErrorLevel:l,getFillingMode:Ls,rgbaToHex:yt,colorToRGBA:xt,positionToZone:oo,isDefined:et,lazy:nt},gC={isMarkdownLink:qe,parseMarkdownLink:Xe,markdownLink:je,openLink:To,urlRepresentation:Ro},pC={ChartPanel:mg,ChartFigure:ar,ChartJsComponent:ao,Grid:hp,GridOverlay:jg,ScorecardChart:vo,LineConfigPanel:hg,LineBarPieDesignPanel:rg,BarConfigPanel:eg,LineBarPieConfigPanel:Ju,GaugeChartConfigPanel:lg,GaugeChartDesignPanel:cg,ScorecardChartConfigPanel:ug,ScorecardChartDesignPanel:gg,FigureComponent:Ig};e.AbstractChart=ns,e.CorePlugin=yv,e.DATETIME_FORMAT=X,e.DispatchResult=cn,e.EvaluationError=c,e.Model=class extends ab{constructor(e={},i={},o=[],n=new Di,s=!0){super(),this.corePlugins=[],this.featurePlugins=[],this.statefulUIPlugins=[],this.coreViewsPlugins=[],this.isReplayingCommand=!1,this.renderers=[],this.status=0,this.handlers=[],this.coreHandlers=[],this.dispatch=(e,t)=>{const i={...t,type:e};let o=this.status;if(this.getters.isReadonly()&&(n=i,!rn.has(n.type)))return new cn(67);var n;if(!this.session.canApplyOptimisticUpdate())return new cn(64);switch(o){case 0:const t=this.checkDispatchAllowed(i);if(!t.isSuccessful)return t;this.status=1;const{changes:o,commands:n}=this.state.recordChanges((()=>{ln(i)&&this.state.addCommand(i),this.dispatchToHandlers(this.handlers,i),this.finalize()}));this.session.save(n,o),this.status=0,this.trigger("update");break;case 1:if(ln(i)){const e=this.checkDispatchAllowed(i);if(!e.isSuccessful)return e;this.state.addCommand(i)}this.dispatchToHandlers(this.handlers,i);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(ln(i))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,i)}return cn.Success},this.dispatchFromCorePlugin=(e,t)=>{const i={...t,type:e},o=this.status;this.status=2;const n=this.isReplayingCommand?[this.range,...this.corePlugins,...this.coreViewsPlugins]:this.handlers;return this.dispatchToHandlers(n,i),this.status=o,cn.Success},o=vv(e,o);const r=mv(e,s);this.state=new ES,this.uuidGenerator=n,this.config=this.setupConfig(i),this.session=this.setupSession(r.revisionId),this.history=new bS(this.dispatchFromCorePlugin,this.session),this.coreGetters={},this.range=new Vv(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 CS(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of Lb.getAll())this.setupCorePlugin(e,r);Object.assign(this.getters,this.coreGetters);for(let e of Ub.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t)}for(let e of Vb.getAll()){const t=this.setupUiPlugin(e);this.coreViewsPlugins.push(t),this.handlers.push(t),this.coreHandlers.push(t)}for(let e of Pb.getAll()){const t=this.setupUiPlugin(e);this.featurePlugins.push(t),this.handlers.push(t)}this.uuidGenerator.setIsFastStrategy(!1),this.handlers.push(this.history),this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.setupSessionEvents(),this.session.loadInitialMessages(o),this.joinSession(),i.snapshotRequested&&(this.session.snapshot(this.exportData()),this.garbageCollectExternalResources()),t.markRaw(this)}joinSession(){this.session.join(this.config.client)}leaveSession(){this.session.leave()}setupUiPlugin(e){const t=new e(this.uiPluginConfig);for(let i of e.getters){if(!(i in t))throw new Error(`Invalid getter name: ${i} for plugin ${t.constructor}`);if(i in this.getters)throw new Error(`Getter "${i}" is already defined.`);this.getters[i]=t[i].bind(t)}const i=e.layers.map((e=>[t,e]));return this.renderers.push(...i),this.renderers.sort(((e,t)=>e[1]-t[1])),t}setupCorePlugin(e,t){const i=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in i))throw new Error(`Invalid getter name: ${t} for plugin ${i.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=i[t].bind(i)}i.import(t),this.corePlugins.push(i),this.coreHandlers.push(i),this.handlers.push(i)}onRemoteRevisionReceived({commands:e}){for(let t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new fb(fS(e,this.state.recordChanges.bind(this.state),(e=>{this.checkDispatchAllowed(e).isSuccessful&&(this.isReplayingCommand=!0,this.dispatchToHandlers([this.range,...this.corePlugins,...this.coreViewsPlugins],e),this.isReplayingCommand=!1)})),this.config.transportService,e)}setupSessionEvents(){this.session.on("remote-revision-received",this,this.onRemoteRevisionReceived),this.session.on("revision-redone",this,this.finalize),this.session.on("revision-undone",this,this.finalize),this.session.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.session.on("collaborative-event-received",this,(()=>{this.trigger("update")}))}setupConfig(e){const t=e.client||{id:this.uuidGenerator.uuidv4(),name:s("Anonymous").toString()},i=e.transportService||new aS;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:e.external||{},transportService:i,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e),lazyEvaluation:!("lazyEvaluation"in e)||e.lazyEvaluation}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,uuidGenerator:this.uuidGenerator,custom:this.config.custom,external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,lazyEvaluation:this.config.lazyEvaluation}}checkDispatchAllowed(e){const t=this.handlers.map((t=>t.allowDispatch(e)));return new cn(t.flat())}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0}dispatchToHandlers(e,t){t=Ne(t);for(const i of e)i.beforeHandle(t);for(const i of e)i.handle(t)}drawGrid(e){for(let[t,i]of this.renderers)e.ctx.save(),t.drawGrid(e,i),e.ctx.restore()}exportData(){let e=Cv();for(let t of this.handlers)t instanceof yv&&t.export(e);return e.revisionId=this.session.getRevisionId()||K,e=Ne(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={...Cv(),sheets:[Ev(pv,"Sheet1")]};for(let t of this.handlers)t instanceof wv&&t.exportForExcel(e);return e=Ne(e),rC(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.Registry=Co,e.Revision=pb,e.SPREADSHEET_DIMENSIONS=hC,e.Spreadsheet=rS,e.UIPlugin=Bv,e.__info__=cC,e.addFunction=function(e,t){Wu.add(e,t)},e.astToFormula=Gm,e.compile=sf,e.components=pC,e.convertAstNodes=Wm,e.coreTypes=an,e.findCellInNewZone=to,e.functionCache=nf,e.helpers=uC,e.invalidateEvaluationCommands=nn,e.links=gC,e.load=mv,e.parse=Hm,e.readonlyAllowedCommands=rn,e.registries=dC,e.setTranslationMethod=function(e){i=e},e.tokenize=Em,Object.defineProperty(e,"__esModule",{value:!0}),cC.version="16.2.9",cC.date="2023-06-12T13:49:57.216Z",cC.hash="37e2719"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
2452
+ `}var cC;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(cC||(cC={}));const hC={},dC={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:O,HEADER_WIDTH:N,TOPBAR_HEIGHT:63,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:_,DEFAULT_CELL_HEIGHT:F,SCROLLBAR_WIDTH:D},uC={autofillModifiersRegistry:wn,autofillRulesRegistry:yn,cellMenuRegistry:oa,colMenuRegistry:na,linkMenuRegistry:es,functionRegistry:Gu,featurePluginRegistry:Ub,statefulUIPluginRegistry:Vb,coreViewsPluginRegistry:zb,corePluginRegistry:Pb,rowMenuRegistry:sa,sidePanelRegistry:xg,figureRegistry:dr,chartSidePanelComponentRegistry:mg,chartComponentRegistry:rr,chartRegistry:sr,topbarMenuRegistry:Zu,topbarComponentRegistry:Ig,clickableCellRegistry:Bb,otRegistry:Xu,inverseCommandRegistry:mr,urlRegistry:yo,cellPopoverRegistry:os},gC={arg:la,toBoolean:Uo,toJsDate:Vo,toNumber:Fo,toString:ko,toXC:Ht,toZone:Pi,toCartesian:Bt,numberToLetters:Vt,UuidGenerator:ki,formatValue:di,computeTextWidth:Le,createEmptyWorkbookData:Ev,createEmptySheet:Cv,createEmptyExcelSheet:wv,getDefaultChartJsRuntime:Fs,chartFontColor:vs,ChartColors:fs,EvaluationError:c,CellErrorLevel:l,getFillingMode:Ps,rgbaToHex:xt,colorToRGBA:It,positionToZone:no,isDefined:tt,lazy:st},pC={isMarkdownLink:Ze,parseMarkdownLink:Ye,markdownLink:Xe,openLink:Ao,urlRepresentation:To},mC={ChartPanel:fg,ChartFigure:lr,ChartJsComponent:lo,Grid:dp,GridOverlay:Xg,ScorecardChart:bo,LineConfigPanel:dg,LineBarPieDesignPanel:ag,BarConfigPanel:tg,LineBarPieConfigPanel:eg,GaugeChartConfigPanel:cg,GaugeChartDesignPanel:hg,ScorecardChartConfigPanel:gg,ScorecardChartDesignPanel:pg,FigureComponent:Rg};e.AbstractChart=ss,e.CorePlugin=xv,e.DATETIME_FORMAT=X,e.DispatchResult=hn,e.EvaluationError=c,e.Model=class extends lb{constructor(e={},i={},o=[],n=new ki,s=!0){super(),this.corePlugins=[],this.featurePlugins=[],this.statefulUIPlugins=[],this.coreViewsPlugins=[],this.isReplayingCommand=!1,this.renderers=[],this.status=0,this.handlers=[],this.coreHandlers=[],this.dispatch=(e,t)=>{const i={...t,type:e};let o=this.status;if(this.getters.isReadonly()&&(n=i,!an.has(n.type)))return new hn(67);var n;if(!this.session.canApplyOptimisticUpdate())return new hn(64);switch(o){case 0:const t=this.checkDispatchAllowed(i);if(!t.isSuccessful)return t;this.status=1;const{changes:o,commands:n}=this.state.recordChanges((()=>{cn(i)&&this.state.addCommand(i),this.dispatchToHandlers(this.handlers,i),this.finalize()}));this.session.save(n,o),this.status=0,this.trigger("update");break;case 1:if(cn(i)){const e=this.checkDispatchAllowed(i);if(!e.isSuccessful)return e;this.state.addCommand(i)}this.dispatchToHandlers(this.handlers,i);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(cn(i))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,i)}return hn.Success},this.dispatchFromCorePlugin=(e,t)=>{const i={...t,type:e},o=this.status;this.status=2;const n=this.isReplayingCommand?[this.range,...this.corePlugins,...this.coreViewsPlugins]:this.handlers;return this.dispatchToHandlers(n,i),this.status=o,hn.Success},o=bv(e,o);const r=fv(e,s);this.state=new wS,this.uuidGenerator=n,this.config=this.setupConfig(i),this.session=this.setupSession(r.revisionId),this.history=new SS(this.dispatchFromCorePlugin,this.session),this.coreGetters={},this.range=new zv(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 ES(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of Pb.getAll())this.setupCorePlugin(e,r);Object.assign(this.getters,this.coreGetters);for(let e of Vb.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t)}for(let e of zb.getAll()){const t=this.setupUiPlugin(e);this.coreViewsPlugins.push(t),this.handlers.push(t),this.coreHandlers.push(t)}for(let e of Ub.getAll()){const t=this.setupUiPlugin(e);this.featurePlugins.push(t),this.handlers.push(t)}this.uuidGenerator.setIsFastStrategy(!1),this.handlers.push(this.history),this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.setupSessionEvents(),this.session.loadInitialMessages(o),this.joinSession(),i.snapshotRequested&&(this.session.snapshot(this.exportData()),this.garbageCollectExternalResources()),t.markRaw(this)}joinSession(){this.session.join(this.config.client)}leaveSession(){this.session.leave()}setupUiPlugin(e){const t=new e(this.uiPluginConfig);for(let i of e.getters){if(!(i in t))throw new Error(`Invalid getter name: ${i} for plugin ${t.constructor}`);if(i in this.getters)throw new Error(`Getter "${i}" is already defined.`);this.getters[i]=t[i].bind(t)}const i=e.layers.map((e=>[t,e]));return this.renderers.push(...i),this.renderers.sort(((e,t)=>e[1]-t[1])),t}setupCorePlugin(e,t){const i=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in i))throw new Error(`Invalid getter name: ${t} for plugin ${i.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=i[t].bind(i)}i.import(t),this.corePlugins.push(i),this.coreHandlers.push(i),this.handlers.push(i)}onRemoteRevisionReceived({commands:e}){for(let t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new vb(vS(e,this.state.recordChanges.bind(this.state),(e=>{this.checkDispatchAllowed(e).isSuccessful&&(this.isReplayingCommand=!0,this.dispatchToHandlers([this.range,...this.corePlugins,...this.coreViewsPlugins],e),this.isReplayingCommand=!1)})),this.config.transportService,e)}setupSessionEvents(){this.session.on("remote-revision-received",this,this.onRemoteRevisionReceived),this.session.on("revision-redone",this,this.finalize),this.session.on("revision-undone",this,this.finalize),this.session.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.session.on("collaborative-event-received",this,(()=>{this.trigger("update")}))}setupConfig(e){const t=e.client||{id:this.uuidGenerator.uuidv4(),name:s("Anonymous").toString()},i=e.transportService||new lS;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:e.external||{},transportService:i,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e),lazyEvaluation:!("lazyEvaluation"in e)||e.lazyEvaluation}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,uuidGenerator:this.uuidGenerator,custom:this.config.custom,external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,lazyEvaluation:this.config.lazyEvaluation}}checkDispatchAllowed(e){const t=this.handlers.map((t=>t.allowDispatch(e)));return new hn(t.flat())}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0}dispatchToHandlers(e,t){t=Ne(t);for(const i of e)i.beforeHandle(t);for(const i of e)i.handle(t)}drawGrid(e){for(let[t,i]of this.renderers)e.ctx.save(),t.drawGrid(e,i),e.ctx.restore()}exportData(){let e=Ev();for(let t of this.handlers)t instanceof xv&&t.export(e);return e.revisionId=this.session.getRevisionId()||K,e=Ne(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={...Ev(),sheets:[wv(mv,"Sheet1")]};for(let t of this.handlers)t instanceof yv&&t.exportForExcel(e);return e=Ne(e),aC(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.Registry=Eo,e.Revision=mb,e.SPREADSHEET_DIMENSIONS=dC,e.Spreadsheet=aS,e.UIPlugin=Hv,e.__info__=hC,e.addFunction=function(e,t){Gu.add(e,t)},e.astToFormula=qm,e.compile=rf,e.components=mC,e.convertAstNodes=Gm,e.coreTypes=ln,e.findCellInNewZone=io,e.functionCache=sf,e.helpers=gC,e.invalidateEvaluationCommands=sn,e.links=pC,e.load=fv,e.parse=$m,e.readonlyAllowedCommands=an,e.registries=uC,e.setTranslationMethod=function(e){i=e},e.tokenize=wm,Object.defineProperty(e,"__esModule",{value:!0}),hC.version="16.2.10",hC.date="2023-06-26T14:33:27.213Z",hC.hash="1d3f47c"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);