@trebco/treb 32.8.1 → 32.9.3

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,17 +1,17 @@
1
- /*! TREB v32.8.1. Copyright 2018-2025 trebco, llc. All rights reserved. LGPL: https://treb.app/license */
2
- var lo=Object.defineProperty;var co=(l,e)=>{for(var t in e)lo(l,t,{get:e[t],enumerable:!0})};var St=class{get list(){return this.sheets_.slice(0)}get length(){return this.sheets_.length}names=new Map;ids=new Map;sheets_=[];Assign(e){this.sheets_=[...e],this.UpdateIndexes()}Add(e){this.sheets_.push(e),this.UpdateIndexes()}Splice(e,t,...r){this.sheets_.splice(e,t,...r),this.UpdateIndexes()}Find(e){return typeof e=="string"?this.names.get(e.toLocaleUpperCase()):this.ids.get(e)}Name(e){return this.ids.get(e)?.name||void 0}ID(e){return this.names.get(e.toLocaleUpperCase())?.id||void 0}UpdateIndexes(){this.names.clear(),this.ids.clear();for(let e of this.sheets_){let t=e.name.toLocaleUpperCase();this.names.set(t,e),this.ids.set(e.id,e)}}};var xi={spreadsheet_semantics:!0,dimensioned_quantities:!1,fractions:!0,decimal_mark:".",argument_separator:",",boolean_true:"TRUE",boolean_false:"FALSE"};var Ce=/[\s-+=<>!()]/,Ri=/['*\\]/,Sr=34,Ar=39,uo=160,Ci=32,ho=9,fo=10,mo=13,Ve=48,ot=57,kr=46,Rr=43,at=45,Si=40,Er=41,st=44,po=37,Tr=95,At=36,bo=123,go=125,lt=91,Ai=93,_o=63,yo=33,ki=59,Mr=35,vo=64,Je=65,ct=97,wo=69,xo=101,kt=90,Rt=122,Co=105,Ur=192,Vr=382,Dr={"==":6,"!=":6,"<>":6,"=":6,"<":7,">":7,"<=":7,">=":7,"+":9,"-":9,"&":9,"*":10,"/":10,"^":11,":":13},So={"@":50,"-":100,"+":100},Ao=[...Object.keys(Dr),"@"].sort((l,e)=>e.length-l.length),We=class{get argument_separator(){return this.flags.argument_separator}get decimal_mark(){return this.flags.decimal_mark}flags={...xi};r1c1_regex=/[rR]((?:\[[-+]{0,1}\d+\]|\d*))[cC]((?:\[[-+]{0,1}\d+\]|\d*))$/;argument_separator_char=st;decimal_mark_char=kr;imaginary_char=Co;imaginary_number="i";id_counter=0;expression="";data=[];index=0;length=0;valid=!0;error_position;error;dependencies={addresses:{},ranges:{}};address_refcount={};full_reference_list=[];parser_state_cache=[];SetLocaleSettings(e,t){if(typeof t>"u"&&(t=e===","?";":","),t===e)throw new Error("invalid locale setting");this.flags.argument_separator=t,this.flags.decimal_mark=e}Save(){this.parser_state_cache.push(JSON.stringify(this.flags))}Restore(){let e=this.parser_state_cache.shift();if(e)try{this.flags=JSON.parse(e)}catch(t){console.error(t)}else console.warn("No parser state to restore")}Walk2(e,t){let r=t(e);if(typeof r=="object")return r;switch(e.type){case"address":case"missing":case"literal":case"complex":case"identifier":case"operator":case"structured-reference":break;case"dimensioned":r&&(e.expression=this.Walk2(e.expression,t),e.unit=this.Walk2(e.unit,t));break;case"range":t(e)&&(e.start=this.Walk2(e.start,t),e.end=this.Walk2(e.end,t));break;case"binary":t(e)&&(e.left=this.Walk2(e.left,t),e.right=this.Walk2(e.right,t));break;case"unary":t(e)&&(e.operand=this.Walk2(e.operand,t));break;case"group":t(e)&&(e.elements=e.elements.map(i=>this.Walk2(i,t)));break;case"implicit-call":t(e)&&(e.call=this.Walk2(e.call,t),e.args=e.args.map(i=>this.Walk2(i,t)));break;case"call":t(e)&&(e.args=e.args.map(i=>this.Walk2(i,t)));break}return e}Walk(e,t){switch(e.type){case"address":case"missing":case"literal":case"complex":case"identifier":case"operator":case"structured-reference":t(e);return;case"dimensioned":t(e)&&(this.Walk(e.expression,t),this.Walk(e.unit,t));return;case"range":t(e)&&(this.Walk(e.start,t),this.Walk(e.end,t));return;case"binary":t(e)&&(this.Walk(e.left,t),this.Walk(e.right,t));return;case"unary":t(e)&&this.Walk(e.operand,t);return;case"group":if(t(e))for(let r of e.elements)this.Walk(r,t);return;case"implicit-call":if(t(e)){this.Walk(e.call,t);for(let r of e.args)this.Walk(r,t)}return;case"call":if(t(e))for(let r of e.args)this.Walk(r,t)}}Transpose(e){let t=e.length,r=[],i=0;for(let n=0;n<t;n++)Array.isArray(e[n])&&(i=Math.max(i,e[n].length));for(let n=0;n<i;n++){r[n]=[];for(let o=0;o<t;o++)r[n][o]=e[o]?e[o][n]:void 0}return r}Render(e,t={}){let r=t.offset||{rows:0,columns:0},i=t.missing??"(missing)",{convert_decimal:n,convert_argument_separator:o,long_structured_references:a,table_name:s}=t,c=this.flags.argument_separator+" ";o===","?c=", ":o===";"&&(c="; ");let d=n===","?",":".",u=this.flags.decimal_mark===","?/,/:/\./,h=this.flags.decimal_mark===","?/,/g:/\./g;switch(e.type){case"address":return t.pass_through_addresses?e.label:t.r1c1?this.R1C1Label(e,t):this.AddressLabel(e,r);case"range":return t.pass_through_addresses?e.label:t.r1c1?this.R1C1Label(e.start,t)+":"+this.R1C1Label(e.end,t):this.AddressLabel(e.start,r)+":"+this.AddressLabel(e.end,r);case"missing":return i;case"array":return"{"+this.Transpose(e.values).map(f=>f.map(m=>typeof m=="string"?'"'+m+'"':m).join(", ")).join("; ")+"}";case"binary":return this.Render(e.left,t)+" "+e.operator+" "+this.Render(e.right,t);case"unary":return e.operator+this.Render(e.operand,t);case"complex":if(e.text)return n?e.text.replace(h,d):e.text;{let f=Math.abs(e.imaginary).toString();if((n===","||this.flags.decimal_mark===",")&&(f=f.replace(/\./,",")),e.real){let m=e.real.toString();(n===","||this.flags.decimal_mark===",")&&(m=m.replace(/\./,","));let p=Math.abs(e.imaginary);return`${m}${e.imaginary<0?" - ":" + "}${p===1?"":f}i`}else return e.imaginary===-1?"-i":e.imaginary===1?"i":`${e.imaginary<0?"-":""}${f}i`}break;case"literal":if(typeof e.value=="string")return'"'+e.value.replace(/"/g,'""')+'"';if(typeof e.value=="boolean")return e.value?t.boolean_true||this.flags.boolean_true||"true":t.boolean_false||this.flags.boolean_false||"false";if(n&&typeof e.value=="number")if(e.text){let f=e.text;return n===","&&this.flags.decimal_mark==="."&&(f=f.replace(/,/g,"")),f.replace(u,d)}else return e.value.toString().replace(/\./,d);else if(e.text)return e.text;return e.value.toString();case"identifier":return e.name;case"operator":return"["+e.operator+"]";case"group":return e.explicit?"("+e.elements.map(f=>this.Render(f,t)).join(c)+")":e.elements.map(f=>this.Render(f,t)).join(c);case"implicit-call":return this.Render(e.call,t)+"("+e.args.map(f=>this.Render(f,t)).join(c)+")";case"call":return e.name+"("+e.args.map(f=>this.Render(f,t)).join(c)+")";case"dimensioned":return this.Render(e.expression)+" "+this.Render(e.unit);case"structured-reference":{let f=e.column;/[^A-Za-z]/.test(f)&&(f="["+f+"]");let m=e.table;switch(!m&&a&&s&&(m=s),e.scope){case"all":return`${m}[[#all],${f}]`;case"row":return a?`${m}[[#this row],${f}]`:`${m}[@${f}]`;case"column":return`${m}[${f}]`}throw new Error("unhandled scope in structured reference")}}return"??"}Parse(e){switch(e=e.trim(),e[0]==="="&&(e=e.substr(1).trim()),this.expression=e,this.data=[],this.length=e.length,this.index=0,this.valid=!0,this.error_position=void 0,this.error=void 0,this.dependencies.addresses={},this.dependencies.ranges={},this.address_refcount={},this.full_reference_list=[],this.id_counter=0,this.flags.argument_separator){case";":this.argument_separator_char=ki;break;default:this.argument_separator_char=st;break}switch(this.flags.decimal_mark){case",":this.decimal_mark_char=st;break;default:this.decimal_mark_char=kr;break}for(let i=0;i<this.length;i++)this.data[i]=e.charCodeAt(i);let t=this.ParseGeneric(),r={};for(let i of Object.keys(this.dependencies.addresses))this.address_refcount[i]&&(r[i]=this.dependencies.addresses[i]);return this.dependencies.addresses=r,{expression:t||void 0,valid:this.valid,error:this.error,error_position:this.error_position,dependencies:this.dependencies,separator:this.flags.argument_separator,decimal_mark:this.flags.decimal_mark,full_reference_list:this.full_reference_list.slice(0)}}ColumnLabel(e){if(e===1/0)return"";let t=String.fromCharCode(65+e%26);for(;e>25;)e=Math.floor(e/26)-1,t=String.fromCharCode(65+e%26)+t;return t}R1C1Label(e,t){let r=!!t.r1c1_force_relative,i=t.r1c1_base,n="";e.sheet&&(n=(Ce.test(e.sheet)?"'"+e.sheet+"'":e.sheet)+"!");let o="",a="";if(r&&t.r1c1_proper_semantics&&i){if(e.absolute_row)o=(e.row+1).toString();else{let s=e.row-i.row;s&&(o=`[${s}]`)}if(e.absolute_column)a=(e.column+1).toString();else{let s=e.column-i.column;s&&(a=`[${s}]`)}}else if(r&&i){let s=e.row-i.row,c=e.column-i.column;s&&(o=`[${s}]`),c&&(a=`[${c}]`)}else o=e.offset_row?`[${e.row}]`:(e.row+1).toString(),a=e.offset_column?`[${e.column}]`:(e.column+1).toString();return n+=`R${o}C${a}`,n}AddressLabel(e,t){let r=e.column;!e.absolute_column&&e.column!==1/0&&(r+=t.columns);let i=e.row;if(!e.absolute_row&&e.row!==1/0&&(i+=t.rows),i<0||r<0||i===1/0&&r===1/0)return"#REF";let n="";return e.sheet&&(n=(Ce.test(e.sheet)?"'"+e.sheet+"'":e.sheet)+"!"),i===1/0?n+(e.absolute_column?"$":"")+this.ColumnLabel(r):r===1/0?n+(e.absolute_row?"$":"")+(i+1):n+(e.absolute_column?"$":"")+this.ColumnLabel(r)+(e.absolute_row?"$":"")+(i+1)+(e.spill?"#":"")}ParseGeneric(e=[0],t=!1){let r=[];for(;this.index<this.length;){let i=this.ParseNext(r.length===0);if(typeof i=="number"){if(e.some(n=>i===n))break;if(i===Si){this.index++;let n=this.ParseGeneric([Er],!0);this.index++,r.push({type:"group",id:this.id_counter++,elements:n?[n]:[],explicit:!0})}else{let n=this.ConsumeOperator();n?r.push(n):t&&i===this.argument_separator_char?(r.push({type:"group-separator",position:this.index,id:this.id_counter++}),this.index++):(this.error=`unexpected character [1]: ${String.fromCharCode(i)}, 0x${i.toString(16)}`,this.valid=!1,this.index++)}}else r.push(i)}if(r.length){if(r=this.BinaryToRange2(r),this.flags.fractions){let i=[],n=a=>a.type==="literal"&&typeof a.value=="number"&&a.value%1===0,o=0;for(;o<r.length-3;o++)if(n(r[o])&&n(r[o+1])&&r[o+2].type==="operator"&&r[o+2].operator==="/"&&n(r[o+3])){let a=r[o],s=r[o+1],c=r[o+3],d=(a.value<0?-1:1)*(s.value/c.value);o+=3,i.push({id:r[o].id,type:"literal",text:this.expression.substring(a.position,c.position+1),value:a.value+d,position:a.position})}else i.push(r[o]);for(;o<r.length;o++)i.push(r[o]);r=i}if(r=r.map(i=>i.type==="identifier"&&i.name===this.imaginary_number?{type:"complex",real:0,imaginary:1,position:i.position,text:i.name,id:this.id_counter++}:i),this.flags.dimensioned_quantities){let i=[],n;for(let o=0;o<r.length;o++){let a=r[o];if(!n)n=a;else if(a.type==="identifier"&&(n.type==="literal"||n.type==="group"||n.type==="call")){let s=a;for(;r[o+1]?.type==="identifier";)s.name+=" "+r[++o].name;i.push({type:"dimensioned",expression:n,unit:a,id:this.id_counter++}),n=void 0}else i.push(n),n=a}n&&i.push(n),r=i}}return r.length===0?null:r.length===1?r[0]:this.BinaryToComplex(this.ArrangeUnits(r))}UnitToAddress(e){if(e.type==="literal"){if(typeof e.value=="number"&&e.value>0&&!/\./.test(e.text||""))return{type:"address",position:e.position,label:e.value.toString(),row:e.value-1,id:this.id_counter++,column:1/0}}else{let t,r=e.name,i=r.split("!");if(i.length>1&&(t=i.slice(0,i.length-1).join("!"),r=r.substr(t.length+1),t[0]==="'"))if(t.length>1&&t[t.length-1]==="'")t=t.substr(1,t.length-2);else return;let n=r[0]==="$";r=(n?r.substr(1):r).toUpperCase();let o=Number(r);if(isNaN(o)){if(/[A-Z]{1,3}/.test(r)){let a=-1;for(let s=0;s<r.length;s++){let c=r[s].charCodeAt(0);a=26*(1+a)+(c-Je)}return{type:"address",position:e.position,absolute_column:n,label:e.name,column:a,id:this.id_counter++,row:1/0,sheet:t}}}else if(o>0&&o!==1/0&&!/\./.test(r))return{type:"address",position:e.position,absolute_row:n,label:e.name,row:o-1,id:this.id_counter++,column:1/0,sheet:t}}}BinaryToRange2(e){let t=[];for(let r=0;r<e.length;r++){let i=e[r],n=e[r+1],o=e[r+2],a,s="",c;if(i&&n&&o&&n.type==="operator"&&n.operator===":"){if(i.type==="address"&&o.type==="address"){let d=i.position+i.label.length,u=o.position;a={type:"range",id:this.id_counter++,position:i.position,start:i,end:o,label:i.label+this.expression.substring(d,u)+o.label},s=a.start.label+":"+a.end.label,this.address_refcount[a.start.label]--,this.address_refcount[a.end.label]--;let h=[i.position,o.position];this.full_reference_list=this.full_reference_list.filter(f=>f.position!==h[0]&&f.position!==h[1])}else if((i.type==="literal"||i.type==="identifier")&&(o.type==="literal"||o.type==="identifier")){let d=this.UnitToAddress(i);if(!d&&i.type==="literal"&&typeof i.value=="number"&&i.value<0){let h={...i,text:(i.text||"").replace(/^-/,""),position:i.position+1,value:-i.value};d=this.UnitToAddress(h),d&&(c={type:"operator",operator:"-",position:i.position,id:this.id_counter++})}let u=this.UnitToAddress(o);d&&u&&(d.column===1/0&&u.column===1/0||d.row===1/0&&u.row===1/0)&&(s=d.label+":"+u.label,a={type:"range",id:this.id_counter++,position:d.position,start:d,end:u,label:s})}}a?(c&&t.push(c),t.push(a),this.dependencies.ranges[s]=a,this.full_reference_list.push(a),r+=2):t.push(i)}return t}BinaryToComplex(e){if(e.type==="binary")if((e.operator==="+"||e.operator==="-")&&e.left.type==="literal"&&typeof e.left.value=="number"&&e.right.type==="complex"&&!e.right.composited){let t="";t=this.expression.substring(e.left.position,e.right.position+(e.right.text?.length||0));let r=e.right.imaginary;return e.operator==="-"&&(r=-r),{type:"complex",position:e.left.position,text:t,id:this.id_counter++,imaginary:r,real:e.left.value,composited:!0}}else e.left=this.BinaryToComplex(e.left),e.right=this.BinaryToComplex(e.right);else if(e.type==="unary"&&(e.operator==="-"||e.operator==="+")&&e.operand.type==="complex"&&e.operand.text===this.imaginary_number)return{...e.operand,position:e.position,text:this.expression.substring(e.position,e.operand.position+(e.operand.text||"").length),imaginary:e.operand.imaginary*(e.operator==="-"?-1:1)};return e}ArrangeUnits(e){if(e.length===0)return{type:"missing",id:this.id_counter++};if(e.length===1)return e[0];let t=[];for(let r=0;r<e.length;r++){let i=e[r];if(i.type!=="group-separator"){if(i.type==="operator")if(t.length===0||t[t.length-1].type==="operator")if(So[i.operator]){let n=this.BinaryToComplex(this.ArrangeUnits(e.slice(r+1)));if(!this.valid)return{type:"group",id:this.id_counter++,elements:e,explicit:!1};n.type==="binary"?(n.left={type:"unary",id:this.id_counter++,operator:i.operator,operand:n.left,position:i.position},i=n):i={type:"unary",id:this.id_counter++,operator:i.operator,operand:n,position:i.position},r=e.length}else return this.error=`unexpected character [2]: ${i.operator}`,this.error_position=i.position,this.valid=!1,{type:"group",id:this.id_counter++,elements:e,explicit:!1};else{t.push(i);continue}if(t.length<2){if(t.length===1){let n=t[0].type;if(i.type==="group"&&i.explicit&&(n==="address"||n==="call"||n==="identifier"||n==="implicit-call")){let o=i.elements;o.length===1&&o[0].type==="group"&&!o[0].explicit&&(o=o[0].elements),t[0]={type:"implicit-call",call:t[0],args:o,id:this.id_counter++,position:t[0].position};continue}}t.push(i)}else if(t[t.length-1].type==="operator"){let n=t[t.length-2],o=t[t.length-1],a=o.operator,s={type:"binary",id:this.id_counter++,left:n,operator:a,position:o.position,right:i};n.type==="binary"&&Dr[a]>Dr[n.operator]&&(s.left=n.left,s.operator=n.operator,s.position=n.position,s.right={type:"binary",id:this.id_counter++,left:n.right,right:i,operator:a,position:o.position}),t.splice(-2,2,s)}else t.push(i)}}return t.length>1?{type:"group",id:this.id_counter++,elements:t,explicit:!1}:t[0]}ParseNext(e=!0){this.ConsumeWhiteSpace();let t=this.data[this.index];if(t===Sr)return{type:"literal",id:this.id_counter++,position:this.index,value:this.ConsumeString()};if(t>=Ve&&t<=ot||t===this.decimal_mark_char)return this.ConsumeNumber();if(t===bo)return this.ConsumeArray();if(e&&(t===at||t===Rr)){let r=this.data[this.index+1];if(r>=Ve&&r<=ot||r===this.decimal_mark_char)return this.ConsumeNumber()}else if(t>=Je&&t<=kt||t>=ct&&t<=Rt||t===Tr||t===Mr||t===Ar||t===At||t===lt||t>=Ur&&t<=Vr)return this.ConsumeToken(t);return t}ConsumeArray(){let e={type:"array",id:this.id_counter++,values:[],position:this.index};this.index++;let t=0,r=0;for(;this.index<this.length;){let i=this.ParseNext(),n=this.index;if(typeof i=="number")switch(this.index++,i){case ki:r++,t=0;break;case st:t++;break;case go:return e;default:this.valid&&(this.error="invalid character in array literal",this.error_position=n,this.valid=!1);break}else switch(i.type){case"literal":e.values[t]||(e.values[t]=[]),e.values[t][r]=i.value;break;default:this.valid&&(this.error="invalid value in array literal",this.error_position=n,this.valid=!1);break}}return e}ConsumeOperator(){for(let e of Ao)if(this.expression.substr(this.index,e.length)===e){let t=this.index;return this.index+=e.length,{type:"operator",id:this.id_counter++,operator:e,position:t}}return null}ConsumeArguments(){this.index++;let e=0,t=[];for(;this.index<this.length;){let r=this.ParseGeneric([this.argument_separator_char,Er]);r!==null&&t.push(r);let i=this.data[this.index];if(i===this.argument_separator_char){this.index++,e++;for(let n=t.length;n<e;n++)t.push({type:"missing",id:this.id_counter++})}else if(i===Er)return this.index++,t}return t}ConsumeToken(e){let t=[e],r=this.index,i=e===Ar,n=0,o=!1;for(e===lt&&(n=1,o=!0),++this.index;this.index<this.length;this.index++){let u=this.data[this.index];if(u>=Je&&u<=kt||u>=ct&&u<=Rt||u>=Ur&&u<=Vr||u===Tr||u===At||u===kr||u===yo||i||u>=Ve&&u<=ot||u===lt||n>0&&u===Ai||u===at&&this.flags.r1c1&&n===1||n>0&&u===vo&&this.data[this.index-1]===lt||n===1&&(u===st||u===Ci)||n>1||u===_o&&n===0)t.push(u),u===lt&&(n++,o=!0),u===Ai&&n--,u===Ar&&(i=!1);else break}this.data[this.index]===Mr&&t.push(this.data[this.index++]);let a=t.map(u=>String.fromCharCode(u)).join("");if(i)return this.error="unbalanced single quote",this.error_position=r,this.valid=!1,{type:"identifier",id:this.id_counter++,name:a,position:r};if(n)return this.error="unbalanced square bracket",this.error_position=r,this.valid=!1,{type:"identifier",id:this.id_counter++,name:a,position:r};if(this.ConsumeWhiteSpace(),this.flags.spreadsheet_semantics){let u=this.ConsumeAddress(a,r);if(u)return u}if(this.data[this.index]===Si){let u=this.ConsumeArguments();return{type:"call",id:this.id_counter++,name:a,args:u,position:r,end:this.index}}if(this.flags.spreadsheet_semantics&&o){let u=this.ConsumeStructuredReference(a,r);if(u)return u}let c=a.toLowerCase();if(c==="true"||this.flags.boolean_true&&c===this.flags.boolean_true.toLowerCase())return{type:"literal",id:this.id_counter++,value:!0,position:r};if(c==="false"||this.flags.boolean_false&&c===this.flags.boolean_false.toLowerCase())return{type:"literal",id:this.id_counter++,value:!1,position:r};let d={type:"identifier",id:this.id_counter++,name:a,position:r};return this.full_reference_list.push(d),d}ConsumeStructuredReference(e,t){let r=e.length,i=e,n="",o=0;for(;o<r;o++){if(e[o]==="["){e=e.substring(o);break}n+=e[o]}if(e[0]!=="["||e[e.length-1]!=="]")return;e=e.substring(1,e.length-1);let a=e.split(",").map(u=>u.trim()),s="column",c="";if(a.length>2)return;a.length===2?(/\[#this row\]/i.test(a[0])?s="row":/\[#all\]/i.test(a[0])&&(s="all"),c=a[1]):(c=a[0],c[0]==="@"&&(s="row",c=c.substring(1,c.length))),c[0]==="["&&c[c.length-1]==="]"&&(c=c.substring(1,c.length-1));let d={type:"structured-reference",id:this.id_counter++,label:i,position:t,scope:s,column:c,table:n};return this.full_reference_list.push(d),d}ConsumeAddress(e,t){let r=t,i=e.length,n,o=e.split("!");if(o.length>1&&(n=o.slice(0,o.length-1).join("!"),t+=n.length+1),this.flags.r1c1){let u=o[o.length-1].match(this.r1c1_regex);if(u){let h={type:"address",id:this.id_counter++,label:e,row:0,column:0,position:r,sheet:n,r1c1:!0};return u[1][0]==="["?(h.offset_row=!0,h.row=Number(u[1].substring(1,u[1].length-1))):u[1]?(h.row=Number(u[1])-1,this.flags.r1c1_proper_semantics&&(h.absolute_row=!0)):(h.offset_row=!0,h.row=0),u[2][0]==="["?(h.offset_column=!0,h.column=Number(u[2].substring(1,u[2].length-1))):u[2]?(h.column=Number(u[2])-1,this.flags.r1c1_proper_semantics&&(h.absolute_column=!0)):(h.offset_column=!0,h.column=0),h}}let a=this.ConsumeAddressColumn(t);if(!a)return null;t=a.position;let s=this.ConsumeAddressRow(t);if(!s||(t=s.position,a.column===8508&&s.row===9))return null;let c=n?n+e.substr(n.length,t-r).toUpperCase():e.substr(0,t-r).toUpperCase();n&&n[0]==="'"&&(n=n.substr(1,n.length-2));let d={type:"address",id:this.id_counter++,label:c,row:s.row,column:a.column,absolute_row:s.absolute,absolute_column:a.absolute,position:r,sheet:n,spill:s.spill};return i!==t-r?null:(this.dependencies.addresses[d.label]=d,this.address_refcount[d.label]=(this.address_refcount[d.label]||0)+1,this.full_reference_list.push(d),d)}ConsumeAddressRow(e){let t=this.data[e]===At;t&&e++;let r=e,i=0;for(;;e++){let o=this.data[e];if(o>=Ve&&o<=ot)i*=10,i+=o-Ve;else break}if(r===e||i===0)return!1;let n=!1;return this.data[e]===Mr&&(e++,n=!0),{absolute:t,row:i-1,position:e,spill:n}}ConsumeAddressColumn(e){let t=-1,r=0,i=this.data[e]===At;for(i&&e++;;e++,r++){if(r>=4)return!1;let n=this.data[e];if(n>=Je&&n<=kt)t=26*(1+t)+(n-Je);else if(n>=ct&&n<=Rt)t=26*(1+t)+(n-ct);else break}return t<0?!1:{absolute:i,column:t,position:e}}ConsumeNumber(){let e=this.index,t=0,r=!1,i=!1,n=0,o=0,a=0,s="integer",c=0,d=!1,u=this.index;for(;this.index<this.length;this.index++,c++){let f=this.data[this.index];if(f===this.decimal_mark_char)if(s==="integer")s="fraction";else break;else if(f===po){n/=100,a/=100,this.index++;break}else if(f===Rr||f===at)if(c===0)f===at&&(i=!0);else break;else if(f===wo||f===xo)if(s==="integer"||s==="fraction")s="exponent",this.index<this.length-1&&(this.data[this.index+1]===Rr?this.index++:this.data[this.index+1]===at&&(this.index++,r=!0));else break;else if(f===this.imaginary_char){let m=this.data[this.index+1];if(m>=Je&&m<=kt||m>=ct&&m<=Rt||m>=Ur&&m<=Vr||m===Tr)break;if(s==="integer"||s==="fraction"){this.index++,d=!0;break}}else if(f>=Ve&&f<=ot)switch(s){case"integer":n=n*10+(f-Ve);break;case"fraction":a=a*10+(f-Ve),o++;break;case"exponent":t=t*10+(f-Ve);break}else break}let h=n+a/Math.pow(10,o);return s==="exponent"&&(h=h*Math.pow(10,(r?-1:1)*t)),d?{type:"complex",id:this.id_counter++,position:e,imaginary:i?-h:h,real:0,text:this.expression.substring(u,this.index)||""}:{type:"literal",id:this.id_counter++,position:e,value:i?-h:h,text:this.expression.substring(u,this.index)||""}}ConsumeString(){this.index++;let e=[];for(;this.index<this.length;this.index++){let t=this.data[this.index];if(t===Sr&&(this.index++,this.index>=this.length||this.data[this.index]!==Sr))break;e.push(t)}return e.map(t=>String.fromCharCode(t)).join("")}ConsumeWhiteSpace(){for(;this.index<this.length;){let e=this.data[this.index];if(e===Ci||e===ho||e===fo||e===mo||e===uo)this.index++;else return}}};var Ei=(l,e=",")=>{let t=0,r=[],i="",n=[],o=l.length;if(/[\r\n"]/.test(e))throw new Error("invalid delimiter");for(let a=0;a<o;a++){let s=l[a];if(!(a===0&&s.charCodeAt(0)===65279))if(t===0)switch(s){case e:r.push(i),i="";break;case"\r":break;case`
1
+ /*! TREB v32.9.3. Copyright 2018-2025 trebco, llc. All rights reserved. LGPL: https://treb.app/license */
2
+ var mo=Object.defineProperty;var fo=(l,e)=>{for(var t in e)mo(l,t,{get:e[t],enumerable:!0})};var At=class{get list(){return this.sheets_.slice(0)}get length(){return this.sheets_.length}names=new Map;ids=new Map;sheets_=[];Assign(e){this.sheets_=[...e],this.UpdateIndexes()}Add(e){this.sheets_.push(e),this.UpdateIndexes()}Splice(e,t,...r){this.sheets_.splice(e,t,...r),this.UpdateIndexes()}Find(e){return typeof e=="string"?this.names.get(e.toLocaleUpperCase()):this.ids.get(e)}Name(e){return this.ids.get(e)?.name||void 0}ID(e){return this.names.get(e.toLocaleUpperCase())?.id||void 0}UpdateIndexes(){this.names.clear(),this.ids.clear();for(let e of this.sheets_){let t=e.name.toLocaleUpperCase();this.names.set(t,e),this.ids.set(e.id,e)}}};var Ri={spreadsheet_semantics:!0,dimensioned_quantities:!1,fractions:!0,decimal_mark:".",argument_separator:",",boolean_true:"TRUE",boolean_false:"FALSE"};var Se=/[\s-+=<>!()]/,Vi=/['*\\]/,kr=34,Rr=39,po=160,Ei=32,bo=9,go=10,_o=13,Ve=48,ot=57,Er=46,Tr=43,at=45,Ti=40,Mr=41,st=44,yo=37,Ur=95,kt=36,vo=123,wo=125,lt=91,Mi=93,xo=63,Co=33,Ui=59,Vr=35,So=64,Je=65,ct=97,Ao=69,ko=101,Rt=90,Et=122,Ro=105,Dr=192,zr=382,Lr={"==":6,"!=":6,"<>":6,"=":6,"<":7,">":7,"<=":7,">=":7,"+":9,"-":9,"&":9,"*":10,"/":10,"^":11,":":13},Eo={"@":50,"-":100,"+":100},To=[...Object.keys(Lr),"@"].sort((l,e)=>e.length-l.length),We=class{get argument_separator(){return this.flags.argument_separator}get decimal_mark(){return this.flags.decimal_mark}flags={...Ri};r1c1_regex=/[rR]((?:\[[-+]{0,1}\d+\]|\d*))[cC]((?:\[[-+]{0,1}\d+\]|\d*))$/;argument_separator_char=st;decimal_mark_char=Er;imaginary_char=Ro;imaginary_number="i";id_counter=0;expression="";data=[];index=0;length=0;valid=!0;error_position;error;dependencies={addresses:{},ranges:{}};address_refcount={};full_reference_list=[];parser_state_cache=[];SetLocaleSettings(e,t){if(typeof t>"u"&&(t=e===","?";":","),t===e)throw new Error("invalid locale setting");this.flags.argument_separator=t,this.flags.decimal_mark=e}Save(){this.parser_state_cache.push(JSON.stringify(this.flags))}Restore(){let e=this.parser_state_cache.shift();if(e)try{this.flags=JSON.parse(e)}catch(t){console.error(t)}else console.warn("No parser state to restore")}Walk2(e,t){let r=t(e);if(typeof r=="object")return r;switch(e.type){case"address":case"missing":case"literal":case"complex":case"identifier":case"operator":case"structured-reference":break;case"dimensioned":r&&(e.expression=this.Walk2(e.expression,t),e.unit=this.Walk2(e.unit,t));break;case"range":t(e)&&(e.start=this.Walk2(e.start,t),e.end=this.Walk2(e.end,t));break;case"binary":t(e)&&(e.left=this.Walk2(e.left,t),e.right=this.Walk2(e.right,t));break;case"unary":t(e)&&(e.operand=this.Walk2(e.operand,t));break;case"group":t(e)&&(e.elements=e.elements.map(i=>this.Walk2(i,t)));break;case"implicit-call":t(e)&&(e.call=this.Walk2(e.call,t),e.args=e.args.map(i=>this.Walk2(i,t)));break;case"call":t(e)&&(e.args=e.args.map(i=>this.Walk2(i,t)));break}return e}Walk(e,t){switch(e.type){case"address":case"missing":case"literal":case"complex":case"identifier":case"operator":case"structured-reference":t(e);return;case"dimensioned":t(e)&&(this.Walk(e.expression,t),this.Walk(e.unit,t));return;case"range":t(e)&&(this.Walk(e.start,t),this.Walk(e.end,t));return;case"binary":t(e)&&(this.Walk(e.left,t),this.Walk(e.right,t));return;case"unary":t(e)&&this.Walk(e.operand,t);return;case"group":if(t(e))for(let r of e.elements)this.Walk(r,t);return;case"implicit-call":if(t(e)){this.Walk(e.call,t);for(let r of e.args)this.Walk(r,t)}return;case"call":if(t(e))for(let r of e.args)this.Walk(r,t)}}Transpose(e){let t=e.length,r=[],i=0;for(let n=0;n<t;n++)Array.isArray(e[n])&&(i=Math.max(i,e[n].length));for(let n=0;n<i;n++){r[n]=[];for(let o=0;o<t;o++)r[n][o]=e[o]?e[o][n]:void 0}return r}Render(e,t={}){let r=t.offset||{rows:0,columns:0},i=t.missing??"(missing)",{convert_decimal:n,convert_argument_separator:o,long_structured_references:a,table_name:s}=t,c=this.flags.argument_separator+" ";o===","?c=", ":o===";"&&(c="; ");let d=n===","?",":".",u=this.flags.decimal_mark===","?/,/:/\./,h=this.flags.decimal_mark===","?/,/g:/\./g;switch(e.type){case"address":return t.pass_through_addresses?e.label:t.r1c1?this.R1C1Label(e,t):this.AddressLabel(e,r);case"range":return t.pass_through_addresses?e.label:t.r1c1?this.R1C1Label(e.start,t)+":"+this.R1C1Label(e.end,t):this.AddressLabel(e.start,r)+":"+this.AddressLabel(e.end,r);case"missing":return i;case"array":return"{"+this.Transpose(e.values).map(m=>m.map(f=>typeof f=="string"?'"'+f+'"':f).join(", ")).join("; ")+"}";case"binary":{let m=e.operator===":"?"":" ";return this.Render(e.left,t)+m+e.operator+m+this.Render(e.right,t)}case"unary":return e.operator+this.Render(e.operand,t);case"complex":if(e.text)return n?e.text.replace(h,d):e.text;{let m=Math.abs(e.imaginary).toString();if((n===","||this.flags.decimal_mark===",")&&(m=m.replace(/\./,",")),e.real){let f=e.real.toString();(n===","||this.flags.decimal_mark===",")&&(f=f.replace(/\./,","));let p=Math.abs(e.imaginary);return`${f}${e.imaginary<0?" - ":" + "}${p===1?"":m}i`}else return e.imaginary===-1?"-i":e.imaginary===1?"i":`${e.imaginary<0?"-":""}${m}i`}break;case"literal":if(typeof e.value=="string")return'"'+e.value.replace(/"/g,'""')+'"';if(typeof e.value=="boolean")return e.value?t.boolean_true||this.flags.boolean_true||"true":t.boolean_false||this.flags.boolean_false||"false";if(n&&typeof e.value=="number")if(e.text){let m=e.text;return n===","&&this.flags.decimal_mark==="."&&(m=m.replace(/,/g,"")),m.replace(u,d)}else return e.value.toString().replace(/\./,d);else if(e.text)return e.text;return e.value.toString();case"identifier":return e.name;case"operator":return"["+e.operator+"]";case"group":return e.explicit?"("+e.elements.map(m=>this.Render(m,t)).join(c)+")":e.elements.map(m=>this.Render(m,t)).join(c);case"implicit-call":return this.Render(e.call,t)+"("+e.args.map(m=>this.Render(m,t)).join(c)+")";case"call":return e.name+"("+e.args.map(m=>this.Render(m,t)).join(c)+")";case"dimensioned":return this.Render(e.expression)+" "+this.Render(e.unit);case"structured-reference":{let m=e.column;/[^A-Za-z]/.test(m)&&(m="["+m+"]");let f=e.table;switch(!f&&a&&s&&(f=s),e.scope){case"all":return`${f}[[#all],${m}]`;case"row":return a?`${f}[[#this row],${m}]`:`${f}[@${m}]`;case"column":return`${f}[${m}]`}throw new Error("unhandled scope in structured reference")}}return"??"}Parse(e){switch(e=e.trim(),e[0]==="="&&(e=e.substr(1).trim()),this.expression=e,this.data=[],this.length=e.length,this.index=0,this.valid=!0,this.error_position=void 0,this.error=void 0,this.dependencies.addresses={},this.dependencies.ranges={},this.address_refcount={},this.full_reference_list=[],this.id_counter=0,this.flags.argument_separator){case";":this.argument_separator_char=Ui;break;default:this.argument_separator_char=st;break}switch(this.flags.decimal_mark){case",":this.decimal_mark_char=st;break;default:this.decimal_mark_char=Er;break}for(let i=0;i<this.length;i++)this.data[i]=e.charCodeAt(i);let t=this.ParseGeneric(),r={};for(let i of Object.keys(this.dependencies.addresses))this.address_refcount[i]&&(r[i]=this.dependencies.addresses[i]);return this.dependencies.addresses=r,{expression:t||void 0,valid:this.valid,error:this.error,error_position:this.error_position,dependencies:this.dependencies,separator:this.flags.argument_separator,decimal_mark:this.flags.decimal_mark,full_reference_list:this.full_reference_list.slice(0)}}ColumnLabel(e){if(e===1/0)return"";let t=String.fromCharCode(65+e%26);for(;e>25;)e=Math.floor(e/26)-1,t=String.fromCharCode(65+e%26)+t;return t}R1C1Label(e,t){let r=!!t.r1c1_force_relative,i=t.r1c1_base,n="";e.sheet&&(n=(Se.test(e.sheet)?"'"+e.sheet+"'":e.sheet)+"!");let o="",a="";if(r&&t.r1c1_proper_semantics&&i){if(e.absolute_row)o=(e.row+1).toString();else{let s=e.row-i.row;s&&(o=`[${s}]`)}if(e.absolute_column)a=(e.column+1).toString();else{let s=e.column-i.column;s&&(a=`[${s}]`)}}else if(r&&i){let s=e.row-i.row,c=e.column-i.column;s&&(o=`[${s}]`),c&&(a=`[${c}]`)}else o=e.offset_row?`[${e.row}]`:(e.row+1).toString(),a=e.offset_column?`[${e.column}]`:(e.column+1).toString();return n+=`R${o}C${a}`,n}AddressLabel(e,t){let r=e.column;!e.absolute_column&&e.column!==1/0&&(r+=t.columns);let i=e.row;if(!e.absolute_row&&e.row!==1/0&&(i+=t.rows),i<0||r<0||i===1/0&&r===1/0)return"#REF";let n="";return e.sheet&&(n=(Se.test(e.sheet)?"'"+e.sheet+"'":e.sheet)+"!"),i===1/0?n+(e.absolute_column?"$":"")+this.ColumnLabel(r):r===1/0?n+(e.absolute_row?"$":"")+(i+1):n+(e.absolute_column?"$":"")+this.ColumnLabel(r)+(e.absolute_row?"$":"")+(i+1)+(e.spill?"#":"")}ParseGeneric(e=[0],t=!1){let r=[];for(;this.index<this.length;){let i=this.ParseNext(r.length===0);if(typeof i=="number"){if(e.some(n=>i===n))break;if(i===Ti){this.index++;let n=this.ParseGeneric([Mr],!0);this.index++,r.push({type:"group",id:this.id_counter++,elements:n?[n]:[],explicit:!0})}else{let n=this.ConsumeOperator();n?r.push(n):t&&i===this.argument_separator_char?(r.push({type:"group-separator",position:this.index,id:this.id_counter++}),this.index++):(this.error=`unexpected character [1]: ${String.fromCharCode(i)}, 0x${i.toString(16)}`,this.valid=!1,this.index++)}}else r.push(i)}if(r.length){if(r=this.BinaryToRange2(r),this.flags.fractions){let i=[],n=a=>a.type==="literal"&&typeof a.value=="number"&&a.value%1===0,o=0;for(;o<r.length-3;o++)if(n(r[o])&&n(r[o+1])&&r[o+2].type==="operator"&&r[o+2].operator==="/"&&n(r[o+3])){let a=r[o],s=r[o+1],c=r[o+3],d=(a.value<0?-1:1)*(s.value/c.value);o+=3,i.push({id:r[o].id,type:"literal",text:this.expression.substring(a.position,c.position+1),value:a.value+d,position:a.position})}else i.push(r[o]);for(;o<r.length;o++)i.push(r[o]);r=i}if(r=r.map(i=>i.type==="identifier"&&i.name===this.imaginary_number?{type:"complex",real:0,imaginary:1,position:i.position,text:i.name,id:this.id_counter++}:i),this.flags.dimensioned_quantities){let i=[],n;for(let o=0;o<r.length;o++){let a=r[o];if(!n)n=a;else if(a.type==="identifier"&&(n.type==="literal"||n.type==="group"||n.type==="call")){let s=a;for(;r[o+1]?.type==="identifier";)s.name+=" "+r[++o].name;i.push({type:"dimensioned",expression:n,unit:a,id:this.id_counter++}),n=void 0}else i.push(n),n=a}n&&i.push(n),r=i}}return r.length===0?null:r.length===1?r[0]:this.BinaryToComplex(this.ArrangeUnits(r))}UnitToAddress(e){if(e.type==="literal"){if(typeof e.value=="number"&&e.value>0&&!/\./.test(e.text||""))return{type:"address",position:e.position,label:e.value.toString(),row:e.value-1,id:this.id_counter++,column:1/0}}else{let t,r=e.name,i=r.split("!");if(i.length>1&&(t=i.slice(0,i.length-1).join("!"),r=r.substr(t.length+1),t[0]==="'"))if(t.length>1&&t[t.length-1]==="'")t=t.substr(1,t.length-2);else return;let n=r[0]==="$";r=(n?r.substr(1):r).toUpperCase();let o=Number(r);if(isNaN(o)){if(/[A-Z]{1,3}/.test(r)){let a=-1;for(let s=0;s<r.length;s++){let c=r[s].charCodeAt(0);a=26*(1+a)+(c-Je)}return{type:"address",position:e.position,absolute_column:n,label:e.name,column:a,id:this.id_counter++,row:1/0,sheet:t}}}else if(o>0&&o!==1/0&&!/\./.test(r))return{type:"address",position:e.position,absolute_row:n,label:e.name,row:o-1,id:this.id_counter++,column:1/0,sheet:t}}}BinaryToRange2(e){let t=[];for(let r=0;r<e.length;r++){let i=e[r],n=e[r+1],o=e[r+2],a,s="",c;if(i&&n&&o&&n.type==="operator"&&n.operator===":"){if(i.type==="address"&&o.type==="address"){let d=i.position+i.label.length,u=o.position;a={type:"range",id:this.id_counter++,position:i.position,start:i,end:o,label:i.label+this.expression.substring(d,u)+o.label},s=a.start.label+":"+a.end.label,this.address_refcount[a.start.label]--,this.address_refcount[a.end.label]--;let h=[i.position,o.position];this.full_reference_list=this.full_reference_list.filter(m=>m.position!==h[0]&&m.position!==h[1])}else if((i.type==="literal"||i.type==="identifier")&&(o.type==="literal"||o.type==="identifier")){let d=this.UnitToAddress(i);if(!d&&i.type==="literal"&&typeof i.value=="number"&&i.value<0){let h={...i,text:(i.text||"").replace(/^-/,""),position:i.position+1,value:-i.value};d=this.UnitToAddress(h),d&&(c={type:"operator",operator:"-",position:i.position,id:this.id_counter++})}let u=this.UnitToAddress(o);d&&u&&(d.column===1/0&&u.column===1/0||d.row===1/0&&u.row===1/0)&&(s=d.label+":"+u.label,a={type:"range",id:this.id_counter++,position:d.position,start:d,end:u,label:s})}}a?(c&&t.push(c),t.push(a),this.dependencies.ranges[s]=a,this.full_reference_list.push(a),r+=2):t.push(i)}return t}BinaryToComplex(e){if(e.type==="binary")if((e.operator==="+"||e.operator==="-")&&e.left.type==="literal"&&typeof e.left.value=="number"&&e.right.type==="complex"&&!e.right.composited){let t="";t=this.expression.substring(e.left.position,e.right.position+(e.right.text?.length||0));let r=e.right.imaginary;return e.operator==="-"&&(r=-r),{type:"complex",position:e.left.position,text:t,id:this.id_counter++,imaginary:r,real:e.left.value,composited:!0}}else e.left=this.BinaryToComplex(e.left),e.right=this.BinaryToComplex(e.right);else if(e.type==="unary"&&(e.operator==="-"||e.operator==="+")&&e.operand.type==="complex"&&e.operand.text===this.imaginary_number)return{...e.operand,position:e.position,text:this.expression.substring(e.position,e.operand.position+(e.operand.text||"").length),imaginary:e.operand.imaginary*(e.operator==="-"?-1:1)};return e}ArrangeUnits(e){if(e.length===0)return{type:"missing",id:this.id_counter++};if(e.length===1)return e[0];let t=[];for(let r=0;r<e.length;r++){let i=e[r];if(i.type!=="group-separator"){if(i.type==="operator")if(t.length===0||t[t.length-1].type==="operator")if(Eo[i.operator]){let n=this.BinaryToComplex(this.ArrangeUnits(e.slice(r+1)));if(!this.valid)return{type:"group",id:this.id_counter++,elements:e,explicit:!1};n.type==="binary"?(n.left={type:"unary",id:this.id_counter++,operator:i.operator,operand:n.left,position:i.position},i=n):i={type:"unary",id:this.id_counter++,operator:i.operator,operand:n,position:i.position},r=e.length}else return this.error=`unexpected character [2]: ${i.operator}`,this.error_position=i.position,this.valid=!1,{type:"group",id:this.id_counter++,elements:e,explicit:!1};else{t.push(i);continue}if(t.length<2){if(t.length===1){let n=t[0].type;if(i.type==="group"&&i.explicit&&(n==="address"||n==="call"||n==="identifier"||n==="implicit-call")){let o=i.elements;o.length===1&&o[0].type==="group"&&!o[0].explicit&&(o=o[0].elements),t[0]={type:"implicit-call",call:t[0],args:o,id:this.id_counter++,position:t[0].position};continue}}t.push(i)}else if(t[t.length-1].type==="operator"){let n=t[t.length-2],o=t[t.length-1],a=o.operator,s={type:"binary",id:this.id_counter++,left:n,operator:a,position:o.position,right:i};n.type==="binary"&&Lr[a]>Lr[n.operator]&&(s.left=n.left,s.operator=n.operator,s.position=n.position,s.right={type:"binary",id:this.id_counter++,left:n.right,right:i,operator:a,position:o.position}),t.splice(-2,2,s)}else t.push(i)}}return t.length>1?{type:"group",id:this.id_counter++,elements:t,explicit:!1}:t[0]}ParseNext(e=!0){this.ConsumeWhiteSpace();let t=this.data[this.index];if(t===kr)return{type:"literal",id:this.id_counter++,position:this.index,value:this.ConsumeString()};if(t>=Ve&&t<=ot||t===this.decimal_mark_char)return this.ConsumeNumber();if(t===vo)return this.ConsumeArray();if(e&&(t===at||t===Tr)){let r=this.data[this.index+1];if(r>=Ve&&r<=ot||r===this.decimal_mark_char)return this.ConsumeNumber()}else if(t>=Je&&t<=Rt||t>=ct&&t<=Et||t===Ur||t===Vr||t===Rr||t===kt||t===lt||t>=Dr&&t<=zr)return this.ConsumeToken(t);return t}ConsumeArray(){let e={type:"array",id:this.id_counter++,values:[],position:this.index};this.index++;let t=0,r=0;for(;this.index<this.length;){let i=this.ParseNext(),n=this.index;if(typeof i=="number")switch(this.index++,i){case Ui:r++,t=0;break;case st:t++;break;case wo:return e;default:this.valid&&(this.error="invalid character in array literal",this.error_position=n,this.valid=!1);break}else switch(i.type){case"literal":e.values[t]||(e.values[t]=[]),e.values[t][r]=i.value;break;default:this.valid&&(this.error="invalid value in array literal",this.error_position=n,this.valid=!1);break}}return e}ConsumeOperator(){for(let e of To)if(this.expression.substr(this.index,e.length)===e){let t=this.index;return this.index+=e.length,{type:"operator",id:this.id_counter++,operator:e,position:t}}return null}ConsumeArguments(){this.index++;let e=0,t=[];for(;this.index<this.length;){let r=this.ParseGeneric([this.argument_separator_char,Mr]);r!==null&&t.push(r);let i=this.data[this.index];if(i===this.argument_separator_char){this.index++,e++;for(let n=t.length;n<e;n++)t.push({type:"missing",id:this.id_counter++})}else if(i===Mr)return this.index++,t}return t}ConsumeToken(e){let t=[e],r=this.index,i=e===Rr,n=0,o=!1;for(e===lt&&(n=1,o=!0),++this.index;this.index<this.length;this.index++){let u=this.data[this.index];if(u>=Je&&u<=Rt||u>=ct&&u<=Et||u>=Dr&&u<=zr||u===Ur||u===kt||u===Er||u===Co||i||u>=Ve&&u<=ot||u===lt||n>0&&u===Mi||u===at&&this.flags.r1c1&&n===1||n>0&&u===So&&this.data[this.index-1]===lt||n===1&&(u===st||u===Ei)||n>1||u===xo&&n===0)t.push(u),u===lt&&(n++,o=!0),u===Mi&&n--,u===Rr&&(i=!1);else break}this.data[this.index]===Vr&&t.push(this.data[this.index++]);let a=t.map(u=>String.fromCharCode(u)).join("");if(i)return this.error="unbalanced single quote",this.error_position=r,this.valid=!1,{type:"identifier",id:this.id_counter++,name:a,position:r};if(n)return this.error="unbalanced square bracket",this.error_position=r,this.valid=!1,{type:"identifier",id:this.id_counter++,name:a,position:r};if(this.ConsumeWhiteSpace(),this.flags.spreadsheet_semantics){let u=this.ConsumeAddress(a,r);if(u)return u}if(this.data[this.index]===Ti){let u=this.ConsumeArguments();return{type:"call",id:this.id_counter++,name:a,args:u,position:r,end:this.index}}if(this.flags.spreadsheet_semantics&&o){let u=this.ConsumeStructuredReference(a,r);if(u)return u}let c=a.toLowerCase();if(c==="true"||this.flags.boolean_true&&c===this.flags.boolean_true.toLowerCase())return{type:"literal",id:this.id_counter++,value:!0,position:r};if(c==="false"||this.flags.boolean_false&&c===this.flags.boolean_false.toLowerCase())return{type:"literal",id:this.id_counter++,value:!1,position:r};let d={type:"identifier",id:this.id_counter++,name:a,position:r};return this.full_reference_list.push(d),d}ConsumeStructuredReference(e,t){let r=e.length,i=e,n="",o=0;for(;o<r;o++){if(e[o]==="["){e=e.substring(o);break}n+=e[o]}if(e[0]!=="["||e[e.length-1]!=="]")return;e=e.substring(1,e.length-1);let a=e.split(",").map(u=>u.trim()),s="column",c="";if(a.length>2)return;a.length===2?(/\[#this row\]/i.test(a[0])?s="row":/\[#all\]/i.test(a[0])&&(s="all"),c=a[1]):(c=a[0],c[0]==="@"&&(s="row",c=c.substring(1,c.length))),c[0]==="["&&c[c.length-1]==="]"&&(c=c.substring(1,c.length-1));let d={type:"structured-reference",id:this.id_counter++,label:i,position:t,scope:s,column:c,table:n};return this.full_reference_list.push(d),d}ConsumeAddress(e,t){let r=t,i=e.length,n,o=e.split("!");if(o.length>1&&(n=o.slice(0,o.length-1).join("!"),t+=n.length+1),this.flags.r1c1){let u=o[o.length-1].match(this.r1c1_regex);if(u){let h={type:"address",id:this.id_counter++,label:e,row:0,column:0,position:r,sheet:n,r1c1:!0};return u[1][0]==="["?(h.offset_row=!0,h.row=Number(u[1].substring(1,u[1].length-1))):u[1]?(h.row=Number(u[1])-1,this.flags.r1c1_proper_semantics&&(h.absolute_row=!0)):(h.offset_row=!0,h.row=0),u[2][0]==="["?(h.offset_column=!0,h.column=Number(u[2].substring(1,u[2].length-1))):u[2]?(h.column=Number(u[2])-1,this.flags.r1c1_proper_semantics&&(h.absolute_column=!0)):(h.offset_column=!0,h.column=0),h}}let a=this.ConsumeAddressColumn(t);if(!a)return null;t=a.position;let s=this.ConsumeAddressRow(t);if(!s||(t=s.position,a.column===8508&&s.row===9))return null;let c=n?n+e.substr(n.length,t-r).toUpperCase():e.substr(0,t-r).toUpperCase();n&&n[0]==="'"&&(n=n.substr(1,n.length-2));let d={type:"address",id:this.id_counter++,label:c,row:s.row,column:a.column,absolute_row:s.absolute,absolute_column:a.absolute,position:r,sheet:n,spill:s.spill};return i!==t-r?null:(this.dependencies.addresses[d.label]=d,this.address_refcount[d.label]=(this.address_refcount[d.label]||0)+1,this.full_reference_list.push(d),d)}ConsumeAddressRow(e){let t=this.data[e]===kt;t&&e++;let r=e,i=0;for(;;e++){let o=this.data[e];if(o>=Ve&&o<=ot)i*=10,i+=o-Ve;else break}if(r===e||i===0)return!1;let n=!1;return this.data[e]===Vr&&(e++,n=!0),{absolute:t,row:i-1,position:e,spill:n}}ConsumeAddressColumn(e){let t=-1,r=0,i=this.data[e]===kt;for(i&&e++;;e++,r++){if(r>=4)return!1;let n=this.data[e];if(n>=Je&&n<=Rt)t=26*(1+t)+(n-Je);else if(n>=ct&&n<=Et)t=26*(1+t)+(n-ct);else break}return t<0?!1:{absolute:i,column:t,position:e}}ConsumeNumber(){let e=this.index,t=0,r=!1,i=!1,n=0,o=0,a=0,s="integer",c=0,d=!1,u=this.index;for(;this.index<this.length;this.index++,c++){let m=this.data[this.index];if(m===this.decimal_mark_char)if(s==="integer")s="fraction";else break;else if(m===yo){n/=100,a/=100,this.index++;break}else if(m===Tr||m===at)if(c===0)m===at&&(i=!0);else break;else if(m===Ao||m===ko)if(s==="integer"||s==="fraction")s="exponent",this.index<this.length-1&&(this.data[this.index+1]===Tr?this.index++:this.data[this.index+1]===at&&(this.index++,r=!0));else break;else if(m===this.imaginary_char){let f=this.data[this.index+1];if(f>=Je&&f<=Rt||f>=ct&&f<=Et||f>=Dr&&f<=zr||f===Ur)break;if(s==="integer"||s==="fraction"){this.index++,d=!0;break}}else if(m>=Ve&&m<=ot)switch(s){case"integer":n=n*10+(m-Ve);break;case"fraction":a=a*10+(m-Ve),o++;break;case"exponent":t=t*10+(m-Ve);break}else break}let h=n+a/Math.pow(10,o);return s==="exponent"&&(h=h*Math.pow(10,(r?-1:1)*t)),d?{type:"complex",id:this.id_counter++,position:e,imaginary:i?-h:h,real:0,text:this.expression.substring(u,this.index)||""}:{type:"literal",id:this.id_counter++,position:e,value:i?-h:h,text:this.expression.substring(u,this.index)||""}}ConsumeString(){this.index++;let e=[];for(;this.index<this.length;this.index++){let t=this.data[this.index];if(t===kr&&(this.index++,this.index>=this.length||this.data[this.index]!==kr))break;e.push(t)}return e.map(t=>String.fromCharCode(t)).join("")}ConsumeWhiteSpace(){for(;this.index<this.length;){let e=this.data[this.index];if(e===Ei||e===bo||e===go||e===_o||e===po)this.index++;else return}}};var Di=(l,e=",")=>{let t=0,r=[],i="",n=[],o=l.length;if(/[\r\n"]/.test(e))throw new Error("invalid delimiter");for(let a=0;a<o;a++){let s=l[a];if(!(a===0&&s.charCodeAt(0)===65279))if(t===0)switch(s){case e:r.push(i),i="";break;case"\r":break;case`
3
3
  `:r.push(i),i="",n.push(r),r=[];break;case'"':i.length===0?t=1:i+=s;break;default:i+=s;break}else s==='"'?a+1<o&&l[a+1]==='"'?(i+='"',a++):t=0:i+=s}return(r.length||i.length)&&(r.push(i),n.push(r)),n};var Ie=class l{static _instance=new l;constructor(){}static get instance(){return this._instance}HTML(e,t={}){t={br:!0,...t};let r=[];for(let i of e){let n=[];for(let o of i)o.pre&&n.push("<pre>"),o.emphasis&&n.push("<em>"),o.strong&&n.push("<strong>"),o.strike&&n.push("<strike>"),n.push(o.text),o.strike&&n.push("</strike>"),o.strong&&n.push("</strong>"),o.emphasis&&n.push("</em>"),o.pre&&n.push("</pre>");r.push(n.join(""))}return r.join(t.br?`<br/>
4
4
  `:`
5
5
  `)}Dummy(e=""){return e.split(/\n/).map(t=>[{text:t}])}Parse(e=""){let t=this.Tokenize(e);for(let r=0;r<t.length;r++){let i=t[r];if(i.type==="delimeter"){let n=t[r-1],o=t[r+1],a=!n||n.type==="whitespace"||n.type==="newline",s=n&&n.type==="text"&&/[^\w\d]$/.test(n.text),c=!o||o.type==="whitespace"||o.type==="newline",d=o&&o.type==="text"&&/^[^\w\d]/.test(o.text);i.left_flanking=!c&&(!d||a),i.right_flanking=!a&&(!s||c||d)}}return this.ApplyFormatting(t),this.Consolidate(t)}IsWhitespace(e){return e===" "||e===" "}IsNewline(e){return e==="\r"||e===`
6
- `}IsDelimeter(e){return e==="*"||e==="_"||e==="~"}Consolidate(e){let t=[],r={},i=[],n={type:"text",text:""};for(let o of e)if(o.type==="newline")n.text.length&&i.push(n),n={...r,text:"",type:"text"},t.push(i),i=[];else switch((!!r.strong!=!!o.strong||!!r.emphasis!=!!o.emphasis||!!r.strike!=!!o.strike)&&(r.strong=!!o.strong,r.emphasis=!!o.emphasis,r.strike=!!o.strike,n.text.length&&i.push(n),n={...r,text:"",type:"text"}),o.type){case"text":case"whitespace":n.text+=o.text;break;case"delimeter":for(let a=0;a<o.length;a++)n.text+=o.char;break}return n.text.length&&i.push(n),i.length&&t.push(i),t}ApplyFormatting(e,t){let r=0,i=e.length;for(r=0;r<i;r++){let n=e[r];if(n.type==="delimeter"){if(t&&n.right_flanking&&t.char===n.char&&n.length>0)return{index:r,token:n};if(n.left_flanking){let o=this.ApplyFormatting(e.slice(r+1),n);if(o.token){let a=Math.min(o.token.length,n.length),s=n.char==="~",c=!s&&!!(a%2),d=!s&&a>=2;for(let u=r+1;u<=r+o.index;u++)e[u].strong=!!e[u].strong||d,e[u].emphasis=!!e[u].emphasis||c,e[u].strike=!!e[u].strike||s;o.token.length-=a,n.length-=a,n.length>0?r--:r+=o.index}}}}return{index:r}}Tokenize(e=""){let t=[],r=e.length,i=0,n=!1,o="";for(i=0;i<r;i++){let a=e[i];if(this.IsWhitespace(a)){o&&t.push({type:"text",text:o});let s=a;for(;;){let c=e[i+1];if(this.IsWhitespace(c))s+=c,i++;else break}t.push({type:"whitespace",text:s}),n=!1,o=""}else if(this.IsNewline(a)){o&&t.push({type:"text",text:o}),t.push({type:"newline",text:a});let s="";for(;;){let c=e[i+1];if(this.IsNewline(c))s+=c,i++;else break}s.length&&t.push({type:"newline",text:s}),n=!1,o=""}else if(n)o+=a,n=!1;else if(this.IsDelimeter(a)){o&&t.push({type:"text",text:o});let s=a;for(;;){let c=e[i+1];if(c===a)s+=c,i++;else break}t.push({type:"delimeter",text:s,char:a,length:s.length}),n=!1,o=""}else a==="\\"?n=!0:o+=a}return o&&t.push({type:"text",text:o}),t}};var N=l=>l!==null&&typeof l=="object"&&"row"in l&&"column"in l,ut=l=>l!==null&&typeof l=="object"&&"start"in l&&N(l.start)&&"end"in l&&N(l.end),v=class l{start_;end_;constructor(e,t=e,r=!1){this.end_=this.PatchNull(t),this.start_=this.PatchNull(e),r&&this.Normalize()}static FromColumn(e){return new l({row:1/0,column:e})}static FromRow(e){return new l({row:e,column:1/0})}static ColumnToLabel(e){let t=String.fromCharCode(65+e%26);for(;e>25;)e=Math.floor(e/26)-1,t=String.fromCharCode(65+e%26)+t;return t}static CellAddressToLabel(e,t=!1){if(e.row===1/0&&e.column===1/0)throw new Error("this is going to break something");let r=t?`${e.sheet_id||0}!`:"";return e.row===1/0?r+(e.absolute_column?"$":"")+this.ColumnToLabel(e.column):e.column===1/0?r+(e.absolute_row?"$":"")+(e.row+1):r+(e.absolute_column?"$":"")+this.ColumnToLabel(e.column)+(e.absolute_row?"$":"")+(e.row+1)+(e.spill?"#":"")}static Join(e,...t){let r=new l(e.start,e.end);for(let i of t)i&&(r.ConsumeAddress(i.start),r.ConsumeAddress(i.end));return r}static Bleed(e,t=1){return new l({row:Math.max(0,e.start.row-t),column:Math.max(0,e.start.column-t),sheet_id:e.start.sheet_id},{row:e.end.row+t,column:e.end.column+t})}static PatchArea(e,t){let{before_column:r,column_count:i,before_row:n,row_count:o}=t,a=new l(e.start,e.end),s=e.start.sheet_id;if(i&&r<=a.end.column){if(i>0)r<=a.start.column?a.Shift(0,i):r>a.start.column&&r<=a.end.column?a.ConsumeAddress({row:a.end.row,column:a.end.column+i}):console.warn("AA X case 1",r,i,JSON.stringify(a));else if(i<0)if(r-i<=a.start.column)a.Shift(0,i);else{if(r<=a.start.column&&r-i>a.end.column)return!1;if(r<=a.start.column){let c=r-i-1;a=new l({row:a.start.row,column:c+1+i,sheet_id:s},{row:a.end.row,column:a.end.column+i})}else r<=a.end.column?r-i-1>=a.end.column?a=new l({row:a.start.row,column:a.start.column,sheet_id:s},{row:a.end.row,column:r-1}):a=new l({row:a.start.row,column:a.start.column,sheet_id:s},{row:a.end.row,column:a.start.column+a.columns+i-1}):console.warn("AA X case 2",r,i,JSON.stringify(a))}}if(o&&n<=a.end.row){if(o>0)n<=a.start.row?a.Shift(o,0):n>a.start.row&&n<=a.end.row?a.ConsumeAddress({row:a.end.row+o,column:a.end.column}):console.warn("AA X case 3",n,o,JSON.stringify(a));else if(o<0)if(n-o<=a.start.row)a.Shift(o,0);else{if(n<=a.start.row&&n-o>a.end.row)return!1;if(n<=a.start.row){let c=n-o-1;a=new l({column:a.start.column,row:c+1+o,sheet_id:s},{column:a.end.column,row:a.end.row+o})}else n<=a.end.row?n-o-1>=a.end.row?a=new l({column:a.start.column,row:a.start.row,sheet_id:s},{column:a.end.column,row:n-1}):a=new l({column:a.start.column,row:a.start.row,sheet_id:s},{column:a.end.column,row:a.start.row+a.rows+o-1}):console.warn("AA X case 4",n,o,JSON.stringify(a))}}return a}get start(){return{...this.start_}}set start(e){this.start_=e}get end(){return{...this.end_}}set end(e){this.end_=e}get rows(){return this.start_.row===1/0||this.end_.row===1/0?1/0:this.end_.row-this.start_.row+1}get columns(){return this.start_.column===1/0||this.end_.column===1/0?1/0:this.end_.column-this.start_.column+1}get count(){return this.rows*this.columns}get entire_sheet(){return this.entire_row&&this.entire_column}get entire_column(){return this.start_.row===1/0}get entire_row(){return this.start_.column===1/0}PatchNull(e){let t={...e};return t.row===null&&(t.row=1/0),t.column===null&&(t.column=1/0),t}SetSheetID(e){this.start_.sheet_id=e}Normalize(){let e={...this.start_},t={...this.end_};e.row===1/0||t.row===1/0?e.row=t.row=1/0:e.row>t.row&&(e.row=this.end_.row,e.absolute_row=this.end_.absolute_row,t.row=this.start_.row,t.absolute_row=this.start_.absolute_row),e.column===1/0||t.column===1/0?e.column=t.column=1/0:e.column>t.column&&(e.column=this.end_.column,e.absolute_column=this.end_.absolute_column,t.column=this.start_.column,t.absolute_column=this.start_.absolute_column),this.start_=e,this.end_=t}TopLeft(){let e={row:0,column:0};return this.entire_row||(e.column=this.start.column),this.entire_column||(e.row=this.start.row),e}BottomRight(){let e={row:0,column:0};return this.entire_row||(e.column=this.end.column),this.entire_column||(e.row=this.end.row),e}ContainsRow(e){return this.entire_column||e>=this.start_.row&&e<=this.end_.row}ContainsColumn(e){return this.entire_row||e>=this.start_.column&&e<=this.end_.column}Contains(e){return(this.entire_column||e.row>=this.start_.row&&e.row<=this.end_.row)&&(this.entire_row||e.column>=this.start_.column&&e.column<=this.end_.column)}ContainsArea(e){return this.start.column<=e.start.column&&this.end.column>=e.end.column&&this.start.row<=e.start.row&&this.end.row>=e.end.row}Intersects(e){return!(e.start.column>this.end.column||this.start.column>e.end.column||e.start.row>this.end.row||this.start.row>e.end.row)}Equals(e){return e.start_.row===this.start_.row&&e.start_.column===this.start_.column&&e.end_.row===this.end_.row&&e.end_.column===this.end_.column}Equals2(e){return e.start.row===this.start_.row&&e.start.column===this.start_.column&&e.end.row===this.end_.row&&e.end.column===this.end_.column}Clone(){return new l(this.start,this.end)}get left(){let e=new l(this.start_,this.end_);return e.end_.column=e.start_.column,e}get right(){let e=new l(this.start_,this.end_);return e.start_.column=e.end_.column,e}get top(){let e=new l(this.start_,this.end_);return e.end_.row=e.start_.row,e}get bottom(){let e=new l(this.start_,this.end_);return e.start_.row=e.end_.row,e}Shift(e,t){return this.start_.row+=e,this.start_.column+=t,this.end_.row+=e,this.end_.column+=t,this}ConsumeAddress(e){this.entire_row||(e.column<this.start_.column&&(this.start_.column=e.column),e.column>this.end_.column&&(this.end_.column=e.column)),this.entire_column||(e.row<this.start_.row&&(this.start_.row=e.row),e.row>this.end_.row&&(this.end_.row=e.row))}Reshape(e,t){return this.end_.row=this.start_.row+e-1,this.end_.column=this.start_.column+t-1,this}ConsumeArea(e){this.ConsumeAddress(e.start),this.ConsumeAddress(e.end)}Resize(e,t){return this.end_.row=this.start_.row+e-1,this.end_.column=this.start_.column+t-1,this}[Symbol.iterator](){if(this.entire_row||this.entire_column)throw new Error("don't iterate infinite area");let e=this.start_.row,t=this.start_.column;return{next:()=>{let r={column:t,row:e,sheet_id:this.start_.sheet_id};return t>this.end_.column?{done:!0,value:void 0}:(++e>this.end_.row&&(e=this.start_.row,t++),{value:r})}}}get spreadsheet_label(){let e;return this.entire_sheet?"":this.entire_column?(e=l.ColumnToLabel(this.start_.column),e+=":"+l.ColumnToLabel(this.end_.column),e):this.entire_row?(e=String(this.start_.row+1),e+=":"+(this.end_.row+1),e):(e=l.CellAddressToLabel(this.start_),this.columns>1||this.rows>1?e+":"+l.CellAddressToLabel(this.end_):e)}toJSON(){return{start:{...this.start_},end:{...this.end_}}}};var he=l=>typeof l=="object"&&!!l&&typeof l.real=="number"&&typeof l.imaginary=="number",Xe=l=>l.real?l.imaginary?l.imaginary>0?`${l.real} + ${l.imaginary}i`:`${l.real} - ${Math.abs(l.imaginary)}i`:l.real.toString():l.imaginary?l.imaginary+"i":"0",Lr=l=>typeof l=="object"&&!!l&&typeof l.value=="number"&&typeof l.unit=="string",ko=l=>typeof l=="object"&&l.type==="function",Ir=["undefined","formula","string","number","boolean","object","function","error","complex","array","dimensioned_quantity"];var be=l=>{switch(typeof l){case"undefined":return 0;case"number":return 3;case"boolean":return 4;case"object":return l===null?0:ko(l)?6:he(l)?8:Lr(l)?10:5;case"string":return l[0]==="="?1:2;default:return 7}};var le=class{static StringToColumn(e){let t=0;e=e.toUpperCase();for(let r=0;r<e.length;r++)t*=26,t+=e.charCodeAt(r)-64;return t-1}value;type=0;calculated;calculated_type;formatted;rendered_type;style;area;spill;merge_area;table;renderer_data;render_clean=[];note;hyperlink;editing;render_function;click_function;constructor(e,t){typeof e<"u"&&this.Set(e,t)}ValueIsNumber(){return this.type===3}ValueIsFormula(){return this.type===1}ValueIsBoolean(){return this.type===4}ValueIsComplex(){return this.type===8}FlushStyle(){this.formatted=this.rendered_type=this.style=void 0,this.render_clean=[]}FlushArray(){this.area=void 0}FlushCache(){this.calculated=this.calculated_type=this.formatted=this.rendered_type=this.render_function=this.click_function=void 0,this.render_clean=[]}Reset(){this.type=0,this.value=this.spill=this.note=this.hyperlink=this.formatted=this.rendered_type=this.style=this.calculated=this.calculated_type=this.area=this.renderer_data=this.render_function=this.click_function=void 0,this.render_clean=[]}Set(e,t=be(e)){this.value=e,this.type=t,this.spill=this.formatted=this.rendered_type=this.style=this.calculated=this.calculated_type=this.render_function=this.click_function=this.area=void 0,this.render_clean=[]}SetCalculatedValue(e,t=be(e)){e===void 0&&(e=0,t=3),this.calculated!==e&&(this.calculated=e,this.calculated_type=t,this.formatted=this.rendered_type=void 0,this.render_clean=[])}GetValue(){return this.calculated_type?this.calculated:typeof this.value=="string"&&this.value[0]==="'"?this.value.slice(1):this.value}GetValue4(){return this.calculated_type?{type:this.calculated_type,value:this.calculated}:this.type===1?{type:3,value:0}:{type:this.type,value:typeof this.value=="string"&&this.value[0]==="'"?this.value.slice(1):this.value}}SetNote(e){this.note=e,this.render_clean=[]}SetCalculationError(e="ERR"){this.SetCalculatedValue(e,7)}SetArray(e){this.type=0,this.value=this.formatted=this.rendered_type=this.style=this.hyperlink=this.calculated=this.calculated_type=void 0,this.area=e,this.render_clean=[]}SetArrayHead(e,t){this.type=be(t),this.value=t,this.formatted=this.rendered_type=this.style=this.calculated=this.calculated_type=void 0,this.area=e,this.render_clean=[]}};var Fr=l=>!l.cells,ht=l=>!!l[0]&&Fr(l[0]),Nr=l=>!!l[0]&&l[0].row!==void 0,Ro=Ir.map((l,e)=>({[l]:e})).reduce((l,e)=>({...l,...e}),{}),Et=class{data=[];rows_=0;columns_=0;get rows(){return this.rows_}get columns(){return this.columns_}EnsureRow(e){this.rows_=Math.max(e+1,this.rows_)}EnsureColumn(e){this.columns_=Math.max(e+1,this.columns_)}InsertColumns(e=0,t=1){this.data=this.data.map(r=>{if(r.length>=e){let i=r.slice(0,e),n=e+t,o=r.slice(e);for(let a=0;a<o.length;a++)i[n++]=o[a];return i}return r}),this.columns_+=t}DeleteColumns(e,t=1){this.data.forEach(r=>r.splice(e,t)),this.columns_-=t}DeleteRows(e,t=1){this.data.splice(e,t),this.rows_-=t}InsertRows(e=0,t=1){let r=[e,0,[]];for(let i=1;i<t;i++)r.push([]);Array.prototype.splice.apply(this.data,r),this.rows_+=t}GetCell(e,t){let{row:r,column:i}=e;if(!this.data[r])if(t)this.data[r]=[],this.rows_=Math.max(this.rows_,r+1);else return;return this.data[r][i]||t&&(this.data[r][i]=new le,this.columns_=Math.max(this.columns_,i+1)),this.data[r][i]}EnsureCell(e){let{row:t,column:r}=e,i=this.data[t];i||(this.data[t]=i=[],this.rows_=Math.max(this.rows_,t+1));let n=i[r];return n||(n=i[r]=new le,this.columns_=Math.max(this.columns_,r+1)),n}FromArray(e=[],t=!1){this.data=[];let r=0,i=0;if(t){i=e.length;for(let n=0;n<i;n++){let o=e[n];r=Math.max(r,o.length);for(let a=0;a<o.length;a++)this.data[a]||(this.data[a]=[]),this.data[a][n]=new le(o[a])}}else{r=e.length;for(let n=0;n<r;n++){let o=[],a=e[n];i=Math.max(i,a.length);for(let s=0;s<a.length;s++)o[s]=new le(a[s]);this.data[n]=o}}this.rows_=r,this.columns_=i}SerializedTypeToValueType(e){if(e)return typeof e=="number"?e:Ro[e]||void 0}ValueTypeToSerializedType(e){return e?Ir[e]:void 0}FromJSON(e=[],t){if(this.data=[],!ht(e)){let i=[];if(Nr(e))for(let n of e)for(let o of n.cells)i.push({...o,row:n.row});else for(let n of e)for(let o of n.cells)i.push({...o,column:n.column});e=i}let r=[];for(let i of e){this.data[i.row]||(this.data[i.row]=[]);let n=new le(i.value);if(typeof i.calculated<"u"&&(n.SetCalculatedValue(i.calculated,this.SerializedTypeToValueType(i.calculated_type)),i.spill&&(n.spill=new v(i.spill.start,i.spill.end))),t&&typeof i.style_ref<"u"&&(n.style=t[i.style_ref]),typeof i.note<"u"&&(n.note=i.note),typeof i.hyperlink<"u"&&(n.hyperlink=i.hyperlink),this.data[i.row][i.column]&&this.data[i.row][i.column].area&&(n.area=this.data[i.row][i.column].area),this.data[i.row][i.column]=n,i.area){let o=new v(i.area.start,i.area.end);for(let a=o.start.row;a<=o.end.row;a++)for(let s=o.start.column;s<=o.end.column;s++)this.data[a]||(this.data[a]=[]),this.data[a][s]||(this.data[a][s]=new le),this.data[a][s].area=o}if(i.table&&r.push({...i.table}),i.merge_area){let o=new v(i.merge_area.start,i.merge_area.end);for(let a=o.start.row;a<=o.end.row;a++)for(let s=o.start.column;s<=o.end.column;s++)this.data[a]||(this.data[a]=[]),this.data[a][s]||(this.data[a][s]=new le),this.data[a][s].merge_area=o}}for(let i of r)for(let n=i.area.start.row;n<=i.area.end.row;n++)for(let o=i.area.start.column;o<=i.area.end.column;o++)this.data[n]||(this.data[n]=[]),this.data[n][o]||(this.data[n][o]=new le),this.data[n][o].table=i;this.rows_=this.data.length,this.columns_=this.data.reduce((i,n)=>Math.max(i,n.length),0)}toJSON(e={}){let t=0,r=0,i=this.data.length-1,n;e.subset&&(t=e.subset.start.column,r=e.subset.start.row,i=e.subset.end.row);let o=[],a=-1,s=-1,c={},d={};for(let u=r;u<=i;u++)if(this.data[u]){let h=this.data[u];n=h.length-1,e.subset&&(n=e.subset.end.column);for(let f=t;f<=n;f++){let m=h[f],p=m&&m.merge_area&&m.merge_area.start.row===u&&m.merge_area.start.column===f,b=m&&m.area&&m.area.start.row===u&&m.area.start.column===f,g=m&&m.table&&m.table.area.start.row===u&&m.table.area.start.column===f,x=m?m.type===2&&!m.value:!0;if(m&&(!x||e.preserve_empty_strings)&&(p||m.type||m.calculated_type&&e.expand_arrays||m.calculated_type&&e.calculated_value||m.note||e.decorated_cells&&m.style&&(m.style.fill||m.style.border_bottom||m.style.border_top||m.style.border_left||m.style.border_right))){let y={row:u,column:f,value:m.value};m.note&&(y.note=m.note),m.hyperlink&&(y.hyperlink=m.hyperlink),e.preserve_type&&(y.type=this.ValueTypeToSerializedType(m.type)),e.sheet_id&&(y.sheet_id=e.sheet_id),e.calculated_value&&typeof m.calculated<"u"&&(y.calculated=m.calculated,m.spill&&(y.spill=m.spill.toJSON()),(e.preserve_type||m.calculated_type===7)&&(y.calculated_type=this.ValueTypeToSerializedType(m.calculated_type))),m.table&&g&&e.tables&&(y.table=JSON.parse(JSON.stringify(m.table))),m.area&&b&&(y.area=m.area.toJSON()),m.merge_area&&(y.merge_area=m.merge_area.toJSON()),e.cell_style_refs&&e.cell_style_refs[f]&&e.cell_style_refs[f][u]&&(y.style_ref=e.cell_style_refs[f][u],e.cell_style_refs[f][u]=0),c[u]=u,d[f]=f,a=Math.max(u,a),s=Math.max(f,s),o.push(y)}}}if(e.nested){let u=Object.keys(c),h=Object.keys(d);if(u.length<=h.length&&u.length){let f={},m=[];for(let p of o){let{row:b,...g}=p;f[p.row]||(f[p.row]=[]),f[p.row].push(g)}for(let p of u){let b=Number(p);m.push({row:b,cells:f[b]})}return{data:m,rows:a,columns:s+1}}else if(h.length){let f={},m=[];for(let p of o){let{column:b,...g}=p;f[p.column]||(f[p.column]=[]),f[p.column].push(g)}for(let p of h){let b=Number(p);m.push({column:b,cells:f[b]})}return{data:m,rows:a,columns:s+1}}}return{data:o,rows:a+1,columns:s+1}}GetAll(e=!1){return this.GetRange({row:0,column:0},{row:this.rows_-1,column:this.columns_-1},e)}Normalize(e,t){return e={...e,row:e.row==1/0?0:e.row,column:e.column==1/0?0:e.column},t&&(t={...t,row:t.row==1/0?this.rows_-1:t.row,column:t.column==1/0?this.columns_-1:t.column}),{from:e,to:t}}RawValue(e,t=e){if({from:e,to:t}=this.Normalize(e,t),e.row===t.row&&e.column===t.column)return this.data[e.row]&&this.data[e.row][e.column]?this.data[e.row][e.column].value:void 0;let r=[],i=this.data.slice(e.row,t.row+1),n=e.column,o=t.column+1;for(let a of i){let s=[];for(let c=n,d=0;c<o;c++,d++){let u=a[c];s.push(u?u.value:void 0)}r.push(s)}return r}GetRange(e,t,r=!1){if({from:e,to:t}=this.Normalize(e,t),!t||e===t||e.column===t.column&&e.row===t.row)return this.data[e.row]&&this.data[e.row][e.column]?this.data[e.row][e.column].GetValue():void 0;let i=[];if(r)for(let n=e.column;n<=t.column;n++){let o=[];for(let a=e.row;a<=t.row;a++)this.data[a]&&this.data[a][n]?o.push(this.data[a][n].GetValue()):o.push(void 0);i.push(o)}else for(let n=e.row;n<=t.row;n++){let o=[];for(let a=e.column;a<=t.column;a++)this.data[n]&&this.data[n][a]?o.push(this.data[n][a].GetValue()):o.push(void 0);i.push(o)}return i}GetRange4(e,t=e,r=!1){if({from:e,to:t}=this.Normalize(e,t),e.row===t.row&&e.column===t.column)return this.data[e.row]&&this.data[e.row][e.column]?this.data[e.row][e.column].GetValue4():{value:void 0,type:0};let i=[];if(r)for(let n=e.column;n<=t.column;n++){let o=[];for(let a=e.row;a<=t.row;a++)this.data[a]&&this.data[a][n]?o.push(this.data[a][n].GetValue4()):o.push({type:0});i.push(o)}else for(let n=e.row;n<=t.row;n++){let o=[];for(let a=e.column;a<=t.column;a++)this.data[n]&&this.data[n][a]?o.push(this.data[n][a].GetValue4()):o.push({type:0});i.push(o)}return{type:9,value:i}}SetArea(e,t){if(ArrayBuffer.isView(t))throw new Error("ABIV");if(Array.isArray(t))for(let r=e.start.row,i=0;r<=e.end.row;r++,i++){this.data[r]||(this.data[r]=[]);let n=this.data[r];if(t[i])for(let o=e.start.column,a=0;o<=e.end.column;o++,a++)n[o]||(n[o]=new le),n[o].Set(t[i][a])}else{let r=be(t);for(let i=e.start.row;i<=e.end.row;i++){this.data[i]||(this.data[i]=[]);let n=this.data[i];for(let o=e.start.column;o<=e.end.column;o++)n[o]||(n[o]=new le),n[o].Set(t,r)}}this.rows_=Math.max(this.rows_,e.end.row+1),this.columns_=Math.max(this.columns_,e.end.column+1)}*IterateRC(e,t=!1){if(!e&&t&&(e=new v({row:0,column:0},{row:this.rows_-1,column:this.columns-1})),e)if(t)for(let r=e.start.row;r<=e.end.row;r++){this.data[r]||(this.data[r]=[]);let i=this.data[r];for(let n=e.start.column;n<=e.end.column;n++)i[n]||(i[n]=new le),yield{cell:i[n],row:r,column:n}}else for(let r=e.start.row;r<=e.end.row;r++){let i=this.data[r];if(i)for(let n=e.start.column;n<=e.end.column;n++){let o=i[n];o&&(yield{cell:o,row:r,column:n})}}else for(let[r,i]of this.data.entries())if(i)for(let[n,o]of i.entries())o&&(yield{cell:o,row:r,column:n})}*Iterate(e,t=!1){if(!e&&t&&(e=new v({row:0,column:0},{row:this.rows_-1,column:this.columns-1})),e){N(e)&&(e=new v(e)),(e.entire_column||e.entire_row)&&(e=new v(e.start,e.end),e.start.column===1/0&&(e.start.column=0,e.end.column=this.columns_-1),e.start.row===1/0&&(e.start.row=0,e.end.row=this.rows_-1));let r=e.start,i=e.end;if(t)for(let n=r.row;n<=i.row;n++){this.data[n]||(this.data[n]=[]);let o=this.data[n];for(let a=r.column;a<=i.column;a++)o[a]||(o[a]=new le),yield o[a]}else for(let n=r.row;n<=i.row;n++)if(this.data[n]){let o=this.data[n];for(let a=r.column;a<=i.column;a++)o[a]&&(yield o[a])}}else for(let r of this.data)if(r)for(let i of r)i&&(yield i)}FlushCellStyles(){for(let e of this.data)if(e)for(let t of e)t&&t.FlushStyle()}FlushCachedValues(){for(let e of this.data)if(e)for(let t of e)t&&t.FlushCache()}};var F=class{static locale="en-us";static decimal_separator=".";static argument_separator=",";static grouping_separator=",";static date_components={short_days:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],long_days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],short_months:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],long_months:["January","February","March","April","May","June","July","August","September","October","November","December"]};static UpdateLocale(e){if(e)this.locale=e;else if(typeof self<"u"){let i=self?.document?.location;if(i&&i.search&&/locale=([^?&]+?)(?:\?|$|&)/.test(i.search)){let n=i.search.match(/locale=(.*?)(?:\?|$|&)/);n&&(this.locale=n[1]),console.info("override locale",this.locale)}else typeof navigator<"u"&&(navigator.languages&&navigator.languages[0]?this.locale=navigator.languages[0]:this.locale=navigator.language)}this.locale==="C"&&(console.warn("Locale not set, defaulting to en-us"),this.locale="en-us");let t=new Intl.NumberFormat(this.locale,{minimumFractionDigits:1}).format(3.3).replace(/\d/g,"");this.decimal_separator=t===","?",":".",this.decimal_separator===","?(this.argument_separator=";",this.grouping_separator=" "):(this.argument_separator=",",this.grouping_separator=",");let r=new Date(2e3,0,2,12,0,0,0);this.UpdateDateComponent(0,0,r),r=new Date(2e3,1,7,12,0,0,0),this.UpdateDateComponent(1,1,r),r=new Date(2e3,2,7,12,0,0,0),this.UpdateDateComponent(2,2,r),r=new Date(2e3,3,5,12,0,0,0),this.UpdateDateComponent(3,3,r),r=new Date(2e3,4,4,12,0,0,0),this.UpdateDateComponent(4,4,r),r=new Date(2e3,5,2,12,0,0,0),this.UpdateDateComponent(5,5,r),r=new Date(2e3,6,1,12,0,0,0),this.UpdateDateComponent(6,6,r),r=new Date(2e3,7,1,12,0,0,0),this.UpdateDateComponent(7,-1,r),r=new Date(2e3,8,1,12,0,0,0),this.UpdateDateComponent(8,-1,r),r=new Date(2e3,9,1,12,0,0,0),this.UpdateDateComponent(9,-1,r),r=new Date(2e3,10,1,12,0,0,0),this.UpdateDateComponent(10,-1,r),r=new Date(2e3,11,1,12,0,0,0),this.UpdateDateComponent(11,-1,r)}static UpdateDateComponent(e,t,r){t>=0&&(this.date_components.short_days[t]=r.toLocaleString(this.locale,{weekday:"short"}),this.date_components.long_days[t]=r.toLocaleString(this.locale,{weekday:"long"})),e>=0&&(this.date_components.short_months[e]=r.toLocaleString(this.locale,{month:"short"}),this.date_components.long_months[e]=r.toLocaleString(this.locale,{month:"long"}))}};F.UpdateLocale();var B=class l{constructor(e=0,t=0,r=0,i=0){this.left=e;this.top=t;this.width=r;this.height=i}get right(){return this.left+this.width}get bottom(){return this.top+this.height}static Create(e){return new l(e.left||0,e.top||0,e.width||0,e.height||0)}static IsRectangle(e){return!!e&&typeof e=="object"&&typeof e.left=="number"&&typeof e.top=="number"&&typeof e.width=="number"&&typeof e.height=="number"}Shift(e=0,t=0){return new l(this.left+e,this.top+t,this.width,this.height)}Scale(e=1,t=e){return new l(this.left*e,this.top*t,this.width*e,this.height*t)}Expand(e=0,t=0){return new l(this.left,this.top,this.width+e,this.height+t)}Combine(e){return new l(Math.min(this.left,e.left),Math.min(this.top,e.top),Math.max(this.right,e.right)-Math.min(this.left,e.left),Math.max(this.bottom,e.bottom)-Math.min(this.top,e.top))}Contains(e,t,r=0){return e>=this.left-r&&e<=this.left+this.width+r&&t>=this.top-r&&t<=this.top+this.height+r}ContextFill(e){e.fillRect(this.left,this.top,this.width,this.height)}ContextStroke(e){e.strokeRect(this.left,this.top,this.width,this.height)}Clamp(e,t){return e=Math.min(Math.max(e,this.left),this.right),t=Math.min(Math.max(t,this.top),this.bottom),{x:e,y:t}}ApplyStyle(e){e.style.top=this.top+"px",e.style.left=this.left+"px",e.style.width=this.width+"px",e.style.height=this.height+"px"}toJSON(){return{top:this.top,left:this.left,width:this.width,height:this.height}}};var Eo=JSON.stringify({}),To={Background:0,Text:1,Background2:2,Text2:3,Accent:4,Accent2:5,Accent3:6,Accent4:7,Accent5:8,Accent6:9},Pr=l=>typeof l.theme=="number"?l.theme:To[l.theme]||0,ee=l=>!!l&&typeof l.text=="string",Ke=l=>!!l&&typeof l.theme<"u",Ti=l=>!!l&&(typeof l.text=="string"||typeof l.theme<"u"),I={DefaultProperties:{horizontal_align:"",vertical_align:"",number_format:"General",nan:"NaN",font_size:{unit:"em",value:1},bold:!1,italic:!1,underline:!1,strike:!1,text:{theme:1},border_top:0,border_left:0,border_right:0,border_bottom:0},CompositeBorders:l=>({top:{width:l.border_top||0,color:l.border_top_fill||{}},left:{width:l.border_left||0,color:l.border_left_fill||{}},right:{width:l.border_right||0,color:l.border_right_fill||{}},bottom:{width:l.border_bottom||0,color:l.border_bottom_fill||{}}}),Serialize:l=>{let e=JSON.parse(JSON.stringify(l));return e.border_bottom_fill&&!e.border_bottom&&(e.border_bottom_fill=void 0),e.border_top_fill&&!e.border_top&&(e.border_top_fill=void 0),e.border_left_fill&&!e.border_left&&(e.border_left_fill=void 0),e.border_right_fill&&!e.border_right&&(e.border_right_fill=void 0),JSON.stringify(e)},Merge:(l,e,t=!0)=>{let r=t?{...l,...e}:{...e};return JSON.parse(JSON.stringify(r))},Composite:l=>JSON.parse(JSON.stringify(l.reduce((e,t)=>({...e,...t}),{}))),Empty:l=>JSON.stringify(l)===Eo,ParseFontSize:(l="",e="em")=>{let t=l.match(/(-*[\d.]+)\s*(\S*)/);if(t){let r=Number(t[1]);if(!r||isNaN(r)||r<0)return{};let i=t[2].toLowerCase()||e;if(i==="pt"||i==="em"||i==="%"||i==="px")return{font_size:{unit:i,value:r}}}return{}},RelativeFontSize:(l,e)=>{let t=12,r=12;switch(l.font_size?.unit){case"pt":if(!l.font_size.value)return 1;r=l.font_size.value;break;case"px":if(!l.font_size.value)return 1;r=Math.round(l.font_size.value*300/4)/100;break;case"em":return l.font_size.value||1;case"%":return(l.font_size.value||100)/100;default:return 1}switch(e.font_size?.unit){case"pt":if(!e.font_size.value)return 1;t=e.font_size.value;break;case"px":if(!e.font_size.value)return 1;t=Math.round(e.font_size.value*300/4)/100;break;default:return 1}return r/t},FontSize:(l,e=!0)=>{let t=l.font_size?.value;switch(l.font_size?.unit){case"pt":return(t||12)+"pt";case"px":return e?Math.round((t||16)*300/4)/100+"pt":(t||16)+"px";case"em":return(t||1)+"em";case"%":return(t||100)+"%"}return""},CompositeFontSize:(l,e,t=1,r=!1)=>{let i={...l};return e.unit==="pt"||e.unit==="px"?i={...e}:(i.value=e.value*l.value,e.unit==="%"&&(i.value/=100)),i.unit==="px"&&r&&(i.value=Math.round((i.value||16)*300/4)/100),i.value*=t,i},CompositeFont:(l,e,t,r)=>{let i,n,o,a=[];e.bold&&a.push("bold"),e.italic&&a.push("italic");let s=e.font_face||"stack:default";if(s.startsWith("stack:")){let c=r.font_stacks[s.substring(6)||"default"];c||(c=r.font_stacks.default),c&&(n=e.font_size,o=I.CompositeFontSize(c.size,e.font_size||{unit:"pt",value:10},t),a.push(o.value.toFixed(2)+o.unit),a.push(c.font||""),i=c.variants)}else o=I.CompositeFontSize(l,e.font_size||{unit:"pt",value:10},t),a.push(o.value.toFixed(2)+o.unit),a.push(s||"");return{font:a.join(" "),variants:i,base:l,size:e.font_size,scale:t,stack_size:n,font_size:o}}};var Tt=l=>!!l&&Array.isArray(l)&&Array.isArray(l[0]),Q=(l,e)=>(typeof e>"u"&&(e=be(l)),{value:l,type:e}),ce=l=>l.imaginary?{type:8,value:l}:{type:3,value:l.real};var W={Darken:(l,e,t,r,i=!1)=>{let{h:n,s:o,l:a}=W.RGBToHSL(l,e,t);return i?a-=a*r/100:a-=r/100,a=Math.max(0,Math.min(1,a)),W.HSLToRGB(n,o,a)},Lighten:(l,e,t,r,i=!1)=>{let{h:n,s:o,l:a}=W.RGBToHSL(l,e,t);return i?a+=a*r/100:a+=r/100,a=Math.max(0,Math.min(1,a)),W.HSLToRGB(n,o,a)},RGBToHSL:(l,e,t)=>{l/=255,e/=255,t/=255;let r=Math.max(l,e,t),i=Math.min(l,e,t),n=0,o=0,a=(r+i)/2;if(r===i)n=o=0;else{let s=r-i;switch(o=a>.5?s/(2-r-i):s/(r+i),r){case l:n=(e-t)/s+(e<t?6:0);break;case e:n=(t-l)/s+2;break;case t:n=(l-e)/s+4;break}n/=6}return{h:n*360,s:o,l:a}},HSLToRGB:(l,e,t)=>{let r,i,n;if(e===0)r=i=n=t;else{l=l/360;let o=t<.5?t*(1+e):t+e-t*e,a=2*t-o;r=W.HueToRGB(a,o,l+.3333333333333333),i=W.HueToRGB(a,o,l),n=W.HueToRGB(a,o,l-.3333333333333333)}return{r:Math.round(r*255),g:Math.round(i*255),b:Math.round(n*255)}},HueToRGB:(l,e,t)=>(t<0&&(t+=1),t>1&&(t-=1),t<.16666666666666666?l+(e-l)*6*t:t<.5?e:t<.6666666666666666?l+(e-l)*(.6666666666666666-t)*6:l),GetLuminance:([l,e,t])=>{let r=[l,e,t].map(i=>(i/=255,i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4)));return .2126*r[0]+.7152*r[1]+.0722*r[2]},WeightedLuminance:([l,e,t],r=[1,1,1])=>{let i=[l,e,t].map(n=>(n/=255,n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4)));return .2126*i[0]*r[0]+.7152*i[1]*r[1]+.0722*i[2]*r[2]},GetContrastRatio:l=>(l.sort((e,t)=>t-e),(l[0]+.05)/(l[1]+.05)),GetTextColor:(l,e,t)=>{let r=[.4,.3,.3],i=W.WeightedLuminance(l,r),n=W.WeightedLuminance(e,r),o=W.WeightedLuminance(t,r),a=W.GetContrastRatio([n,i]),s=W.GetContrastRatio([o,i]);return a>s?e:t}};var Mo="http://www.w3.org/2000/svg",O=class l{static instances=[];static GetInstance(e){for(let r of this.instances)if(r.doc===e)return r;let t=new l(e);return this.instances.push(t),t}doc;view;get HTMLElement(){return this.view?.HTMLElement}constructor(e){e&&(this.doc=e,this.view=e?.defaultView)}GetSelection(){return this.view?.getSelection()}Div(e,t,r){return this.Create("div",e,t,r)}ClassNames(e,t){e.classList.add(...(Array.isArray(t)?t:[t]).reduce((r,i)=>[...r,...i.split(/\s+/g)],[]))}SVG(e,t,r){let i=this.doc.createElementNS(Mo,e);return t&&this.ClassNames(i,t),r&&r.appendChild(i),i}Text(e){return this.doc.createTextNode(e)}Fragment(){return this.doc.createDocumentFragment()}Create(e,t,r,i){let n=this.doc.createElement(e);if(t&&this.ClassNames(n,t),i){if(i.attrs)for(let[o,a]of Object.entries(i.attrs))n.setAttribute(o,a);if(i.data)for(let[o,a]of Object.entries(i.data))n.dataset[o]=a;if(i.text&&(n.textContent=i.text),i.html&&(n.innerHTML=i.html),i.events)for(let[o,a]of Object.entries(i.events))n.addEventListener(o,a);if(i.style)for(let[o,a]of Object.entries(i.style))n.style[o]=a}return r&&r.appendChild(n),n}};var Uo=1e3,ge=class{constructor(e=!1,t){this.verbose=e;this.log_id=t}queue=[];dispatched=!1;subscribers=[];Publish(e){this.verbose&&console.info(`es publish (${this.log_id})`,e),Array.isArray(e)?this.queue.push(...e):this.queue.push(e),this.dispatched||(this.dispatched=!0,Promise.resolve().then(()=>{let t=this.queue.slice(0);this.dispatched=!1,this.queue=[];for(let r of t)for(let i of this.subscribers)i.subscriber(r)}))}Subscribe(e){let t=Uo++;return this.subscribers.push({subscriber:e,token:t}),t}Cancel(e){this.subscribers=this.subscribers.filter(t=>t.token!==e)}CancelAll(){this.subscribers=[]}};var ae=class{static color_measurement_canvas;static text_measurement_node;static color_cache={};static MeasureColorARGB(e){let t=this.MeasureColor(e),r="FF";for(let i=0;i<3;i++){let n=t[i].toString(16);n.length===0?r+="00":n.length===1?r+=`0${n}`:r+=n}return r.toUpperCase()}static MeasureColor(e){let t=this.color_cache[e];if(t)return t;this.color_measurement_canvas||(this.color_measurement_canvas=document.createElement("canvas"),this.color_measurement_canvas.width=1,this.color_measurement_canvas.height=1);let r=this.color_measurement_canvas.getContext("2d",{willReadFrequently:!0});return r?(r.fillStyle="#fff",r.fillRect(0,0,1,1),r.fillStyle=e,r.fillRect(0,0,1,1),t=new Uint8ClampedArray(r.getImageData(0,0,1,1).data),this.color_cache[e]=t,t):new Uint8ClampedArray(3)}static EnsureMeasurementNode(){if(!this.text_measurement_node){let e=document.querySelector(".treb-chart-measurement-node");e?this.text_measurement_node=e:(this.text_measurement_node=document.createElement("div"),this.text_measurement_node.classList.add("treb-chart-measurement-node"),this.text_measurement_node.style.margin="0px",this.text_measurement_node.style.padding="0px",this.text_measurement_node.style.height="initial",this.text_measurement_node.style.width="initial",this.text_measurement_node.style.whiteSpace="nowrap",this.text_measurement_node.style.position="fixed",this.text_measurement_node.style.border="0px",this.text_measurement_node.style.border="1px solid red",this.text_measurement_node.style.boxSizing="content-box",this.text_measurement_node.style.top=this.text_measurement_node.style.left="-1000px",document.body.appendChild(this.text_measurement_node))}}static FontLoaded(e,t=!1,r=400){let i=`${t?"italic":""} ${r} 20pt ${e}`,n=this.MeasureText(`${i}, sans-serif`,"check font"),o=this.MeasureText(`${i}, serif`,"check font"),a=this.MeasureText(`${i}, monospace`,"check font");return n.width===o.width&&o.width===a.width}static MeasureText(e,t,r=0){this.EnsureMeasurementNode(),this.text_measurement_node.style.font=e,/\n/.test(t)?(t=t.replace(/\n/g,"<BR/>"),this.text_measurement_node.innerHTML=t):this.text_measurement_node.textContent=t,this.text_measurement_node.style.lineHeight="1em",r?this.text_measurement_node.style.transform=`rotate(${r}deg)`:this.text_measurement_node.style.transform="";let i=this.text_measurement_node.getBoundingClientRect();return{width:i.width,height:i.height}}};var Or,Mi=l=>{let e=new Map;for(let t=0;t<l.length;t++){let r=l[t];e.set(r,l.getPropertyValue(r))}return e},Vo=(l,e,t)=>{let r=new Map,i=Mi(e);for(let[o,a]of i.entries())a!==t.get(o)&&r.set(o,a);return(Array.from(r.entries()).map(([o,a])=>`${o}: ${a}`).join("; ")+"; "+(l.getAttribute("style")||"")).trim().replace(/"/g,"'")},Ui=(l,e)=>{let t=l.cloneNode(!1),r=getComputedStyle(l),i=Vo(l,r,e);t.removeAttribute("class"),t.setAttribute("style",i);let n;return Array.prototype.forEach.call(l.childNodes,o=>{switch(o.nodeType){case Node.ELEMENT_NODE:n||(n=Mi(r)),t.appendChild(Ui(o,n));break;case Node.TEXT_NODE:l.textContent&&t.appendChild(document.createTextNode(l.textContent));break;case Node.COMMENT_NODE:break;default:console.warn("unhandled node type in serialize",o)}}),t},Vi=l=>{if(!Or){let t=new Map,r=document.createElement("iframe");r.style.width="10px",r.style.height="10px",r.style.position="absolute",r.style.left="-100px",document.body.appendChild(r);let i=r.contentDocument;if(i){let n=i.createElement("div");i.body.appendChild(n);let o=getComputedStyle(n);Array.prototype.forEach.call(o,a=>t.set(a,o[a]))}document.body.removeChild(r),Or=t}let e=Ui(l,Or);return e instanceof Element&&e.tagName==="svg"&&(e.hasAttribute("version")||e.setAttribute("version","1.1"),e.hasAttribute("xmlns")||e.setAttribute("xmlns","http://www.w3.org/2000/svg"),e.hasAttribute("xmlns:xlink")||e.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink")),e};var Do={data:!0,same_origin:!0,remote:!1},Mt=(l,e={})=>{let t={...Do,...e};try{let r=new URL(l,document.location.href);return r.protocol==="data:"?t.data?r.href:void 0:r.origin===document.location.origin?t.same_origin?r.href:void 0:t.remote?r.hash:void 0}catch(r){console.error(r)}};var Di=(l,e,t=6.5,r=!1,i=!1)=>{if(e===l)e++,l&&l--;else{let u=Math.round(e*1e5)/1e5;Math.abs(u-e)/(e-l)<1e-5&&(e=u)}let n=e-l,o=Math.log(n)/Math.log(10),a=Math.floor(Math.abs(o))*(o<0?-1:1)-1;i&&(a=Math.max(0,a));let s=i?[1,2,5,10,15,20,25,50,100]:[.1,.25,.5,1,2.5,5,10,25,50,100],c=-1,d=0;for(let u of s){let h=u*Math.pow(10,a),f=Math.floor(l/h)*h,p=(Math.ceil(e/h)*h-f)/h,b=Math.abs(p-t);(c<0||b<d)&&(!r||p<=t)&&(d=b,c=h)}return l=Math.floor(l/c)*c,e=Math.ceil(e/c)*c,t=Math.round((e-l)/c),{scale:a,step:c,count:t,min:l,max:e}};var De=class{date_format=!1;string_format=!1;fraction_format=!1;twelve_hour=!1;fraction_denominator=0;fraction_integer=!0;fraction_align=0;fraction_denominator_digits=0;integer_min_digits=0;decimal_min_digits=0;decimal_max_digits=0;grouping=!1;has_number_format=!1;prefix=[{text:""}];suffix=[{text:""}];scaling=0;percent=!1;exponential=!1;has_asterisk=!1};var zi=42,Li=95,Hr=63,Ut=48,Ii=46,Gr=44,Fi=37,Br=34,ft=35,Ni=59,Vt=92,Pi=64,zo=91,Lo=93,Oi=69,Hi=101,Io=72,Fo=104,No=77,Po=109,Oo=83,Ho=115,Go=68,Bo=100,$o=89,jo=121,qo=65,Jo=97;var Dt=class{static date_pattern=!1;static pattern="";static char_index=0;static characters=[];static sections=[];static current_section=new De;static preserve_formatting_characters=!1;static decimal_mark=Ii;static group_separator=Gr;static Parse(e){if(this.pattern=e,this.characters=e.split("").map(t=>t.charCodeAt(0)),this.char_index=0,this.current_section=new De,this.sections=[this.current_section],this.ParseDatePattern())return this.sections;for(this.char_index=0,this.current_section=new De,this.sections=[this.current_section];this.char_index<this.characters.length;)this.ConsumeChar();return this.sections}static ConsumeString(){let e="";for(this.preserve_formatting_characters&&(e+=this.pattern[this.char_index]),++this.char_index;this.char_index<this.characters.length;this.char_index++)switch(this.characters[this.char_index]){case Vt:this.preserve_formatting_characters&&(e+=this.pattern[this.char_index]),this.char_index+1<this.characters.length&&(e+=this.pattern[++this.char_index]);break;case Br:return this.preserve_formatting_characters&&(e+=this.pattern[this.char_index]),this.char_index++,e;default:e+=this.pattern[this.char_index];break}throw new Error("unterminated string")}static ConsumeFormatting(){let e="";for(++this.char_index;this.char_index<this.characters.length;this.char_index++)switch(this.characters[this.char_index]){case Vt:throw new Error("invalid escape character in formatting block");case Lo:return this.char_index++,e;default:e+=this.pattern[this.char_index];break}throw new Error("unterminated format")}static ScanFractionFormat(){let e=/^([#?]+ +){0,1}([#?]+)\/([#?0-9]+)(?:$|[^#?0-9])/,r=this.pattern.substr(this.char_index).match(e);if(!r)return!1;let i=(r[1]||"").length+r[2].length+r[3].length+1;this.current_section.fraction_format=!0,this.current_section.fraction_integer=!!r[1];let n=Number(r[3]);return isNaN(n)||(this.current_section.fraction_denominator=n),this.current_section.decimal_max_digits=this.current_section.fraction_denominator_digits=r[3].length,this.char_index+=i,this.current_section.has_number_format=!0,!0}static ConsumeNumberFormat(){let e=0;for(this.char_index;this.char_index<this.characters.length;this.char_index++)switch(this.characters[this.char_index]){case this.group_separator:{let r=!1;for(let i=this.char_index+1;!r&&i<this.characters.length;i++){let n=this.characters[i];if(n===this.decimal_mark||n===ft||n===Ut)r=!0;else if(n!==Gr)break}if(r){if(e===1)throw new Error("invalid grouping in decimal part");this.current_section.grouping=!0}else this.current_section.scaling=(this.current_section.scaling||1)*1e3}break;case this.decimal_mark:if(e===1)throw new Error("too many decimal marks");e=1;break;case ft:e===1?this.current_section.decimal_max_digits++:this.current_section.integer_min_digits&&this.current_section.integer_min_digits++;break;case Ut:e===1?(this.current_section.decimal_max_digits++,this.current_section.decimal_min_digits=this.current_section.decimal_max_digits):this.current_section.integer_min_digits++;break;default:return}}static AppendCharAsText(e=!0){this.current_section.has_number_format?this.current_section.suffix[this.current_section.suffix.length-1].text+=this.pattern[this.char_index]:this.current_section.prefix[this.current_section.prefix.length-1].text+=this.pattern[this.char_index],e&&this.char_index++}static AppendString(e){this.current_section.has_number_format?this.current_section.suffix[this.current_section.suffix.length-1].text+=e:this.current_section.prefix[this.current_section.prefix.length-1].text+=e}static AppendTextPart(e){this.current_section.has_number_format?(this.current_section.suffix.push(e),this.current_section.suffix.push({text:""})):(this.current_section.prefix.push(e),this.current_section.prefix.push({text:""}))}static ConsumeChar(){let e=this.characters[this.char_index];if(!((e===Hr||e===ft)&&!this.current_section.has_number_format&&!this.current_section.string_format&&this.ScanFractionFormat()))switch(e){case Ni:this.char_index++,this.current_section=new De,this.sections.length===3&&(this.current_section.string_format=!0),this.sections.push(this.current_section);break;case Pi:this.char_index++,this.AppendTextPart({text:"@",flag:5}),this.current_section.string_format=!0;break;case Ut:case ft:case Ii:case Gr:!this.current_section.has_number_format&&!this.current_section.string_format?(this.ConsumeNumberFormat(),this.current_section.has_number_format=!0):this.AppendCharAsText();break;case zo:this.AppendTextPart({text:this.ConsumeFormatting(),flag:6});break;case Br:this.AppendString(this.ConsumeString());break;case Hr:this.preserve_formatting_characters?this.AppendCharAsText():(this.AppendTextPart({text:"0",flag:1}),this.char_index++);break;case Li:if(this.preserve_formatting_characters)this.AppendCharAsText();else{if(++this.char_index>=this.characters.length)throw new Error("invalid pad character at end");this.AppendTextPart({text:this.pattern[this.char_index++],flag:1})}break;case zi:if(this.current_section.has_asterisk)throw new Error("we don't support multiple asterisks");if(this.preserve_formatting_characters)this.AppendCharAsText();else{if(++this.char_index>=this.characters.length)throw new Error("invalid pad character at end");this.AppendTextPart({text:this.pattern[this.char_index++],flag:2}),this.current_section.has_asterisk=!0}break;case Hi:case Oi:this.current_section.percent||this.current_section.exponential||this.current_section.string_format?this.AppendCharAsText():(this.current_section.exponential=!0,this.char_index++);break;case Fi:!this.current_section.exponential&&!this.current_section.string_format&&(this.current_section.percent=!0),this.AppendCharAsText();break;case Vt:if(this.preserve_formatting_characters&&this.AppendCharAsText(!1),++this.char_index>=this.characters.length)throw new Error("invalid escape character at end");this.AppendCharAsText();break;default:this.AppendCharAsText()}}static ParseDatePattern(){for(this.date_pattern=!0;this.date_pattern&&this.char_index<this.pattern.length;)this.DatePatternConsumeChar();if(this.date_pattern){this.date_pattern=!1;for(let e of this.sections)for(let t of e.prefix)t.flag&&t.flag&7&&(this.date_pattern=!0)}return this.date_pattern&&(this.sections[0].date_format=!0,this.sections[0].prefix.forEach((e,t)=>{if(e.flag===3&&(e.text==="mm"||e.text==="m")){if(t)for(let r=t-1;r;r--){let i=this.sections[0].prefix[r];if(i.flag===3){/h/i.test(i.text)&&(e.flag=4,e.text=e.text.toLowerCase());break}}if(t<this.sections[0].prefix.length-1)for(let r=t+1;r<this.sections[0].prefix.length;r++){let i=this.sections[0].prefix[r];if(i.flag===3){/s/i.test(i.text)&&(e.flag=4,e.text=e.text.toLowerCase());break}}}})),this.date_pattern}static ConsumeDatePart(){let e=this.pattern[this.char_index++],t=e.toLowerCase(),r={text:e,flag:3};for(;this.pattern[this.char_index]&&this.pattern[this.char_index].toLowerCase()===t;)r.text+=this.pattern[this.char_index++];if(t==="s"&&this.pattern[this.char_index]===".")for(r.text+=this.pattern[this.char_index++];this.pattern[this.char_index]==="0";)r.text+=this.pattern[this.char_index++];return r}static ConsumeAMPM(){let e=this.pattern.substr(this.char_index,5);if(e==="am/pm"||e==="AM/PM")return this.char_index+=5,this.sections[0].twelve_hour=!0,{text:e,flag:3};if(e=this.pattern.substr(this.char_index,3),e==="a/p"||e==="A/P")return this.char_index+=3,this.sections[0].twelve_hour=!0,{text:e,flag:3}}static DatePatternConsumeChar(){switch(this.characters[this.char_index]){case Ni:this.char_index=this.characters.length;break;case Ut:case ft:case Hi:case Oi:case Fi:case Pi:this.date_pattern=!1;break;case Io:case Fo:case No:case Po:case Oo:case Ho:case Go:case Bo:case $o:case jo:this.AppendTextPart(this.ConsumeDatePart());break;case qo:case Jo:{let t=this.ConsumeAMPM();t?this.AppendTextPart(t):this.AppendCharAsText()}break;case Br:this.AppendString(this.ConsumeString());break;case Hr:this.preserve_formatting_characters?this.AppendCharAsText():(this.AppendTextPart({text:"0",flag:1}),this.char_index++);break;case Li:if(this.preserve_formatting_characters)this.AppendCharAsText();else{if(++this.char_index>=this.characters.length)throw new Error("invalid pad character at end");this.AppendTextPart({text:this.pattern[this.char_index++],flag:1})}break;case zi:if(this.current_section.has_asterisk)throw new Error("we don't support multiple asterisks");if(this.preserve_formatting_characters)this.AppendCharAsText();else{if(++this.char_index>=this.characters.length)throw new Error("invalid pad character at end");this.AppendTextPart({text:this.pattern[this.char_index++],flag:2}),this.current_section.has_asterisk=!0}break;case Vt:if(this.preserve_formatting_characters&&this.AppendCharAsText(!1),++this.char_index>=this.characters.length)throw new Error("invalid escape character at end");this.AppendCharAsText();break;default:this.AppendCharAsText()}}};var Re=l=>(l>=60&&l--,new Date(-22090752e5+864e5*l)),Se=(l,e=!0)=>{if(e){let t=new Date(l);l=new Date(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()).getTime()}return l=(l+22090752e5)/864e5,l>=60&&l++,l},de=class l{static grouping_regexp=/\d{1,3}(?=(\d{3})+(?!\d))/g;static fraction_limits=[9,99,999,9999];static imaginary_character="\u{1D456}";static minus_character="-";magic_decimal=!1;transform_value;_pattern="";sections;decimal_zero_regexp=[];cloned=[];get pattern(){return this._pattern}get date_format(){return this.sections[0]&&this.sections[0].date_format}constructor(e){if(this._pattern=e,this.sections=Dt.Parse(e),this.sections.length||(this.sections=[]),this.sections[0]||(this.sections[0]=new De),this.sections[1]||(this.sections[1]={...this.sections[0]},this.sections[1].prefix=JSON.parse(JSON.stringify(this.sections[1].prefix)),this.sections[1].suffix=JSON.parse(JSON.stringify(this.sections[1].suffix)),this.sections[1].prefix.push({text:"-"}),this.cloned[1]=!0),this.sections[2]||(this.sections[2]={...this.sections[0]},this.cloned[2]=!0),!this.sections[3]){for(let t of this.sections[0].prefix)if(t.flag===5){this.sections[3]={...this.sections[0]},this.sections[3].string_format=!0,this.cloned[3]=!0;break}}this.decimal_zero_regexp=this.sections.map(t=>{if(t.decimal_max_digits>t.decimal_min_digits)return new RegExp(`0{1,${t.decimal_max_digits-t.decimal_min_digits}}(?:$|e)`)})}static FormatPartsAsText(e,t=0){let r=-1,i=e.map((n,o)=>{switch(n.flag){case 2:return r=o,n.text;case 1:return n.text.replace(/./g," ");case 6:return"";default:return n.text}});if(r>=0&&t){let n=i.reduce((a,s,c)=>c===r?a:a+s.length,0),o="";for(let a=0;a<t-n;a++)o+=i[r];i[r]=o}return i.join("")}SetDecimal(e){for(let t of this.sections)t.fraction_format||(t.decimal_min_digits=e,t.decimal_max_digits=e)}IncreaseDecimal(){this.sections.forEach(e=>{e.fraction_format?e.fraction_denominator||(e.fraction_denominator_digits=Math.min(e.fraction_denominator_digits+1,4)):(e.decimal_min_digits++,e.decimal_max_digits=e.decimal_min_digits)})}DecreaseDecimal(){this.sections.forEach(e=>{e.fraction_format?e.fraction_denominator||(e.fraction_denominator_digits=Math.max(e.fraction_denominator_digits-1,1)):(e.decimal_min_digits=Math.max(0,e.decimal_min_digits-1),e.decimal_max_digits=e.decimal_min_digits)})}AddGrouping(){this.sections.forEach(e=>{e.grouping=!0})}RemoveGrouping(){this.sections.forEach(e=>{e.grouping=!1})}ToggleGrouping(){let e=!this.sections[0].grouping;this.sections.forEach(t=>{t.grouping=e})}toString(){return this.sections[0].date_format?this._pattern:this.sections.filter((e,t)=>!this.cloned[t]).map(e=>{let t="",r=0;if(e.fraction_format){e.fraction_integer&&(t+="? ");let i="";for(let n=0;n<e.fraction_denominator_digits;n++)i+="#";t+=i,t+="/",e.fraction_denominator?t+=e.fraction_denominator:t+=i}else if(e.has_number_format){for(r=0;r<e.integer_min_digits;r++)t+="0";if(e.grouping&&(t.length<4&&(t=("####"+t).slice(-4)),t=t.replace(/[\d#]{1,3}(?=([\d#]{3})+(?![\d#]))/g,"$&,")),e.decimal_max_digits||e.decimal_min_digits){for(t+=".",r=0;r<e.decimal_min_digits;r++)t+="0";for(;r<e.decimal_max_digits;r++)t+="#"}if(e.scaling){let i=Math.log10(e.scaling)/3;for(r=0;r<i;r++)t+=","}e.exponential&&(t+="e")}return e.prefix.map(i=>i.flag===1?i.text==="0"?"?":"_"+i.text:i.flag===2?"*"+i.text:i.flag===6?"["+i.text+"]":i.text).join("")+t+e.suffix.map(i=>i.flag===1?i.text==="0"?"?":"_"+i.text:i.flag===2?"*"+i.text:i.text).join("")}).join(";")}FormatDimensionedQuantity(e){if(this.transform_value){let r=this.transform_value(e);if(Lr(r))e=r;else return typeof r=="string"?r:this.FormatParts(r)}let t=this.FormatParts(e.value||0);return e.unit&&t.push({text:" "},{text:e.unit}),t}FormatComplex(e){if(e.imaginary===1/0||e.imaginary===-1/0||e.real===1/0||e.real===-1/0)return[{text:"Infinity"}];let t=[],r=[],i=!1,n=!!e.imaginary;n&&(t=this.FormatParts(e.imaginary),n=t.some(s=>/[1-9]/.test(s.text)),t.length===1&&this.sections[0].integer_min_digits<=1&&t[0].text==="1"?(t[0].text="",i=!0):t.length===1&&this.sections[1].integer_min_digits<=1&&t[0].text==="-1"&&(t[0].text="-",i=!0));let o=!!e.real;o&&(r=this.FormatParts(e.real),o=r.some(s=>/[1-9]/.test(s.text)));let a=[];if(o||!o&&!n){if(a.push(...r),n){a.push({text:e.imaginary<0?` ${l.minus_character} `:" + "});let s=i?[]:this.FormatParts(Math.abs(e.imaginary));a.push(...s,{text:l.imaginary_character})}}else n&&a.push(...t,{text:l.imaginary_character});return a}FormatParts(e){if(typeof e!="number"&&!this.sections[3])return[{text:(e??"").toString()}];let{parts:t,section:r}=this.BaseFormat(e),i=[];if(r.date_format||r.string_format)for(let n of t)typeof n=="string"?i.push({text:n}):i.push(n);else this.magic_decimal&&t[1]===""&&t.splice(1,1),i=[...r.prefix.map(n=>({...n})),{text:r.has_number_format?t.join(F.decimal_separator):""},...r.suffix.map(n=>({...n}))];for(let n=1;n<i.length;n++)i[n].flag===i[n-1].flag&&(i[n].text=i[n-1].text+i[n].text,i[n-1].text="");return i.filter(n=>n.text)}Format(e,t=0){return l.FormatPartsAsText(this.FormatParts(e),t)}ZeroPad(e,t){for(;e.length<t;)e="0"+e;return e}DateFormat(e){let t=Re(e),r=this.sections[0],i=t.getUTCHours();return r.twelve_hour&&(i>12&&(i-=12),i===0&&(i=12)),{parts:r.prefix.map(o=>{if(o.flag===4)return o.text==="mm"?{text:this.ZeroPad(t.getUTCMinutes().toString(),2)}:{text:this.ZeroPad(t.getUTCMinutes().toString(),1)};if(o.flag===3){switch(o.text.toLowerCase()){case"am/pm":case"a/p":{let s=o.text.split("/");return{text:t.getUTCHours()>12?s[1]:s[0]}}case"mmmmm":return{text:F.date_components.long_months[t.getUTCMonth()][0]};case"mmmm":return o.text==="MMMM"?{text:F.date_components.long_months[t.getUTCMonth()].toUpperCase()}:{text:F.date_components.long_months[t.getUTCMonth()]};case"mmm":return o.text==="MMM"?{text:F.date_components.short_months[t.getUTCMonth()].toUpperCase()}:{text:F.date_components.short_months[t.getUTCMonth()]};case"mm":return{text:this.ZeroPad((t.getUTCMonth()+1).toString(),2)};case"m":return{text:this.ZeroPad((t.getUTCMonth()+1).toString(),1)};case"ddddd":case"dddd":return o.text==="DDDDD"||o.text==="DDDD"?{text:F.date_components.long_days[t.getUTCDay()].toUpperCase()}:{text:F.date_components.long_days[t.getUTCDay()]};case"ddd":return o.text==="DDD"?{text:F.date_components.short_days[t.getUTCDay()].toUpperCase()}:{text:F.date_components.short_days[t.getUTCDay()]};case"dd":return{text:this.ZeroPad(t.getUTCDate().toString(),2)};case"d":return{text:this.ZeroPad(t.getUTCDate().toString(),1)};case"yyyy":case"yyy":return{text:t.getUTCFullYear().toString()};case"yy":case"y":return{text:this.ZeroPad((t.getUTCFullYear()%100).toString(),2)};case"hh":return{text:this.ZeroPad(i.toString(),2)};case"h":return{text:this.ZeroPad(i.toString(),1)};case"ss":return{text:this.ZeroPad(t.getUTCSeconds().toString(),2)};case"s":return{text:this.ZeroPad(t.getUTCSeconds().toString(),1)}}let a=o.text.match(/^(s+)\.(0+)$/);if(a)return{text:this.ZeroPad(t.getUTCSeconds().toString(),a[1].length)+F.decimal_separator+(t.getUTCMilliseconds()/1e3).toFixed(a[2].length).substr(2)}}return{...o}}),section:r}}StringFormat(e,t){let r=[];for(let i of t.prefix)i.flag===5?r.push({text:e}):r.push({...i});return{parts:r,section:t}}Round2(e,t){let r=Math.pow(10,t);return Math.round(r*e)/r}FormatFraction(e,t){t.percent&&(e*=100);let r={denominator:1,numerator:Math.round(e),error:Math.abs(Math.round(e)-e)};if(t.fraction_denominator)r.denominator=t.fraction_denominator,r.numerator=Math.round(e*r.denominator);else if(r.error){let n=l.fraction_limits[t.fraction_denominator_digits-1]||l.fraction_limits[0];for(let o=2;o<=n;o++){let a=Math.round(e*o),s=Math.abs(a/o-e);if(s<r.error&&(r={numerator:a,denominator:o,error:s},!s))break}}let i=[];if(t.fraction_integer){let n=Math.floor(r.numerator/r.denominator);r.numerator%=r.denominator,(n||!r.numerator)&&(i.push(n.toString()),r.numerator&&i.push(" "))}else r.numerator||i.push("0");return r.numerator&&(i.push(r.numerator.toString()),i.push("/"),i.push(r.denominator.toString())),i.join("")}BaseFormat(e){if(this.sections[0].date_format)return this.DateFormat(Number(e));if(typeof e!="number")return this.StringFormat((e??"").toString(),this.sections[3]);let t=this.sections[0],r=this.decimal_zero_regexp[0];e<0&&(t=this.sections[1]);let i=t.percent?t.decimal_max_digits+2:t.decimal_max_digits,n=Math.pow(10,-i)/2,o=Math.abs(e);if(o<n&&(t=this.sections[2],r=this.decimal_zero_regexp[2]),t.scaling&&(o/=t.scaling,o<n&&(t=this.sections[2],r=this.decimal_zero_regexp[2])),t.string_format)return this.StringFormat(e.toString(),t);let a="";if(t.fraction_format)return{parts:[this.FormatFraction(o,t)],section:t};t.exponential?a=o.toExponential(t.decimal_max_digits):(t.percent&&(o*=100),a=this.Round2(o,t.decimal_max_digits).toFixed(t.decimal_max_digits)),r&&(a=a.replace(r,""));let s=a.split(".");for(;s[0].length<t.integer_min_digits;)s[0]=("0000000000000000"+s[0]).slice(-t.integer_min_digits);return t.integer_min_digits===0&&s[0]==="0"&&(s[0]=""),t.grouping&&(s[0]=s[0].replace(l.grouping_regexp,"$&"+F.grouping_separator)),{parts:s,section:t}}};var L=class{static cache={};static complex_general;static symbolc_name_map={};static base_formats={Accounting:"_(#,##0.00_);(#,##0.00);-???",Number:"0.00",Integer:"0",Percent:"0.00%",General:"0.######",Fraction:"# ?/?",Dollar:"$* _(#,##0.00_);$* (#,##0.00);$* -???",Exponential:"0.000e","Short Date":"mm/dd/yy","Long Date":"dddd, mmm d yyyy",Timestamp:"mm-dd-yy hh:mm:ss"};static aliases={Scientific:"Exponential",Percentage:"Percent",Currency:"Dollar"};static Get(e,t=!1){if(t&&e==="General")return this.complex_general;let r=this.symbolc_name_map[e.toLowerCase()],i=this.cache[r||e];return i||(i=new de(e),this.cache[e]=i),i}static Equals(e,t){if(e===t)return!0;let r=this.Get(e),i=this.Get(t);return r.pattern===i.pattern}static Translate(e){let t=this.symbolc_name_map[e.toLowerCase()];return t?this.cache[t].toString():e}static SymbolicName(e){for(let t of Object.keys(this.base_formats))if(e===this.base_formats[t])return t;return null}static InitCache(){for(let e of Object.keys(this.base_formats))this.cache[e]=new de(this.base_formats[e]),this.symbolc_name_map[e.toLowerCase()]=e;this.cache.General.magic_decimal=!0,this.complex_general=new de("0.###"),this.complex_general.magic_decimal=!0;for(let e of Object.keys(this.aliases))this.cache[e]=this.cache[this.aliases[e]],this.symbolc_name_map[e.toLowerCase()]=e}};L.InitCache();var Gi=new Date().getUTCFullYear(),jr=class{compare_day;compare_month;TestDate(e){let t=Date.parse(e);if(isNaN(t))return!1;let r=new Date(t),n=e.replace(/[\d\-\\/,.\s]+/g," ").toLocaleLowerCase().split(/\s+/).map(s=>s.trim()).filter(s=>!!s);if(!n.length)return t;if(!this.compare_month){this.compare_month={};for(let s=0;s<12;s++)this.compare_month[F.date_components.long_months[s].toLocaleLowerCase().replace(/\./,"")]=s,this.compare_month[F.date_components.short_months[s].toLocaleLowerCase().replace(/\./,"")]=s}if(!this.compare_day){this.compare_day={};for(let s=0;s<7;s++)this.compare_day[F.date_components.long_days[s].toLocaleLowerCase().replace(/\./,"")]=s,this.compare_day[F.date_components.short_days[s].toLocaleLowerCase().replace(/\./,"")]=s}let o=!1,a=!1;for(let s of n){let c=!1;for(let[d,u]of Object.entries(this.compare_month))if(s===d){if(o||r.getUTCMonth()!==u)return!1;c=!0,o=!0}if(!c){for(let[d,u]of Object.entries(this.compare_day))if(s===d){if(a||r.getUTCDay()!==u)return!1;c=!0,a=!0}}if(!c)return!1}return a&&!o?!1:t}TryParse(e=""){let t={};if(e[0]==="'")return{value:e,type:2};if(e==="")return{value:e,type:2};if(e==="NaN")return{value:NaN,type:3,hints:{Nan:!0}};let r=e.trim(),i=r.match(/^[$](.*?)$/);i&&(r=i[1],t.Currency=!0);let n=r.match(/^\((.*?)\)$/);n&&(r=n[1],t.Parens=!0);let o=r.match(/^(.*?)%\s*$/);o&&(r=o[1],t.Percent=!0),F.decimal_separator==="."?/,/.test(r)&&(r=r.replace(/,/g,""),t.Grouping=!0):(r=r.replace(/(\d)\s+/g,"$1"),r=r.replace(/\./g,""),r=r.replace(/,/,"."));let a=Number(r);if(a===null||isNaN(a)){let s=e.toLowerCase();if(s==="false")return{value:!1,type:4};if(s==="true")return{value:!0,type:4};let c=this.TestDate(e);if(c!==!1&&!isNaN(c)){let d=new Date(c),u=d.getUTCFullYear();if(u>=Gi-200&&u<=Gi+200)return t={Date:!0},(d.getHours()||d.getMinutes()||d.getSeconds())&&(t.Time=!0),{value:Se(c,!0),type:3,hints:t}}return{value:e,type:2}}if(n&&(a=-a),o){let s=a<0?-1:1,c=(s*a).toString().split(".");c[0]=("00"+c[0]).replace(/(\d\d)$/,".$1"),a=Number(c.join(""))*s}return/e/.test(e)&&(t.Exponential=!0),{value:a,type:3,hints:t}}},_e=new jr;var zt=class{constructor(e,t,r={x:0,y:0},i){this.theme=t;this.offset=r;let n=O.GetInstance(i.ownerDocument);this.g=n.SVG("g"),this.g.setAttribute("transform",`translate(${r.x}, ${r.y})`),this.outline=n.SVG("rect","treb-selection-outline"),e?(this.g.setAttribute("class","selection primary-selection"),this.fill=n.SVG("path","treb-selection-fill"),this.nub=n.SVG("rect","treb-selection-nub"),this.g.appendChild(this.fill),this.g.appendChild(this.outline),this.g.appendChild(this.nub)):(this.g.setAttribute("class","selection alternate-selection"),this.fill=n.SVG("rect","treb-selection-fill"),this.g.appendChild(this.fill),this.g.appendChild(this.outline))}g;outline;fill;nub;Offset(e){this.g.setAttribute("transform",`translate(${e.x}, ${e.y})`)}Show(e=!0){this.g.style.display=e?"block":"none"}SetOutline(e,t=!1){this.outline.setAttribute("x",(e.left-1).toString()),this.outline.setAttribute("y",(e.top-1).toString()),this.outline.setAttribute("width",(e.width+1).toString()),this.outline.setAttribute("height",(e.height+1).toString()),t&&this.fill&&(this.fill.setAttribute("x",e.left.toString()),this.fill.setAttribute("y",e.top.toString()),this.fill.setAttribute("width",e.width.toString()),this.fill.setAttribute("height",e.height.toString()))}SetFill(e,t){if(!this.fill)return;let r=[];r.push("M"+e.left+" "+e.top),r.push("L"+e.left+" "+e.bottom),r.push("L"+e.right+" "+e.bottom),r.push("L"+e.right+" "+e.top),r.push("Z"),r.push("M"+t.left+" "+t.top),r.push("L"+t.right+" "+t.top),r.push("L"+t.right+" "+t.bottom),r.push("L"+t.left+" "+t.bottom),r.push("Z"),this.fill.setAttribute("d",r.join(" "))}SetNub(e){this.nub&&(this.nub.setAttribute("x",(e.left+e.width-4).toString()),this.nub.setAttribute("y",(e.top+e.height-4).toString()),this.nub.setAttribute("width","7"),this.nub.setAttribute("height","7"))}};var He=class{constructor(e,t,r){this.theme=e;this.container=t;this.orientation=r;let i=O.GetInstance(t.ownerDocument);this.g=i.SVG("g","treb-header-overlay"),this.overlay=i.SVG("rect","treb-overlay"),this.highlight=i.SVG("rect","treb-highlight"),this.g.style.display="none",this.g.appendChild(this.highlight),this.g.appendChild(this.overlay),t.appendChild(this.g)}g;overlay;highlight;Remove(){this.container.removeChild(this.g)}Hide(){this.g.style.display="none"}Show(e,t,r,i){this.overlay.setAttribute("x",e.toString()),this.overlay.setAttribute("y",t.toString()),this.overlay.setAttribute("width",r.toString()),this.overlay.setAttribute("height",i.toString()),this.orientation===0?(this.highlight.setAttribute("x",e.toString()),this.highlight.setAttribute("y",(t+i-2).toString()),this.highlight.setAttribute("width",r.toString()),this.highlight.setAttribute("height","2")):(this.highlight.setAttribute("x",(e+r-2).toString()),this.highlight.setAttribute("y",t.toString()),this.highlight.setAttribute("width","2"),this.highlight.setAttribute("height",i.toString())),this.g.style.display="block"}};var Lt=class{constructor(e,t,r,i,n,o){this.theme=e;this.layout=t;this.model=r;this.view=i;this.primary_selection=n;this.additional_selections=o}nub_rectangle=new B(-1,-1,0,0);cached_additional_selections="";grid_selections=[];row_header_selections=[];column_header_selections=[];corner_selections=[];row_overlay;column_overlay;corner_row_overlay;corner_column_overlay;Initialize(){this.row_overlay=new He(this.theme,this.layout.row_header_selection,0),this.column_overlay=new He(this.theme,this.layout.column_header_selection,1),this.corner_row_overlay=new He(this.theme,this.layout.corner_selection,0),this.corner_column_overlay=new He(this.theme,this.layout.corner_selection,1)}RenderSelections(e=!0,t=!0){let r=this.primary_selection.empty;e||(this.primary_selection.empty=!0);let i=[this.primary_selection].concat(this.additional_selections);this.RenderSelectionGroup(i,this.layout.grid_selection,void 0,void 0,this.grid_selections,void 0,t);let n=new B(-1,-1,0,0);if(!this.primary_selection.empty){let s=this.view.active_sheet.RealArea(this.primary_selection.area);n=this.layout.CellAddressToRectangle(s.start).Combine(this.layout.CellAddressToRectangle(s.end))}if(!this.primary_selection.empty&&this.layout.header_offset.y>2?(this.row_overlay.Show(n.left,0,n.width,this.layout.header_offset.y),this.corner_row_overlay.Show(n.left+this.layout.header_offset.x,0,n.width,this.layout.header_offset.y)):(this.row_overlay.Hide(),this.corner_row_overlay.Hide()),!this.primary_selection.empty&&this.layout.header_offset.x>2?(this.column_overlay.Show(0,n.top,this.layout.header_offset.x,n.height),this.corner_column_overlay.Show(0,n.top+this.layout.header_offset.y,this.layout.header_offset.x,n.height)):(this.column_overlay.Hide(),this.corner_column_overlay.Hide()),!this.view.active_sheet.freeze.columns&&!this.view.active_sheet.freeze.rows){this.primary_selection.empty=r;return}let o=[],a=[];if(this.primary_selection.empty)o.push(!1),a.push(!1);else{let s=this.primary_selection.area.start;o.push(s.row<=this.view.active_sheet.freeze.rows||s.row===1/0),a.push(s.column<=this.view.active_sheet.freeze.columns||s.column===1/0)}for(let{area:s}of this.additional_selections)o.push(s.start.row<=this.view.active_sheet.freeze.rows||s.start.row===1/0),a.push(s.start.column<=this.view.active_sheet.freeze.columns||s.start.column===1/0);this.view.active_sheet.freeze.rows&&this.RenderSelectionGroup(i,this.layout.row_header_selection,o,void 0,this.row_header_selections,{x:0,y:this.layout.header_offset.y}),this.view.active_sheet.freeze.columns&&this.RenderSelectionGroup(i,this.layout.column_header_selection,a,void 0,this.column_header_selections,{x:this.layout.header_offset.x,y:0}),this.view.active_sheet.freeze.rows&&this.view.active_sheet.freeze.columns&&this.RenderSelectionGroup(i,this.layout.corner_selection,a,o,this.corner_selections,{...this.layout.header_offset}),this.primary_selection.empty=r}RenderSelectionGroup(e,t,r,i,n,o,a=!0){for(let s=0;s<e.length;s++)if((!e[s].area.start.sheet_id||e[s].area.start.sheet_id===this.view.active_sheet.id)&&!e[s].empty&&(!r||r[s])&&(!i||i[s])){if(a||!e[s].rendered){let d=this.EnsureGridSelectionBlock(t,n,s,o);this.RenderSVGSelection(e[s],d,s)}}else n[s]&&n[s].Show(!1);for(let s=e.length;s<n.length;s++)n[s]&&n[s].Show(!1)}EnsureGridSelectionBlock(e,t,r,i){let n=t[r];if(!n)if(n=new zt(!r,this.theme,void 0,e),t[r]=n,r){let o=e.querySelector(".alternate-selections");o||(o=this.layout.DOM.SVG("g","alternate-selections"),e.appendChild(o)),o?.appendChild(n.g)}else e.appendChild(n.g);return i&&n.Offset(i),n}ClampEnd(e){return{row:Math.min(e.row,this.view.active_sheet.rows-1),column:Math.min(e.column,this.view.active_sheet.columns-1)}}RenderSVGSelection(e,t,r=0){let i=this.view.active_sheet.RealArea(e.area,!0),n=this.layout.CellAddressToRectangle(i.start);if(i.count>1)n=n.Combine(this.layout.CellAddressToRectangle(i.end));else if(r){let o=this.view.active_sheet.CellData(e.target);o.merge_area&&(n=this.layout.CellAddressToRectangle(o.merge_area.start),n=n.Combine(this.layout.CellAddressToRectangle(o.merge_area.end)))}if(r||(this.nub_rectangle=new B(n.left+n.width-6,n.top+n.height-6,11,11)),n.top===0&&this.layout.header_offset.y<=1&&(n.top=1,n.height-=1),n.left===0&&this.layout.header_offset.x<=1&&(n.left=1,n.width-=1),n.height<=0||n.height<=0){t.Show(!1);return}if(t.SetOutline(n,!!r),r)e.rendered=!0;else{let o=this.layout.CellAddressToRectangle(e.target),a=this.view.active_sheet.CellData(e.target);a.merge_area&&(o=this.layout.CellAddressToRectangle(a.merge_area.start),o=o.Combine(this.layout.CellAddressToRectangle(a.merge_area.end))),t.SetFill(o,n),t.SetNub(n)}t.Show()}};function Ae(l,e=[],t,r){typeof e=="string"&&(e=[e]);let i,n=a=>{a.stopPropagation(),a.preventDefault(),i(),r&&r(a)},o=a=>{if(a.stopPropagation(),a.preventDefault(),!a.buttons){i(),r&&r(a);return}t&&t(a)};i=()=>{l.style.display="none",l.removeEventListener("mousemove",o),l.removeEventListener("mouseup",n);for(let a of e)l.classList.remove(a)};for(let a of e)l.classList.add(a);l.style.display="block",t&&l.addEventListener("mousemove",o),r&&l.addEventListener("mouseup",n)}var It=class extends ge{constructor(t){super();this.container=t;this.format=L.Get("0.0");let r=O.GetInstance(t.ownerDocument);this.input=r.Create("input","treb-scale-input",t,{events:{keypress:n=>{switch(n.key){case"ArrowUp":case"ArrowDown":n.stopPropagation(),n.preventDefault(),console.info("mark?");break}},keydown:n=>{switch(n.key){case"Enter":this.input.blur();break;case"ArrowUp":this.Tick(-1);break;case"ArrowDown":this.Tick(1);break;case"Escape":this.input.value=this.format.Format(this.scale)+"%",this.input.blur();break;default:return}n.stopPropagation(),n.preventDefault()},focusin:()=>this.input.select(),change:()=>{let n=this.input.value;n=n.replace(/%/g,"");let o=_e.TryParse(n);o.type===3?this.UpdateScale(Number(o.value),!0):this.input.value=this.format.Format(this.scale)+"%"}}});let i=r.Div("treb-slider-container",t);this.slider=r.Create("input",void 0,i,{attrs:{type:"range",min:"50",max:"200",value:"100",step:"2.5"},events:{input:()=>this.UpdateScale(Number(this.slider.value),!0)}}),t.addEventListener("wheel",n=>{n.stopPropagation(),n.preventDefault(),this.Tick(n.deltaY)})}input;slider;scale=0;format;timeout=0;Tick(t){let r=Math.round(this.scale/2.5)*2.5;t>0?this.UpdateScale(r-2.5,!0,!0):t<0&&this.UpdateScale(r+2.5,!0,!0)}UpdateScale(t,r=!1,i=!1){t=Math.max(50,Math.min(200,t)),t!==this.scale&&(this.scale=t,this.input.value=this.format.Format(t)+"%",this.slider.value=t.toFixed(1),r&&(this.timeout||(this.timeout=requestAnimationFrame(()=>{this.timeout=0,this.Publish({type:"scale",value:this.scale/100,keep_focus:i})}))))}};var Ft=class extends ge{constructor(t,r,i,n,o,a){super();this.layout=t;this.model=r;this.view=i;this.options=n;this.theme=o;if(this.DOM=O.GetInstance(a.ownerDocument),this.container=a.querySelector(".treb-spreadsheet-footer"),!this.container)throw new Error("missing container for tab bar");if(n.tab_bar!=="auto"&&this.container.removeAttribute("hidden"),this.tab_container=this.container.querySelector(".treb-spreadsheet-tabs"),this.container.addEventListener("click",s=>{let c=s.target?.dataset.command;if(c)switch(s.stopPropagation(),s.preventDefault(),c){case"add-tab":this.Publish({type:"add-sheet"});break;case"delete-tab":this.Publish({type:"delete-sheet"});break;default:console.info("unhandled command",c)}}),this.options.stats&&(this.stats_panel=this.container.querySelector(".treb-stats-panel")),this.options.scale_control){let s=this.container.querySelector(".treb-scale-control");this.scale_control=new It(s),this.scale_control.Subscribe(c=>{this.Publish(c)}),this.UpdateScale(this.options.initial_scale||1)}}tab_container;scale_control;stats_panel;dragging=!1;double_click_data={};tab_color_cache=new Map;_visible=!1;get visible(){return this._visible}set stats_data(t){if(this.stats_panel){this.stats_panel.innerText="";for(let r of t)this.DOM.Create("span","treb-stats-label",this.stats_panel,{text:r.label}),this.DOM.Create("span","treb-stats-value",this.stats_panel,{text:r.value})}}container;DOM;IsDoubleClick(t,r=300){return this.double_click_data.index===t?(clearTimeout(this.double_click_data.timeout),this.double_click_data.index=void 0,this.double_click_data.timeout=void 0,!0):(this.double_click_data.timeout&&clearTimeout(this.double_click_data.timeout),this.double_click_data.index=t,this.double_click_data.timeout=window.setTimeout(()=>{this.double_click_data.index=void 0,this.double_click_data.timeout=void 0},r),!1)}Hide(){this.Show(!1)}Show(t=!0){this.container&&(this._visible=t,t?this.container.removeAttribute("hidden"):this.container.setAttribute("hidden",""))}SetActive(t,r,i=!1){r?(t.setAttribute("selected",""),t.dataset.background_color&&(t.style.backgroundColor=`color-mix(in srgb, ${t.dataset.background_color} 20%, var(--treb-tab-bar-active-tab-background, #fff))`,t.style.color=""),requestAnimationFrame(()=>{if(i)t.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"});else if(t.parentElement){let n=t.offsetLeft,o=t.offsetWidth,a=t.parentElement.clientWidth||0,s=t.parentElement.scrollLeft||0;n>a?t.parentElement.scrollLeft=n-o:s>n&&(t.parentElement.scrollLeft=n)}})):(t.removeAttribute("selected"),t.dataset.background_color&&(t.style.backgroundColor=t.dataset.background_color),t.dataset.foreground_color&&(t.style.color=t.dataset.foreground_color))}UpdateScale(t){this.scale_control?.UpdateScale(t*100)}DoubleClickTab(t,r,i){if(r.contentEditable="true",this.DOM.doc){let n=this.DOM.GetSelection();if(n){n.removeAllRanges();let o=this.DOM.doc.createRange();o.selectNodeContents(r),n.addRange(o)}}r.addEventListener("keydown",n=>{switch(n.key){case"Enter":this.Publish({type:"rename-sheet",name:r.innerText.trim(),sheet:i});break;case"Escape":r.innerText=i.name,this.Publish({type:"cancel"}),this.Update(!0);break;default:return}n.stopPropagation(),n.preventDefault()}),r.addEventListener("focusout",()=>{let n=r.innerText.trim();n!==i.name?this.Publish({type:"rename-sheet",name:n,sheet:i}):this.Update(!0)}),r.focus()}MouseDownTab(t,r,i,n,o){if(t.stopPropagation(),t.preventDefault(),this.IsDoubleClick(n))return;this.Publish({type:"activate-sheet",sheet:i});let a=o.map(p=>p.getBoundingClientRect()),s=n*2-1,c=a[0].left,d=a[a.length-1].right,u=a[0].top,h=a[0].bottom,f=-1,m=(a.length-1)*2+1;for(let p of o)this.SetActive(p,p===r,!0);this.dragging=!0,Ae(this.layout.mask,[],p=>{let[b,g]=[p.clientX,p.clientY];if(g>u&&g<h){let x=s;if(b<c)x=f;else if(b>d)x=m;else for(let y=0;y<a.length;y++){let w=a[y];if(b>=w.left&&b<=w.right){y!==n&&(b>=w.left+w.width/2?x=y*2+1:x=y*2-1);break}}x!==s&&(s=x,r.style.order=s.toString(),a=o.map(y=>y.getBoundingClientRect()))}},()=>{let p=n,b=(s+1)/2;this.dragging=!1;for(let g=0;g<this.model.sheets.length;g++)this.model.sheets.list[g].visible||(p>=g&&p++,b>=g&&b++);p===b||p===0&&b<=0||p===o.length-1&&b>=o.length-1||this.Publish({type:"reorder-sheet",index:p,move_before:b})})}UpdateTheme(){this.tab_color_cache.clear(),this.Update()}Update(t=!1){if(this.tab_color_cache.clear(),this.dragging)return;if(this.options.tab_bar==="auto"){if(this.model.sheets.list.reduce((n,o)=>o.visible?n+1:n,0)<=1){this.Show(!1);return}this.Show(!0)}if(!this.tab_container)return;this.tab_container.innerText="";let r=[];for(let i of this.model.sheets.list){if(!i.visible)continue;let n=r.length,o=this.DOM.Create("li");if(o.setAttribute("tabindex","0"),i.tab_color){let c=i.id;if(!this.tab_color_cache.has(c)){let u=D(this.theme,i.tab_color),h=D(this.theme,{offset:i.tab_color});u&&h&&this.tab_color_cache.set(c,{background:u,foreground:h})}let d=this.tab_color_cache.get(c);d&&(o.style.backgroundColor=d.background,o.style.color=d.foreground,o.dataset.background_color=d.background,o.dataset.foreground_color=d.foreground)}o.style.order=(n*2).toString(),o.role="tab",this.SetActive(o,i===this.view.active_sheet,t);let a=c=>this.MouseDownTab(c,o,i,n,r),s=c=>{o.removeEventListener("mousedown",a),o.removeEventListener("dblclick",s),this.DoubleClickTab(c,o,i)};o.textContent=i.name,o.addEventListener("dblclick",s),o.addEventListener("mousedown",a),this.tab_container.appendChild(o),r.push(o)}}};var Ye=class{constructor(e,t,r=!1,i=O.GetInstance()){this.model=e;this.view=t;this.DOM=i;if(r)return;if(!i)throw new Error("missing DOM context");this.dpr=Math.max(1,self.devicePixelRatio||1),this.mask=i.Div("treb-mouse-mask"),this.tooltip=i.Div("treb-tooltip"),this.spill_border=i.SVG("svg","treb-spill-border"),this.spill_border.tabIndex=-1,this.dropdown_caret=i.SVG("svg","treb-dropdown-caret"),this.dropdown_caret.setAttribute("viewBox","0 0 24 24"),this.dropdown_caret.tabIndex=-1;let n=i.SVG("path");n.setAttribute("d","M5,7 L12,17 L19,7"),this.dropdown_caret.appendChild(n),this.dropdown_caret.addEventListener("click",o=>{o.stopPropagation(),o.preventDefault(),this.grid_cover.classList.remove("nub-select");let a=this.dropdown_caret.getAttribute("class")||"";/active/i.test(a)?this.dropdown_caret.setAttribute("class","treb-dropdown-caret"):(this.dropdown_caret.setAttribute("class","treb-dropdown-caret active"),this.dropdown_list.focus())}),this.dropdown_list=i.Div("treb-dropdown-list",void 0,{attrs:{tabindex:"-1"}}),this.dropdown_list.addEventListener("keydown",o=>{let a=0;switch(o.key){case"ArrowDown":a=1;break;case"ArrowUp":a=-1;break;case"Escape":break;case"Enter":break;default:console.info(o.key);return}if(o.stopPropagation(),o.preventDefault(),o.key==="Escape"||o.key==="Enter"){if(this.container?.focus(),this.dropdown_caret.setAttribute("class","treb-dropdown-caret"),o.key==="Enter"&&this.dropdown_callback&&this.dropdown_selected){let s=this.dropdown_selected.dataset.dropdown_value;this.dropdown_callback.call(0,s?JSON.parse(s):void 0)}}else if(a&&this.dropdown_selected)if(a>0&&this.dropdown_selected.nextSibling){this.dropdown_selected.nextSibling.classList.add("selected"),this.dropdown_selected.classList.remove("selected"),this.dropdown_selected=this.dropdown_selected.nextSibling;let s=this.dropdown_selected.offsetTop+this.dropdown_selected.offsetHeight;s>this.dropdown_list.offsetHeight+this.dropdown_list.scrollTop&&(this.dropdown_list.scrollTop=s-this.dropdown_list.offsetHeight)}else a<0&&this.dropdown_selected.previousSibling&&(this.dropdown_selected.previousSibling.classList.add("selected"),this.dropdown_selected.classList.remove("selected"),this.dropdown_selected=this.dropdown_selected.previousSibling,this.dropdown_selected.offsetTop<this.dropdown_list.scrollTop&&(this.dropdown_list.scrollTop=this.dropdown_selected.offsetTop))}),this.dropdown_list.addEventListener("mousedown",o=>{let a=o.target;if(o.target!==this.dropdown_list&&(o.stopPropagation(),o.preventDefault(),this.container?.focus(),this.dropdown_caret.setAttribute("class","treb-dropdown-caret"),this.dropdown_callback)){let s=a.dataset.dropdown_value;this.dropdown_callback.call(0,s?JSON.parse(s):void 0)}}),this.dropdown_list.addEventListener("mousemove",o=>{let a=o.target;a!==this.dropdown_selected&&(this.grid_cover.classList.remove("nub-select"),this.dropdown_selected&&this.dropdown_selected.classList.remove("selected"),a.classList.add("selected"),this.dropdown_selected=a)}),this.mock_selection=i.Div("mock-selection-node",void 0,{html:"&nbsp;"}),this.note_node=i.Div("treb-note"),this.title_node=i.Div("treb-hover-title"),this.sort_button=i.Create("button","treb-sort-button",void 0,{attrs:{title:"Sort table",tabindex:"-1"}}),this.HideNote()}column_header;row_header;contents;buffer_canvas;corner;corner_canvas;grid_selection;grid_cover;column_header_cover;row_header_cover;annotation_container;mask;mock_selection;container;grid_tiles=[];column_header_tiles=[];row_header_tiles=[];corner_selection;row_header_selection;column_header_selection;corner_annotations;row_header_annotations;column_header_annotations;frozen_row_tiles=[];frozen_column_tiles=[];header_size={width:0,height:0};applied_theme_colors=[];last_column=0;total_height=0;total_width=0;default_row_height=0;default_column_width=0;header_offset={x:0,y:0};dpr=1;scale=1;scroll_reference_node;get scroll_offset(){return this.scroll_reference_node?{x:this.scroll_reference_node.scrollLeft,y:this.scroll_reference_node.scrollTop}:{x:0,y:0}}set scroll_offset(e){this.scroll_reference_node&&(this.scroll_reference_node.scrollLeft=e.x,this.scroll_reference_node.scrollTop=e.y)}dropdown_caret;spill_border;trident=typeof navigator<"u"&&navigator.userAgent&&/trident/i.test(navigator.userAgent);default_tile_size={width:1200,height:800};tooltip_state;tooltip;dropdown_list;dropdown_caret_visible=!1;dropdown_callback;dropdown_selected;note_node;sort_button;title_node;row_cache=[];column_cache=[];initialized=!1;FocusInLayout(e){return!1}UpdateDPR(){let e=Math.max(1,self.devicePixelRatio||1);return e===this.dpr?!1:(this.dpr=e,!0)}ColumnWidth(e){return Math.round(this.view.active_sheet.GetColumnWidth(e)*this.scale)}RowHeight(e){return Math.round(this.view.active_sheet.GetRowHeight(e)*this.scale)}SetRowHeight(e,t){this.view.active_sheet.SetRowHeight(e,Math.round(t/this.scale))}SetColumnWidth(e,t){this.view.active_sheet.SetColumnWidth(e,Math.round(t/this.scale))}ShowSelections(e=!0){this.grid_selection.style.display=e?"block":"none"}HideTitle(){this.title_node.style.opacity="0"}ShowTitle(e,t){if(this.title_node.textContent=e,!this.title_node.parentElement)return;let r=this.title_node.parentElement.getBoundingClientRect(),i=this.OffsetCellAddressToRectangle(t).Shift(this.header_size.width,this.header_size.height);this.title_node.style.left=r.left+i.left-this.scroll_reference_node.scrollLeft+0+"px",this.title_node.style.top=r.top+i.bottom-this.scroll_reference_node.scrollTop+8+"px",this.title_node.style.opacity="1"}HideNote(){this.note_node.style.opacity="0",this.note_node.style.pointerEvents="none"}HideTableSortButton(){this.sort_button.style.opacity="0",this.sort_button.style.pointerEvents="none",this.sort_button.setAttribute("tabindex","-1")}ShowTableSortButton(e,t,r){if(!this.sort_button.parentElement)return;let i=!0,n=!1;e.sort&&e.sort.column===t&&(i=!e.sort.asc,n=!0),this.sort_button.setAttribute("tabindex","0 "),this.sort_button.style.opacity="1",this.sort_button.style.pointerEvents="initial",this.sort_button.classList.remove("asc","desc"),n&&this.sort_button.classList.add(i?"asc":"desc"),this.sort_button.dataset.asc=i.toString(),this.sort_button.dataset.table=e.name,this.sort_button.dataset.column=t.toString();let o=this.OffsetCellAddressToRectangle(r).Shift(this.header_size.width,this.header_size.height),a=this.sort_button.getBoundingClientRect();this.sort_button.style.left=o.right-a.width-a.width/2+"px",this.sort_button.style.top=o.top+(o.height-a.height)/2+"px"}ShowNote(e,t,r,i){if(i?this.note_node.innerHTML=i:this.note_node.textContent=e,!this.note_node.parentElement)return;let n=this.note_node.getBoundingClientRect(),o=this.note_node.parentElement.getBoundingClientRect(),a={x:8,y:2},s=this.OffsetCellAddressToRectangle(t).Shift(this.header_size.width,this.header_size.height);this.note_node.style.left=o.left+s.right-this.scroll_reference_node.scrollLeft+a.x+"px",this.note_node.style.top=o.top+s.top-this.scroll_reference_node.scrollTop-n.height/5-a.y+"px",this.note_node.style.opacity="1",this.note_node.style.pointerEvents="auto"}AnnotationLayoutOrder(e,t){let r=-1;for(let n=0;n<this.view.active_sheet.annotations.length;n++)if(this.view.active_sheet.annotations[n]===e){r=n;break}if(r<0)return!1;let i=Math.min(Math.max(0,r+t),this.view.active_sheet.annotations.length-1);if(i===r)return!1;this.view.active_sheet.annotations.splice(r,1),this.view.active_sheet.annotations.splice(i,0,e);for(let n=0;n<this.view.active_sheet.annotations.length;n++){let o=this.view.active_sheet.annotations[n].key,a=this.container?.querySelectorAll(`.annotation[data-key="${o}"]`);if(a)for(let s=0;s<a?.length;s++)a[s].style.zIndex=(n+1).toString()}return!0}PointToAnnotationCorner(e){let t=this.PointToAddress_Grid(e,!1),r=this.CellAddressToRectangle(t);return{address:t,offset:{x:(e.x-r.left)/r.width,y:(e.y-r.top)/r.height}}}RectToAnnotationLayout(e){return{tl:this.PointToAnnotationCorner({x:(e.left||0)+1,y:(e.top||0)+1}),br:this.PointToAnnotationCorner({x:e.right||e.left||100,y:e.bottom||e.top||100})}}AddressToAnnotationLayout(e,t){let r={tl:this.CellAddressToRectangle(e),br:this.CellAddressToRectangle(t)};return{tl:this.PointToAnnotationCorner({x:r.tl.left||0,y:r.tl.top||0}),br:this.PointToAnnotationCorner({x:r.br.right||r.tl.left||100,y:r.br.bottom||r.tl.left||100})}}AnnotationLayoutToRect(e){let t=this.CellAddressToRectangle(e.tl.address),r=this.CellAddressToRectangle(e.br.address),i=t.left+t.width*e.tl.offset.x-1,n=t.top+t.height*e.tl.offset.y-1;return new B(i,n,r.left+r.width*e.br.offset.x-i,r.top+r.height*e.br.offset.y-n)}UpdateAnnotation(e,t){Array.isArray(e)||(e=[e]);for(let r of e){let i=r.view[this.view.view_index]||{};if(i.node){let n=10*this.scale;if(r.data.style?.font_size?.unit==="em"&&(n*=r.data.style.font_size.value),i.node.dataset.scale=this.scale.toString(),r.data.style?.font_face&&r.data.style.font_face.startsWith("stack:")){let o=r.data.style.font_face.substring(6),a=t.font_stacks[o];a?(i.node.classList.add("treb-inherit-font"),i.node.style.fontFamily=a.font||"",a.variants&&(i.node.style.fontVariant=a.variants)):(i.node.classList.remove("treb-inherit-font"),i.node.style.fontFamily="",i.node.style.fontVariant="")}else i.node.classList.remove("treb-inherit-font"),i.node.style.fontFamily="",i.node.style.fontVariant="";if(r.data.style?.bold?i.node.style.fontWeight="600":i.node.style.fontWeight="400",r.data.style?.italic?i.node.style.fontStyle="italic":i.node.style.fontStyle="",r.data.style?.underline?i.node.style.textDecoration="underline":i.node.style.textDecoration="",i.node.style.fontSize=`${n}pt`,r.rect&&!r.data.layout&&(r.scaled_rect=r.rect.Scale(this.scale),r.data.layout=this.RectToAnnotationLayout(r.scaled_rect)),r.data.layout){let o=this.AnnotationLayoutToRect(r.data.layout);o.ApplyStyle(i.node),r.scaled_rect=o}i.node.dataset.key=r.key.toString(),(this.view.active_sheet.freeze.rows||this.view.active_sheet.freeze.columns)&&this.CloneFrozenAnnotation(r)}}}GetFrozenAnnotations(e){return[this.row_header_annotations,this.column_header_annotations,this.corner_annotations].map(r=>r.querySelector(`.annotation[data-key="${e.key}"]`)).filter(r=>r!==null)}CloneFrozenAnnotations(){for(let e of this.view.active_sheet.annotations)e.view[this.view.view_index]?.node&&e.key&&this.CloneFrozenAnnotation(e)}ClearFrozenAnnotations(){for(let e of[this.row_header_annotations,this.column_header_annotations,this.corner_annotations]){let t=e.querySelectorAll(".annotation");for(let r=0;r<t.length;r++)t[r].parentElement?.removeChild(t[r])}}RemoveFrozenAnnotation(e){for(let t of[this.row_header_annotations,this.column_header_annotations,this.corner_annotations]){let r=t.querySelector(`.annotation[data-key="${e.key}"]`);r&&r.parentElement?.removeChild(r)}}CloneFrozenAnnotation(e){for(let t of[this.row_header_annotations,this.column_header_annotations,this.corner_annotations]){let r=t.querySelector(`.annotation[data-key="${e.key}"]`);r&&r.parentElement?.removeChild(r);let i=e.view[this.view.view_index];if(r=i?.node?.cloneNode(!0),r){let n=r.querySelector(".annotation-move-target"),o=r.querySelector(".annotation-resize-target");r.addEventListener("mousedown",a=>{let s=i.node;requestAnimationFrame(()=>{s?.focus()}),this.AnnotationMouseDown(e,i.node,a,n,o)}),t.appendChild(r)}}}RemoveAnnotation(e){let t=e.view[this.view.view_index]||{};t.node&&t.node.parentElement?.removeChild(t.node),this.RemoveFrozenAnnotation(e)}RemoveAnnotationNodes(){let e=Array.prototype.map.call(this.annotation_container.children,t=>t);for(let t of e)this.annotation_container.removeChild(t);(this.view.active_sheet.freeze.rows||this.view.active_sheet.freeze.columns)&&this.ClearFrozenAnnotations()}AddAnnotation(e,t){let r=e.view[this.view.view_index]||{};if(!r.node)throw new Error("annotation view/node missing");this.annotation_container.appendChild(r.node),this.UpdateAnnotation(e,t)}AnnotationMouseDown(e,t,r,i,n){let o=e.scaled_rect;return o?new Promise(a=>{let s={left:o.left,top:o.top,width:o.width,height:o.height},c=this.scroll_reference_node,d=c.getBoundingClientRect(),u=t.getBoundingClientRect();if(r.target===i||r.target!==n&&r.altKey){r.stopPropagation(),r.preventDefault(),t.focus();let h={x:u.left+r.offsetX-o.left,y:u.top+r.offsetY-o.top},f=[t,...this.GetFrozenAnnotations(e)],m=25,p=this.CellAddressToRectangle({row:0,column:0}).Combine(this.CellAddressToRectangle({row:this.view.active_sheet.rows-1,column:this.view.active_sheet.columns-1})).Expand(-1,-1);Ae(this.mask,"move",b=>{if(b.offsetY-d.top<this.header_offset.y){let g=Math.min(m,c.scrollTop);c.scrollTop-=g,h.y+=g}else if(b.offsetY-d.top>=d.height&&c.scrollTop+d.height<p.height){let g=m;c.scrollTop+=g,h.y-=g}if(b.offsetX-d.left<this.header_offset.x){let g=Math.min(m,c.scrollLeft);c.scrollLeft-=g,h.x+=g}else if(b.offsetX-d.left>=d.width&&c.scrollLeft+d.width<p.width){let g=m;c.scrollLeft+=g,h.x-=g}if(o.top=b.offsetY-h.y,o.left=b.offsetX-h.x,b.shiftKey){let g=Math.abs(o.left-s.left),x=Math.abs(o.top-s.top);g<=x?o.left=s.left:o.top=s.top}if(b.ctrlKey){let g=this.ClampToGrid({x:o.left,y:o.top});o.left=g.x,o.top=g.y}for(let g of f)g.style.top=o.top+"px",g.style.left=o.left+"px"},()=>{e.data.extent=void 0,e.data.layout=this.RectToAnnotationLayout(o),a({type:"annotation",annotation:e,event:"move"})});return}else if(r.target===n){r.stopPropagation(),r.preventDefault(),t.focus();let h=0;e.data.type==="image"&&e.data.data&&e.data.data.original_size&&e.data.data.original_size.width&&e.data.data.original_size.height&&(h=e.data.data.original_size.width/e.data.data.original_size.height);let f=t.getBoundingClientRect(),m={x:f.left+r.offsetX-o.width+n.offsetLeft,y:f.top+r.offsetY-o.height+n.offsetTop};Ae(this.mask,"nw-resize",p=>{let b=[t,...this.GetFrozenAnnotations(e)];if(o.height=p.offsetY-m.y,o.width=p.offsetX-m.x,p.shiftKey&&p.ctrlKey){if(h){let g=Math.abs(o.width-s.width),x=Math.abs(o.height-s.height);g<x?o.width=h*o.height:o.height=o.width/h}}else if(p.shiftKey){let g=Math.abs(o.height-s.height),x=Math.abs(o.width-s.width);g>x?o.width=s.width:o.height=s.height}else if(p.ctrlKey){let g=this.ClampToGrid({x:o.right,y:o.bottom});o.width=g.x-o.left+1,o.height=g.y-o.top+1}for(let g of b)g.style.height=o.height+"px",g.style.width=o.width+"px"},()=>{e.data.extent=void 0,e.data.layout=this.RectToAnnotationLayout(o),a({type:"annotation",annotation:e,event:"resize"})});return}else a()}):(console.info("missing scaled rect!"),Promise.reject())}Initialize(e,t,r=!0){this.mask.parentElement||e.parentElement?.parentElement?.appendChild(this.mask),this.tooltip.parentElement||e.appendChild(this.tooltip),this.spill_border.parentElement||e.appendChild(this.spill_border),this.dropdown_caret.parentElement||e.appendChild(this.dropdown_caret),this.dropdown_list.parentElement||e.appendChild(this.dropdown_list),this.note_node.parentElement||e.appendChild(this.note_node),this.sort_button.parentElement||(e.appendChild(this.sort_button),this.sort_button.addEventListener("click",()=>{t.sort(this.sort_button.dataset.table||"",Number(this.sort_button.dataset.column||"0")||0,/true/i.test(this.sort_button.dataset.asc||"")),this.sort_button.classList.remove("asc","desc"),this.sort_button.dataset.asc==="true"?(this.sort_button.dataset.asc="false",this.sort_button.classList.add("desc")):(this.sort_button.dataset.asc="true",this.sort_button.classList.add("asc")),t.focus()})),this.title_node.parentElement||e.appendChild(this.title_node),this.InitializeInternal(e,t.scroll),!r&&this.scroll_reference_node&&(this.scroll_reference_node.style.overflow="hidden"),this.dropdown_callback=t.dropdown,this.initialized=!0}MockSelection(){if(this.container&&!this.trident&&this.DOM.doc){let e=this.DOM.GetSelection();if(e){let t=this.DOM.doc.createRange();t.selectNodeContents(this.mock_selection),e.removeAllRanges(),e.addRange(t)}}}CreateTile(e,t,r,i,n,o,a,s=!0){let c=this.DOM.Create("canvas");return c.setAttribute("class",e),c.logical_size=t,c.width=t.width*this.dpr,c.height=t.height*this.dpr,c.style.width=`${t.width}px`,c.style.height=`${t.height}px`,c.tile_position=r,c.first_cell=i,this.UpdateTileGridPosition(c),c.last_cell={row:i.row+n.rows-1,column:i.column+n.columns-1},c.pixel_start=o,c.pixel_end={x:o.x+t.width,y:o.y+t.height},c.dirty=!!s,c.needs_full_repaint=!0,a.appendChild(c),c}ApplyThemeColors(){if(this.container)for(let[e,t]of this.applied_theme_colors.entries())this.container.style.setProperty(`--treb-applied-theme-color-${e+1}`,t)}ApplyTheme(e){this.row_header.style.backgroundColor=this.column_header.style.backgroundColor=this.corner.style.backgroundColor=e.headers?.fill?D(e,e.headers.fill,0):"",this.corner.style.borderColor=e.grid_color||"";for(let t of this.grid_tiles)for(let r of t)r.style.backgroundColor=D(e,e.grid_cell?.fill,0)||"#fff";this.dropdown_list.style.font=I.CompositeFont(e.grid_cell_font_size,{font_face:"stack:default"},this.scale,e).font,this.applied_theme_colors=e.theme_colors?.slice(4,10)||[],this.container&&this.ApplyThemeColors()}UpdateTotalSize(){this.total_height=0;let e=this.view.active_sheet.rows;for(let r=0;r<e;r++)this.total_height+=this.RowHeight(r);this.total_width=0;let t=this.view.active_sheet.columns;for(let r=0;r<t;r++)this.total_width+=this.ColumnWidth(r)}UpdateContentsSize(){let e=this.row_header_tiles.reduce((r,i)=>r+i.logical_size.height,0),t=this.column_header_tiles.reduce((r,i)=>r+i.logical_size.width,0);this.column_header.style.width=this.contents.style.width=`${t}px`,this.row_header.style.height=this.contents.style.height=`${e}px`}HideTooltip(){this.tooltip.style.display="none",this.tooltip_state=void 0,this.tooltip.classList.remove("arrow-up"),this.tooltip.classList.remove("arrow-left")}ShowTooltip(e={}){e.up?(this.tooltip.classList.add("arrow-up"),this.tooltip_state="up"):e.left&&(this.tooltip.classList.add("arrow-left"),this.tooltip_state="left"),this.tooltip.style.display="block",this.UpdateTooltip(e)}ShowDropdownCaret(e,t,r){let i=this.OffsetCellAddressToRectangle(e.start);e.count>1&&(i=i.Combine(this.OffsetCellAddressToRectangle(e.end))),i=i.Shift(this.header_size.width,this.header_size.height);let n=Math.round(this.scale*Math.max(8,Math.min(20,i.height)));this.dropdown_caret.style.height=`${n}px`,this.dropdown_caret.style.width=`${n}px`,this.dropdown_caret.style.left=`${i.right+1}px`,this.dropdown_caret.style.top=`${i.bottom-n}px`,this.dropdown_list.style.top=`${i.bottom+2}px`,this.dropdown_list.style.left=`${i.left+2}px`,this.dropdown_list.style.minWidth=`${i.width}px`,this.dropdown_list.style.fontSize=this.scale.toFixed(2)+"em",this.dropdown_list.textContent="";for(let o of t){let a=this.DOM.Div(void 0,this.dropdown_list);r===o&&(this.dropdown_selected=a,a.classList.add("selected")),a.dataset.dropdown_value=JSON.stringify(o),a.textContent=o?.toString()||""}this.dropdown_caret.setAttribute("class","treb-dropdown-caret"),this.dropdown_caret.style.display="block",this.dropdown_caret_visible=!0}ShowSpillBorder(e){if(this.spill_border.textContent="",e){let t=new v(e.start,e.end),r=this.OffsetCellAddressToRectangle(t.start);t.count>1&&(r=r.Combine(this.OffsetCellAddressToRectangle(t.end))),r=r.Shift(this.header_size.width,this.header_size.height),this.spill_border.style.display="block",this.spill_border.style.top=(r.top-5).toString()+"px",this.spill_border.style.left=(r.left-5).toString()+"px",this.spill_border.style.width=(r.width+10).toString()+"px",this.spill_border.style.height=(r.height+10).toString()+"px";let i=this.DOM.SVG("rect",void 0,this.spill_border);i.setAttribute("x","4.5"),i.setAttribute("y","4.5"),i.setAttribute("width",(r.width+1).toString()),i.setAttribute("height",(r.height+1).toString())}else this.spill_border.style.display="none"}HideDropdownCaret(){this.dropdown_caret_visible&&(this.dropdown_caret.setAttribute("class","treb-dropdown-caret"),this.dropdown_caret_visible=!1,this.dropdown_caret.style.display="none")}GetScrollOffset(){return{x:this.scroll_reference_node.scrollLeft+this.header_offset.x,y:this.scroll_reference_node.scrollTop+this.header_offset.y}}ScrollTo(e,t=!0,r=!0,i=!1){let n=this.CellAddressToRectangle(e);if(i&&this.scroll_reference_node.scrollTo){let o={left:this.scroll_reference_node.scrollLeft,top:this.scroll_reference_node.scrollTop},a={left:t?n.left:o.left,top:r?n.top:o.top,behavior:"smooth"};this.scroll_reference_node.scrollTo(a)}else r&&(this.scroll_reference_node.scrollTop=n.top),t&&(this.scroll_reference_node.scrollLeft=n.left)}ScrollIntoView(e,t=!1){let r=this.CellAddressToRectangle(e),i=this.scroll_reference_node.clientWidth-this.row_header.offsetWidth,n=this.scroll_reference_node.clientHeight-this.column_header.offsetHeight,o={x:0,y:0},a={x:!1,y:!1},s=new B(this.scroll_reference_node.scrollLeft,this.scroll_reference_node.scrollTop,i,n);(this.view.active_sheet.freeze.rows||this.view.active_sheet.freeze.columns)&&(this.view.active_sheet.freeze.rows&&e.row>=this.view.active_sheet.freeze.rows?o.y=this.frozen_row_tiles[0].logical_size.height:this.view.active_sheet.freeze.rows&&(a.y=!0),this.view.active_sheet.freeze.columns&&e.column>=this.view.active_sheet.freeze.columns?o.x=this.frozen_column_tiles[0].logical_size.width:this.view.active_sheet.freeze.columns&&(a.x=!0));let c={behavior:t?"smooth":"auto"};e.row!==1/0&&(r.top<s.top+o.y&&!a.y?c.top=r.top-o.y:r.bottom>s.bottom&&(c.top=r.bottom-n)),e.column!==1/0&&(r.left<s.left+o.x&&!a.x?c.left=r.left-o.x:r.right>s.right&&(c.left=r.right-i)),this.scroll_reference_node.scrollTo(c)}UpdateTooltip(e={}){if(typeof e.text<"u"&&(this.tooltip.textContent=e.text),typeof e.x<"u"){let t=e.x||0;this.tooltip_state==="up"&&(t-=this.tooltip.offsetWidth/2),this.tooltip.style.left=Math.round(t)+"px"}if(typeof e.y<"u"){let t=e.y||0;this.tooltip_state==="left"&&(t-=this.tooltip.offsetHeight/2),this.tooltip.style.top=Math.round(t)+"px"}}CoordinateToRowHeader(e){let t={column:1/0,row:0};if(this.view.active_sheet.freeze.rows&&this.frozen_row_tiles[0].pixel_end.y>=e-this.scroll_reference_node.scrollTop){let r=0;e-=this.scroll_reference_node.scrollTop;for(let i=0;i<this.view.active_sheet.freeze.rows;i++)if(r+=this.RowHeight(i),r>=e)return t.row=i,t}for(let r of this.row_header_tiles)if(r.pixel_end.y>=e){let i=e-r.pixel_start.y,n=0;for(t.row=r.first_cell.row;t.row<=r.last_cell.row;t.row++,i-=n)if(n=this.RowHeight(t.row),n>i)return t;return t}return t}CoordinateToColumnHeader(e){let t={row:1/0,column:0};if(this.view.active_sheet.freeze.columns&&this.frozen_column_tiles[0].pixel_end.x>=e-this.scroll_reference_node.scrollLeft){let r=0;e-=this.scroll_reference_node.scrollLeft;for(let i=0;i<this.view.active_sheet.freeze.columns;i++)if(r+=this.ColumnWidth(i),r>=e)return t.column=i,t}for(let r of this.column_header_tiles)if(r.pixel_end.x>=e){let i=e-r.pixel_start.x,n=0;for(t.column=r.first_cell.column;t.column<=r.last_cell.column;t.column++,i-=n)if(n=this.ColumnWidth(t.column),n>i)return t;return t}return t}PointToAddress_Grid(e,t=!0){if(t){if(this.view.active_sheet.freeze.rows){let o=this.frozen_row_tiles[0].logical_size.height;e.y-this.scroll_reference_node.scrollTop<o&&(e.y-=this.scroll_reference_node.scrollTop)}if(this.view.active_sheet.freeze.columns){let o=this.frozen_column_tiles[0].logical_size.width;e.x-this.scroll_reference_node.scrollLeft<o&&(e.x-=this.scroll_reference_node.scrollLeft)}}let r={row:0,column:0},i=this.grid_tiles[this.grid_tiles.length-1],n=i[i.length-1];if(e.y>n.pixel_end.y){let o=e.y-n.pixel_end.y;for(r.row=n.last_cell.row;o>0;)r.row++,o-=this.default_row_height}else for(let o of i)if(o.pixel_start.y<=e.y&&o.pixel_end.y>=e.y){let a=e.y-o.pixel_start.y,s=0;for(r.row=o.first_cell.row;r.row<=o.last_cell.row&&(s=this.RowHeight(r.row),!(s>a));r.row++,a-=s);break}if(e.x>n.pixel_end.x){let o=e.x-n.pixel_end.x;for(r.column=n.last_cell.column;o>0;)r.column++,o-=this.default_column_width}else for(let o of this.grid_tiles)if(o[0].pixel_start.x<=e.x&&o[0].pixel_end.x>=e.x){let a=o[0],s=e.x-a.pixel_start.x,c=0;for(r.column=a.first_cell.column;r.column<=a.last_cell.column&&(c=this.ColumnWidth(r.column),!(c>s));r.column++,s-=c);break}return r}AdjacentTile(e,t=0,r=0){if(!t&&!r)return e;let i=e.tile_position,n=e.tile_position.row+t,o=e.tile_position.column+r;if(!(n<0||o<0)){if(this.grid_tiles[i.column]&&this.grid_tiles[i.column][i.row]===e&&this.grid_tiles[o])return this.grid_tiles[o][n];if(!i.column&&this.frozen_column_tiles[i.row]===e)return this.frozen_column_tiles[n];if(!i.row&&this.frozen_row_tiles[i.column]===e)return this.frozen_row_tiles[o]}}UpdateTiles(){if(!this.container)throw new Error("invalid container");this.grid_tiles.forEach(w=>{w.forEach(_=>{_.parentElement&&_.parentElement.removeChild(_)})});for(let w of[this.column_header_tiles,this.row_header_tiles,this.frozen_row_tiles,this.frozen_column_tiles])for(let _ of w)_.parentElement&&_.parentElement.removeChild(_);this.frozen_row_tiles=[],this.frozen_column_tiles=[],this.row_header_tiles=[],this.column_header_tiles=[],this.grid_tiles=[];let e=this.view.active_sheet;this.default_row_height=Math.round(e.default_row_height*this.scale),this.default_column_width=Math.round(e.default_column_width*this.scale),this.header_offset={x:Math.round(e.header_offset.x*this.scale),y:Math.round(e.header_offset.y*this.scale)},this.UpdateContainingGrid();let t=this.view.active_sheet.rows,r=this.view.active_sheet.columns;t||(t=100),r||(r=40);let i=0,n=0;for(let w=0;w<t;w++)i+=this.RowHeight(w);for(let w=0;w<r;w++)n+=this.ColumnWidth(w);if(!n||!i)throw"unexpected missing total size";if(i||(i=this.default_row_height*t),n||(n=this.default_column_width*r),this.container.clientWidth>n+this.header_size.width){let w=Math.ceil((this.container.offsetWidth-n)/this.default_column_width);n+=w*this.default_column_width,r+=w}if(this.last_column=r,this.container.clientHeight>i+this.header_size.height){let w=Math.ceil((this.container.offsetHeight-i)/this.default_row_height);i+=w*this.default_row_height,t+=w}this.column_header.style.width=this.contents.style.width=`${n}px`,this.row_header.style.height=this.contents.style.height=`${i}px`;let o=[],a=[],s=0,c=0;for(let w=0;w<r;w++){let _=this.ColumnWidth(w);s&&s+_>this.default_tile_size.width&&(o.push(s),a.push(c),c=w,s=0),s+=_}o.push(s),a.push(c);let d=[],u=[],h=0,f=0;for(let w=0;w<t;w++){let _=this.RowHeight(w);h&&h+_>this.default_tile_size.height&&(d.push(h),u.push(f),h=0,f=w),h+=_}d.push(h),u.push(f);let m=o.length,p=d.length,b=0,g=0,x=0,y=0;for(let w=0;w<this.view.active_sheet.freeze.rows;w++)x+=this.RowHeight(w);for(let w=0;w<this.view.active_sheet.freeze.columns;w++)y+=this.ColumnWidth(w);for(let w=0;w<m;w++){let _=[];b=0;let C=w===m-1?r-a[w]:a[w+1]-a[w];this.column_header_tiles.push(this.CreateTile("column-header-tile",{height:this.header_offset.y,width:o[w]},{row:0,column:w},{row:0,column:a[w]},{rows:0,columns:C},{x:g,y:0},this.column_header)),this.view.active_sheet.freeze.rows&&this.frozen_row_tiles.push(this.CreateTile("frozen-row-tile",{height:x,width:o[w]},{row:1,column:w},{row:0,column:a[w]},{rows:0,columns:C},{x:g,y:0},this.column_header));for(let S=0;S<p;S++){let A=S===p-1?t-u[S]:u[S+1]-u[S];w||(this.row_header_tiles.push(this.CreateTile("row-header-tile",{height:d[S],width:this.header_offset.x},{row:S,column:0},{row:u[S],column:0},{rows:A,columns:1},{x:0,y:b},this.row_header)),this.view.active_sheet.freeze.columns&&this.frozen_column_tiles.push(this.CreateTile("frozen-column-tile",{height:d[S],width:y},{row:S,column:1},{row:u[S],column:0},{rows:A,columns:1},{x:0,y:b},this.row_header))),_.push(this.CreateTile("grid-tile",{height:d[S],width:o[w]},{row:S,column:w},{row:u[S],column:a[w]},{rows:A,columns:C},{x:g,y:b},this.contents)),b+=d[S]}this.grid_tiles.push(_),g+=o[w]}this.total_height=i,this.total_width=n,this.ClearLayoutCaches(),this.UpdateGridTemplates(!0,!0)}ClearLayoutCaches(){this.row_cache=[],this.column_cache=[]}TileIndexForColumn(e){for(let t of this.column_header_tiles)if(t.first_cell.column<=e&&t.last_cell.column>=e)return t.tile_position.column;return-1}TileIndexForRow(e){for(let t of this.row_header_tiles)if(t.first_cell.row<=e&&t.last_cell.row>=e)return t.tile_position.row;return-1}DirtyHeaders(e){if(e){for(let t of this.column_header_tiles){if(t.dirty)continue;let r=new v({row:e.start.row,column:t.first_cell.column},{row:e.start.row,column:t.last_cell.column});(e.entire_row||r.Intersects(e))&&(t.dirty=!0)}for(let t of this.row_header_tiles){if(t.dirty)continue;let r=new v({column:e.start.column,row:t.first_cell.row},{column:e.start.column,row:t.last_cell.row});(e.entire_column||r.Intersects(e))&&(t.dirty=!0)}}}DirtyAll(){for(let e of this.grid_tiles)for(let t of e)t.dirty=!0}DirtyArea(e){if(this.initialized){Array.isArray(e)||(e=[e]);for(let t of e){let r={row:0,column:0},i={row:this.grid_tiles[0].length-1,column:this.grid_tiles.length-1};t.start.column!==1/0&&(r.column=i.column=this.TileIndexForColumn(t.start.column),t.end.column!==t.start.column&&(i.column=this.TileIndexForColumn(t.end.column))),t.start.row!==1/0&&(r.row=i.row=this.TileIndexForRow(t.start.row),t.end.row!==t.start.row&&(i.row=this.TileIndexForRow(t.end.row)));for(let n=r.column;n<=i.column;n++)for(let o=r.row;o<=i.row;o++)this.grid_tiles[n][o].dirty=!0}}}VisibleTiles(){let e=[{row:0,column:0},{row:0,column:0}];if(!this.container||!this.grid_tiles.length||!this.grid_tiles[0].length)return new v(e[0],e[1]);let t=this.scroll_reference_node.scrollLeft,r=t+this.scroll_reference_node.offsetWidth,i=this.scroll_reference_node.scrollTop,n=i+this.scroll_reference_node.offsetHeight;for(let o of this.grid_tiles){let a=o[0];if(a.pixel_start.x<=t&&a.pixel_end.x>=t){for(a of o)if(a.pixel_start.y<=i&&a.pixel_end.y>=i){e[0]=a.tile_position;break}}if(o===this.grid_tiles[this.grid_tiles.length-1]||a.pixel_start.x<=r&&a.pixel_end.x>=r){for(a of o)if(a===o[o.length-1]||a.pixel_start.y<=n&&a.pixel_end.y>=n)return e[1]=a.tile_position,new v(e[0],e[1])}}return new v(e[0],e[1])}UpdateTileHeights(e=!0,t=-1){let r=0;for(let i=0;i<this.row_header_tiles.length;i++){let n=this.row_header_tiles[i];if(t>n.last_cell.row){r+=n.logical_size.height;continue}let o=0;for(let s=n.first_cell.row;s<=n.last_cell.row;s++)o+=this.RowHeight(s);let a=n.logical_size.height===o;if(n.pixel_start.y=r,r+=o,n.pixel_end.y=r,!a){if(n.logical_size.height=o,n.style.height=`${o}px`,n.height=this.dpr*o,this.view.active_sheet.freeze.columns){let s=this.frozen_column_tiles[i];s.logical_size.height=o,s.style.height=`${o}px`,s.height=this.dpr*o}e&&(n.dirty=!0,n.needs_full_repaint=!0)}for(let s of this.grid_tiles){let c=s[i];c.pixel_start.y=n.pixel_start.y,c.pixel_end.y=n.pixel_end.y,a||(c.logical_size.height=o,c.style.height=`${o}px`,c.height=this.dpr*o,e&&(c.dirty=!0,c.needs_full_repaint=!0))}}if(this.view.active_sheet.freeze.rows){let i=0;for(let n=0;n<this.view.active_sheet.freeze.rows;n++)i+=this.RowHeight(n);for(let n of this.frozen_row_tiles)n.style.height=`${i}px`,n.height=i*this.dpr;i+=this.header_offset.y,this.corner_canvas.style.height=`${i}px`,this.corner_canvas.height=i*this.dpr;for(let n of this.grid_tiles)n[0].dirty=!0}this.UpdateGridTemplates(!1,!0),this.row_header.style.height=this.contents.style.height=`${r}px`,this.ClearLayoutCaches()}UpdateTileWidths(e=!0,t=-1){let r=0;for(let i=0;i<this.column_header_tiles.length;i++){let n=this.column_header_tiles[i],o=this.grid_tiles[i];if(t>n.last_cell.column){r+=n.logical_size.width;continue}let a=0;for(let c=n.first_cell.column;c<=n.last_cell.column;c++)a+=this.ColumnWidth(c);let s=n.logical_size.width===a;if(n.pixel_start.x=r,r+=a,n.pixel_end.x=r,!s){if(n.logical_size.width=a,n.style.width=`${a}px`,n.width=this.dpr*a,this.view.active_sheet.freeze.rows){let c=this.frozen_row_tiles[i];c.logical_size.width=a,c.style.width=`${a}px`,c.width=this.dpr*a}e&&(n.dirty=!0,n.needs_full_repaint=!0)}for(let c of o)c.pixel_start.x=n.pixel_start.x,c.pixel_end.x=n.pixel_end.x,s||(c.logical_size.width=a,c.style.width=`${a}px`,c.width=this.dpr*a,e&&(c.dirty=!0,c.needs_full_repaint=!0))}if(this.view.active_sheet.freeze.columns){let i=0;for(let n=0;n<this.view.active_sheet.freeze.columns;n++)i+=this.ColumnWidth(n);for(let n of this.frozen_column_tiles)n.style.width=`${i}px`,n.width=i*this.dpr;i+=this.header_offset.x,this.corner_canvas.style.width=`${i}px`,this.corner_canvas.width=i*this.dpr;for(let n of this.grid_tiles[0])n.dirty=!0}this.UpdateGridTemplates(!0,!1),this.column_header.style.width=this.contents.style.width=`${r}px`,this.ClearLayoutCaches()}ClampToGrid(e){let t=this.PointToAddress_Grid(e),r=this.OffsetCellAddressToRectangle(t);return e.x>r.left+r.width/2?e.x=r.left+r.width-1:e.x=r.left-1,e.y>r.top+r.height/2?e.y=r.top+r.height-1:e.y=r.top-1,e}OffsetCellAddressToRectangle(e){let t=this.CellAddressToRectangle(e);return e.column>=0&&e.column<this.view.active_sheet.freeze.columns&&(t=t.Shift(this.scroll_reference_node.scrollLeft,0)),e.row>=0&&e.row<this.view.active_sheet.freeze.rows&&(t=t.Shift(0,this.scroll_reference_node.scrollTop)),t}CellAddressToRectangle(e){let t=e.row===1/0||e.row<0?0:e.row,r=e.column===1/0||e.column<0?0:e.column;if(this.column_cache.length<=r+1){this.column_cache.length||(this.column_cache[0]=0);for(let o=this.column_cache.length-1;o<=r;o++)this.column_cache[o+1]=this.column_cache[o]+this.ColumnWidth(o)}if(this.row_cache.length<=t+1){this.row_cache.length||(this.row_cache[0]=0);for(let o=this.row_cache.length-1;o<=t;o++)this.row_cache[o+1]=this.row_cache[o]+this.RowHeight(o)}let i=this.column_cache[r],n=this.row_cache[t];return new B(i,n,this.column_cache[r+1]-i,this.row_cache[t+1]-n)}ResizeTileWidth(e,t,r=!0){let i=this.column_header_tiles[e],n=t-i.logical_size.width;i.logical_size.width=t,i.style.width=`${t}px`,i.width=this.dpr*t,i.pixel_end.x+=n,r&&(i.dirty=!0,i.needs_full_repaint=!0);for(let a=e+1;a<this.column_header_tiles.length;a++){this.column_header_tiles[a].pixel_start.x+=n,this.column_header_tiles[a].pixel_end.x+=n;for(let s of this.grid_tiles[a])s.pixel_start.x+=n,s.pixel_end.x+=n}let o=this.grid_tiles[e];for(i of o)i.logical_size.width=t,i.style.width=`${t}px`,i.width=this.dpr*t,i.pixel_end.x+=n,r&&(i.dirty=!0,i.needs_full_repaint=!0);this.UpdateTotalSize(),this.UpdateGridTemplates(!0,!1),this.UpdateContentsSize()}ResizeTileHeight(e,t,r=!0){let i=this.row_header_tiles[e],n=t-i.logical_size.height;i.logical_size.height=t,i.style.height=`${t}px`,i.height=this.dpr*t,i.pixel_end.y+=n,r&&(i.dirty=!0,i.needs_full_repaint=!0);for(let o=e+1;o<this.row_header_tiles.length;o++)i=this.row_header_tiles[o],i.pixel_start.y+=n,i.pixel_end.y+=n;for(let o of this.grid_tiles){i=o[e],i.logical_size.height=t,i.style.height=`${t}px`,i.height=this.dpr*t,i.pixel_end.y+=n,r&&(i.dirty=!0,i.needs_full_repaint=!0);for(let a=e+1;a<o.length;a++)o[a].pixel_start.y+=n,o[a].pixel_end.y+=n}this.UpdateTotalSize(),this.UpdateGridTemplates(!1,!0),this.UpdateContentsSize()}};var Nt=class extends Ye{constructor(e,t){super(e,t,!0)}InitializeInternal(){}UpdateGridTemplates(){}UpdateTileGridPosition(){}UpdateContainingGrid(){}ResizeCursor(){}};var Pt=class extends Ye{constructor(e,t,r){super(e,t,!1,r),this.column_header=r.Div("treb-top-header"),this.row_header=r.Div("treb-left-header"),this.corner=r.Div("treb-corner"),this.corner_canvas=r.Create("canvas"),this.corner.appendChild(this.corner_canvas),this.contents=r.Div("treb-contents"),this.buffer_canvas=r.Create("canvas","treb-buffer-canvas",this.contents),this.grid_selection=r.SVG("svg","treb-grid-selection",this.contents),this.row_header_selection=r.SVG("svg",["frozen-selection","frozen-selection-rows"],this.column_header),this.row_header_annotations=r.Div("frozen-annotation-container frozen-annotation-container-rows",this.column_header),this.column_header_selection=r.SVG("svg",["frozen-selection","frozen-selection-columns"],this.row_header),this.column_header_annotations=r.Div("frozen-annotation-container frozen-annotation-container-columns",this.row_header),this.corner_selection=r.SVG("svg","frozen-selection",this.corner),this.corner_annotations=r.Div("frozen-annotation-container frozen-annotation-container-corner",this.corner),this.annotation_container=r.Div("treb-annotation-container"),this.grid_cover=r.Div("tile-cover grid-cover"),this.column_header_cover=r.Div("tile-cover column-header-cover"),this.row_header_cover=r.Div("tile-cover row-header-cover")}InitializeInternal(e,t){this.container=e,this.scroll_reference_node=this.container,e.appendChild(this.column_header),e.appendChild(this.row_header),e.appendChild(this.corner),e.appendChild(this.contents),e.appendChild(this.annotation_container),e.appendChild(this.grid_cover),e.appendChild(this.column_header_cover),e.appendChild(this.row_header_cover),e.appendChild(this.mock_selection),this.container.addEventListener("scroll",()=>t()),this.ApplyThemeColors()}FocusInLayout(e){return!!(e&&e instanceof Element&&this.container?.contains(e))}ResizeCursor(e){switch(e){case"row":this.row_header_cover.classList.add("resize");break;case"column":this.column_header_cover.classList.add("resize");break;default:this.row_header_cover.classList.remove("resize"),this.column_header_cover.classList.remove("resize");break}}UpdateTileGridPosition(e){e.style.gridColumn=`${e.tile_position.column+1} / ${e.tile_position.column+2}`,e.style.gridRow=`${e.tile_position.row+1} / ${e.tile_position.row+2}`}UpdateContainingGrid(){if(!this.container)throw new Error("missing container");this.header_size.width=this.header_offset.x,this.header_size.height=this.header_offset.y;let e=this.header_offset.x,t=this.header_offset.y;if(this.view.active_sheet.freeze.columns)for(let r=0;r<this.view.active_sheet.freeze.columns;r++)e+=this.ColumnWidth(r);if(this.view.active_sheet.freeze.rows)for(let r=0;r<this.view.active_sheet.freeze.rows;r++)t+=this.RowHeight(r);this.container.style.gridTemplateColumns=`${this.header_offset.x}px auto`,this.container.style.gridTemplateRows=`${this.header_offset.y}px auto`,this.corner_canvas.setAttribute("width",`${this.dpr*e}`),this.corner_canvas.setAttribute("height",`${this.dpr*t}`),this.column_header.style.height=`${t}px`,this.corner_canvas.style.width=`${e}px`,this.corner_canvas.style.height=`${t}px`}UpdateGridTemplates(){let e=0,t=0;this.column_header.style.gridTemplateColumns=this.contents.style.gridTemplateColumns=this.column_header_tiles.map(a=>(e+=a.logical_size.width,`${a.logical_size.width}px`)).join(" "),this.column_header.style.gridTemplateRows=`${this.header_offset.y}px auto`,this.row_header.style.gridTemplateRows=this.contents.style.gridTemplateRows=this.row_header_tiles.map(a=>(t+=a.logical_size.height,`${a.logical_size.height}px`)).join(" ");let r=this.header_offset.y;if(this.view.active_sheet.freeze.rows)for(let a=0;a<this.view.active_sheet.freeze.rows;a++)r+=this.RowHeight(a);this.column_header.style.height=`${r}px`,this.row_header_selection.style.display="block",this.row_header_selection.style.width=`${e}px`,this.corner_selection.style.height=this.row_header_selection.style.height=`${r}px`,this.corner_selection.style.top=this.row_header_selection.style.top="0px",this.row_header_selection.style.left="0px";let i=this.header_offset.x;if(this.view.active_sheet.freeze.columns)for(let a=0;a<this.view.active_sheet.freeze.columns;a++)i+=this.ColumnWidth(a);this.column_header_selection.style.display="block",this.corner_selection.style.width=this.column_header_selection.style.width=`${i}px`,this.column_header_selection.style.height=`${t}px`,this.column_header_selection.style.top="0px",this.corner_selection.style.left=this.column_header_selection.style.left="0px";let n={x:this.view.active_sheet.header_offset.x*this.scale,y:this.view.active_sheet.header_offset.y*this.scale},o=this.view.active_sheet.freeze;o.rows&&o.columns?(this.row_header_annotations.style.display="block",this.column_header_annotations.style.display="block",this.corner_annotations.style.display="block"):o.rows?(this.row_header_annotations.style.display="block",this.column_header_annotations.style.display="none",this.corner_annotations.style.display="none"):o.columns?(this.row_header_annotations.style.display="none",this.column_header_annotations.style.display="block",this.corner_annotations.style.display="none"):(this.row_header_annotations.style.display="none",this.column_header_annotations.style.display="none",this.corner_annotations.style.display="none"),this.row_header_annotations.style.width=`${e}px`,this.corner_annotations.style.height=this.row_header_annotations.style.height=`${r-n.y}px`,this.corner_annotations.style.top=this.row_header_annotations.style.top=`${n.y}px`,this.column_header_annotations.style.width=this.corner_annotations.style.width=`${i-n.x}px`,this.column_header_annotations.style.height=`${t}px`,this.corner_annotations.style.left=this.column_header_annotations.style.left=`${n.x}px`,this.corner_selection.style.display="block",this.grid_selection.style.width=`${e}px`,this.grid_selection.style.height=`${t}px`,this.grid_selection.style.top=`${this.header_offset.y}px`,this.grid_selection.style.left=`${this.header_offset.x}px`,this.annotation_container.style.width=`${e}px`,this.annotation_container.style.height=`${t}px`,this.annotation_container.style.top=`${this.header_offset.y}px`,this.annotation_container.style.left=`${this.header_offset.x}px`}};var Fe=class l extends ge{constructor(t,r,i){super();this.model=t;this.view=r;this.autocomplete=i;this.parser=t.parser}static FormulaChars=("$^&*(-+={[<>/~%@"+F.argument_separator).split("");active_cell;autocomplete_matcher;container_node;active_editor;nodes=[];target_address;assume_formula=!1;text_formula=!1;get selecting(){if(this.assume_formula)return!0;if(!this.text_formula)return!1;if(this.active_editor&&this.active_editor.node===this.active_editor.node.ownerDocument.activeElement){let t=this.active_editor.node.ownerDocument.defaultView,r=t.getSelection();if(r?.rangeCount){let o=r?.getRangeAt(0);if((o?.endContainer instanceof t.HTMLElement?o.endContainer:o.endContainer?.parentElement)?.dataset.reference!==void 0)return!0;if(o?.startContainer instanceof t.Text){let s=(o.startContainer.textContent?.substring(0,o.startOffset)||"").trim();if(s.length&&l.FormulaChars.includes(s[s.length-1]))return!0}else console.info("mark 21",o)}let n=this.SubstringToCaret2(this.active_editor.node)[1].trim();if(n.length){let o=n[n.length-1];return l.FormulaChars.includes(o)}}return!1}composite_dependencies=[];get dependencies(){return this.composite_dependencies}parser;FocusEditor(){this.active_editor&&this.active_editor.node.focus()}RegisterListener(t,r,i){t.node.addEventListener(r,i),t.listeners||(t.listeners=new Map),t.listeners.set(r,i)}SelectAll(t){let i=t.ownerDocument.defaultView.getSelection(),n=t.ownerDocument.createRange();n.selectNode(t),i?.removeAllRanges(),i?.addRange(n)}SetCaret(t,r){let i=t.node.ownerDocument,n=i?.defaultView,o=n.getSelection(),a=i?.createRange(),s=d=>{let u=d;for(;u&&!(u instanceof n.Text)&&u.firstChild;)u=u.firstChild;return u},c=s(t.node);if(r){let d=s(r.node);o&&a&&(a.setStart(c,t.offset),a.setEnd(d,r.offset),o.removeAllRanges(),o.addRange(a))}else o&&a&&(a.setStart(c,t.offset),a.setEnd(c,t.offset),a.collapse(!0),o.removeAllRanges(),o.addRange(a))}InsertReference(t){if(!this.active_editor)return;let r=this.active_editor.node.ownerDocument.defaultView,i=r.getSelection();if(!i)throw new Error("error getting selection");if(i.rangeCount===0)return"";let n=i.getRangeAt(0),o=this.active_editor.node.textContent||"";if(n.startContainer instanceof r.Text)if(!n.collapsed&&n.startOffset<n.endOffset){let a=this.SubstringToCaret2(this.active_editor.node);this.active_editor.node.textContent=a[0]+t+o.substring(a[1].length),this.SetCaret({node:this.active_editor.node,offset:a[0].length},{node:this.active_editor.node,offset:a[0].length+t.length})}else{let a=n.startContainer.parentElement;if(a instanceof r.HTMLElement&&a.dataset.reference)a.textContent=t,this.SetCaret({node:a,offset:t.length});else{let s=this.SubstringToCaret2(this.active_editor.node)[1],c="",d=s.trim();if(d.length){let u=d[d.length-1];l.FormulaChars.includes(u)||(s.length===d.length?c=" +":c="+")}this.active_editor.node.textContent=s+c+t+o.substring(s.length),this.SetCaret({node:this.active_editor.node,offset:s.length+t.length+c.length})}}else n.startContainer instanceof r.HTMLElement?(n.startContainer.textContent=t,this.SetCaret({node:n.startContainer,offset:t.length})):console.warn("unexpected range start container",n.startContainer);this.UpdateText(this.active_editor),this.UpdateColors(),this.active_editor.node.dispatchEvent(new Event("input",{bubbles:!0,cancelable:!0}))}UpdateColors(t=!1,r=!1){let i=new Map,n=new Map;for(let a of this.nodes)for(let s of a.references||[]){let c=this.model.AddressToLabel(s);i.has(c)||(i.set(c,s),n.set(c,n.size))}for(let a of this.nodes){for(let s of Array.from(a.node.childNodes)){let c=s.ownerDocument?.defaultView;if(c&&s instanceof c.HTMLElement&&s.dataset.reference){let d=n.get(s.dataset.reference);s.dataset.highlightIndex=typeof d=="number"?(d%5+1).toString():"?"}}a.check=a.node.innerHTML.length}let o=Array.from(i.values());!t&&JSON.stringify(this.composite_dependencies)===JSON.stringify(o)||(this.composite_dependencies=o,r||this.Publish({type:"update",dependencies:this.composite_dependencies}))}UpdateDependencies(t,r){let i=[];for(let s of r.full_reference_list||[])switch(s.type){case"address":case"range":{let c=s.type==="range"?s.start:s;c.sheet_id||(c.sheet?c.sheet_id=this.model.sheets.Find(c.sheet)?.id||0:c.sheet_id=this.view.active_sheet.id),i.push(s);break}case"structured-reference":if(this.target_address){let c=this.model.ResolveStructuredReference(s,this.target_address);c&&i.push(c)}else console.info("target address not set");break;case"identifier":{let c=this.model.GetName(s.name,this.view.active_sheet.id);c?.type==="range"&&(c.area.count===1?i.push({type:"address",...c.area.start,label:s.name,position:s.position,id:s.id}):i.push({type:"range",start:{type:"address",position:s.position,id:s.id,label:s.name,...c.area.start},end:{type:"address",position:s.position,label:s.name,id:s.id,...c.area.end},label:s.name,position:s.position,id:s.id}));break}}i.sort((s,c)=>s.position-c.position);let n=[],o=new Set,a=new Map;for(let s of i){let c=this.model.AddressToLabel(s),d=N(s)?new v(s):new v(s.start,s.end);o.has(c)||(n.push(d),o.add(c)),a.set(s.label,c)}return this.UpdateReferences(t,n),a}UpdateReferences(t,r=[]){t.node.dataset.references=JSON.stringify(r.map(i=>this.model.AddressToLabel(i))),t.references=r}UpdateText(t,r={}){let i=t.node,n=i.textContent||"",o=O.GetInstance(i.ownerDocument);if(this.text_formula=n[0]==="=",this.active_editor&&!this.assume_formula&&(this.active_editor.node.spellcheck=!this.text_formula,!this.text_formula)||n===t.formatted_text)return;let[a,s]=this.SubstringToCaret2(i),c=a.length,d=s.length;if(c===0&&d===0&&(d=n.length),!n)this.UpdateReferences(t);else{let h=this.parser.Parse(n);if(h.expression){let f=this.UpdateDependencies(t,h),m=n[0]==="="?1:0,p=0,b,g,x=0,y,w=o.Fragment(),_=(C,S="text",A="",E=!1)=>{let R=o.Text(C);if((E||(c>x||c===0&&x===0)&&c<=x+C.length)&&(b={offset:c-x,node:R}),d>x&&d<=x+C.length&&(g={offset:d-x,node:R}),S!=="text"){let z=o.Create("span",S);A&&(z.dataset.reference=A),z.appendChild(R),w.appendChild(z)}else w.appendChild(R);y=R,x+=C.length};this.parser.Walk(h.expression,C=>{if(C.type==="missing"||C.type==="group"||C.type==="dimensioned")return!0;let S=C.position+m,A=n.substring(p,S),E="",R=C.type,z="";switch(C.type){case"identifier":E=n.substring(S,S+C.name.length),z=f.get(C.name)||"";break;case"call":E=n.substring(S,S+C.name.length);break;case"literal":if(typeof C.value=="string")E=n.substring(S,S+C.value.length+2),R="string";else return!1;break;case"address":case"range":case"structured-reference":z=f.get(C.label)||"???",E=r.rewrite_addresses?C.label:n.substring(S,S+C.label.length);break;default:return!0}return _(A),_(E,R,z),p=S+E.length,C.type!=="range"}),p<n.length&&_(n.substring(p)),b||(y?b={node:y,offset:(y.data||"").length}:_("",void 0,"",!0)),i.textContent="",i.appendChild(w),b&&!r.format_only&&i===this.active_editor?.node&&this.SetCaret(b,g)}}t.formatted_text=n;let u=this.autocomplete_matcher;u&&Promise.resolve().then(()=>{let h=u.Exec({text:n,cursor:s.length});this.selecting&&h.completions?.length&&(h.completions=void 0);let f=this.NodeAtIndex(h.completions?.length?h.position||0:h.function_position||0);this.Autocomplete(h,f)})}NodeAtIndex(t){let r=this.active_editor?.node.childNodes||[];for(let i=0;i<r.length;i++){let n=r[i].textContent?.length||0;if(n>t)return r[i];t-=n}}AcceptAutocomplete(t){if(!this.active_editor)return;let r;if(t.data&&t.data.completions){for(let d of t.data.completions)if(d.name.toLowerCase()===t.value?.toLowerCase()){r=d.type;break}}let i=t.data?.position||0,n=i+(t.data?.token?.length||0),o=r==="token"?t.value:t.value+"(",a=this.active_editor.node.textContent||"",s=a.substring(0,i)+o,c=s.length;s+=a.substring(n),this.active_editor.node.textContent=s,this.SetCaret({node:this.active_editor.node,offset:c}),this.autocomplete?.Hide(),this.UpdateText(this.active_editor),this.UpdateColors()}Autocomplete(t,r){if(!this.container_node||!this.autocomplete)return;let i;r?.nodeType===Node.ELEMENT_NODE?i=r.getBoundingClientRect():i=this.container_node.getBoundingClientRect();let n=new B(Math.round(i.left),Math.round(i.top),i.width,i.height);this.autocomplete.Show(this.AcceptAutocomplete.bind(this),t,n)}SubstringToCaret2(t,r=!1){let i=["",""];if(!r&&t!==t.ownerDocument.activeElement||t!==this.active_editor?.node)return i;let o=t.ownerDocument.defaultView,a=[!1,!1],s=(d,u)=>{if(d===u.startContainer&&d===u.endContainer&&!(d instanceof o.Text)){a[0]=a[1]=!0,i[0]+=d.textContent,i[1]+=d.textContent;return}if(d===u.startContainer&&(i[0]+=(d.textContent||"").substring(0,u.startOffset),a[0]=!0),d===u.endContainer&&(i[1]+=(d.textContent||"").substring(0,u.endOffset),a[1]=!0),!(a[0]&&a[1])){if(d instanceof o.Text){let h=d.textContent||"";a[0]||(i[0]+=h),a[1]||(i[1]+=h)}else if(d.hasChildNodes()){for(let h of Array.from(d.childNodes))if(s(h,u),a[0]&&a[1])return}}},c=o.getSelection();if(c?.rangeCount??!1){let d=c?.getRangeAt(0);d&&s(t,d)}return i}};var Wo=typeof navigator>"u"?"":navigator.appVersion,Ee=typeof navigator>"u"?"":navigator.userAgent,qr=class{is_edge=/Edge/.test(Wo);is_ipad=/iPad|iPhone/.test(Ee);is_iphone=/iPhone/.test(Ee);is_android=/android|samsung/i.test(Ee);is_mobile=this.is_ipad||this.is_android;is_firefox=/firefox/i.test(Ee);is_safari=/safari/i.test(Ee)&&!/edg/i.test(Ee);is_mac=/macintosh/i.test(Ee);is_chrome=/Chrome/i.test(Ee);is_windows=/win64|win32|windows\s+nt/i.test(Ee);is_modern=!this.is_edge&&!(this.is_firefox&&this.is_android)&&/webkit|firefox/i.test(Ee)},Xo={is_edge:!1,is_ipad:!1,is_iphone:!1,is_android:!1,is_firefox:!1,is_safari:!1,is_mac:!1,is_chrome:!1,is_windows:!1,is_modern:!0,is_mobile:!1},j=typeof navigator>"u"?Xo:new qr;var Ot=class extends Fe{constructor(t,r,i,n,o){super(i,n,o);this.container=t;this.theme=r;this.container_node=t.querySelector(".treb-overlay-container"),this.edit_node=this.container_node.querySelector(".treb-overlay-editor"),j.is_firefox&&this.edit_node.classList.add("firefox"),this.edit_node.inputMode="none";let a={node:this.edit_node};this.nodes=[a],this.active_editor=a,this.RegisterListener(a,"input",s=>{if(s instanceof InputEvent&&s.isComposing)return;if(!s.isTrusted){this.reset_selection=!0;return}this.reset_selection&&this.Publish({type:"reset-selection"});let c=this.edit_node.firstChild;c&&c.tagName==="BR"&&this.edit_node.removeChild(c),this.editing&&(this.UpdateText(a),this.UpdateColors())}),this.RegisterListener(a,"keyup",s=>{s.isComposing||!this.editing||this.autocomplete&&this.autocomplete.HandleKey("keyup",s).handled}),this.edit_inset=this.container_node.querySelector(".treb-overlay-inset"),this.ClearContents()}internal_selection={target:{row:0,column:0},area:new v({row:0,column:0})};get selection(){return this.internal_selection}set selection(t){if(t){let r=t.target||t.area.start;this.internal_selection={target:{row:r.row,column:r.column},area:new v(t.area.start,t.area.end)}}else{let r={row:0,column:0};this.internal_selection={target:r,area:new v(r)}}}edit_style;reset_selection=!1;edit_node;container_node;edit_inset;scale=1;internal_editing=!1;get editing(){return this.internal_editing}set editing(t){this.internal_editing!==t&&(this.internal_editing=t,t?(this.container_node.style.opacity="1",this.container_node.style.pointerEvents="initial"):(this.container_node.style.opacity="0",this.container_node.style.pointerEvents="none"))}UpdateCaption(t=""){this.edit_node.setAttribute("aria-label",t)}Focus(t=""){this.edit_node!==this.edit_node.ownerDocument.activeElement&&(this.container_node.style.top=`${this.container.scrollTop+this.view.active_sheet.header_offset.y}px`,this.container_node.style.left=`${this.container.scrollLeft+this.view.active_sheet.header_offset.x}px`),this.edit_node.focus(),this.UpdateCaption(t)}CloseEditor(){this.editing=!1,this.reset_selection=!1,this.ClearContents(),this.edit_node.spellcheck=!0,this.autocomplete?.Hide(),this.active_cell=void 0}ClearContents(){j.is_firefox?this.edit_node.innerHTML="<span></span>":this.edit_node.textContent=""}Edit(t,r,i,n,o,a){this.Publish({type:"start-editing",editor:"ice"}),this.active_cell=i,this.target_address={...t.target},this.reset_selection=!1;let s=JSON.parse(JSON.stringify(i.style||{}));this.edit_style=a,a?.font_face&&(s.font_face=a.font_face);let c=I.CompositeFont(this.theme.grid_cell_font_size,s,this.scale,this.theme);switch(this.edit_node.style.font=c.font,c.variants?this.edit_node.style.fontVariant=c.variants:this.edit_node.style.fontVariant="",this.edit_node.style.color=D(this.theme,s.text,1),this.edit_inset.style.backgroundColor=D(this.theme,s.fill,0),s.horizontal_align){case"right":this.container_node.classList.remove("align-center","align-left"),this.container_node.classList.add("align-right");break;case"center":this.container_node.classList.remove("align-right","align-left"),this.container_node.classList.add("align-center");break;default:this.container_node.classList.remove("align-right","align-center"),this.container_node.classList.add("align-left");break}this.edit_node.style.paddingBottom=`${Math.max(0,(self.devicePixelRatio||1)-1)}px`;let d=n?.toString()||"";d&&d[0]==="="&&(this.edit_node.spellcheck=!1),r.ApplyStyle(this.container_node);let u=j.is_mac?0:.5;if(this.edit_node.style.bottom=u.toFixed(2)+"px",this.autocomplete?.ResetBlock(),this.selection=t,typeof n<"u"){let h=d[0]!=="="&&d[d.length-1]==="%",f=d.length;this.edit_node.textContent=d,this.SetCaret({node:this.edit_node,offset:f-(h?1:0)})}this.editing=!0,Promise.resolve().then(()=>{this.active_editor&&(this.active_editor.formatted_text=void 0,this.UpdateText(this.active_editor),this.UpdateColors()),!o&&n!==void 0&&this.Publish({type:"update",text:n.toString(),dependencies:this.composite_dependencies})})}GetEditState(){let t=this.active_editor?.node?.textContent||"",r="";return this.active_editor?.node&&(r=this.SubstringToCaret2(this.active_editor.node,!0)[0]),{text:t,substring:r}}HandleKeyDown(t){if(this.editing){if(this.autocomplete){let r=this.autocomplete.HandleKey("keydown",t);if(r.accept&&this.AcceptAutocomplete(r),r.handled)return"handled"}switch(t.key){case"Enter":case"Tab":return"commit";case"Escape":case"Esc":return"discard";case"ArrowUp":case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"Up":case"Down":case"Left":case"Right":return this.selecting?void 0:"commit"}return"handled"}}UpdateScale(t){this.scale=t}};var Bi=new Map,Qe,Ge=(l,e)=>{let t=l,r=Bi.get(t);return r||(r=Ko(l,e),Bi.set(t,r),r)};var Ko=(l,e)=>{Qe||typeof document<"u"&&(Qe=document.createElement("canvas")),Qe&&(e?Qe.style.fontVariant=e:Qe.style.fontVariant="");let t=Qe?.getContext("2d",{alpha:!1});if(!t)throw new Error("invalid context");t.textBaseline="alphabetic",t.textAlign="center",t.font=l;let r=t.measureText("("),i=r.actualBoundingBoxRight+r.actualBoundingBoxLeft;r=t.measureText("#");let n=r.actualBoundingBoxRight+r.actualBoundingBoxLeft;return r=t.measureText("Mljy!"),{paren:i,hash:n,ascent:r.fontBoundingBoxAscent,descent:r.fontBoundingBoxDescent,height:r.fontBoundingBoxAscent+r.fontBoundingBoxDescent}};var Yo=" ",Ht=class{constructor(e,t,r,i,n){this.theme=e;this.layout=t;this.model=r;this.view=i;this.options=n;this.buffer_canvas=t.buffer_canvas,this.buffer_canvas.width=this.buffer_canvas_size.width,this.buffer_canvas.height=this.buffer_canvas_size.height;let o=this.buffer_canvas.getContext("2d",{alpha:!1});if(o){let a=this.layout.dpr;this.buffer_context=o,this.buffer_context.setTransform(a,0,0,a,0,0),this.buffer_context.textAlign="left",this.buffer_context.textBaseline="alphabetic"}}cell_edge_buffer=4;overflow_areas=[];buffer_canvas;buffer_context;buffer_canvas_size={width:256,height:256};FlushOverflows(){let e=this.view.active_sheet.cells;for(let t of e.Iterate())t.renderer_data?.overflowed&&(t.renderer_data=void 0,t.render_clean[this.view.view_index]=!1);for(let t of this.overflow_areas)t.tile.dirty=!0;this.overflow_areas=[]}MeasureText(e,t,r){let i=this.layout.grid_tiles[0][0],n=r??this.layout.scale,o=e.style||{},a=I.CompositeFont(this.theme.grid_cell_font_size,o,n,this.theme),s=Ge(a.font,a.variants),c={base:a.font,strong:I.CompositeFont(this.theme.grid_cell_font_size,{...o,bold:!0},n,this.theme).font,emphasis:I.CompositeFont(this.theme.grid_cell_font_size,{...o,italic:!0},n,this.theme).font,strong_emphasis:I.CompositeFont(this.theme.grid_cell_font_size,{...o,bold:!0,italic:!0},n,this.theme).font};a.variants?i.style.fontVariant=a.variants:i.style.fontVariant="";let d=i.getContext("2d",{alpha:!1});if(!d)throw new Error("context failed");let u=this.PrepText(d,c,e,t),h=u.width,f=s.height*u.strings.length;return{width:h,height:f}}EnsureBuffer(e=0,t=0,r=0){let i=this.layout.dpr;if(e=e*i,t=t*i,r=r*i,e>this.buffer_canvas_size.width||t>this.buffer_canvas_size.height){this.buffer_canvas_size.width=Math.max(Math.ceil(e/256)*256,this.buffer_canvas_size.width),this.buffer_canvas_size.height=Math.max(Math.ceil(t/256)*256,this.buffer_canvas_size.height),this.buffer_canvas.width=this.buffer_canvas_size.width,this.buffer_canvas.height=this.buffer_canvas_size.height;let n=this.buffer_canvas.getContext("2d",{alpha:!1});n&&(this.buffer_context=n,this.buffer_context.textAlign="left",this.buffer_context.textBaseline="alphabetic")}this.buffer_context.setTransform(i,0,0,i,r,0)}OverflowDirty(e=!1){let t=[];for(let r of this.overflow_areas){let i=r.area.start.row,n=e;if(!n)for(let o=r.area.start.column;!n&&o<=r.area.end.column;o++){let a=this.view.active_sheet.cells.GetCell({row:i,column:o},!1);n=!!(a&&!a.render_clean[this.view.view_index])}if(n){for(let o=r.area.start.column;o<=r.area.end.column;o++){let a=this.view.active_sheet.cells.GetCell({row:i,column:o},!1);a&&(a.render_clean[this.view.view_index]=!1,a.renderer_data&&a.renderer_data.overflowed&&(a.renderer_data=void 0))}r.tile.dirty=!0}else t.push(r)}this.overflow_areas=t}RenderCorner(){let t=this.layout.corner_canvas.getContext("2d",{alpha:!1});if(!t)throw new Error("invalid context");let r=I.CompositeFont(this.theme.grid_cell_font_size,this.theme.headers||{},this.layout.scale,this.theme),i=Ge(r.font,r.variants),n=this.layout.dpr,o=this.layout.header_offset,a=o.x;for(let c=0;c<this.view.active_sheet.freeze.columns;c++)a+=this.layout.ColumnWidth(c);let s=o.y;for(let c=0;c<this.view.active_sheet.freeze.rows;c++)s+=this.layout.RowHeight(c);t.setTransform(n,0,0,n,0,0),t.fillStyle=this.theme.headers?.fill?D(this.theme,this.theme.headers.fill):"",t.fillRect(0,0,a,o.y),t.fillRect(0,0,o.x,s),t.strokeStyle=this.theme.headers_grid_color||"",t.beginPath(),t.moveTo(o.x-.5,0),t.lineTo(o.x-.5,o.y),t.moveTo(0,o.y-.5),t.lineTo(o.x,o.y-.5),t.stroke(),!(!this.view.active_sheet.freeze.columns&&!this.view.active_sheet.freeze.rows)&&(t.strokeStyle=this.theme.grid_color||"",t.beginPath(),s!==o.y&&(t.moveTo(o.x-.5,o.y),t.lineTo(o.x-.5,s)),a!==o.x&&(t.moveTo(o.x,o.y-.5),t.lineTo(a,o.y-.5)),t.stroke(),t.strokeStyle=this.theme.headers_grid_color||"",t.textAlign="center",t.textBaseline="middle",t.font=r.font,t.fillStyle=D(this.theme,this.theme.headers?.text),this.view.active_sheet.freeze.rows&&this.layout.header_offset.x>1&&(t.setTransform(n,0,0,n,0,0),t.translate(0,o.y),t.beginPath(),t.moveTo(0,0-.5),t.lineTo(o.x,0-.5),t.stroke(),this.RenderRowLabels(t,0,this.view.active_sheet.freeze.rows-1,i.height)),this.view.active_sheet.freeze.columns&&this.layout.header_offset.y>1&&(t.setTransform(n,0,0,n,0,0),t.translate(o.x,0),t.beginPath(),t.moveTo(0-.5,0),t.lineTo(0-.5,o.y),t.stroke(),this.RenderColumnLabels(t,0,this.view.active_sheet.freeze.columns-1)))}RenderColumnLabels(e,t,r){let i=this.layout.header_offset.y;if(!(i<=1)){for(e.fillStyle=D(this.theme,this.theme.headers?.text,0),e.beginPath();t<=r;t++){let n=this.layout.ColumnWidth(t),o=v.ColumnToLabel(t),a=e.measureText(o);n>a.width&&e.fillText(o,n/2,i/2+1),e.moveTo(n-.5,0),e.lineTo(n-.5,i),e.translate(n,0)}e.stroke()}}RenderRowLabels(e,t,r,i){let n=this.layout.header_offset.x;if(!(n<=1)){for(e.fillStyle=D(this.theme,this.theme.headers?.text,0),e.beginPath();t<=r;t++){let o=this.layout.RowHeight(t);o>=i*1.2&&e.fillText(`${t+1}`,n/2,o/2+1),e.moveTo(0,o-.5),e.lineTo(n,o-.5),e.translate(0,o)}e.stroke()}}RenderHeaders(e,t=!1){let r=this.layout.dpr,i=this.layout.header_offset,n=I.CompositeFont(this.theme.grid_cell_font_size,this.theme.headers||{},this.layout.scale,this.theme),o=Ge(n.font,n.variants);for(let a=e.start.column;a<=e.end.column;a++){let s=this.layout.column_header_tiles[a];if(s.dirty||t){let c=s.getContext("2d",{alpha:!1});if(!c)continue;c.setTransform(r,0,0,r,0,0),c.textAlign="center",c.textBaseline="middle",c.font=n.font,n.variants?s.style.fontVariant=n.variants:s.style.fontVariant="",c.fillStyle=this.theme.headers?.fill?D(this.theme,this.theme.headers.fill):"",c.fillRect(0,0,s.logical_size.width,this.layout.header_offset.y),c.strokeStyle=this.theme.headers_grid_color||"",c.beginPath(),c.moveTo(0,i.y-.5),c.lineTo(s.logical_size.width,i.y-.5),c.stroke(),c.strokeStyle=this.theme.headers_grid_color||"",this.RenderColumnLabels(c,s.first_cell.column,s.last_cell.column),s.dirty=!1}}for(let a=e.start.row;a<=e.end.row;a++){let s=this.layout.row_header_tiles[a];if(s.dirty||t){let c=s.getContext("2d",{alpha:!1});if(!c)continue;c.fillStyle=this.theme.headers?.fill?D(this.theme,this.theme.headers.fill):"",c.setTransform(r,0,0,r,0,0),c.textAlign="center",c.textBaseline="middle",c.font=n.font,n.variants?s.style.fontVariant=n.variants:s.style.fontVariant="",c.fillRect(0,0,this.layout.header_offset.x,s.logical_size.height),c.strokeStyle=this.theme.headers_grid_color||"",c.beginPath(),c.moveTo(i.x-.5,0),c.lineTo(i.x-.5,s.logical_size.height),c.stroke(),c.strokeStyle=this.theme.headers_grid_color||"",this.RenderRowLabels(c,s.first_cell.row,s.last_cell.row,o.height),s.dirty=!1}}(this.view.active_sheet.freeze.rows||this.view.active_sheet.freeze.columns)&&this.RenderCorner()}CopyToAdjacent(e,t,r,i,n,o,a){let s=this.layout.AdjacentTile(e,i,r);if(!s)return;let c=n,d=o;r>0?c=n-(e.pixel_end.x-e.pixel_start.x)*t:r<0&&(c=n+(s.pixel_end.x-s.pixel_start.x)*t),i>0&&(d=o-(e.pixel_end.y-e.pixel_start.y)*t);let u=s.getContext("2d",{alpha:!1});u&&(u.setTransform(t,0,0,t,c,d),u.drawImage(this.buffer_canvas,0,0,(a.width||0)*t,(a.height||0)*t,a.left||0,0,a.width||0,a.height||0))}Render(e){let t=e.getContext("2d",{alpha:!1});if(!t)return;t.textBaseline="alphabetic";let r=this.layout.dpr;t.setTransform(r,0,0,r,0,0);let i=0,n=0;for(let s=e.first_cell.column;s<=e.last_cell.column;s++){let c=this.layout.ColumnWidth(s);if(c){n=0;for(let d=e.first_cell.row;d<=e.last_cell.row;d++){let u=this.layout.RowHeight(d);if(u){t.setTransform(r,0,0,r,i,n);let h=this.view.active_sheet.CellData({row:d,column:s});if(e.needs_full_repaint||!h.render_clean[this.view.view_index]){let f=this.RenderCell(e,h,t,{row:d,column:s},c,u,e.pixel_start.x+i,e.pixel_start.y+n);f.tile_overflow_right&&this.CopyToAdjacent(e,r,1,0,i,n,f),f.tile_overflow_left&&this.CopyToAdjacent(e,r,-1,0,i,n,f),f.tile_overflow_bottom&&this.CopyToAdjacent(e,r,0,1,i,n,f)}}n+=u*r}i+=c*r}}if(!this.view.active_sheet.freeze.rows&&!this.view.active_sheet.freeze.columns)return;let o=0,a=0;if(e.first_cell.row<=this.view.active_sheet.freeze.rows-1)for(let s=e.first_cell.row;s<this.view.active_sheet.freeze.rows&&s<=e.last_cell.row;s++)o+=this.layout.RowHeight(s);if(e.first_cell.column<=this.view.active_sheet.freeze.columns-1)for(let s=e.first_cell.column;s<this.view.active_sheet.freeze.columns&&s<=e.last_cell.column;s++)a+=this.layout.ColumnWidth(s);if(o){let s=this.layout.frozen_row_tiles[e.tile_position.column];if(!s)throw new Error("can't find matching header tile");let c=s.getContext("2d",{alpha:!0});if(!c)throw new Error("header context failed");c.setTransform(r,0,0,r,0,0),c.drawImage(e,0,0,e.logical_size.width*r,o*r,0,0,e.logical_size.width,o)}if(a){let s=this.layout.frozen_column_tiles[e.tile_position.row];if(!s)throw new Error("can't find matching header tile");let c=s.getContext("2d",{alpha:!0});if(!c)throw new Error("header context failed");c.setTransform(r,0,0,r,0,0),c.drawImage(e,0,0,a*r,e.logical_size.height*r,0,0,a,e.logical_size.height)}if(a&&o){let s=this.layout.corner_canvas.getContext("2d",{alpha:"false"});if(!s)throw new Error("corner context failed");s.setTransform(r,0,0,r,this.layout.header_offset.x*r,this.layout.header_offset.y*r),s.drawImage(e,0,0,a*r,o*r,0,0,a,o)}}PrepText(e,t,r,i){let n=[],o=r.style||{},a,s=0;if(r.rendered_type===4){let f=r.calculated_type?r.calculated:r.value;r.formatted=f?this.model.language_model?.boolean_true||"TRUE":this.model.language_model?.boolean_false||"FALSE"}let c,d=r.editing?"":r.formatted;Array.isArray(d)&&(d=d.filter(f=>f.flag!==8));let u="",h;if(o.indent){for(let f=0;f<o.indent;f++)u+=Yo;h=o.horizontal_align,h||(h=r.type===3||r.calculated_type===3||r.type===8||r.calculated_type===8?"right":"left")}if(Array.isArray(d)){u&&(h==="right"?d.push({text:u,flag:8}):(h==="left"||typeof h>"u")&&d.unshift({text:u,flag:8}));for(let f of d){if(f.flag===6){c=f.text;continue}let m=e.measureText(f.text).width,p={width:m,text:f.text,hidden:f.flag===1};n.push(p),f.flag===2?a=p:s+=m}if(a){let f=a.text,m=a.width,p=i-s-2*this.cell_edge_buffer;if(a.width=Math.max(0,p),p>0){let b=Math.floor(p/m);for(let g=1;g<b;g++)a.text+=f;s=i-2*this.cell_edge_buffer}else a.text=""}return{strings:[n],format:c,width:s}}else if(d){r.type===2&&d[0]==="'"&&(d=d.slice(1));let f;this.options.markdown?f=Ie.instance.Parse(d):(f=Ie.instance.Dummy(d),e.font=t.base);let m=0,p=i-2*this.cell_edge_buffer,b=[];if(o.wrap){let g=u&&o.horizontal_align!=="center"?e.measureText(u).width:0;p-=g;for(let x of f){for(let w=1;w<x.length;w++){let _=x[w].text.match(/^(\s+)/);_&&(x[w-1].text+=_[1],x[w].text=x[w].text.replace(/^\s+/,""))}let y=[];for(let w of x){this.options.markdown&&(w.strong&&w.emphasis?e.font=t.strong_emphasis:w.strong?e.font=t.strong:w.emphasis?e.font=t.emphasis:e.font=t.base);let _=w.text.match(/\S+\s*/g);if(_&&_.length)for(let C of _){let S=e.measureText(C.trim()).width,A=e.measureText(C).width;y.push({part:w,text:C,trimmed:S,width:A})}}for(;y.length;){let w=y.shift(),_=[w],C=w.trimmed;for(;C<p&&y.length;){let A=y[0],E=C-w.trimmed+w.width+A.trimmed;if(E>=p)break;w=A,_.push(A),C=E,y.shift(),m=Math.max(m,C)}w.text=w.text.trim(),w.width=w.trimmed,m=Math.max(m,w.width);let S=_.map(A=>({...A.part,hidden:!1,width:A.width,text:A.text}));o.indent&&(h==="right"?S.push({text:u,hidden:!1,width:g}):h==="left"&&S.unshift({text:u,hidden:!1,width:g})),b.push(S)}}}else for(let g of f){let x=[];o.indent&&(h==="right"?g.push({text:u}):h==="left"&&g.unshift({text:u}));let y=0;for(let w of g){this.options.markdown&&(w.strong&&w.emphasis?e.font=t.strong_emphasis:w.strong?e.font=t.strong:w.emphasis?e.font=t.emphasis:e.font=t.base);let _=e.measureText(w.text).width;y+=_,x.push({...w,hidden:!1,width:_})}m=Math.max(m,y),b.push(x)}return{strings:b,width:m}}return{strings:[[{text:"",hidden:!1,width:0}]],width:0}}ResolveColors(e){let t={...e};return t.text={text:D(this.theme,e.text,1)},t}RenderCellBorders(e,t,r,i=0,n=0,o=0,a=0){let s=this.view.active_sheet.SurroundingStyle(e,this.theme.table),c=D(this.theme,s[8].fill);c&&(t.fillStyle=c,t.fillRect(i+0,n-1,o,1)),c=D(this.theme,s[4].fill),c&&(t.fillStyle=c,t.fillRect(i-1,n,1,a)),c=D(this.theme,r.fill),c&&(t.fillStyle=c,t.fillRect(i-1,n-1,o+1,a+1)),c=D(this.theme,s[6].fill),c&&(t.fillStyle=c,t.fillRect(i+o-1,n-1,1,a+1)),c=D(this.theme,s[2].fill),c&&(t.fillStyle=c,t.fillRect(i-1,n+a-1,o+1,1)),s[6].border_top&&!s[6].border_left&&(t.fillStyle=D(this.theme,s[6].border_top_fill,1),t.fillRect(i+o-1,n-2+s[6].border_top,1,1)),s[9].border_left&&(t.fillStyle=D(this.theme,s[9].border_left_fill,1),t.fillRect(i+o-1,n-1,1,1)),s[9].border_bottom&&(t.fillStyle=D(this.theme,s[9].border_bottom_fill,1),t.fillRect(i+o-1,n-2+s[9].border_bottom,1,1)),s[4].border_top&&!s[4].border_right&&(t.fillStyle=D(this.theme,s[4].border_right_fill,1),t.fillRect(i-1,n-2+s[4].border_top,1,1)),s[7].border_right&&(t.fillStyle=D(this.theme,s[7].border_right_fill,1),t.fillRect(i-1,n-1,1,1)),s[7].border_bottom&&(t.fillStyle=D(this.theme,s[7].border_bottom_fill,1),t.fillRect(i-1,n-2+s[7].border_bottom,1,1)),s[6].border_bottom&&!s[6].border_left&&(t.fillStyle=D(this.theme,s[6].border_bottom_fill,1),t.fillRect(i+o-1,n+a-s[6].border_bottom,1,1)),s[3].border_left&&(t.fillStyle=D(this.theme,s[3].border_left_fill,1),t.fillRect(i+o-1,n+a-1,1,1)),s[3].border_top&&(t.fillStyle=D(this.theme,s[3].border_top_fill,1),t.fillRect(i+o-1,n+a-s[3].border_top,1,1)),s[4].border_bottom&&!s[4].border_right&&(t.fillStyle=D(this.theme,s[4].border_bottom_fill,1),t.fillRect(i-1,n+a-s[4].border_bottom,1,1)),s[1].border_right&&(t.fillStyle=D(this.theme,s[1].border_right_fill,1),t.fillRect(i-1,n+a-1,1,1)),s[1].border_top&&(t.fillStyle=D(this.theme,s[1].border_top_fill,1),t.fillRect(i-1,n+a-s[1].border_top,1,1)),s[8].border_bottom&&(t.fillStyle=D(this.theme,s[8].border_bottom_fill,1),s[8].border_bottom===2&&(t.fillRect(i-1,n-2,o+1,1),t.fillRect(i-1,n-0,o+1,1),t.fillStyle=D(this.theme,s[8].fill)||D(this.theme,this.theme.grid_cell?.fill,0)||"#fff"),t.fillRect(i-1,n-1,o+1,1)),s[4].border_right&&(t.fillStyle=D(this.theme,s[4].border_right_fill,1),t.fillRect(i-1,n-1,1,a+1)),s[6].border_left&&(t.fillStyle=D(this.theme,s[6].border_left_fill,1),t.fillRect(i+o-1,n-1,1,a+1)),s[2].border_top&&(t.fillStyle=D(this.theme,s[2].border_top_fill,1),s[2].border_top===2&&(t.fillRect(i-1,n+a-2,o+1,1),t.fillRect(i-1,n+a-0,o+1,1),t.fillStyle=D(this.theme,s[2].fill)||D(this.theme,this.theme.grid_cell?.fill,0)||"#fff"),t.fillRect(i-1,n+a-1,o+1,1)),r.border_top&&(t.fillStyle=D(this.theme,r.border_top_fill,1),r.border_top===2&&(t.fillRect(i-1,n-2,o+1,1),t.fillRect(i-1,n+0,o+1,1),t.fillStyle=D(this.theme,r.fill)||D(this.theme,this.theme.grid_cell?.fill,0)||"#fff"),t.fillRect(i-1,n-1,o+1,1)),r.border_left&&(t.fillStyle=D(this.theme,r.border_left_fill,1),t.fillRect(i-1,n-1,1,a+1)),r.border_right&&(t.fillStyle=D(this.theme,r.border_right_fill,1),t.fillRect(i+o-1,n-1,1,a+1)),r.border_bottom&&(t.fillStyle=D(this.theme,r.border_bottom_fill,1),r.border_bottom===2&&(t.fillRect(i-1,n+a-2,o+1,1),t.fillRect(i-1,n+a+0,o+1,1),t.fillStyle=D(this.theme,r.fill)||D(this.theme,this.theme.grid_cell?.fill,0)||"#fff"),t.fillRect(i-1,n+a-1,o+1,1))}PaintBackgroundImage(e,t,r,i,n,o,a=0,s=0,c=0){if(!t.width||!t.height)return;let d=(this.layout.scale||1)*this.layout.dpr,u=r/d%t.width,h=i/d%t.height,f=n/d,m=o/d,p=u+f>t.width,b=h+m>t.height;p&&e.drawImage(t,u-t.width,h,f,m,a,s,n-c,o-c),b&&e.drawImage(t,u,h-t.height,f,m,a,s,n-c,o-c),p&&b&&e.drawImage(t,u-t.width,h-t.height,f,m,a,s,n-c,o-c),e.drawImage(t,u,h,f,m,a,s,n-c,o-c)}RenderCellBackground(e,t,r,i,n,o,a=0,s=0){if(r.fillStyle=this.theme.grid_color,r.fillRect(0,0,n,o),this.view.active_sheet.image)this.PaintBackgroundImage(r,this.view.active_sheet.image,a,s,n,o,0,0,1);else{let c=D(this.theme,i.fill);c?(r.fillStyle=c,r.fillRect(0,0,n-1,o-1)):(r.fillStyle=D(this.theme,this.theme.grid_cell?.fill,0)||"#fff",r.fillRect(0,0,n-1,o-1))}this.RenderCellBorders(t,r,i,0,0,n,o),e&&(r.fillStyle=this.theme.note_marker_color,r.beginPath(),r.moveTo(n-2,1),r.lineTo(n-2-8,1),r.lineTo(n-2,9),r.lineTo(n-2,1),r.fill())}RenderCell(e,t,r,i,n,o,a=0,s=0){let c={},d=!t.render_clean[this.view.view_index];if(t.render_clean[this.view.view_index]=!0,e.needs_full_repaint&&t.renderer_data?.overflowed)return{};let u=t.style?{...t.style}:{};if(t.table&&(u=this.view.active_sheet.CellStyleData(i,t.table.theme||this.theme.table)||{}),t.merge_area)if(i.row===t.merge_area.start.row&&i.column===t.merge_area.start.column){for(let T=t.merge_area.start.column+1;T<=t.merge_area.end.column;T++)n+=this.layout.ColumnWidth(T);for(let T=t.merge_area.start.row+1;T<=t.merge_area.end.row;T++)o+=this.layout.RowHeight(T);if(t.merge_area.count>1){let T=this.view.active_sheet.CellStyleData(t.merge_area.end);T&&(u.border_bottom=T.border_bottom,u.border_right=T.border_right,u.border_bottom_fill=T.border_bottom_fill,u.border_right_fill=T.border_right_fill)}t.merge_area.end.column>e.last_cell.column&&(c.tile_overflow_right=!0),t.merge_area.end.row>e.last_cell.row&&(c.tile_overflow_bottom=!0),(c.tile_overflow_bottom||c.tile_overflow_right)&&this.overflow_areas.push({tile:e,head:{...i},area:new v(t.merge_area.start,t.merge_area.end)})}else return{};let h=!!t.hyperlink;if(t.render_function){this.RenderCellBackground(!!t.note,i,r,u,n,o),r.strokeStyle=r.fillStyle=D(this.theme,u.text,1);let T=this.ResolveColors(u);if(t.render_function.call(void 0,{width:n,height:o,context:r,cell:t,style:T,scale:this.layout.scale||1}).handled)return c}let f=I.CompositeFont(this.theme.grid_cell_font_size,u,this.layout.scale,this.theme),m={base:f.font,strong:I.CompositeFont(this.theme.grid_cell_font_size,{...u,bold:!0},this.layout.scale,this.theme).font,emphasis:I.CompositeFont(this.theme.grid_cell_font_size,{...u,italic:!0},this.layout.scale,this.theme).font,strong_emphasis:I.CompositeFont(this.theme.grid_cell_font_size,{...u,bold:!0,italic:!0},this.layout.scale,this.theme).font};if(f.variants?e.style.fontVariant=f.variants:e.style.fontVariant="",r.font=m.base,d||!t.renderer_data||t.renderer_data.width!==n||t.renderer_data.height!==o){let T=this.PrepText(r,m,t,n);t.renderer_data={text_data:T,width:n,height:o}}let p=t.renderer_data.text_data,b=p.width>n-2*this.cell_edge_buffer,g=n,x=0,y=!1,w=t.type===3||t.calculated_type===3||t.type===8||t.calculated_type===8||t.type===10||t.calculated_type===10,_=u.horizontal_align;_||(_=w?"right":"left");let C=[];if(b)if(t.type!==3&&t.calculated_type!==3&&!u.wrap&&!t.merge_area){let q=p.width-n+this.cell_edge_buffer,se=0,Y=0;_==="center"?se=Y=q/2:_==="right"?se=q:Y=q;let J=i.column,k=i.column;for(;Y>0&&J<this.layout.last_column;){J++;let P={row:i.row,column:J},Z=this.view.active_sheet.CellData(P),pe=this.layout.ColumnWidth(J);if(Y-=pe,Z&&!Z.type&&!Z.calculated_type)C.push({address:P,cell:Z,grid:new B(g,0,pe,o),background:new B(g-1,0,pe,o-1),border:new B(g,0,pe,o)}),g+=pe,Z.render_clean[this.view.view_index]=!0,Z.renderer_data={overflowed:!0};else{y=!0;break}}for(J>e.last_cell.column&&(c.tile_overflow_right=!0);se>0&&k>=1;){k--;let P={row:i.row,column:k},Z=this.view.active_sheet.CellData(P),pe=this.layout.ColumnWidth(k);if(se-=pe,Z&&!Z.type&&!Z.calculated_type)x-=pe,C.push({address:P,cell:Z,grid:new B(x,0,pe,o),background:new B(x,0,pe,o-1),border:new B(x,0,pe,o)});else{y=!0;break}}k<e.first_cell.column&&(c.tile_overflow_left=!0),this.overflow_areas.push({head:{...i},tile:e,area:new v({row:i.row,column:k},{row:i.row,column:J})})}else y=!w;let S=!1,A=r;(c.tile_overflow_bottom||c.tile_overflow_left||c.tile_overflow_right)&&(S=!0,c.width=g-x,c.height=o,c.left=x,this.EnsureBuffer(c.width+1,o+1,-x),r=this.buffer_context,r.font=m.base),this.RenderCellBackground(!!t.note,i,r,u,n,o,a,s);for(let T of C)T.cell.style?.fill&&Ti(T.cell.style.fill)&&!this.options.grid_over_background?(r.fillStyle=D(this.theme,T.cell.style.fill,0),r.fillRect(T.grid.left,T.grid.top,T.grid.width,T.grid.height)):(r.fillStyle=this.theme.grid_color||"",r.fillRect(T.grid.left,T.grid.top,T.grid.width,T.grid.height),this.view.active_sheet.image?this.PaintBackgroundImage(r,this.view.active_sheet.image,a+T.background.left,s+T.background.top,T.background.width,T.background.height,T.background.left,T.background.top,0):(r.fillStyle=this.theme.grid_cell?.fill?D(this.theme,this.theme.grid_cell.fill,0):"",r.fillRect(T.background.left,T.background.top,T.background.width,T.background.height))),T.cell.style&&this.RenderCellBorders(T.address,r,T.cell.style,T.border.left,T.border.top,T.border.width,T.border.height);if(u.databar&&o>7&&n>9){let T=u.databar;if(T){let q={x:4,y:3};r.fillStyle=D(this.theme,T.fill);let se=q.y,Y=o-(q.y*2+1),J=q.x,k=0;T.zero>0?(J=J+T.zero*(n-(q.x*2+1)),T.value>T.zero?k=(n-(q.x*2+1))*(T.value-T.zero):(T.negative&&(r.fillStyle=D(this.theme,T.negative)),k=(n-(q.x*2+1))*(T.zero-T.value),J-=k)):k=(n-(q.x*2+1))*T.value,r.fillRect(J,se,k,Y)}}let E=Ge(m.base,f.variants);r.lineWidth=1,r.strokeStyle=r.fillStyle=p.format?p.format:D(this.theme,u.text,1),r.beginPath();let R=this.cell_edge_buffer,z=1,K=p.strings.length,ie=K*E.height*z;y=(y||ie>=o)&&!S,y&&(r.save(),r.beginPath(),r.moveTo(x+1.5,0),r.lineTo(x+1.5,o),r.lineTo(g-1.5,o),r.lineTo(g-1.5,0),r.clip()),r.beginPath();let me=Math.round(o-E.descent-2+-z*E.height*(K-1));switch(u.vertical_align){case"top":me=Math.round(2+E.ascent);break;case"middle":me=Math.round((o-ie)/2+E.ascent)-1.5;break}if(!u.databar?.hide_values)if((t.type===3||t.calculated_type===3||t.type===8||t.calculated_type===8)&&b){let T=Math.floor((n-2*this.cell_edge_buffer)/E.hash),q="";for(let Y=0;Y<T;Y++)q+="#";let se=r.measureText(q).width;_==="center"?R=Math.round((n-se)/2):_==="right"&&(R=n-this.cell_edge_buffer-se),r.fillText(q,R,me)}else{let T=me;for(let q of p.strings){let se=0;for(let P of q)se+=P.width;_==="center"?R=Math.round((n-se)/2):_==="right"&&(R=n-this.cell_edge_buffer-se);let Y=T+2.5,J=Math.floor(T-E.ascent*1/3)+.5,k=R;for(let P of q)P.strong&&P.emphasis?r.font=m.strong_emphasis:P.strong?r.font=m.strong:P.emphasis?r.font=m.emphasis:r.font=m.base,P.hidden||(P.text&&r.fillText(P.text,k,T),u.underline&&(r.moveTo(k,Y),r.lineTo(k+P.width,Y)),(u.strike||P.strike)&&(r.moveTo(k,J),r.lineTo(k+P.width,J)),h&&(P.left=k,P.top=T-E.ascent,P.height=E.height)),k+=P.width;T+=z*E.height}}if(r.stroke(),y)r.restore();else if(S){let T=this.layout.dpr;A.drawImage(this.buffer_canvas,0,0,(c.width||0)*T,o*T,x,0,c.width||0,o)}return c}};var Gt=class extends Fe{constructor(t,r,i,n,o){super(r,i,o);this.options=n;let a=O.GetInstance(t.ownerDocument),s=t.querySelector(".treb-formula-bar");s.removeAttribute("hidden"),this.address_label_container=s.querySelector(".treb-address-label"),this.address_label=this.address_label_container.firstElementChild,this.InitAddressLabel(),this.container_node=t.querySelector(".treb-editor-container");let c=this.container_node.firstElementChild,d={node:c};if(this.active_editor=d,this.nodes=[d],c&&this.RegisterListener(d,"input",u=>{u.isTrusted&&(this.UpdateText(d),this.UpdateColors())}),this.active_editor.node.spellcheck=!1,this.RegisterListener(d,"focusin",()=>{let u=this.tolled!==void 0;if(this.tolled=void 0,!this.active_editor)return;let h=this.active_editor.node.textContent||"";if(this.shadow&&(this.shadow=!1,h="",this.active_editor.node.textContent=h,this.active_editor.formatted_text=void 0),h[0]==="{"&&h[h.length-1]==="}"&&(h=h.substring(1,h.length-1),this.active_editor.node.textContent=h,this.active_editor.formatted_text=void 0),this.autocomplete?.ResetBlock(),this.UpdateText(this.active_editor),this.UpdateColors(void 0,!0),u){let f=this.NodeAtIndex(h.length-1);f&&this.SetCaret({node:f,offset:(f.textContent||"").length})}this.committed=!1,this.Publish([{type:"start-editing",editor:"formula-bar"},{type:"update",text:h,cell:this.active_cell,dependencies:this.composite_dependencies}]),this.focused_=!0}),this.RegisterListener(d,"focusout",u=>{let h=u.relatedTarget instanceof HTMLElement&&u.relatedTarget.dataset.tollEditor;this.selecting&&console.info("focusout, but selecting..."),this.autocomplete?.Hide();let f=(this.active_editor?this.GetTextContent(this.active_editor.node).join(""):"").trim();if(h){let m=f;this.active_editor?.node&&(m=this.SubstringToCaret2(this.active_editor.node,!0)[0]),this.committed=!0,this.tolled={text:f,substring:m},this.Publish({type:"toll",value:f})}else this.committed?this.Publish([{type:"stop-editing"}]):(this.committed=!0,this.Publish({type:"commit",value:f}));this.Publish([{type:"stop-editing"}]),this.focused_=!1,this.active_editor&&(this.active_editor.node.spellcheck=!1)}),this.RegisterListener(d,"keydown",this.FormulaKeyDown.bind(this)),this.RegisterListener(d,"keyup",this.FormulaKeyUp.bind(this)),this.options.expand_formula_button){let u;this.expand_button=a.Create("button","expand-button",s,{events:{focus:h=>{u=h.relatedTarget instanceof HTMLElement?h.relatedTarget:void 0},click:h=>{h.stopPropagation(),h.preventDefault(),this.active_editor&&(this.active_editor.node.scrollTop=0),s.hasAttribute("expanded")?s.removeAttribute("expanded"):s.setAttribute("expanded",""),u&&u.focus()}}})}}committed=!1;tolled;shadow_=!1;get shadow(){return this.shadow_}set shadow(t){this.shadow_=t,this.active_editor?.node&&(t?this.active_editor.node.classList.add("treb-editor-shadow"):this.active_editor.node.classList.remove("treb-editor-shadow"))}focused_=!1;get focused(){return this.focused_}address_label_container;address_label;button;expand_button;label_update_timer=0;get formula(){return this.active_editor&&this.active_editor.node.textContent||""}set formula(t){this.active_editor&&(this.active_editor.node.textContent=t,this.active_editor.formatted_text=void 0)}get label(){return this.address_label?.textContent||""}set label(t){t.trim().length?(this.address_label.textContent=t,this.label_update_timer||(this.label_update_timer=requestAnimationFrame(()=>{this.label_update_timer=0,this.address_label.scrollWidth>this.address_label.offsetWidth?this.address_label.setAttribute("title",t):this.address_label.removeAttribute("title")}))):(this.address_label.innerHTML="&nbsp;",this.address_label.removeAttribute("title"))}set editable(t){!this.active_editor||!this.container_node||(t?(this.active_editor.node.setAttribute("contenteditable","true"),this.container_node.removeAttribute("locked")):(this.active_editor.node.removeAttribute("contenteditable"),this.container_node.setAttribute("locked","")))}Restore(){let t=this.container_node?.firstElementChild;t&&t.focus()}Release(){this.tolled=void 0}IsElement(t){return t===this.active_editor?.node}IsExpandButton(t){return this.expand_button&&t===this.expand_button}InitAddressLabel(){this.address_label.contentEditable="true",this.address_label.spellcheck=!1,this.address_label.addEventListener("focusin",()=>{let t=this.address_label.ownerDocument;requestAnimationFrame(()=>{let r=t.defaultView.getSelection(),i=t.createRange();i.selectNodeContents(this.address_label),r?.removeAllRanges(),r?.addRange(i)})}),this.address_label.addEventListener("keydown",t=>{if(!t.isComposing)switch(t.key){case"Enter":t.stopPropagation(),t.preventDefault(),this.Publish({type:"address-label-event",text:this.address_label.textContent||void 0});break;case"Esc":case"Escape":t.stopPropagation(),t.preventDefault(),this.Publish({type:"address-label-event"});break}})}GetTextContent(t){let r=t.childNodes,i=[];for(let n=0;n<r.length;n++){let o=r[n];switch(o.nodeType){case Node.ELEMENT_NODE:i.push(...this.GetTextContent(o)),o instanceof Element&&o.tagName==="DIV"&&i.push(`
7
- `);break;case Node.TEXT_NODE:o.nodeValue&&i.push(o.nodeValue);break}}return i}FormulaKeyUp(t){t.isComposing||this.autocomplete&&this.autocomplete.HandleKey("keyup",t).handled}FormulaKeyDown(t){if(!t.isComposing){if(this.autocomplete){let r=this.autocomplete.HandleKey("keydown",t);if(r.accept&&this.AcceptAutocomplete(r),r.handled)return}switch(t.key){case"Enter":case"Tab":{let r=t.key==="Enter"&&t.ctrlKey&&t.shiftKey,i=(this.active_editor?this.GetTextContent(this.active_editor.node).join(""):"").trim();this.committed=!0,this.Publish({type:"commit",value:i,event:t,array:r})}break;case"Escape":case"Esc":this.committed=!0,this.Publish({type:"discard"});break;default:return}t.stopPropagation(),t.preventDefault()}}};var mt=class{constructor(e={}){this.options=e;if(this.DOM=O.GetInstance(e.container?.ownerDocument),!this.DOM.doc)throw new Error("invalid context");this.completion_list=this.DOM.Div("treb-cell-editor-ac-list treb-autocomplete",e.container||this.DOM.doc.body,{events:{mousedown:t=>this.ListMouseDown(t),mousemove:t=>this.ListMouseMove(t)}}),this.tooltip=this.DOM.Div("treb-cell-editor-ac-tooltip treb-autocomplete-tooltip",e.container||this.DOM.doc.body)}completion_list_visible=!1;tooltip_visible=!1;last_completion;completion_list;tooltip;selected_index=0;block=!1;autocomplete_data={};callback;active_element;DOM;Hide(){this.tooltip.style.top="-1000px",this.completion_list.style.top="-1000px",this.completion_list_visible=!1,this.tooltip_visible=!1,this.active_element=void 0}SetBlock(){this.block=!0}ResetBlock(){this.block=!1}ListMouseMove(e){let t=e.target;t.tagName==="A"&&t!==this.active_element&&this.active_element&&(this.active_element.classList.remove("selected"),this.active_element=t,this.active_element.classList.add("selected"),this.selected_index=Number(t.dataset.index||"0"),this.last_completion=t.textContent||"")}ListMouseDown(e){e.stopPropagation(),e.preventDefault();let t=e.target;for(;t;){if(t===this.completion_list)return;if(t.tagName==="A")break;t=t.parentElement}t&&(console.info(t),this.callback&&this.callback({handled:!0,accept:!0,value:t.textContent?t.textContent:void 0,data:this.autocomplete_data,click:!0}))}HandleKey(e,t){if(!this.completion_list_visible)return{handled:!1};let r=0,i=!1,n=!1;switch(t.key){case"Up":case"ArrowUp":r=-1;break;case"Down":case"ArrowDown":r=1;break;case"Tab":n=!0;break;case"Escape":case"Esc":i=!0;break;default:return{handled:!1}}if(t.stopPropagation(),t.preventDefault(),e==="keyup")return{handled:!0};if(r){let o=this.completion_list.getBoundingClientRect();this.selected_index+=r,this.selected_index=Math.max(0,this.selected_index);let a=this.completion_list.querySelectorAll("a");this.selected_index=Math.min(this.selected_index,a.length-1);for(let s=0;s<a.length;s++){let c=a[s];if(s===this.selected_index){c.classList.add("selected"),this.active_element=c;let d=c.getBoundingClientRect();d.top<o.top?this.completion_list.scrollBy(0,-d.height):d.bottom>o.bottom&&this.completion_list.scrollBy(0,d.height),this.last_completion=c.textContent||void 0}else c.classList.remove("selected")}return{handled:!0}}else{if(i)return this.block=!0,this.Hide(),{handled:!0};if(n)return{handled:!0,accept:!0,value:this.last_completion,data:this.autocomplete_data}}return{handled:!1}}Show(e,t={},r){if(this.completion_list_visible=!1,this.tooltip_visible=!1,this.autocomplete_data=t,this.callback=e,!this.block)if(t.tooltip?(this.tooltip.innerHTML=t.tooltip+t.arguments+(t.description?`
6
+ `}IsDelimeter(e){return e==="*"||e==="_"||e==="~"}Consolidate(e){let t=[],r={},i=[],n={type:"text",text:""};for(let o of e)if(o.type==="newline")n.text.length&&i.push(n),n={...r,text:"",type:"text"},t.push(i),i=[];else switch((!!r.strong!=!!o.strong||!!r.emphasis!=!!o.emphasis||!!r.strike!=!!o.strike)&&(r.strong=!!o.strong,r.emphasis=!!o.emphasis,r.strike=!!o.strike,n.text.length&&i.push(n),n={...r,text:"",type:"text"}),o.type){case"text":case"whitespace":n.text+=o.text;break;case"delimeter":for(let a=0;a<o.length;a++)n.text+=o.char;break}return n.text.length&&i.push(n),i.length&&t.push(i),t}ApplyFormatting(e,t){let r=0,i=e.length;for(r=0;r<i;r++){let n=e[r];if(n.type==="delimeter"){if(t&&n.right_flanking&&t.char===n.char&&n.length>0)return{index:r,token:n};if(n.left_flanking){let o=this.ApplyFormatting(e.slice(r+1),n);if(o.token){let a=Math.min(o.token.length,n.length),s=n.char==="~",c=!s&&!!(a%2),d=!s&&a>=2;for(let u=r+1;u<=r+o.index;u++)e[u].strong=!!e[u].strong||d,e[u].emphasis=!!e[u].emphasis||c,e[u].strike=!!e[u].strike||s;o.token.length-=a,n.length-=a,n.length>0?r--:r+=o.index}}}}return{index:r}}Tokenize(e=""){let t=[],r=e.length,i=0,n=!1,o="";for(i=0;i<r;i++){let a=e[i];if(this.IsWhitespace(a)){o&&t.push({type:"text",text:o});let s=a;for(;;){let c=e[i+1];if(this.IsWhitespace(c))s+=c,i++;else break}t.push({type:"whitespace",text:s}),n=!1,o=""}else if(this.IsNewline(a)){o&&t.push({type:"text",text:o}),t.push({type:"newline",text:a});let s="";for(;;){let c=e[i+1];if(this.IsNewline(c))s+=c,i++;else break}s.length&&t.push({type:"newline",text:s}),n=!1,o=""}else if(n)o+=a,n=!1;else if(this.IsDelimeter(a)){o&&t.push({type:"text",text:o});let s=a;for(;;){let c=e[i+1];if(c===a)s+=c,i++;else break}t.push({type:"delimeter",text:s,char:a,length:s.length}),n=!1,o=""}else a==="\\"?n=!0:o+=a}return o&&t.push({type:"text",text:o}),t}};var N=l=>l!==null&&typeof l=="object"&&"row"in l&&"column"in l,ut=l=>l!==null&&typeof l=="object"&&"start"in l&&N(l.start)&&"end"in l&&N(l.end),v=class l{start_;end_;constructor(e,t=e,r=!1){this.end_=this.PatchNull(t),this.start_=this.PatchNull(e),r&&this.Normalize()}static FromColumn(e){return new l({row:1/0,column:e})}static FromRow(e){return new l({row:e,column:1/0})}static ColumnToLabel(e){let t=String.fromCharCode(65+e%26);for(;e>25;)e=Math.floor(e/26)-1,t=String.fromCharCode(65+e%26)+t;return t}static CellAddressToLabel(e,t=!1){if(e.row===1/0&&e.column===1/0)throw new Error("this is going to break something");let r=t?`${e.sheet_id||0}!`:"";return e.row===1/0?r+(e.absolute_column?"$":"")+this.ColumnToLabel(e.column):e.column===1/0?r+(e.absolute_row?"$":"")+(e.row+1):r+(e.absolute_column?"$":"")+this.ColumnToLabel(e.column)+(e.absolute_row?"$":"")+(e.row+1)+(e.spill?"#":"")}static Join(e,...t){let r=new l(e.start,e.end);for(let i of t)i&&(r.ConsumeAddress(i.start),r.ConsumeAddress(i.end));return r}static Bleed(e,t=1){return new l({row:Math.max(0,e.start.row-t),column:Math.max(0,e.start.column-t),sheet_id:e.start.sheet_id},{row:e.end.row+t,column:e.end.column+t})}static PatchArea(e,t){let{before_column:r,column_count:i,before_row:n,row_count:o}=t,a=new l(e.start,e.end),s=e.start.sheet_id;if(i&&r<=a.end.column){if(i>0)r<=a.start.column?a.Shift(0,i):r>a.start.column&&r<=a.end.column?a.ConsumeAddress({row:a.end.row,column:a.end.column+i}):console.warn("AA X case 1",r,i,JSON.stringify(a));else if(i<0)if(r-i<=a.start.column)a.Shift(0,i);else{if(r<=a.start.column&&r-i>a.end.column)return!1;if(r<=a.start.column){let c=r-i-1;a=new l({row:a.start.row,column:c+1+i,sheet_id:s},{row:a.end.row,column:a.end.column+i})}else r<=a.end.column?r-i-1>=a.end.column?a=new l({row:a.start.row,column:a.start.column,sheet_id:s},{row:a.end.row,column:r-1}):a=new l({row:a.start.row,column:a.start.column,sheet_id:s},{row:a.end.row,column:a.start.column+a.columns+i-1}):console.warn("AA X case 2",r,i,JSON.stringify(a))}}if(o&&n<=a.end.row){if(o>0)n<=a.start.row?a.Shift(o,0):n>a.start.row&&n<=a.end.row?a.ConsumeAddress({row:a.end.row+o,column:a.end.column}):console.warn("AA X case 3",n,o,JSON.stringify(a));else if(o<0)if(n-o<=a.start.row)a.Shift(o,0);else{if(n<=a.start.row&&n-o>a.end.row)return!1;if(n<=a.start.row){let c=n-o-1;a=new l({column:a.start.column,row:c+1+o,sheet_id:s},{column:a.end.column,row:a.end.row+o})}else n<=a.end.row?n-o-1>=a.end.row?a=new l({column:a.start.column,row:a.start.row,sheet_id:s},{column:a.end.column,row:n-1}):a=new l({column:a.start.column,row:a.start.row,sheet_id:s},{column:a.end.column,row:a.start.row+a.rows+o-1}):console.warn("AA X case 4",n,o,JSON.stringify(a))}}return a}get start(){return{...this.start_}}set start(e){this.start_=e}get end(){return{...this.end_}}set end(e){this.end_=e}get rows(){return this.start_.row===1/0||this.end_.row===1/0?1/0:this.end_.row-this.start_.row+1}get columns(){return this.start_.column===1/0||this.end_.column===1/0?1/0:this.end_.column-this.start_.column+1}get count(){return this.rows*this.columns}get entire_sheet(){return this.entire_row&&this.entire_column}get entire_column(){return this.start_.row===1/0}get entire_row(){return this.start_.column===1/0}PatchNull(e){let t={...e};return t.row===null&&(t.row=1/0),t.column===null&&(t.column=1/0),t}SetSheetID(e){this.start_.sheet_id=e}Normalize(){let e={...this.start_},t={...this.end_};e.row===1/0||t.row===1/0?e.row=t.row=1/0:e.row>t.row&&(e.row=this.end_.row,e.absolute_row=this.end_.absolute_row,t.row=this.start_.row,t.absolute_row=this.start_.absolute_row),e.column===1/0||t.column===1/0?e.column=t.column=1/0:e.column>t.column&&(e.column=this.end_.column,e.absolute_column=this.end_.absolute_column,t.column=this.start_.column,t.absolute_column=this.start_.absolute_column),this.start_=e,this.end_=t}TopLeft(){let e={row:0,column:0};return this.entire_row||(e.column=this.start.column),this.entire_column||(e.row=this.start.row),e}BottomRight(){let e={row:0,column:0};return this.entire_row||(e.column=this.end.column),this.entire_column||(e.row=this.end.row),e}ContainsRow(e){return this.entire_column||e>=this.start_.row&&e<=this.end_.row}ContainsColumn(e){return this.entire_row||e>=this.start_.column&&e<=this.end_.column}Contains(e){return(this.entire_column||e.row>=this.start_.row&&e.row<=this.end_.row)&&(this.entire_row||e.column>=this.start_.column&&e.column<=this.end_.column)}ContainsArea(e){return this.start.column<=e.start.column&&this.end.column>=e.end.column&&this.start.row<=e.start.row&&this.end.row>=e.end.row}Intersects(e){return!(e.start.column>this.end.column||this.start.column>e.end.column||e.start.row>this.end.row||this.start.row>e.end.row)}Equals(e){return e.start_.row===this.start_.row&&e.start_.column===this.start_.column&&e.end_.row===this.end_.row&&e.end_.column===this.end_.column}Equals2(e){return e.start.row===this.start_.row&&e.start.column===this.start_.column&&e.end.row===this.end_.row&&e.end.column===this.end_.column}Clone(){return new l(this.start,this.end)}get left(){let e=new l(this.start_,this.end_);return e.end_.column=e.start_.column,e}get right(){let e=new l(this.start_,this.end_);return e.start_.column=e.end_.column,e}get top(){let e=new l(this.start_,this.end_);return e.end_.row=e.start_.row,e}get bottom(){let e=new l(this.start_,this.end_);return e.start_.row=e.end_.row,e}Shift(e,t){return this.start_.row+=e,this.start_.column+=t,this.end_.row+=e,this.end_.column+=t,this}ConsumeAddress(e){this.entire_row||(e.column<this.start_.column&&(this.start_.column=e.column),e.column>this.end_.column&&(this.end_.column=e.column)),this.entire_column||(e.row<this.start_.row&&(this.start_.row=e.row),e.row>this.end_.row&&(this.end_.row=e.row))}Reshape(e,t){return this.end_.row=this.start_.row+e-1,this.end_.column=this.start_.column+t-1,this}ConsumeArea(e){this.ConsumeAddress(e.start),this.ConsumeAddress(e.end)}Resize(e,t){return this.end_.row=this.start_.row+e-1,this.end_.column=this.start_.column+t-1,this}[Symbol.iterator](){if(this.entire_row||this.entire_column)throw new Error("don't iterate infinite area");let e=this.start_.row,t=this.start_.column;return{next:()=>{let r={column:t,row:e,sheet_id:this.start_.sheet_id};return t>this.end_.column?{done:!0,value:void 0}:(++e>this.end_.row&&(e=this.start_.row,t++),{value:r})}}}get spreadsheet_label(){let e;return this.entire_sheet?"":this.entire_column?(e=l.ColumnToLabel(this.start_.column),e+=":"+l.ColumnToLabel(this.end_.column),e):this.entire_row?(e=String(this.start_.row+1),e+=":"+(this.end_.row+1),e):(e=l.CellAddressToLabel(this.start_),this.columns>1||this.rows>1?e+":"+l.CellAddressToLabel(this.end_):e)}toJSON(){return{start:{...this.start_},end:{...this.end_}}}};var me=l=>typeof l=="object"&&!!l&&typeof l.real=="number"&&typeof l.imaginary=="number",Xe=l=>l.real?l.imaginary?l.imaginary>0?`${l.real} + ${l.imaginary}i`:`${l.real} - ${Math.abs(l.imaginary)}i`:l.real.toString():l.imaginary?l.imaginary+"i":"0",Fr=l=>typeof l=="object"&&!!l&&typeof l.value=="number"&&typeof l.unit=="string",Mo=l=>typeof l=="object"&&l.type==="function",Nr=["undefined","formula","string","number","boolean","object","function","error","complex","array","dimensioned_quantity"];var ge=l=>{switch(typeof l){case"undefined":return 0;case"number":return 3;case"boolean":return 4;case"object":return l===null?0:Mo(l)?6:me(l)?8:Fr(l)?10:5;case"string":return l[0]==="="?1:2;default:return 7}};var ce=class{static StringToColumn(e){let t=0;e=e.toUpperCase();for(let r=0;r<e.length;r++)t*=26,t+=e.charCodeAt(r)-64;return t-1}value;type=0;calculated;calculated_type;formatted;rendered_type;style;area;spill;merge_area;table;renderer_data;render_clean=[];note;hyperlink;editing;render_function;click_function;constructor(e,t){typeof e<"u"&&this.Set(e,t)}ValueIsNumber(){return this.type===3}ValueIsFormula(){return this.type===1}ValueIsBoolean(){return this.type===4}ValueIsComplex(){return this.type===8}FlushStyle(){this.formatted=this.rendered_type=this.style=void 0,this.render_clean=[]}FlushArray(){this.area=void 0}FlushCache(){this.calculated=this.calculated_type=this.formatted=this.rendered_type=this.render_function=this.click_function=void 0,this.render_clean=[]}Reset(){this.type=0,this.value=this.spill=this.note=this.hyperlink=this.formatted=this.rendered_type=this.style=this.calculated=this.calculated_type=this.area=this.renderer_data=this.render_function=this.click_function=void 0,this.render_clean=[]}Set(e,t=ge(e)){this.value=e,this.type=t,this.spill=this.formatted=this.rendered_type=this.style=this.calculated=this.calculated_type=this.render_function=this.click_function=this.area=void 0,this.render_clean=[]}SetCalculatedValue(e,t=ge(e)){e===void 0&&(e=0,t=3),this.calculated!==e&&(this.calculated=e,this.calculated_type=t,this.formatted=this.rendered_type=void 0,this.render_clean=[])}GetValue(){return this.calculated_type?this.calculated:typeof this.value=="string"&&this.value[0]==="'"?this.value.slice(1):this.value}GetValue4(){return this.calculated_type?{type:this.calculated_type,value:this.calculated}:this.type===1?{type:3,value:0}:{type:this.type,value:typeof this.value=="string"&&this.value[0]==="'"?this.value.slice(1):this.value}}SetNote(e){this.note=e,this.render_clean=[]}SetCalculationError(e="ERR"){this.SetCalculatedValue(e,7)}SetArray(e){this.type=0,this.value=this.formatted=this.rendered_type=this.style=this.hyperlink=this.calculated=this.calculated_type=void 0,this.area=e,this.render_clean=[]}SetArrayHead(e,t){this.type=ge(t),this.value=t,this.formatted=this.rendered_type=this.style=this.calculated=this.calculated_type=void 0,this.area=e,this.render_clean=[]}};var Pr=l=>!l.cells,ht=l=>!!l[0]&&Pr(l[0]),Or=l=>!!l[0]&&l[0].row!==void 0,Uo=Nr.map((l,e)=>({[l]:e})).reduce((l,e)=>({...l,...e}),{}),Tt=class{data=[];rows_=0;columns_=0;get rows(){return this.rows_}get columns(){return this.columns_}EnsureRow(e){this.rows_=Math.max(e+1,this.rows_)}EnsureColumn(e){this.columns_=Math.max(e+1,this.columns_)}InsertColumns(e=0,t=1){this.data=this.data.map(r=>{if(r.length>=e){let i=r.slice(0,e),n=e+t,o=r.slice(e);for(let a=0;a<o.length;a++)i[n++]=o[a];return i}return r}),this.columns_+=t}DeleteColumns(e,t=1){this.data.forEach(r=>r.splice(e,t)),this.columns_-=t}DeleteRows(e,t=1){this.data.splice(e,t),this.rows_-=t}InsertRows(e=0,t=1){let r=[e,0,[]];for(let i=1;i<t;i++)r.push([]);Array.prototype.splice.apply(this.data,r),this.rows_+=t}GetCell(e,t){let{row:r,column:i}=e;if(!this.data[r])if(t)this.data[r]=[],this.rows_=Math.max(this.rows_,r+1);else return;return this.data[r][i]||t&&(this.data[r][i]=new ce,this.columns_=Math.max(this.columns_,i+1)),this.data[r][i]}EnsureCell(e){let{row:t,column:r}=e,i=this.data[t];i||(this.data[t]=i=[],this.rows_=Math.max(this.rows_,t+1));let n=i[r];return n||(n=i[r]=new ce,this.columns_=Math.max(this.columns_,r+1)),n}FromArray(e=[],t=!1){this.data=[];let r=0,i=0;if(t){i=e.length;for(let n=0;n<i;n++){let o=e[n];r=Math.max(r,o.length);for(let a=0;a<o.length;a++)this.data[a]||(this.data[a]=[]),this.data[a][n]=new ce(o[a])}}else{r=e.length;for(let n=0;n<r;n++){let o=[],a=e[n];i=Math.max(i,a.length);for(let s=0;s<a.length;s++)o[s]=new ce(a[s]);this.data[n]=o}}this.rows_=r,this.columns_=i}SerializedTypeToValueType(e){if(e)return typeof e=="number"?e:Uo[e]||void 0}ValueTypeToSerializedType(e){return e?Nr[e]:void 0}FromJSON(e=[],t){if(this.data=[],!ht(e)){let i=[];if(Or(e))for(let n of e)for(let o of n.cells)i.push({...o,row:n.row});else for(let n of e)for(let o of n.cells)i.push({...o,column:n.column});e=i}let r=[];for(let i of e){this.data[i.row]||(this.data[i.row]=[]);let n=new ce(i.value);if(typeof i.calculated<"u"&&(n.SetCalculatedValue(i.calculated,this.SerializedTypeToValueType(i.calculated_type)),i.spill&&(n.spill=new v(i.spill.start,i.spill.end))),t&&typeof i.style_ref<"u"&&(n.style=t[i.style_ref]),typeof i.note<"u"&&(n.note=i.note),typeof i.hyperlink<"u"&&(n.hyperlink=i.hyperlink),this.data[i.row][i.column]&&this.data[i.row][i.column].area&&(n.area=this.data[i.row][i.column].area),this.data[i.row][i.column]=n,i.area){let o=new v(i.area.start,i.area.end);for(let a=o.start.row;a<=o.end.row;a++)for(let s=o.start.column;s<=o.end.column;s++)this.data[a]||(this.data[a]=[]),this.data[a][s]||(this.data[a][s]=new ce),this.data[a][s].area=o}if(i.table&&r.push({...i.table}),i.merge_area){let o=new v(i.merge_area.start,i.merge_area.end);for(let a=o.start.row;a<=o.end.row;a++)for(let s=o.start.column;s<=o.end.column;s++)this.data[a]||(this.data[a]=[]),this.data[a][s]||(this.data[a][s]=new ce),this.data[a][s].merge_area=o}}for(let i of r)for(let n=i.area.start.row;n<=i.area.end.row;n++)for(let o=i.area.start.column;o<=i.area.end.column;o++)this.data[n]||(this.data[n]=[]),this.data[n][o]||(this.data[n][o]=new ce),this.data[n][o].table=i;this.rows_=this.data.length,this.columns_=this.data.reduce((i,n)=>Math.max(i,n.length),0)}toJSON(e={}){let t=0,r=0,i=this.data.length-1,n;e.subset&&(t=e.subset.start.column,r=e.subset.start.row,i=e.subset.end.row);let o=[],a=-1,s=-1,c={},d={};for(let u=r;u<=i;u++)if(this.data[u]){let h=this.data[u];n=h.length-1,e.subset&&(n=e.subset.end.column);for(let m=t;m<=n;m++){let f=h[m],p=f&&f.merge_area&&f.merge_area.start.row===u&&f.merge_area.start.column===m,b=f&&f.area&&f.area.start.row===u&&f.area.start.column===m,g=f&&f.table&&f.table.area.start.row===u&&f.table.area.start.column===m,x=f?f.type===2&&!f.value:!0;if(f&&(!x||e.preserve_empty_strings)&&(p||f.type||f.calculated_type&&e.expand_arrays||f.calculated_type&&e.calculated_value||f.note||e.decorated_cells&&f.style&&(f.style.fill||f.style.border_bottom||f.style.border_top||f.style.border_left||f.style.border_right))){let y={row:u,column:m,value:f.value};f.note&&(y.note=f.note),f.hyperlink&&(y.hyperlink=f.hyperlink),e.preserve_type&&(y.type=this.ValueTypeToSerializedType(f.type)),e.sheet_id&&(y.sheet_id=e.sheet_id),e.calculated_value&&typeof f.calculated<"u"&&(y.calculated=f.calculated,f.spill&&(y.spill=f.spill.toJSON()),(e.preserve_type||f.calculated_type===7)&&(y.calculated_type=this.ValueTypeToSerializedType(f.calculated_type))),f.table&&g&&e.tables&&(y.table=JSON.parse(JSON.stringify(f.table))),f.area&&b&&(y.area=f.area.toJSON()),f.merge_area&&(y.merge_area=f.merge_area.toJSON()),e.cell_style_refs&&e.cell_style_refs[m]&&e.cell_style_refs[m][u]&&(y.style_ref=e.cell_style_refs[m][u],e.cell_style_refs[m][u]=0),c[u]=u,d[m]=m,a=Math.max(u,a),s=Math.max(m,s),o.push(y)}}}if(e.nested){let u=Object.keys(c),h=Object.keys(d);if(u.length<=h.length&&u.length){let m={},f=[];for(let p of o){let{row:b,...g}=p;m[p.row]||(m[p.row]=[]),m[p.row].push(g)}for(let p of u){let b=Number(p);f.push({row:b,cells:m[b]})}return{data:f,rows:a,columns:s+1}}else if(h.length){let m={},f=[];for(let p of o){let{column:b,...g}=p;m[p.column]||(m[p.column]=[]),m[p.column].push(g)}for(let p of h){let b=Number(p);f.push({column:b,cells:m[b]})}return{data:f,rows:a,columns:s+1}}}return{data:o,rows:a+1,columns:s+1}}GetAll(e=!1){return this.GetRange({row:0,column:0},{row:this.rows_-1,column:this.columns_-1},e)}Normalize(e,t){return e={...e,row:e.row==1/0?0:e.row,column:e.column==1/0?0:e.column},t&&(t={...t,row:t.row==1/0?this.rows_-1:t.row,column:t.column==1/0?this.columns_-1:t.column}),{from:e,to:t}}RawValue(e,t=e){if({from:e,to:t}=this.Normalize(e,t),e.row===t.row&&e.column===t.column)return this.data[e.row]&&this.data[e.row][e.column]?this.data[e.row][e.column].value:void 0;let r=[],i=this.data.slice(e.row,t.row+1),n=e.column,o=t.column+1;for(let a of i){let s=[];for(let c=n,d=0;c<o;c++,d++){let u=a[c];s.push(u?u.value:void 0)}r.push(s)}return r}GetRange(e,t,r=!1){if({from:e,to:t}=this.Normalize(e,t),!t||e===t||e.column===t.column&&e.row===t.row)return this.data[e.row]&&this.data[e.row][e.column]?this.data[e.row][e.column].GetValue():void 0;let i=[];if(r)for(let n=e.column;n<=t.column;n++){let o=[];for(let a=e.row;a<=t.row;a++)this.data[a]&&this.data[a][n]?o.push(this.data[a][n].GetValue()):o.push(void 0);i.push(o)}else for(let n=e.row;n<=t.row;n++){let o=[];for(let a=e.column;a<=t.column;a++)this.data[n]&&this.data[n][a]?o.push(this.data[n][a].GetValue()):o.push(void 0);i.push(o)}return i}GetRange4(e,t=e,r=!1){if({from:e,to:t}=this.Normalize(e,t),e.row===t.row&&e.column===t.column)return this.data[e.row]&&this.data[e.row][e.column]?this.data[e.row][e.column].GetValue4():{value:void 0,type:0};let i=[];if(r)for(let n=e.column;n<=t.column;n++){let o=[];for(let a=e.row;a<=t.row;a++)this.data[a]&&this.data[a][n]?o.push(this.data[a][n].GetValue4()):o.push({type:0});i.push(o)}else for(let n=e.row;n<=t.row;n++){let o=[];for(let a=e.column;a<=t.column;a++)this.data[n]&&this.data[n][a]?o.push(this.data[n][a].GetValue4()):o.push({type:0});i.push(o)}return{type:9,value:i}}SetArea(e,t){if(ArrayBuffer.isView(t))throw new Error("ABIV");if(Array.isArray(t))for(let r=e.start.row,i=0;r<=e.end.row;r++,i++){this.data[r]||(this.data[r]=[]);let n=this.data[r];if(t[i])for(let o=e.start.column,a=0;o<=e.end.column;o++,a++)n[o]||(n[o]=new ce),n[o].Set(t[i][a])}else{let r=ge(t);for(let i=e.start.row;i<=e.end.row;i++){this.data[i]||(this.data[i]=[]);let n=this.data[i];for(let o=e.start.column;o<=e.end.column;o++)n[o]||(n[o]=new ce),n[o].Set(t,r)}}this.rows_=Math.max(this.rows_,e.end.row+1),this.columns_=Math.max(this.columns_,e.end.column+1)}*IterateRC(e,t=!1){if(!e&&t&&(e=new v({row:0,column:0},{row:this.rows_-1,column:this.columns-1})),e)if(t)for(let r=e.start.row;r<=e.end.row;r++){this.data[r]||(this.data[r]=[]);let i=this.data[r];for(let n=e.start.column;n<=e.end.column;n++)i[n]||(i[n]=new ce),yield{cell:i[n],row:r,column:n}}else for(let r=e.start.row;r<=e.end.row;r++){let i=this.data[r];if(i)for(let n=e.start.column;n<=e.end.column;n++){let o=i[n];o&&(yield{cell:o,row:r,column:n})}}else for(let[r,i]of this.data.entries())if(i)for(let[n,o]of i.entries())o&&(yield{cell:o,row:r,column:n})}*Iterate(e,t=!1){if(!e&&t&&(e=new v({row:0,column:0},{row:this.rows_-1,column:this.columns-1})),e){N(e)&&(e=new v(e)),(e.entire_column||e.entire_row)&&(e=new v(e.start,e.end),e.start.column===1/0&&(e.start.column=0,e.end.column=this.columns_-1),e.start.row===1/0&&(e.start.row=0,e.end.row=this.rows_-1));let r=e.start,i=e.end;if(t)for(let n=r.row;n<=i.row;n++){this.data[n]||(this.data[n]=[]);let o=this.data[n];for(let a=r.column;a<=i.column;a++)o[a]||(o[a]=new ce),yield o[a]}else for(let n=r.row;n<=i.row;n++)if(this.data[n]){let o=this.data[n];for(let a=r.column;a<=i.column;a++)o[a]&&(yield o[a])}}else for(let r of this.data)if(r)for(let i of r)i&&(yield i)}FlushCellStyles(){for(let e of this.data)if(e)for(let t of e)t&&t.FlushStyle()}FlushCachedValues(){for(let e of this.data)if(e)for(let t of e)t&&t.FlushCache()}};var F=class{static locale="en-us";static decimal_separator=".";static argument_separator=",";static grouping_separator=",";static date_components={short_days:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],long_days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],short_months:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],long_months:["January","February","March","April","May","June","July","August","September","October","November","December"]};static UpdateLocale(e){if(e)this.locale=e;else if(typeof self<"u"){let i=self?.document?.location;if(i&&i.search&&/locale=([^?&]+?)(?:\?|$|&)/.test(i.search)){let n=i.search.match(/locale=(.*?)(?:\?|$|&)/);n&&(this.locale=n[1]),console.info("override locale",this.locale)}else typeof navigator<"u"&&(navigator.languages&&navigator.languages[0]?this.locale=navigator.languages[0]:this.locale=navigator.language)}this.locale==="C"&&(console.warn("Locale not set, defaulting to en-us"),this.locale="en-us");let t=new Intl.NumberFormat(this.locale,{minimumFractionDigits:1}).format(3.3).replace(/\d/g,"");this.decimal_separator=t===","?",":".",this.decimal_separator===","?(this.argument_separator=";",this.grouping_separator=" "):(this.argument_separator=",",this.grouping_separator=",");let r=new Date(2e3,0,2,12,0,0,0);this.UpdateDateComponent(0,0,r),r=new Date(2e3,1,7,12,0,0,0),this.UpdateDateComponent(1,1,r),r=new Date(2e3,2,7,12,0,0,0),this.UpdateDateComponent(2,2,r),r=new Date(2e3,3,5,12,0,0,0),this.UpdateDateComponent(3,3,r),r=new Date(2e3,4,4,12,0,0,0),this.UpdateDateComponent(4,4,r),r=new Date(2e3,5,2,12,0,0,0),this.UpdateDateComponent(5,5,r),r=new Date(2e3,6,1,12,0,0,0),this.UpdateDateComponent(6,6,r),r=new Date(2e3,7,1,12,0,0,0),this.UpdateDateComponent(7,-1,r),r=new Date(2e3,8,1,12,0,0,0),this.UpdateDateComponent(8,-1,r),r=new Date(2e3,9,1,12,0,0,0),this.UpdateDateComponent(9,-1,r),r=new Date(2e3,10,1,12,0,0,0),this.UpdateDateComponent(10,-1,r),r=new Date(2e3,11,1,12,0,0,0),this.UpdateDateComponent(11,-1,r)}static UpdateDateComponent(e,t,r){t>=0&&(this.date_components.short_days[t]=r.toLocaleString(this.locale,{weekday:"short"}),this.date_components.long_days[t]=r.toLocaleString(this.locale,{weekday:"long"})),e>=0&&(this.date_components.short_months[e]=r.toLocaleString(this.locale,{month:"short"}),this.date_components.long_months[e]=r.toLocaleString(this.locale,{month:"long"}))}};F.UpdateLocale();var B=class l{constructor(e=0,t=0,r=0,i=0){this.left=e;this.top=t;this.width=r;this.height=i}get right(){return this.left+this.width}get bottom(){return this.top+this.height}static Create(e){return new l(e.left||0,e.top||0,e.width||0,e.height||0)}static IsRectangle(e){return!!e&&typeof e=="object"&&typeof e.left=="number"&&typeof e.top=="number"&&typeof e.width=="number"&&typeof e.height=="number"}Shift(e=0,t=0){return new l(this.left+e,this.top+t,this.width,this.height)}Scale(e=1,t=e){return new l(this.left*e,this.top*t,this.width*e,this.height*t)}Expand(e=0,t=0){return new l(this.left,this.top,this.width+e,this.height+t)}Combine(e){return new l(Math.min(this.left,e.left),Math.min(this.top,e.top),Math.max(this.right,e.right)-Math.min(this.left,e.left),Math.max(this.bottom,e.bottom)-Math.min(this.top,e.top))}Contains(e,t,r=0){return e>=this.left-r&&e<=this.left+this.width+r&&t>=this.top-r&&t<=this.top+this.height+r}ContextFill(e){e.fillRect(this.left,this.top,this.width,this.height)}ContextStroke(e){e.strokeRect(this.left,this.top,this.width,this.height)}Clamp(e,t){return e=Math.min(Math.max(e,this.left),this.right),t=Math.min(Math.max(t,this.top),this.bottom),{x:e,y:t}}ApplyStyle(e){e.style.top=this.top+"px",e.style.left=this.left+"px",e.style.width=this.width+"px",e.style.height=this.height+"px"}toJSON(){return{top:this.top,left:this.left,width:this.width,height:this.height}}};var Vo=JSON.stringify({}),Do={Background:0,Text:1,Background2:2,Text2:3,Accent:4,Accent2:5,Accent3:6,Accent4:7,Accent5:8,Accent6:9},Hr=l=>typeof l.theme=="number"?l.theme:Do[l.theme]||0,ee=l=>!!l&&typeof l.text=="string",Ke=l=>!!l&&typeof l.theme<"u",zi=l=>!!l&&(typeof l.text=="string"||typeof l.theme<"u"),I={DefaultProperties:{horizontal_align:"",vertical_align:"",number_format:"General",nan:"NaN",font_size:{unit:"em",value:1},bold:!1,italic:!1,underline:!1,strike:!1,text:{theme:1},border_top:0,border_left:0,border_right:0,border_bottom:0},CompositeBorders:l=>({top:{width:l.border_top||0,color:l.border_top_fill||{}},left:{width:l.border_left||0,color:l.border_left_fill||{}},right:{width:l.border_right||0,color:l.border_right_fill||{}},bottom:{width:l.border_bottom||0,color:l.border_bottom_fill||{}}}),Serialize:l=>{let e=JSON.parse(JSON.stringify(l));return e.border_bottom_fill&&!e.border_bottom&&(e.border_bottom_fill=void 0),e.border_top_fill&&!e.border_top&&(e.border_top_fill=void 0),e.border_left_fill&&!e.border_left&&(e.border_left_fill=void 0),e.border_right_fill&&!e.border_right&&(e.border_right_fill=void 0),JSON.stringify(e)},Merge:(l,e,t=!0)=>{let r=t?{...l,...e}:{...e};return JSON.parse(JSON.stringify(r))},Composite:l=>JSON.parse(JSON.stringify(l.reduce((e,t)=>({...e,...t}),{}))),Empty:l=>JSON.stringify(l)===Vo,ParseFontSize:(l="",e="em")=>{let t=l.match(/(-*[\d.]+)\s*(\S*)/);if(t){let r=Number(t[1]);if(!r||isNaN(r)||r<0)return{};let i=t[2].toLowerCase()||e;if(i==="pt"||i==="em"||i==="%"||i==="px")return{font_size:{unit:i,value:r}}}return{}},RelativeFontSize:(l,e)=>{let t=12,r=12;switch(l.font_size?.unit){case"pt":if(!l.font_size.value)return 1;r=l.font_size.value;break;case"px":if(!l.font_size.value)return 1;r=Math.round(l.font_size.value*300/4)/100;break;case"em":return l.font_size.value||1;case"%":return(l.font_size.value||100)/100;default:return 1}switch(e.font_size?.unit){case"pt":if(!e.font_size.value)return 1;t=e.font_size.value;break;case"px":if(!e.font_size.value)return 1;t=Math.round(e.font_size.value*300/4)/100;break;default:return 1}return r/t},FontSize:(l,e=!0)=>{let t=l.font_size?.value;switch(l.font_size?.unit){case"pt":return(t||12)+"pt";case"px":return e?Math.round((t||16)*300/4)/100+"pt":(t||16)+"px";case"em":return(t||1)+"em";case"%":return(t||100)+"%"}return""},CompositeFontSize:(l,e,t=1,r=!1)=>{let i={...l};return e.unit==="pt"||e.unit==="px"?i={...e}:(i.value=e.value*l.value,e.unit==="%"&&(i.value/=100)),i.unit==="px"&&r&&(i.value=Math.round((i.value||16)*300/4)/100),i.value*=t,i},CompositeFont:(l,e,t,r)=>{let i,n,o,a=[];e.bold&&a.push("bold"),e.italic&&a.push("italic");let s=e.font_face||"stack:default";if(s.startsWith("stack:")){let c=r.font_stacks[s.substring(6)||"default"];c||(c=r.font_stacks.default),c&&(n=e.font_size,o=I.CompositeFontSize(c.size,e.font_size||{unit:"pt",value:10},t),a.push(o.value.toFixed(2)+o.unit),a.push(c.font||""),i=c.variants)}else o=I.CompositeFontSize(l,e.font_size||{unit:"pt",value:10},t),a.push(o.value.toFixed(2)+o.unit),a.push(s||"");return{font:a.join(" "),variants:i,base:l,size:e.font_size,scale:t,stack_size:n,font_size:o}}};var Mt=l=>!!l&&Array.isArray(l)&&Array.isArray(l[0]),Q=(l,e)=>(typeof e>"u"&&(e=ge(l)),{value:l,type:e}),de=l=>l.imaginary?{type:8,value:l}:{type:3,value:l.real};var W={Darken:(l,e,t,r,i=!1)=>{let{h:n,s:o,l:a}=W.RGBToHSL(l,e,t);return i?a-=a*r/100:a-=r/100,a=Math.max(0,Math.min(1,a)),W.HSLToRGB(n,o,a)},Lighten:(l,e,t,r,i=!1)=>{let{h:n,s:o,l:a}=W.RGBToHSL(l,e,t);return i?a+=a*r/100:a+=r/100,a=Math.max(0,Math.min(1,a)),W.HSLToRGB(n,o,a)},RGBToHSL:(l,e,t)=>{l/=255,e/=255,t/=255;let r=Math.max(l,e,t),i=Math.min(l,e,t),n=0,o=0,a=(r+i)/2;if(r===i)n=o=0;else{let s=r-i;switch(o=a>.5?s/(2-r-i):s/(r+i),r){case l:n=(e-t)/s+(e<t?6:0);break;case e:n=(t-l)/s+2;break;case t:n=(l-e)/s+4;break}n/=6}return{h:n*360,s:o,l:a}},HSLToRGB:(l,e,t)=>{let r,i,n;if(e===0)r=i=n=t;else{l=l/360;let o=t<.5?t*(1+e):t+e-t*e,a=2*t-o;r=W.HueToRGB(a,o,l+.3333333333333333),i=W.HueToRGB(a,o,l),n=W.HueToRGB(a,o,l-.3333333333333333)}return{r:Math.round(r*255),g:Math.round(i*255),b:Math.round(n*255)}},HueToRGB:(l,e,t)=>(t<0&&(t+=1),t>1&&(t-=1),t<.16666666666666666?l+(e-l)*6*t:t<.5?e:t<.6666666666666666?l+(e-l)*(.6666666666666666-t)*6:l),GetLuminance:([l,e,t])=>{let r=[l,e,t].map(i=>(i/=255,i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4)));return .2126*r[0]+.7152*r[1]+.0722*r[2]},WeightedLuminance:([l,e,t],r=[1,1,1])=>{let i=[l,e,t].map(n=>(n/=255,n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4)));return .2126*i[0]*r[0]+.7152*i[1]*r[1]+.0722*i[2]*r[2]},GetContrastRatio:l=>(l.sort((e,t)=>t-e),(l[0]+.05)/(l[1]+.05)),GetTextColor:(l,e,t)=>{let r=[.4,.3,.3],i=W.WeightedLuminance(l,r),n=W.WeightedLuminance(e,r),o=W.WeightedLuminance(t,r),a=W.GetContrastRatio([n,i]),s=W.GetContrastRatio([o,i]);return a>s?e:t}};var zo="http://www.w3.org/2000/svg",O=class l{static instances=[];static GetInstance(e){for(let r of this.instances)if(r.doc===e)return r;let t=new l(e);return this.instances.push(t),t}doc;view;get HTMLElement(){return this.view?.HTMLElement}constructor(e){e&&(this.doc=e,this.view=e?.defaultView)}GetSelection(){return this.view?.getSelection()}Div(e,t,r){return this.Create("div",e,t,r)}ClassNames(e,t){e.classList.add(...(Array.isArray(t)?t:[t]).reduce((r,i)=>[...r,...i.split(/\s+/g)],[]))}SVG(e,t,r){let i=this.doc.createElementNS(zo,e);return t&&this.ClassNames(i,t),r&&r.appendChild(i),i}Text(e){return this.doc.createTextNode(e)}Fragment(){return this.doc.createDocumentFragment()}Create(e,t,r,i){let n=this.doc.createElement(e);if(t&&this.ClassNames(n,t),i){if(i.attrs)for(let[o,a]of Object.entries(i.attrs))n.setAttribute(o,a);if(i.data)for(let[o,a]of Object.entries(i.data))n.dataset[o]=a;if(i.text&&(n.textContent=i.text),i.html&&(n.innerHTML=i.html),i.events)for(let[o,a]of Object.entries(i.events))n.addEventListener(o,a);if(i.style)for(let[o,a]of Object.entries(i.style))n.style[o]=a}return r&&r.appendChild(n),n}};var Lo=1e3,_e=class{constructor(e=!1,t){this.verbose=e;this.log_id=t}queue=[];dispatched=!1;subscribers=[];Publish(e){this.verbose&&console.info(`es publish (${this.log_id})`,e),Array.isArray(e)?this.queue.push(...e):this.queue.push(e),this.dispatched||(this.dispatched=!0,Promise.resolve().then(()=>{let t=this.queue.slice(0);this.dispatched=!1,this.queue=[];for(let r of t)for(let i of this.subscribers)i.subscriber(r)}))}Subscribe(e){let t=Lo++;return this.subscribers.push({subscriber:e,token:t}),t}Cancel(e){this.subscribers=this.subscribers.filter(t=>t.token!==e)}CancelAll(){this.subscribers=[]}};var se=class{static color_measurement_canvas;static text_measurement_node;static color_cache={};static MeasureColorARGB(e){let t=this.MeasureColor(e),r="FF";for(let i=0;i<3;i++){let n=t[i].toString(16);n.length===0?r+="00":n.length===1?r+=`0${n}`:r+=n}return r.toUpperCase()}static MeasureColor(e){let t=this.color_cache[e];if(t)return t;this.color_measurement_canvas||(this.color_measurement_canvas=document.createElement("canvas"),this.color_measurement_canvas.width=1,this.color_measurement_canvas.height=1);let r=this.color_measurement_canvas.getContext("2d",{willReadFrequently:!0});return r?(r.fillStyle="#fff",r.fillRect(0,0,1,1),r.fillStyle=e,r.fillRect(0,0,1,1),t=new Uint8ClampedArray(r.getImageData(0,0,1,1).data),this.color_cache[e]=t,t):new Uint8ClampedArray(3)}static EnsureMeasurementNode(){if(!this.text_measurement_node){let e=document.querySelector(".treb-chart-measurement-node");e?this.text_measurement_node=e:(this.text_measurement_node=document.createElement("div"),this.text_measurement_node.classList.add("treb-chart-measurement-node"),this.text_measurement_node.style.margin="0px",this.text_measurement_node.style.padding="0px",this.text_measurement_node.style.height="initial",this.text_measurement_node.style.width="initial",this.text_measurement_node.style.whiteSpace="nowrap",this.text_measurement_node.style.position="fixed",this.text_measurement_node.style.border="0px",this.text_measurement_node.style.border="1px solid red",this.text_measurement_node.style.boxSizing="content-box",this.text_measurement_node.style.top=this.text_measurement_node.style.left="-1000px",document.body.appendChild(this.text_measurement_node))}}static FontLoaded(e,t=!1,r=400){let i=`${t?"italic":""} ${r} 20pt ${e}`,n=this.MeasureText(`${i}, sans-serif`,"check font"),o=this.MeasureText(`${i}, serif`,"check font"),a=this.MeasureText(`${i}, monospace`,"check font");return n.width===o.width&&o.width===a.width}static MeasureText(e,t,r=0){this.EnsureMeasurementNode(),this.text_measurement_node.style.font=e,/\n/.test(t)?(t=t.replace(/\n/g,"<BR/>"),this.text_measurement_node.innerHTML=t):this.text_measurement_node.textContent=t,this.text_measurement_node.style.lineHeight="1em",r?this.text_measurement_node.style.transform=`rotate(${r}deg)`:this.text_measurement_node.style.transform="";let i=this.text_measurement_node.getBoundingClientRect();return{width:i.width,height:i.height}}};var Gr,Li=l=>{let e=new Map;for(let t=0;t<l.length;t++){let r=l[t];e.set(r,l.getPropertyValue(r))}return e},Io=(l,e,t)=>{let r=new Map,i=Li(e);for(let[o,a]of i.entries())a!==t.get(o)&&r.set(o,a);return(Array.from(r.entries()).map(([o,a])=>`${o}: ${a}`).join("; ")+"; "+(l.getAttribute("style")||"")).trim().replace(/"/g,"'")},Ii=(l,e)=>{let t=l.cloneNode(!1),r=getComputedStyle(l),i=Io(l,r,e);t.removeAttribute("class"),t.setAttribute("style",i);let n;return Array.prototype.forEach.call(l.childNodes,o=>{switch(o.nodeType){case Node.ELEMENT_NODE:n||(n=Li(r)),t.appendChild(Ii(o,n));break;case Node.TEXT_NODE:l.textContent&&t.appendChild(document.createTextNode(l.textContent));break;case Node.COMMENT_NODE:break;default:console.warn("unhandled node type in serialize",o)}}),t},Fi=l=>{if(!Gr){let t=new Map,r=document.createElement("iframe");r.style.width="10px",r.style.height="10px",r.style.position="absolute",r.style.left="-100px",document.body.appendChild(r);let i=r.contentDocument;if(i){let n=i.createElement("div");i.body.appendChild(n);let o=getComputedStyle(n);Array.prototype.forEach.call(o,a=>t.set(a,o[a]))}document.body.removeChild(r),Gr=t}let e=Ii(l,Gr);return e instanceof Element&&e.tagName==="svg"&&(e.hasAttribute("version")||e.setAttribute("version","1.1"),e.hasAttribute("xmlns")||e.setAttribute("xmlns","http://www.w3.org/2000/svg"),e.hasAttribute("xmlns:xlink")||e.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink")),e};var Fo={data:!0,same_origin:!0,remote:!1},Ut=(l,e={})=>{let t={...Fo,...e};try{let r=new URL(l,document.location.href);return r.protocol==="data:"?t.data?r.href:void 0:r.origin===document.location.origin?t.same_origin?r.href:void 0:t.remote?r.hash:void 0}catch(r){console.error(r)}};var Ni=(l,e,t=6.5,r=!1,i=!1)=>{if(e===l)e++,l&&l--;else{let u=Math.round(e*1e5)/1e5;Math.abs(u-e)/(e-l)<1e-5&&(e=u)}let n=e-l,o=Math.log(n)/Math.log(10),a=Math.floor(Math.abs(o))*(o<0?-1:1)-1;i&&(a=Math.max(0,a));let s=i?[1,2,5,10,15,20,25,50,100]:[.1,.25,.5,1,2.5,5,10,25,50,100],c=-1,d=0;for(let u of s){let h=u*Math.pow(10,a),m=Math.floor(l/h)*h,p=(Math.ceil(e/h)*h-m)/h,b=Math.abs(p-t);(c<0||b<d)&&(!r||p<=t)&&(d=b,c=h)}return l=Math.floor(l/c)*c,e=Math.ceil(e/c)*c,t=Math.round((e-l)/c),{scale:a,step:c,count:t,min:l,max:e}};var De=class{date_format=!1;string_format=!1;fraction_format=!1;twelve_hour=!1;fraction_denominator=0;fraction_integer=!0;fraction_align=0;fraction_denominator_digits=0;integer_min_digits=0;decimal_min_digits=0;decimal_max_digits=0;grouping=!1;has_number_format=!1;prefix=[{text:""}];suffix=[{text:""}];scaling=0;percent=!1;exponential=!1;has_asterisk=!1};var Pi=42,Oi=95,Br=63,Vt=48,Hi=46,$r=44,Gi=37,jr=34,mt=35,Bi=59,Dt=92,$i=64,No=91,Po=93,ji=69,qi=101,Oo=72,Ho=104,Go=77,Bo=109,$o=83,jo=115,qo=68,Jo=100,Wo=89,Xo=121,Ko=65,Yo=97;var zt=class{static date_pattern=!1;static pattern="";static char_index=0;static characters=[];static sections=[];static current_section=new De;static preserve_formatting_characters=!1;static decimal_mark=Hi;static group_separator=$r;static Parse(e){if(this.pattern=e,this.characters=e.split("").map(t=>t.charCodeAt(0)),this.char_index=0,this.current_section=new De,this.sections=[this.current_section],this.ParseDatePattern())return this.sections;for(this.char_index=0,this.current_section=new De,this.sections=[this.current_section];this.char_index<this.characters.length;)this.ConsumeChar();return this.sections}static ConsumeString(){let e="";for(this.preserve_formatting_characters&&(e+=this.pattern[this.char_index]),++this.char_index;this.char_index<this.characters.length;this.char_index++)switch(this.characters[this.char_index]){case Dt:this.preserve_formatting_characters&&(e+=this.pattern[this.char_index]),this.char_index+1<this.characters.length&&(e+=this.pattern[++this.char_index]);break;case jr:return this.preserve_formatting_characters&&(e+=this.pattern[this.char_index]),this.char_index++,e;default:e+=this.pattern[this.char_index];break}throw new Error("unterminated string")}static ConsumeFormatting(){let e="";for(++this.char_index;this.char_index<this.characters.length;this.char_index++)switch(this.characters[this.char_index]){case Dt:throw new Error("invalid escape character in formatting block");case Po:return this.char_index++,e;default:e+=this.pattern[this.char_index];break}throw new Error("unterminated format")}static ScanFractionFormat(){let e=/^([#?]+ +){0,1}([#?]+)\/([#?0-9]+)(?:$|[^#?0-9])/,r=this.pattern.substr(this.char_index).match(e);if(!r)return!1;let i=(r[1]||"").length+r[2].length+r[3].length+1;this.current_section.fraction_format=!0,this.current_section.fraction_integer=!!r[1];let n=Number(r[3]);return isNaN(n)||(this.current_section.fraction_denominator=n),this.current_section.decimal_max_digits=this.current_section.fraction_denominator_digits=r[3].length,this.char_index+=i,this.current_section.has_number_format=!0,!0}static ConsumeNumberFormat(){let e=0;for(this.char_index;this.char_index<this.characters.length;this.char_index++)switch(this.characters[this.char_index]){case this.group_separator:{let r=!1;for(let i=this.char_index+1;!r&&i<this.characters.length;i++){let n=this.characters[i];if(n===this.decimal_mark||n===mt||n===Vt)r=!0;else if(n!==$r)break}if(r){if(e===1)throw new Error("invalid grouping in decimal part");this.current_section.grouping=!0}else this.current_section.scaling=(this.current_section.scaling||1)*1e3}break;case this.decimal_mark:if(e===1)throw new Error("too many decimal marks");e=1;break;case mt:e===1?this.current_section.decimal_max_digits++:this.current_section.integer_min_digits&&this.current_section.integer_min_digits++;break;case Vt:e===1?(this.current_section.decimal_max_digits++,this.current_section.decimal_min_digits=this.current_section.decimal_max_digits):this.current_section.integer_min_digits++;break;default:return}}static AppendCharAsText(e=!0){this.current_section.has_number_format?this.current_section.suffix[this.current_section.suffix.length-1].text+=this.pattern[this.char_index]:this.current_section.prefix[this.current_section.prefix.length-1].text+=this.pattern[this.char_index],e&&this.char_index++}static AppendString(e){this.current_section.has_number_format?this.current_section.suffix[this.current_section.suffix.length-1].text+=e:this.current_section.prefix[this.current_section.prefix.length-1].text+=e}static AppendTextPart(e){this.current_section.has_number_format?(this.current_section.suffix.push(e),this.current_section.suffix.push({text:""})):(this.current_section.prefix.push(e),this.current_section.prefix.push({text:""}))}static ConsumeChar(){let e=this.characters[this.char_index];if(!((e===Br||e===mt)&&!this.current_section.has_number_format&&!this.current_section.string_format&&this.ScanFractionFormat()))switch(e){case Bi:this.char_index++,this.current_section=new De,this.sections.length===3&&(this.current_section.string_format=!0),this.sections.push(this.current_section);break;case $i:this.char_index++,this.AppendTextPart({text:"@",flag:5}),this.current_section.string_format=!0;break;case Vt:case mt:case Hi:case $r:!this.current_section.has_number_format&&!this.current_section.string_format?(this.ConsumeNumberFormat(),this.current_section.has_number_format=!0):this.AppendCharAsText();break;case No:this.AppendTextPart({text:this.ConsumeFormatting(),flag:6});break;case jr:this.AppendString(this.ConsumeString());break;case Br:this.preserve_formatting_characters?this.AppendCharAsText():(this.AppendTextPart({text:"0",flag:1}),this.char_index++);break;case Oi:if(this.preserve_formatting_characters)this.AppendCharAsText();else{if(++this.char_index>=this.characters.length)throw new Error("invalid pad character at end");this.AppendTextPart({text:this.pattern[this.char_index++],flag:1})}break;case Pi:if(this.current_section.has_asterisk)throw new Error("we don't support multiple asterisks");if(this.preserve_formatting_characters)this.AppendCharAsText();else{if(++this.char_index>=this.characters.length)throw new Error("invalid pad character at end");this.AppendTextPart({text:this.pattern[this.char_index++],flag:2}),this.current_section.has_asterisk=!0}break;case qi:case ji:this.current_section.percent||this.current_section.exponential||this.current_section.string_format?this.AppendCharAsText():(this.current_section.exponential=!0,this.char_index++);break;case Gi:!this.current_section.exponential&&!this.current_section.string_format&&(this.current_section.percent=!0),this.AppendCharAsText();break;case Dt:if(this.preserve_formatting_characters&&this.AppendCharAsText(!1),++this.char_index>=this.characters.length)throw new Error("invalid escape character at end");this.AppendCharAsText();break;default:this.AppendCharAsText()}}static ParseDatePattern(){for(this.date_pattern=!0;this.date_pattern&&this.char_index<this.pattern.length;)this.DatePatternConsumeChar();if(this.date_pattern){this.date_pattern=!1;for(let e of this.sections)for(let t of e.prefix)t.flag&&t.flag&7&&(this.date_pattern=!0)}return this.date_pattern&&(this.sections[0].date_format=!0,this.sections[0].prefix.forEach((e,t)=>{if(e.flag===3&&(e.text==="mm"||e.text==="m")){if(t)for(let r=t-1;r;r--){let i=this.sections[0].prefix[r];if(i.flag===3){/h/i.test(i.text)&&(e.flag=4,e.text=e.text.toLowerCase());break}}if(t<this.sections[0].prefix.length-1)for(let r=t+1;r<this.sections[0].prefix.length;r++){let i=this.sections[0].prefix[r];if(i.flag===3){/s/i.test(i.text)&&(e.flag=4,e.text=e.text.toLowerCase());break}}}})),this.date_pattern}static ConsumeDatePart(){let e=this.pattern[this.char_index++],t=e.toLowerCase(),r={text:e,flag:3};for(;this.pattern[this.char_index]&&this.pattern[this.char_index].toLowerCase()===t;)r.text+=this.pattern[this.char_index++];if(t==="s"&&this.pattern[this.char_index]===".")for(r.text+=this.pattern[this.char_index++];this.pattern[this.char_index]==="0";)r.text+=this.pattern[this.char_index++];return r}static ConsumeAMPM(){let e=this.pattern.substr(this.char_index,5);if(e==="am/pm"||e==="AM/PM")return this.char_index+=5,this.sections[0].twelve_hour=!0,{text:e,flag:3};if(e=this.pattern.substr(this.char_index,3),e==="a/p"||e==="A/P")return this.char_index+=3,this.sections[0].twelve_hour=!0,{text:e,flag:3}}static DatePatternConsumeChar(){switch(this.characters[this.char_index]){case Bi:this.char_index=this.characters.length;break;case Vt:case mt:case qi:case ji:case Gi:case $i:this.date_pattern=!1;break;case Oo:case Ho:case Go:case Bo:case $o:case jo:case qo:case Jo:case Wo:case Xo:this.AppendTextPart(this.ConsumeDatePart());break;case Ko:case Yo:{let t=this.ConsumeAMPM();t?this.AppendTextPart(t):this.AppendCharAsText()}break;case jr:this.AppendString(this.ConsumeString());break;case Br:this.preserve_formatting_characters?this.AppendCharAsText():(this.AppendTextPart({text:"0",flag:1}),this.char_index++);break;case Oi:if(this.preserve_formatting_characters)this.AppendCharAsText();else{if(++this.char_index>=this.characters.length)throw new Error("invalid pad character at end");this.AppendTextPart({text:this.pattern[this.char_index++],flag:1})}break;case Pi:if(this.current_section.has_asterisk)throw new Error("we don't support multiple asterisks");if(this.preserve_formatting_characters)this.AppendCharAsText();else{if(++this.char_index>=this.characters.length)throw new Error("invalid pad character at end");this.AppendTextPart({text:this.pattern[this.char_index++],flag:2}),this.current_section.has_asterisk=!0}break;case Dt:if(this.preserve_formatting_characters&&this.AppendCharAsText(!1),++this.char_index>=this.characters.length)throw new Error("invalid escape character at end");this.AppendCharAsText();break;default:this.AppendCharAsText()}}};var Re=l=>(l>=60&&l--,new Date(-22090752e5+864e5*l)),Ae=(l,e=!0)=>{if(e){let t=new Date(l);l=new Date(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()).getTime()}return l=(l+22090752e5)/864e5,l>=60&&l++,l},ue=class l{static grouping_regexp=/\d{1,3}(?=(\d{3})+(?!\d))/g;static fraction_limits=[9,99,999,9999];static imaginary_character="\u{1D456}";static minus_character="-";magic_decimal=!1;transform_value;_pattern="";sections;decimal_zero_regexp=[];cloned=[];get pattern(){return this._pattern}get date_format(){return this.sections[0]&&this.sections[0].date_format}constructor(e){if(this._pattern=e,this.sections=zt.Parse(e),this.sections.length||(this.sections=[]),this.sections[0]||(this.sections[0]=new De),this.sections[1]||(this.sections[1]={...this.sections[0]},this.sections[1].prefix=JSON.parse(JSON.stringify(this.sections[1].prefix)),this.sections[1].suffix=JSON.parse(JSON.stringify(this.sections[1].suffix)),this.sections[1].prefix.push({text:"-"}),this.cloned[1]=!0),this.sections[2]||(this.sections[2]={...this.sections[0]},this.cloned[2]=!0),!this.sections[3]){for(let t of this.sections[0].prefix)if(t.flag===5){this.sections[3]={...this.sections[0]},this.sections[3].string_format=!0,this.cloned[3]=!0;break}}this.decimal_zero_regexp=this.sections.map(t=>{if(t.decimal_max_digits>t.decimal_min_digits)return new RegExp(`0{1,${t.decimal_max_digits-t.decimal_min_digits}}(?:$|e)`)})}static FormatPartsAsText(e,t=0){let r=-1,i=e.map((n,o)=>{switch(n.flag){case 2:return r=o,n.text;case 1:return n.text.replace(/./g," ");case 6:return"";default:return n.text}});if(r>=0&&t){let n=i.reduce((a,s,c)=>c===r?a:a+s.length,0),o="";for(let a=0;a<t-n;a++)o+=i[r];i[r]=o}return i.join("")}SetDecimal(e){for(let t of this.sections)t.fraction_format||(t.decimal_min_digits=e,t.decimal_max_digits=e)}IncreaseDecimal(){this.sections.forEach(e=>{e.fraction_format?e.fraction_denominator||(e.fraction_denominator_digits=Math.min(e.fraction_denominator_digits+1,4)):(e.decimal_min_digits++,e.decimal_max_digits=e.decimal_min_digits)})}DecreaseDecimal(){this.sections.forEach(e=>{e.fraction_format?e.fraction_denominator||(e.fraction_denominator_digits=Math.max(e.fraction_denominator_digits-1,1)):(e.decimal_min_digits=Math.max(0,e.decimal_min_digits-1),e.decimal_max_digits=e.decimal_min_digits)})}AddGrouping(){this.sections.forEach(e=>{e.grouping=!0})}RemoveGrouping(){this.sections.forEach(e=>{e.grouping=!1})}ToggleGrouping(){let e=!this.sections[0].grouping;this.sections.forEach(t=>{t.grouping=e})}toString(){return this.sections[0].date_format?this._pattern:this.sections.filter((e,t)=>!this.cloned[t]).map(e=>{let t="",r=0;if(e.fraction_format){e.fraction_integer&&(t+="? ");let i="";for(let n=0;n<e.fraction_denominator_digits;n++)i+="#";t+=i,t+="/",e.fraction_denominator?t+=e.fraction_denominator:t+=i}else if(e.has_number_format){for(r=0;r<e.integer_min_digits;r++)t+="0";if(e.grouping&&(t.length<4&&(t=("####"+t).slice(-4)),t=t.replace(/[\d#]{1,3}(?=([\d#]{3})+(?![\d#]))/g,"$&,")),e.decimal_max_digits||e.decimal_min_digits){for(t+=".",r=0;r<e.decimal_min_digits;r++)t+="0";for(;r<e.decimal_max_digits;r++)t+="#"}if(e.scaling){let i=Math.log10(e.scaling)/3;for(r=0;r<i;r++)t+=","}e.exponential&&(t+="e")}return e.prefix.map(i=>i.flag===1?i.text==="0"?"?":"_"+i.text:i.flag===2?"*"+i.text:i.flag===6?"["+i.text+"]":i.text).join("")+t+e.suffix.map(i=>i.flag===1?i.text==="0"?"?":"_"+i.text:i.flag===2?"*"+i.text:i.text).join("")}).join(";")}FormatDimensionedQuantity(e){if(this.transform_value){let r=this.transform_value(e);if(Fr(r))e=r;else return typeof r=="string"?r:this.FormatParts(r)}let t=this.FormatParts(e.value||0);return e.unit&&t.push({text:" "},{text:e.unit}),t}FormatComplex(e){if(e.imaginary===1/0||e.imaginary===-1/0||e.real===1/0||e.real===-1/0)return[{text:"Infinity"}];let t=[],r=[],i=!1,n=!!e.imaginary;n&&(t=this.FormatParts(e.imaginary),n=t.some(s=>/[1-9]/.test(s.text)),t.length===1&&this.sections[0].integer_min_digits<=1&&t[0].text==="1"?(t[0].text="",i=!0):t.length===1&&this.sections[1].integer_min_digits<=1&&t[0].text==="-1"&&(t[0].text="-",i=!0));let o=!!e.real;o&&(r=this.FormatParts(e.real),o=r.some(s=>/[1-9]/.test(s.text)));let a=[];if(o||!o&&!n){if(a.push(...r),n){a.push({text:e.imaginary<0?` ${l.minus_character} `:" + "});let s=i?[]:this.FormatParts(Math.abs(e.imaginary));a.push(...s,{text:l.imaginary_character})}}else n&&a.push(...t,{text:l.imaginary_character});return a}FormatParts(e){if(typeof e!="number"&&!this.sections[3])return[{text:(e??"").toString()}];let{parts:t,section:r}=this.BaseFormat(e),i=[];if(r.date_format||r.string_format)for(let n of t)typeof n=="string"?i.push({text:n}):i.push(n);else this.magic_decimal&&t[1]===""&&t.splice(1,1),i=[...r.prefix.map(n=>({...n})),{text:r.has_number_format?t.join(F.decimal_separator):""},...r.suffix.map(n=>({...n}))];for(let n=1;n<i.length;n++)i[n].flag===i[n-1].flag&&(i[n].text=i[n-1].text+i[n].text,i[n-1].text="");return i.filter(n=>n.text)}Format(e,t=0){return l.FormatPartsAsText(this.FormatParts(e),t)}ZeroPad(e,t){for(;e.length<t;)e="0"+e;return e}DateFormat(e){let t=Re(e),r=this.sections[0],i=t.getUTCHours();return r.twelve_hour&&(i>12&&(i-=12),i===0&&(i=12)),{parts:r.prefix.map(o=>{if(o.flag===4)return o.text==="mm"?{text:this.ZeroPad(t.getUTCMinutes().toString(),2)}:{text:this.ZeroPad(t.getUTCMinutes().toString(),1)};if(o.flag===3){switch(o.text.toLowerCase()){case"am/pm":case"a/p":{let s=o.text.split("/");return{text:t.getUTCHours()>12?s[1]:s[0]}}case"mmmmm":return{text:F.date_components.long_months[t.getUTCMonth()][0]};case"mmmm":return o.text==="MMMM"?{text:F.date_components.long_months[t.getUTCMonth()].toUpperCase()}:{text:F.date_components.long_months[t.getUTCMonth()]};case"mmm":return o.text==="MMM"?{text:F.date_components.short_months[t.getUTCMonth()].toUpperCase()}:{text:F.date_components.short_months[t.getUTCMonth()]};case"mm":return{text:this.ZeroPad((t.getUTCMonth()+1).toString(),2)};case"m":return{text:this.ZeroPad((t.getUTCMonth()+1).toString(),1)};case"ddddd":case"dddd":return o.text==="DDDDD"||o.text==="DDDD"?{text:F.date_components.long_days[t.getUTCDay()].toUpperCase()}:{text:F.date_components.long_days[t.getUTCDay()]};case"ddd":return o.text==="DDD"?{text:F.date_components.short_days[t.getUTCDay()].toUpperCase()}:{text:F.date_components.short_days[t.getUTCDay()]};case"dd":return{text:this.ZeroPad(t.getUTCDate().toString(),2)};case"d":return{text:this.ZeroPad(t.getUTCDate().toString(),1)};case"yyyy":case"yyy":return{text:t.getUTCFullYear().toString()};case"yy":case"y":return{text:this.ZeroPad((t.getUTCFullYear()%100).toString(),2)};case"hh":return{text:this.ZeroPad(i.toString(),2)};case"h":return{text:this.ZeroPad(i.toString(),1)};case"ss":return{text:this.ZeroPad(t.getUTCSeconds().toString(),2)};case"s":return{text:this.ZeroPad(t.getUTCSeconds().toString(),1)}}let a=o.text.match(/^(s+)\.(0+)$/);if(a)return{text:this.ZeroPad(t.getUTCSeconds().toString(),a[1].length)+F.decimal_separator+(t.getUTCMilliseconds()/1e3).toFixed(a[2].length).substr(2)}}return{...o}}),section:r}}StringFormat(e,t){let r=[];for(let i of t.prefix)i.flag===5?r.push({text:e}):r.push({...i});return{parts:r,section:t}}Round2(e,t){let r=Math.pow(10,t);return Math.round(r*e)/r}FormatFraction(e,t){t.percent&&(e*=100);let r={denominator:1,numerator:Math.round(e),error:Math.abs(Math.round(e)-e)};if(t.fraction_denominator)r.denominator=t.fraction_denominator,r.numerator=Math.round(e*r.denominator);else if(r.error){let n=l.fraction_limits[t.fraction_denominator_digits-1]||l.fraction_limits[0];for(let o=2;o<=n;o++){let a=Math.round(e*o),s=Math.abs(a/o-e);if(s<r.error&&(r={numerator:a,denominator:o,error:s},!s))break}}let i=[];if(t.fraction_integer){let n=Math.floor(r.numerator/r.denominator);r.numerator%=r.denominator,(n||!r.numerator)&&(i.push(n.toString()),r.numerator&&i.push(" "))}else r.numerator||i.push("0");return r.numerator&&(i.push(r.numerator.toString()),i.push("/"),i.push(r.denominator.toString())),i.join("")}BaseFormat(e){if(this.sections[0].date_format)return this.DateFormat(Number(e));if(typeof e!="number")return this.StringFormat((e??"").toString(),this.sections[3]);let t=this.sections[0],r=this.decimal_zero_regexp[0];e<0&&(t=this.sections[1]);let i=t.percent?t.decimal_max_digits+2:t.decimal_max_digits,n=Math.pow(10,-i)/2,o=Math.abs(e);if(o<n&&(t=this.sections[2],r=this.decimal_zero_regexp[2]),t.scaling&&(o/=t.scaling,o<n&&(t=this.sections[2],r=this.decimal_zero_regexp[2])),t.string_format)return this.StringFormat(e.toString(),t);let a="";if(t.fraction_format)return{parts:[this.FormatFraction(o,t)],section:t};t.exponential?a=o.toExponential(t.decimal_max_digits):(t.percent&&(o*=100),a=this.Round2(o,t.decimal_max_digits).toFixed(t.decimal_max_digits)),r&&(a=a.replace(r,""));let s=a.split(".");for(;s[0].length<t.integer_min_digits;)s[0]=("0000000000000000"+s[0]).slice(-t.integer_min_digits);return t.integer_min_digits===0&&s[0]==="0"&&(s[0]=""),t.grouping&&(s[0]=s[0].replace(l.grouping_regexp,"$&"+F.grouping_separator)),{parts:s,section:t}}};var L=class{static cache={};static complex_general;static symbolc_name_map={};static base_formats={Accounting:"_(#,##0.00_);(#,##0.00);-???",Number:"0.00",Integer:"0",Percent:"0.00%",General:"0.######",Fraction:"# ?/?",Dollar:"$* _(#,##0.00_);$* (#,##0.00);$* -???",Exponential:"0.000e","Short Date":"mm/dd/yy","Long Date":"dddd, mmm d yyyy",Timestamp:"mm-dd-yy hh:mm:ss"};static aliases={Scientific:"Exponential",Percentage:"Percent",Currency:"Dollar"};static Get(e,t=!1){if(t&&e==="General")return this.complex_general;let r=this.symbolc_name_map[e.toLowerCase()],i=this.cache[r||e];return i||(i=new ue(e),this.cache[e]=i),i}static Equals(e,t){if(e===t)return!0;let r=this.Get(e),i=this.Get(t);return r.pattern===i.pattern}static Translate(e){let t=this.symbolc_name_map[e.toLowerCase()];return t?this.cache[t].toString():e}static SymbolicName(e){for(let t of Object.keys(this.base_formats))if(e===this.base_formats[t])return t;return null}static InitCache(){for(let e of Object.keys(this.base_formats))this.cache[e]=new ue(this.base_formats[e]),this.symbolc_name_map[e.toLowerCase()]=e;this.cache.General.magic_decimal=!0,this.complex_general=new ue("0.###"),this.complex_general.magic_decimal=!0;for(let e of Object.keys(this.aliases))this.cache[e]=this.cache[this.aliases[e]],this.symbolc_name_map[e.toLowerCase()]=e}};L.InitCache();var Ji=new Date().getUTCFullYear(),Jr=class{compare_day;compare_month;TestDate(e){let t=Date.parse(e);if(isNaN(t))return!1;let r=new Date(t),n=e.replace(/[\d\-\\/,.\s]+/g," ").toLocaleLowerCase().split(/\s+/).map(s=>s.trim()).filter(s=>!!s);if(!n.length)return t;if(!this.compare_month){this.compare_month={};for(let s=0;s<12;s++)this.compare_month[F.date_components.long_months[s].toLocaleLowerCase().replace(/\./,"")]=s,this.compare_month[F.date_components.short_months[s].toLocaleLowerCase().replace(/\./,"")]=s}if(!this.compare_day){this.compare_day={};for(let s=0;s<7;s++)this.compare_day[F.date_components.long_days[s].toLocaleLowerCase().replace(/\./,"")]=s,this.compare_day[F.date_components.short_days[s].toLocaleLowerCase().replace(/\./,"")]=s}let o=!1,a=!1;for(let s of n){let c=!1;for(let[d,u]of Object.entries(this.compare_month))if(s===d){if(o||r.getUTCMonth()!==u)return!1;c=!0,o=!0}if(!c){for(let[d,u]of Object.entries(this.compare_day))if(s===d){if(a||r.getUTCDay()!==u)return!1;c=!0,a=!0}}if(!c)return!1}return a&&!o?!1:t}TryParse(e=""){let t={};if(e[0]==="'")return{value:e,type:2};if(e==="")return{value:e,type:2};if(e==="NaN")return{value:NaN,type:3,hints:{Nan:!0}};let r=e.trim(),i=r.match(/^[$](.*?)$/);i&&(r=i[1],t.Currency=!0);let n=r.match(/^\((.*?)\)$/);n&&(r=n[1],t.Parens=!0);let o=r.match(/^(.*?)%\s*$/);o&&(r=o[1],t.Percent=!0),F.decimal_separator==="."?/,/.test(r)&&(r=r.replace(/,/g,""),t.Grouping=!0):(r=r.replace(/(\d)\s+/g,"$1"),r=r.replace(/\./g,""),r=r.replace(/,/,"."));let a=Number(r);if(a===null||isNaN(a)){let s=e.toLowerCase();if(s==="false")return{value:!1,type:4};if(s==="true")return{value:!0,type:4};let c=this.TestDate(e);if(c!==!1&&!isNaN(c)){let d=new Date(c),u=d.getUTCFullYear();if(u>=Ji-200&&u<=Ji+200)return t={Date:!0},(d.getHours()||d.getMinutes()||d.getSeconds())&&(t.Time=!0),{value:Ae(c,!0),type:3,hints:t}}return{value:e,type:2}}if(n&&(a=-a),o){let s=a<0?-1:1,c=(s*a).toString().split(".");c[0]=("00"+c[0]).replace(/(\d\d)$/,".$1"),a=Number(c.join(""))*s}return/e/.test(e)&&(t.Exponential=!0),{value:a,type:3,hints:t}}},ye=new Jr;var Lt=class{constructor(e,t,r={x:0,y:0},i){this.theme=t;this.offset=r;let n=O.GetInstance(i.ownerDocument);this.g=n.SVG("g"),this.g.setAttribute("transform",`translate(${r.x}, ${r.y})`),this.outline=n.SVG("rect","treb-selection-outline"),e?(this.g.setAttribute("class","selection primary-selection"),this.fill=n.SVG("path","treb-selection-fill"),this.nub=n.SVG("rect","treb-selection-nub"),this.g.appendChild(this.fill),this.g.appendChild(this.outline),this.g.appendChild(this.nub)):(this.g.setAttribute("class","selection alternate-selection"),this.fill=n.SVG("rect","treb-selection-fill"),this.g.appendChild(this.fill),this.g.appendChild(this.outline))}g;outline;fill;nub;Offset(e){this.g.setAttribute("transform",`translate(${e.x}, ${e.y})`)}Show(e=!0){this.g.style.display=e?"block":"none"}SetOutline(e,t=!1){this.outline.setAttribute("x",(e.left-1).toString()),this.outline.setAttribute("y",(e.top-1).toString()),this.outline.setAttribute("width",(e.width+1).toString()),this.outline.setAttribute("height",(e.height+1).toString()),t&&this.fill&&(this.fill.setAttribute("x",e.left.toString()),this.fill.setAttribute("y",e.top.toString()),this.fill.setAttribute("width",e.width.toString()),this.fill.setAttribute("height",e.height.toString()))}SetFill(e,t){if(!this.fill)return;let r=[];r.push("M"+e.left+" "+e.top),r.push("L"+e.left+" "+e.bottom),r.push("L"+e.right+" "+e.bottom),r.push("L"+e.right+" "+e.top),r.push("Z"),r.push("M"+t.left+" "+t.top),r.push("L"+t.right+" "+t.top),r.push("L"+t.right+" "+t.bottom),r.push("L"+t.left+" "+t.bottom),r.push("Z"),this.fill.setAttribute("d",r.join(" "))}SetNub(e){this.nub&&(this.nub.setAttribute("x",(e.left+e.width-4).toString()),this.nub.setAttribute("y",(e.top+e.height-4).toString()),this.nub.setAttribute("width","7"),this.nub.setAttribute("height","7"))}};var He=class{constructor(e,t,r){this.theme=e;this.container=t;this.orientation=r;let i=O.GetInstance(t.ownerDocument);this.g=i.SVG("g","treb-header-overlay"),this.overlay=i.SVG("rect","treb-overlay"),this.highlight=i.SVG("rect","treb-highlight"),this.g.style.display="none",this.g.appendChild(this.highlight),this.g.appendChild(this.overlay),t.appendChild(this.g)}g;overlay;highlight;Remove(){this.container.removeChild(this.g)}Hide(){this.g.style.display="none"}Show(e,t,r,i){this.overlay.setAttribute("x",e.toString()),this.overlay.setAttribute("y",t.toString()),this.overlay.setAttribute("width",r.toString()),this.overlay.setAttribute("height",i.toString()),this.orientation===0?(this.highlight.setAttribute("x",e.toString()),this.highlight.setAttribute("y",(t+i-2).toString()),this.highlight.setAttribute("width",r.toString()),this.highlight.setAttribute("height","2")):(this.highlight.setAttribute("x",(e+r-2).toString()),this.highlight.setAttribute("y",t.toString()),this.highlight.setAttribute("width","2"),this.highlight.setAttribute("height",i.toString())),this.g.style.display="block"}};var It=class{constructor(e,t,r,i,n,o){this.theme=e;this.layout=t;this.model=r;this.view=i;this.primary_selection=n;this.additional_selections=o}nub_rectangle=new B(-1,-1,0,0);cached_additional_selections="";grid_selections=[];row_header_selections=[];column_header_selections=[];corner_selections=[];row_overlay;column_overlay;corner_row_overlay;corner_column_overlay;Initialize(){this.row_overlay=new He(this.theme,this.layout.row_header_selection,0),this.column_overlay=new He(this.theme,this.layout.column_header_selection,1),this.corner_row_overlay=new He(this.theme,this.layout.corner_selection,0),this.corner_column_overlay=new He(this.theme,this.layout.corner_selection,1)}RenderSelections(e=!0,t=!0){let r=this.primary_selection.empty;e||(this.primary_selection.empty=!0);let i=[this.primary_selection].concat(this.additional_selections);this.RenderSelectionGroup(i,this.layout.grid_selection,void 0,void 0,this.grid_selections,void 0,t);let n=new B(-1,-1,0,0);if(!this.primary_selection.empty){let s=this.view.active_sheet.RealArea(this.primary_selection.area);n=this.layout.CellAddressToRectangle(s.start).Combine(this.layout.CellAddressToRectangle(s.end))}if(!this.primary_selection.empty&&this.layout.header_offset.y>2?(this.row_overlay.Show(n.left,0,n.width,this.layout.header_offset.y),this.corner_row_overlay.Show(n.left+this.layout.header_offset.x,0,n.width,this.layout.header_offset.y)):(this.row_overlay.Hide(),this.corner_row_overlay.Hide()),!this.primary_selection.empty&&this.layout.header_offset.x>2?(this.column_overlay.Show(0,n.top,this.layout.header_offset.x,n.height),this.corner_column_overlay.Show(0,n.top+this.layout.header_offset.y,this.layout.header_offset.x,n.height)):(this.column_overlay.Hide(),this.corner_column_overlay.Hide()),!this.view.active_sheet.freeze.columns&&!this.view.active_sheet.freeze.rows){this.primary_selection.empty=r;return}let o=[],a=[];if(this.primary_selection.empty)o.push(!1),a.push(!1);else{let s=this.primary_selection.area.start;o.push(s.row<=this.view.active_sheet.freeze.rows||s.row===1/0),a.push(s.column<=this.view.active_sheet.freeze.columns||s.column===1/0)}for(let{area:s}of this.additional_selections)o.push(s.start.row<=this.view.active_sheet.freeze.rows||s.start.row===1/0),a.push(s.start.column<=this.view.active_sheet.freeze.columns||s.start.column===1/0);this.view.active_sheet.freeze.rows&&this.RenderSelectionGroup(i,this.layout.row_header_selection,o,void 0,this.row_header_selections,{x:0,y:this.layout.header_offset.y}),this.view.active_sheet.freeze.columns&&this.RenderSelectionGroup(i,this.layout.column_header_selection,a,void 0,this.column_header_selections,{x:this.layout.header_offset.x,y:0}),this.view.active_sheet.freeze.rows&&this.view.active_sheet.freeze.columns&&this.RenderSelectionGroup(i,this.layout.corner_selection,a,o,this.corner_selections,{...this.layout.header_offset}),this.primary_selection.empty=r}RenderSelectionGroup(e,t,r,i,n,o,a=!0){for(let s=0;s<e.length;s++)if((!e[s].area.start.sheet_id||e[s].area.start.sheet_id===this.view.active_sheet.id)&&!e[s].empty&&(!r||r[s])&&(!i||i[s])){if(a||!e[s].rendered){let d=this.EnsureGridSelectionBlock(t,n,s,o);this.RenderSVGSelection(e[s],d,s)}}else n[s]&&n[s].Show(!1);for(let s=e.length;s<n.length;s++)n[s]&&n[s].Show(!1)}EnsureGridSelectionBlock(e,t,r,i){let n=t[r];if(!n)if(n=new Lt(!r,this.theme,void 0,e),t[r]=n,r){let o=e.querySelector(".alternate-selections");o||(o=this.layout.DOM.SVG("g","alternate-selections"),e.appendChild(o)),o?.appendChild(n.g)}else e.appendChild(n.g);return i&&n.Offset(i),n}ClampEnd(e){return{row:Math.min(e.row,this.view.active_sheet.rows-1),column:Math.min(e.column,this.view.active_sheet.columns-1)}}RenderSVGSelection(e,t,r=0){let i=this.view.active_sheet.RealArea(e.area,!0),n=this.layout.CellAddressToRectangle(i.start);if(i.count>1)n=n.Combine(this.layout.CellAddressToRectangle(i.end));else if(r){let o=this.view.active_sheet.CellData(e.target);o.merge_area&&(n=this.layout.CellAddressToRectangle(o.merge_area.start),n=n.Combine(this.layout.CellAddressToRectangle(o.merge_area.end)))}if(r||(this.nub_rectangle=new B(n.left+n.width-6,n.top+n.height-6,11,11)),n.top===0&&this.layout.header_offset.y<=1&&(n.top=1,n.height-=1),n.left===0&&this.layout.header_offset.x<=1&&(n.left=1,n.width-=1),n.height<=0||n.height<=0){t.Show(!1);return}if(t.SetOutline(n,!!r),r)e.rendered=!0;else{let o=this.layout.CellAddressToRectangle(e.target),a=this.view.active_sheet.CellData(e.target);a.merge_area&&(o=this.layout.CellAddressToRectangle(a.merge_area.start),o=o.Combine(this.layout.CellAddressToRectangle(a.merge_area.end))),t.SetFill(o,n),t.SetNub(n)}t.Show()}};function ke(l,e=[],t,r){typeof e=="string"&&(e=[e]);let i,n=a=>{a.stopPropagation(),a.preventDefault(),i(),r&&r(a)},o=a=>{if(a.stopPropagation(),a.preventDefault(),!a.buttons){i(),r&&r(a);return}t&&t(a)};i=()=>{l.style.display="none",l.removeEventListener("mousemove",o),l.removeEventListener("mouseup",n);for(let a of e)l.classList.remove(a)};for(let a of e)l.classList.add(a);l.style.display="block",t&&l.addEventListener("mousemove",o),r&&l.addEventListener("mouseup",n)}var Ft=class extends _e{constructor(t){super();this.container=t;this.format=L.Get("0.0");let r=O.GetInstance(t.ownerDocument);this.input=r.Create("input","treb-scale-input",t,{events:{keypress:n=>{switch(n.key){case"ArrowUp":case"ArrowDown":n.stopPropagation(),n.preventDefault(),console.info("mark?");break}},keydown:n=>{switch(n.key){case"Enter":this.input.blur();break;case"ArrowUp":this.Tick(-1);break;case"ArrowDown":this.Tick(1);break;case"Escape":this.input.value=this.format.Format(this.scale)+"%",this.input.blur();break;default:return}n.stopPropagation(),n.preventDefault()},focusin:()=>this.input.select(),change:()=>{let n=this.input.value;n=n.replace(/%/g,"");let o=ye.TryParse(n);o.type===3?this.UpdateScale(Number(o.value),!0):this.input.value=this.format.Format(this.scale)+"%"}}});let i=r.Div("treb-slider-container",t);this.slider=r.Create("input",void 0,i,{attrs:{type:"range",min:"50",max:"200",value:"100",step:"2.5"},events:{input:()=>this.UpdateScale(Number(this.slider.value),!0)}}),t.addEventListener("wheel",n=>{n.stopPropagation(),n.preventDefault(),this.Tick(n.deltaY)})}input;slider;scale=0;format;timeout=0;Tick(t){let r=Math.round(this.scale/2.5)*2.5;t>0?this.UpdateScale(r-2.5,!0,!0):t<0&&this.UpdateScale(r+2.5,!0,!0)}UpdateScale(t,r=!1,i=!1){t=Math.max(50,Math.min(200,t)),t!==this.scale&&(this.scale=t,this.input.value=this.format.Format(t)+"%",this.slider.value=t.toFixed(1),r&&(this.timeout||(this.timeout=requestAnimationFrame(()=>{this.timeout=0,this.Publish({type:"scale",value:this.scale/100,keep_focus:i})}))))}};var Nt=class extends _e{constructor(t,r,i,n,o,a){super();this.layout=t;this.model=r;this.view=i;this.options=n;this.theme=o;if(this.DOM=O.GetInstance(a.ownerDocument),this.container=a.querySelector(".treb-spreadsheet-footer"),!this.container)throw new Error("missing container for tab bar");if(n.tab_bar!=="auto"&&this.container.removeAttribute("hidden"),this.tab_container=this.container.querySelector(".treb-spreadsheet-tabs"),this.container.addEventListener("click",s=>{let c=s.target?.dataset.command;if(c)switch(s.stopPropagation(),s.preventDefault(),c){case"add-tab":this.Publish({type:"add-sheet"});break;case"delete-tab":this.Publish({type:"delete-sheet"});break;default:console.info("unhandled command",c)}}),this.options.stats&&(this.stats_panel=this.container.querySelector(".treb-stats-panel")),this.options.scale_control){let s=this.container.querySelector(".treb-scale-control");this.scale_control=new Ft(s),this.scale_control.Subscribe(c=>{this.Publish(c)}),this.UpdateScale(this.options.initial_scale||1)}}tab_container;scale_control;stats_panel;dragging=!1;double_click_data={};tab_color_cache=new Map;_visible=!1;get visible(){return this._visible}set stats_data(t){if(this.stats_panel){this.stats_panel.innerText="";for(let r of t)this.DOM.Create("span","treb-stats-label",this.stats_panel,{text:r.label}),this.DOM.Create("span","treb-stats-value",this.stats_panel,{text:r.value})}}container;DOM;IsDoubleClick(t,r=300){return this.double_click_data.index===t?(clearTimeout(this.double_click_data.timeout),this.double_click_data.index=void 0,this.double_click_data.timeout=void 0,!0):(this.double_click_data.timeout&&clearTimeout(this.double_click_data.timeout),this.double_click_data.index=t,this.double_click_data.timeout=window.setTimeout(()=>{this.double_click_data.index=void 0,this.double_click_data.timeout=void 0},r),!1)}Hide(){this.Show(!1)}Show(t=!0){this.container&&(this._visible=t,t?this.container.removeAttribute("hidden"):this.container.setAttribute("hidden",""))}SetActive(t,r,i=!1){r?(t.setAttribute("selected",""),t.dataset.background_color&&(t.style.backgroundColor=`color-mix(in srgb, ${t.dataset.background_color} 20%, var(--treb-tab-bar-active-tab-background, #fff))`,t.style.color=""),requestAnimationFrame(()=>{if(i)t.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"});else if(t.parentElement){let n=t.offsetLeft,o=t.offsetWidth,a=t.parentElement.clientWidth||0,s=t.parentElement.scrollLeft||0;n>a?t.parentElement.scrollLeft=n-o:s>n&&(t.parentElement.scrollLeft=n)}})):(t.removeAttribute("selected"),t.dataset.background_color&&(t.style.backgroundColor=t.dataset.background_color),t.dataset.foreground_color&&(t.style.color=t.dataset.foreground_color))}UpdateScale(t){this.scale_control?.UpdateScale(t*100)}DoubleClickTab(t,r,i){if(r.contentEditable="true",this.DOM.doc){let n=this.DOM.GetSelection();if(n){n.removeAllRanges();let o=this.DOM.doc.createRange();o.selectNodeContents(r),n.addRange(o)}}r.addEventListener("keydown",n=>{switch(n.key){case"Enter":this.Publish({type:"rename-sheet",name:r.innerText.trim(),sheet:i});break;case"Escape":r.innerText=i.name,this.Publish({type:"cancel"}),this.Update(!0);break;default:return}n.stopPropagation(),n.preventDefault()}),r.addEventListener("focusout",()=>{let n=r.innerText.trim();n!==i.name?this.Publish({type:"rename-sheet",name:n,sheet:i}):this.Update(!0)}),r.focus()}MouseDownTab(t,r,i,n,o){if(t.stopPropagation(),t.preventDefault(),this.IsDoubleClick(n))return;this.Publish({type:"activate-sheet",sheet:i});let a=o.map(p=>p.getBoundingClientRect()),s=n*2-1,c=a[0].left,d=a[a.length-1].right,u=a[0].top,h=a[0].bottom,m=-1,f=(a.length-1)*2+1;for(let p of o)this.SetActive(p,p===r,!0);this.dragging=!0,ke(this.layout.mask,[],p=>{let[b,g]=[p.clientX,p.clientY];if(g>u&&g<h){let x=s;if(b<c)x=m;else if(b>d)x=f;else for(let y=0;y<a.length;y++){let w=a[y];if(b>=w.left&&b<=w.right){y!==n&&(b>=w.left+w.width/2?x=y*2+1:x=y*2-1);break}}x!==s&&(s=x,r.style.order=s.toString(),a=o.map(y=>y.getBoundingClientRect()))}},()=>{let p=n,b=(s+1)/2;this.dragging=!1;for(let g=0;g<this.model.sheets.length;g++)this.model.sheets.list[g].visible||(p>=g&&p++,b>=g&&b++);p===b||p===0&&b<=0||p===o.length-1&&b>=o.length-1||this.Publish({type:"reorder-sheet",index:p,move_before:b})})}UpdateTheme(){this.tab_color_cache.clear(),this.Update()}Update(t=!1){if(this.tab_color_cache.clear(),this.dragging)return;if(this.options.tab_bar==="auto"){if(this.model.sheets.list.reduce((n,o)=>o.visible?n+1:n,0)<=1){this.Show(!1);return}this.Show(!0)}if(!this.tab_container)return;this.tab_container.innerText="";let r=[];for(let i of this.model.sheets.list){if(!i.visible)continue;let n=r.length,o=this.DOM.Create("li");if(o.setAttribute("tabindex","0"),i.tab_color){let c=i.id;if(!this.tab_color_cache.has(c)){let u=D(this.theme,i.tab_color),h=D(this.theme,{offset:i.tab_color});u&&h&&this.tab_color_cache.set(c,{background:u,foreground:h})}let d=this.tab_color_cache.get(c);d&&(o.style.backgroundColor=d.background,o.style.color=d.foreground,o.dataset.background_color=d.background,o.dataset.foreground_color=d.foreground)}o.style.order=(n*2).toString(),o.role="tab",this.SetActive(o,i===this.view.active_sheet,t);let a=c=>this.MouseDownTab(c,o,i,n,r),s=c=>{o.removeEventListener("mousedown",a),o.removeEventListener("dblclick",s),this.DoubleClickTab(c,o,i)};o.textContent=i.name,o.addEventListener("dblclick",s),o.addEventListener("mousedown",a),this.tab_container.appendChild(o),r.push(o)}}};var Ye=class{constructor(e,t,r=!1,i=O.GetInstance()){this.model=e;this.view=t;this.DOM=i;if(r)return;if(!i)throw new Error("missing DOM context");this.dpr=Math.max(1,self.devicePixelRatio||1),this.mask=i.Div("treb-mouse-mask"),this.tooltip=i.Div("treb-tooltip"),this.spill_border=i.SVG("svg","treb-spill-border"),this.spill_border.tabIndex=-1,this.dropdown_caret=i.SVG("svg","treb-dropdown-caret"),this.dropdown_caret.setAttribute("viewBox","0 0 24 24"),this.dropdown_caret.tabIndex=-1;let n=i.SVG("path");n.setAttribute("d","M5,7 L12,17 L19,7"),this.dropdown_caret.appendChild(n),this.dropdown_caret.addEventListener("click",o=>{o.stopPropagation(),o.preventDefault(),this.grid_cover.classList.remove("nub-select");let a=this.dropdown_caret.getAttribute("class")||"";/active/i.test(a)?this.dropdown_caret.setAttribute("class","treb-dropdown-caret"):(this.dropdown_caret.setAttribute("class","treb-dropdown-caret active"),this.dropdown_list.focus())}),this.dropdown_list=i.Div("treb-dropdown-list",void 0,{attrs:{tabindex:"-1"}}),this.dropdown_list.addEventListener("keydown",o=>{let a=0;switch(o.key){case"ArrowDown":a=1;break;case"ArrowUp":a=-1;break;case"Escape":break;case"Enter":break;default:console.info(o.key);return}if(o.stopPropagation(),o.preventDefault(),o.key==="Escape"||o.key==="Enter"){if(this.container?.focus(),this.dropdown_caret.setAttribute("class","treb-dropdown-caret"),o.key==="Enter"&&this.dropdown_callback&&this.dropdown_selected){let s=this.dropdown_selected.dataset.dropdown_value;this.dropdown_callback.call(0,s?JSON.parse(s):void 0)}}else if(a&&this.dropdown_selected)if(a>0&&this.dropdown_selected.nextSibling){this.dropdown_selected.nextSibling.classList.add("selected"),this.dropdown_selected.classList.remove("selected"),this.dropdown_selected=this.dropdown_selected.nextSibling;let s=this.dropdown_selected.offsetTop+this.dropdown_selected.offsetHeight;s>this.dropdown_list.offsetHeight+this.dropdown_list.scrollTop&&(this.dropdown_list.scrollTop=s-this.dropdown_list.offsetHeight)}else a<0&&this.dropdown_selected.previousSibling&&(this.dropdown_selected.previousSibling.classList.add("selected"),this.dropdown_selected.classList.remove("selected"),this.dropdown_selected=this.dropdown_selected.previousSibling,this.dropdown_selected.offsetTop<this.dropdown_list.scrollTop&&(this.dropdown_list.scrollTop=this.dropdown_selected.offsetTop))}),this.dropdown_list.addEventListener("mousedown",o=>{let a=o.target;if(o.target!==this.dropdown_list&&(o.stopPropagation(),o.preventDefault(),this.container?.focus(),this.dropdown_caret.setAttribute("class","treb-dropdown-caret"),this.dropdown_callback)){let s=a.dataset.dropdown_value;this.dropdown_callback.call(0,s?JSON.parse(s):void 0)}}),this.dropdown_list.addEventListener("mousemove",o=>{let a=o.target;a!==this.dropdown_selected&&(this.grid_cover.classList.remove("nub-select"),this.dropdown_selected&&this.dropdown_selected.classList.remove("selected"),a.classList.add("selected"),this.dropdown_selected=a)}),this.mock_selection=i.Div("mock-selection-node",void 0,{html:"&nbsp;"}),this.note_node=i.Div("treb-note"),this.title_node=i.Div("treb-hover-title"),this.sort_button=i.Create("button","treb-sort-button",void 0,{attrs:{title:"Sort table",tabindex:"-1"}}),this.HideNote()}column_header;row_header;contents;buffer_canvas;corner;corner_canvas;grid_selection;grid_cover;column_header_cover;row_header_cover;annotation_container;mask;mock_selection;container;grid_tiles=[];column_header_tiles=[];row_header_tiles=[];corner_selection;row_header_selection;column_header_selection;corner_annotations;row_header_annotations;column_header_annotations;frozen_row_tiles=[];frozen_column_tiles=[];header_size={width:0,height:0};applied_theme_colors=[];last_column=0;total_height=0;total_width=0;default_row_height=0;default_column_width=0;header_offset={x:0,y:0};dpr=1;scale=1;scroll_reference_node;get scroll_offset(){return this.scroll_reference_node?{x:this.scroll_reference_node.scrollLeft,y:this.scroll_reference_node.scrollTop}:{x:0,y:0}}set scroll_offset(e){this.scroll_reference_node&&(this.scroll_reference_node.scrollLeft=e.x,this.scroll_reference_node.scrollTop=e.y)}dropdown_caret;spill_border;trident=typeof navigator<"u"&&navigator.userAgent&&/trident/i.test(navigator.userAgent);default_tile_size={width:1200,height:800};tooltip_state;tooltip;dropdown_list;dropdown_caret_visible=!1;dropdown_callback;dropdown_selected;note_node;sort_button;title_node;row_cache=[];column_cache=[];initialized=!1;FocusInLayout(e){return!1}UpdateDPR(){let e=Math.max(1,self.devicePixelRatio||1);return e===this.dpr?!1:(this.dpr=e,!0)}ColumnWidth(e){return Math.round(this.view.active_sheet.GetColumnWidth(e)*this.scale)}RowHeight(e){return Math.round(this.view.active_sheet.GetRowHeight(e)*this.scale)}SetRowHeight(e,t){this.view.active_sheet.SetRowHeight(e,Math.round(t/this.scale))}SetColumnWidth(e,t){this.view.active_sheet.SetColumnWidth(e,Math.round(t/this.scale))}ShowSelections(e=!0){this.grid_selection.style.display=e?"block":"none"}HideTitle(){this.title_node.style.opacity="0"}ShowTitle(e,t){if(this.title_node.textContent=e,!this.title_node.parentElement)return;let r=this.title_node.parentElement.getBoundingClientRect(),i=this.OffsetCellAddressToRectangle(t).Shift(this.header_size.width,this.header_size.height);this.title_node.style.left=r.left+i.left-this.scroll_reference_node.scrollLeft+0+"px",this.title_node.style.top=r.top+i.bottom-this.scroll_reference_node.scrollTop+8+"px",this.title_node.style.opacity="1"}HideNote(){this.note_node.style.opacity="0",this.note_node.style.pointerEvents="none"}HideTableSortButton(){this.sort_button.style.opacity="0",this.sort_button.style.pointerEvents="none",this.sort_button.setAttribute("tabindex","-1")}ShowTableSortButton(e,t,r){if(!this.sort_button.parentElement)return;let i=!0,n=!1;e.sort&&e.sort.column===t&&(i=!e.sort.asc,n=!0),this.sort_button.setAttribute("tabindex","0 "),this.sort_button.style.opacity="1",this.sort_button.style.pointerEvents="initial",this.sort_button.classList.remove("asc","desc"),n&&this.sort_button.classList.add(i?"asc":"desc"),this.sort_button.dataset.asc=i.toString(),this.sort_button.dataset.table=e.name,this.sort_button.dataset.column=t.toString();let o=this.OffsetCellAddressToRectangle(r).Shift(this.header_size.width,this.header_size.height),a=this.sort_button.getBoundingClientRect();this.sort_button.style.left=o.right-a.width-a.width/2+"px",this.sort_button.style.top=o.top+(o.height-a.height)/2+"px"}ShowNote(e,t,r,i){if(i?this.note_node.innerHTML=i:this.note_node.textContent=e,!this.note_node.parentElement)return;let n=this.note_node.getBoundingClientRect(),o=this.note_node.parentElement.getBoundingClientRect(),a={x:8,y:2},s=this.OffsetCellAddressToRectangle(t).Shift(this.header_size.width,this.header_size.height);this.note_node.style.left=o.left+s.right-this.scroll_reference_node.scrollLeft+a.x+"px",this.note_node.style.top=o.top+s.top-this.scroll_reference_node.scrollTop-n.height/5-a.y+"px",this.note_node.style.opacity="1",this.note_node.style.pointerEvents="auto"}AnnotationLayoutOrder(e,t){let r=-1;for(let n=0;n<this.view.active_sheet.annotations.length;n++)if(this.view.active_sheet.annotations[n]===e){r=n;break}if(r<0)return!1;let i=Math.min(Math.max(0,r+t),this.view.active_sheet.annotations.length-1);if(i===r)return!1;this.view.active_sheet.annotations.splice(r,1),this.view.active_sheet.annotations.splice(i,0,e);for(let n=0;n<this.view.active_sheet.annotations.length;n++){let o=this.view.active_sheet.annotations[n].key,a=this.container?.querySelectorAll(`.annotation[data-key="${o}"]`);if(a)for(let s=0;s<a?.length;s++)a[s].style.zIndex=(n+1).toString()}return!0}PointToAnnotationCorner(e){let t=this.PointToAddress_Grid(e,!1),r=this.CellAddressToRectangle(t);return{address:t,offset:{x:(e.x-r.left)/r.width,y:(e.y-r.top)/r.height}}}RectToAnnotationLayout(e){return{tl:this.PointToAnnotationCorner({x:(e.left||0)+1,y:(e.top||0)+1}),br:this.PointToAnnotationCorner({x:e.right||e.left||100,y:e.bottom||e.top||100})}}AddressToAnnotationLayout(e,t){let r={tl:this.CellAddressToRectangle(e),br:this.CellAddressToRectangle(t)};return{tl:this.PointToAnnotationCorner({x:r.tl.left||0,y:r.tl.top||0}),br:this.PointToAnnotationCorner({x:r.br.right||r.tl.left||100,y:r.br.bottom||r.tl.left||100})}}AnnotationLayoutToRect(e){let t=this.CellAddressToRectangle(e.tl.address),r=this.CellAddressToRectangle(e.br.address),i=t.left+t.width*e.tl.offset.x-1,n=t.top+t.height*e.tl.offset.y-1;return new B(i,n,r.left+r.width*e.br.offset.x-i,r.top+r.height*e.br.offset.y-n)}UpdateAnnotation(e,t){Array.isArray(e)||(e=[e]);for(let r of e){let i=r.view[this.view.view_index]||{};if(i.node){let n=10*this.scale;if(r.data.style?.font_size?.unit==="em"&&(n*=r.data.style.font_size.value),i.node.dataset.scale=this.scale.toString(),r.data.style?.font_face&&r.data.style.font_face.startsWith("stack:")){let o=r.data.style.font_face.substring(6),a=t.font_stacks[o];a?(i.node.classList.add("treb-inherit-font"),i.node.style.fontFamily=a.font||"",a.variants&&(i.node.style.fontVariant=a.variants)):(i.node.classList.remove("treb-inherit-font"),i.node.style.fontFamily="",i.node.style.fontVariant="")}else i.node.classList.remove("treb-inherit-font"),i.node.style.fontFamily="",i.node.style.fontVariant="";if(r.data.style?.bold?i.node.style.fontWeight="600":i.node.style.fontWeight="400",r.data.style?.italic?i.node.style.fontStyle="italic":i.node.style.fontStyle="",r.data.style?.underline?i.node.style.textDecoration="underline":i.node.style.textDecoration="",i.node.style.fontSize=`${n}pt`,r.rect&&!r.data.layout&&(r.scaled_rect=r.rect.Scale(this.scale),r.data.layout=this.RectToAnnotationLayout(r.scaled_rect)),r.data.layout){let o=this.AnnotationLayoutToRect(r.data.layout);o.ApplyStyle(i.node),r.scaled_rect=o}i.node.dataset.key=r.key.toString(),(this.view.active_sheet.freeze.rows||this.view.active_sheet.freeze.columns)&&this.CloneFrozenAnnotation(r)}}}GetFrozenAnnotations(e){return[this.row_header_annotations,this.column_header_annotations,this.corner_annotations].map(r=>r.querySelector(`.annotation[data-key="${e.key}"]`)).filter(r=>r!==null)}CloneFrozenAnnotations(){for(let e of this.view.active_sheet.annotations)e.view[this.view.view_index]?.node&&e.key&&this.CloneFrozenAnnotation(e)}ClearFrozenAnnotations(){for(let e of[this.row_header_annotations,this.column_header_annotations,this.corner_annotations]){let t=e.querySelectorAll(".annotation");for(let r=0;r<t.length;r++)t[r].parentElement?.removeChild(t[r])}}RemoveFrozenAnnotation(e){for(let t of[this.row_header_annotations,this.column_header_annotations,this.corner_annotations]){let r=t.querySelector(`.annotation[data-key="${e.key}"]`);r&&r.parentElement?.removeChild(r)}}CloneFrozenAnnotation(e){for(let t of[this.row_header_annotations,this.column_header_annotations,this.corner_annotations]){let r=t.querySelector(`.annotation[data-key="${e.key}"]`);r&&r.parentElement?.removeChild(r);let i=e.view[this.view.view_index];if(r=i?.node?.cloneNode(!0),r){let n=r.querySelector(".annotation-move-target"),o=r.querySelector(".annotation-resize-target");r.addEventListener("mousedown",a=>{let s=i.node;requestAnimationFrame(()=>{s?.focus()}),this.AnnotationMouseDown(e,i.node,a,n,o)}),t.appendChild(r)}}}RemoveAnnotation(e){let t=e.view[this.view.view_index]||{};t.node&&t.node.parentElement?.removeChild(t.node),this.RemoveFrozenAnnotation(e)}RemoveAnnotationNodes(){let e=Array.prototype.map.call(this.annotation_container.children,t=>t);for(let t of e)this.annotation_container.removeChild(t);(this.view.active_sheet.freeze.rows||this.view.active_sheet.freeze.columns)&&this.ClearFrozenAnnotations()}AddAnnotation(e,t){let r=e.view[this.view.view_index]||{};if(!r.node)throw new Error("annotation view/node missing");this.annotation_container.appendChild(r.node),this.UpdateAnnotation(e,t)}AnnotationMouseDown(e,t,r,i,n){let o=e.scaled_rect;return o?new Promise(a=>{let s={left:o.left,top:o.top,width:o.width,height:o.height},c=this.scroll_reference_node,d=c.getBoundingClientRect(),u=t.getBoundingClientRect();if(r.target===i||r.target!==n&&r.altKey){r.stopPropagation(),r.preventDefault(),t.focus();let h={x:u.left+r.offsetX-o.left,y:u.top+r.offsetY-o.top},m=[t,...this.GetFrozenAnnotations(e)],f=25,p=this.CellAddressToRectangle({row:0,column:0}).Combine(this.CellAddressToRectangle({row:this.view.active_sheet.rows-1,column:this.view.active_sheet.columns-1})).Expand(-1,-1);ke(this.mask,"move",b=>{if(b.offsetY-d.top<this.header_offset.y){let g=Math.min(f,c.scrollTop);c.scrollTop-=g,h.y+=g}else if(b.offsetY-d.top>=d.height&&c.scrollTop+d.height<p.height){let g=f;c.scrollTop+=g,h.y-=g}if(b.offsetX-d.left<this.header_offset.x){let g=Math.min(f,c.scrollLeft);c.scrollLeft-=g,h.x+=g}else if(b.offsetX-d.left>=d.width&&c.scrollLeft+d.width<p.width){let g=f;c.scrollLeft+=g,h.x-=g}if(o.top=b.offsetY-h.y,o.left=b.offsetX-h.x,b.shiftKey){let g=Math.abs(o.left-s.left),x=Math.abs(o.top-s.top);g<=x?o.left=s.left:o.top=s.top}if(b.ctrlKey){let g=this.ClampToGrid({x:o.left,y:o.top});o.left=g.x,o.top=g.y}for(let g of m)g.style.top=o.top+"px",g.style.left=o.left+"px"},()=>{e.data.extent=void 0,e.data.layout=this.RectToAnnotationLayout(o),a({type:"annotation",annotation:e,event:"move"})});return}else if(r.target===n){r.stopPropagation(),r.preventDefault(),t.focus();let h=0;e.data.type==="image"&&e.data.data&&e.data.data.original_size&&e.data.data.original_size.width&&e.data.data.original_size.height&&(h=e.data.data.original_size.width/e.data.data.original_size.height);let m=t.getBoundingClientRect(),f={x:m.left+r.offsetX-o.width+n.offsetLeft,y:m.top+r.offsetY-o.height+n.offsetTop};ke(this.mask,"nw-resize",p=>{let b=[t,...this.GetFrozenAnnotations(e)];if(o.height=p.offsetY-f.y,o.width=p.offsetX-f.x,p.shiftKey&&p.ctrlKey){if(h){let g=Math.abs(o.width-s.width),x=Math.abs(o.height-s.height);g<x?o.width=h*o.height:o.height=o.width/h}}else if(p.shiftKey){let g=Math.abs(o.height-s.height),x=Math.abs(o.width-s.width);g>x?o.width=s.width:o.height=s.height}else if(p.ctrlKey){let g=this.ClampToGrid({x:o.right,y:o.bottom});o.width=g.x-o.left+1,o.height=g.y-o.top+1}for(let g of b)g.style.height=o.height+"px",g.style.width=o.width+"px"},()=>{e.data.extent=void 0,e.data.layout=this.RectToAnnotationLayout(o),a({type:"annotation",annotation:e,event:"resize"})});return}else a()}):(console.info("missing scaled rect!"),Promise.reject())}Initialize(e,t,r=!0){this.mask.parentElement||e.parentElement?.parentElement?.appendChild(this.mask),this.tooltip.parentElement||e.appendChild(this.tooltip),this.spill_border.parentElement||e.appendChild(this.spill_border),this.dropdown_caret.parentElement||e.appendChild(this.dropdown_caret),this.dropdown_list.parentElement||e.appendChild(this.dropdown_list),this.note_node.parentElement||e.appendChild(this.note_node),this.sort_button.parentElement||(e.appendChild(this.sort_button),this.sort_button.addEventListener("click",()=>{t.sort(this.sort_button.dataset.table||"",Number(this.sort_button.dataset.column||"0")||0,/true/i.test(this.sort_button.dataset.asc||"")),this.sort_button.classList.remove("asc","desc"),this.sort_button.dataset.asc==="true"?(this.sort_button.dataset.asc="false",this.sort_button.classList.add("desc")):(this.sort_button.dataset.asc="true",this.sort_button.classList.add("asc")),t.focus()})),this.title_node.parentElement||e.appendChild(this.title_node),this.InitializeInternal(e,t.scroll),!r&&this.scroll_reference_node&&(this.scroll_reference_node.style.overflow="hidden"),this.dropdown_callback=t.dropdown,this.initialized=!0}MockSelection(){if(this.container&&!this.trident&&this.DOM.doc){let e=this.DOM.GetSelection();if(e){let t=this.DOM.doc.createRange();t.selectNodeContents(this.mock_selection),e.removeAllRanges(),e.addRange(t)}}}CreateTile(e,t,r,i,n,o,a,s=!0){let c=this.DOM.Create("canvas");return c.setAttribute("class",e),c.logical_size=t,c.width=t.width*this.dpr,c.height=t.height*this.dpr,c.style.width=`${t.width}px`,c.style.height=`${t.height}px`,c.tile_position=r,c.first_cell=i,this.UpdateTileGridPosition(c),c.last_cell={row:i.row+n.rows-1,column:i.column+n.columns-1},c.pixel_start=o,c.pixel_end={x:o.x+t.width,y:o.y+t.height},c.dirty=!!s,c.needs_full_repaint=!0,a.appendChild(c),c}ApplyThemeColors(){if(this.container)for(let[e,t]of this.applied_theme_colors.entries())this.container.style.setProperty(`--treb-applied-theme-color-${e+1}`,t)}ApplyTheme(e){this.row_header.style.backgroundColor=this.column_header.style.backgroundColor=this.corner.style.backgroundColor=e.headers?.fill?D(e,e.headers.fill,0):"",this.corner.style.borderColor=e.grid_color||"";for(let t of this.grid_tiles)for(let r of t)r.style.backgroundColor=D(e,e.grid_cell?.fill,0)||"#fff";this.dropdown_list.style.font=I.CompositeFont(e.grid_cell_font_size,{font_face:"stack:default"},this.scale,e).font,this.applied_theme_colors=e.theme_colors?.slice(4,10)||[],this.container&&this.ApplyThemeColors()}UpdateTotalSize(){this.total_height=0;let e=this.view.active_sheet.rows;for(let r=0;r<e;r++)this.total_height+=this.RowHeight(r);this.total_width=0;let t=this.view.active_sheet.columns;for(let r=0;r<t;r++)this.total_width+=this.ColumnWidth(r)}UpdateContentsSize(){let e=this.row_header_tiles.reduce((r,i)=>r+i.logical_size.height,0),t=this.column_header_tiles.reduce((r,i)=>r+i.logical_size.width,0);this.column_header.style.width=this.contents.style.width=`${t}px`,this.row_header.style.height=this.contents.style.height=`${e}px`}HideTooltip(){this.tooltip.style.display="none",this.tooltip_state=void 0,this.tooltip.classList.remove("arrow-up"),this.tooltip.classList.remove("arrow-left")}ShowTooltip(e={}){e.up?(this.tooltip.classList.add("arrow-up"),this.tooltip_state="up"):e.left&&(this.tooltip.classList.add("arrow-left"),this.tooltip_state="left"),this.tooltip.style.display="block",this.UpdateTooltip(e)}ShowDropdownCaret(e,t,r){let i=this.OffsetCellAddressToRectangle(e.start);e.count>1&&(i=i.Combine(this.OffsetCellAddressToRectangle(e.end))),i=i.Shift(this.header_size.width,this.header_size.height);let n=Math.round(this.scale*Math.max(8,Math.min(20,i.height)));this.dropdown_caret.style.height=`${n}px`,this.dropdown_caret.style.width=`${n}px`,this.dropdown_caret.style.left=`${i.right+1}px`,this.dropdown_caret.style.top=`${i.bottom-n}px`,this.dropdown_list.style.top=`${i.bottom+2}px`,this.dropdown_list.style.left=`${i.left+2}px`,this.dropdown_list.style.minWidth=`${i.width}px`,this.dropdown_list.style.fontSize=this.scale.toFixed(2)+"em",this.dropdown_list.textContent="";for(let o of t){let a=this.DOM.Div(void 0,this.dropdown_list);r===o&&(this.dropdown_selected=a,a.classList.add("selected")),a.dataset.dropdown_value=JSON.stringify(o),a.textContent=o?.toString()||""}this.dropdown_caret.setAttribute("class","treb-dropdown-caret"),this.dropdown_caret.style.display="block",this.dropdown_caret_visible=!0}ShowSpillBorder(e){if(this.spill_border.textContent="",e){let t=new v(e.start,e.end),r=this.OffsetCellAddressToRectangle(t.start);t.count>1&&(r=r.Combine(this.OffsetCellAddressToRectangle(t.end))),r=r.Shift(this.header_size.width,this.header_size.height),this.spill_border.style.display="block",this.spill_border.style.top=(r.top-5).toString()+"px",this.spill_border.style.left=(r.left-5).toString()+"px",this.spill_border.style.width=(r.width+10).toString()+"px",this.spill_border.style.height=(r.height+10).toString()+"px";let i=this.DOM.SVG("rect",void 0,this.spill_border);i.setAttribute("x","4.5"),i.setAttribute("y","4.5"),i.setAttribute("width",(r.width+1).toString()),i.setAttribute("height",(r.height+1).toString())}else this.spill_border.style.display="none"}HideDropdownCaret(){this.dropdown_caret_visible&&(this.dropdown_caret.setAttribute("class","treb-dropdown-caret"),this.dropdown_caret_visible=!1,this.dropdown_caret.style.display="none")}GetScrollOffset(){return{x:this.scroll_reference_node.scrollLeft+this.header_offset.x,y:this.scroll_reference_node.scrollTop+this.header_offset.y}}ScrollTo(e,t=!0,r=!0,i=!1){let n=this.CellAddressToRectangle(e);if(i&&this.scroll_reference_node.scrollTo){let o={left:this.scroll_reference_node.scrollLeft,top:this.scroll_reference_node.scrollTop},a={left:t?n.left:o.left,top:r?n.top:o.top,behavior:"smooth"};this.scroll_reference_node.scrollTo(a)}else r&&(this.scroll_reference_node.scrollTop=n.top),t&&(this.scroll_reference_node.scrollLeft=n.left)}ScrollIntoView(e,t=!1){let r=this.CellAddressToRectangle(e),i=this.scroll_reference_node.clientWidth-this.row_header.offsetWidth,n=this.scroll_reference_node.clientHeight-this.column_header.offsetHeight,o={x:0,y:0},a={x:!1,y:!1},s=new B(this.scroll_reference_node.scrollLeft,this.scroll_reference_node.scrollTop,i,n);(this.view.active_sheet.freeze.rows||this.view.active_sheet.freeze.columns)&&(this.view.active_sheet.freeze.rows&&e.row>=this.view.active_sheet.freeze.rows?o.y=this.frozen_row_tiles[0].logical_size.height:this.view.active_sheet.freeze.rows&&(a.y=!0),this.view.active_sheet.freeze.columns&&e.column>=this.view.active_sheet.freeze.columns?o.x=this.frozen_column_tiles[0].logical_size.width:this.view.active_sheet.freeze.columns&&(a.x=!0));let c={behavior:t?"smooth":"auto"};e.row!==1/0&&(r.top<s.top+o.y&&!a.y?c.top=r.top-o.y:r.bottom>s.bottom&&(c.top=r.bottom-n)),e.column!==1/0&&(r.left<s.left+o.x&&!a.x?c.left=r.left-o.x:r.right>s.right&&(c.left=r.right-i)),this.scroll_reference_node.scrollTo(c)}UpdateTooltip(e={}){if(typeof e.text<"u"&&(this.tooltip.textContent=e.text),typeof e.x<"u"){let t=e.x||0;this.tooltip_state==="up"&&(t-=this.tooltip.offsetWidth/2),this.tooltip.style.left=Math.round(t)+"px"}if(typeof e.y<"u"){let t=e.y||0;this.tooltip_state==="left"&&(t-=this.tooltip.offsetHeight/2),this.tooltip.style.top=Math.round(t)+"px"}}CoordinateToRowHeader(e){let t={column:1/0,row:0};if(this.view.active_sheet.freeze.rows&&this.frozen_row_tiles[0].pixel_end.y>=e-this.scroll_reference_node.scrollTop){let r=0;e-=this.scroll_reference_node.scrollTop;for(let i=0;i<this.view.active_sheet.freeze.rows;i++)if(r+=this.RowHeight(i),r>=e)return t.row=i,t}for(let r of this.row_header_tiles)if(r.pixel_end.y>=e){let i=e-r.pixel_start.y,n=0;for(t.row=r.first_cell.row;t.row<=r.last_cell.row;t.row++,i-=n)if(n=this.RowHeight(t.row),n>i)return t;return t}return t}CoordinateToColumnHeader(e){let t={row:1/0,column:0};if(this.view.active_sheet.freeze.columns&&this.frozen_column_tiles[0].pixel_end.x>=e-this.scroll_reference_node.scrollLeft){let r=0;e-=this.scroll_reference_node.scrollLeft;for(let i=0;i<this.view.active_sheet.freeze.columns;i++)if(r+=this.ColumnWidth(i),r>=e)return t.column=i,t}for(let r of this.column_header_tiles)if(r.pixel_end.x>=e){let i=e-r.pixel_start.x,n=0;for(t.column=r.first_cell.column;t.column<=r.last_cell.column;t.column++,i-=n)if(n=this.ColumnWidth(t.column),n>i)return t;return t}return t}PointToAddress_Grid(e,t=!0){if(t){if(this.view.active_sheet.freeze.rows){let o=this.frozen_row_tiles[0].logical_size.height;e.y-this.scroll_reference_node.scrollTop<o&&(e.y-=this.scroll_reference_node.scrollTop)}if(this.view.active_sheet.freeze.columns){let o=this.frozen_column_tiles[0].logical_size.width;e.x-this.scroll_reference_node.scrollLeft<o&&(e.x-=this.scroll_reference_node.scrollLeft)}}let r={row:0,column:0},i=this.grid_tiles[this.grid_tiles.length-1],n=i[i.length-1];if(e.y>n.pixel_end.y){let o=e.y-n.pixel_end.y;for(r.row=n.last_cell.row;o>0;)r.row++,o-=this.default_row_height}else for(let o of i)if(o.pixel_start.y<=e.y&&o.pixel_end.y>=e.y){let a=e.y-o.pixel_start.y,s=0;for(r.row=o.first_cell.row;r.row<=o.last_cell.row&&(s=this.RowHeight(r.row),!(s>a));r.row++,a-=s);break}if(e.x>n.pixel_end.x){let o=e.x-n.pixel_end.x;for(r.column=n.last_cell.column;o>0;)r.column++,o-=this.default_column_width}else for(let o of this.grid_tiles)if(o[0].pixel_start.x<=e.x&&o[0].pixel_end.x>=e.x){let a=o[0],s=e.x-a.pixel_start.x,c=0;for(r.column=a.first_cell.column;r.column<=a.last_cell.column&&(c=this.ColumnWidth(r.column),!(c>s));r.column++,s-=c);break}return r}AdjacentTile(e,t=0,r=0){if(!t&&!r)return e;let i=e.tile_position,n=e.tile_position.row+t,o=e.tile_position.column+r;if(!(n<0||o<0)){if(this.grid_tiles[i.column]&&this.grid_tiles[i.column][i.row]===e&&this.grid_tiles[o])return this.grid_tiles[o][n];if(!i.column&&this.frozen_column_tiles[i.row]===e)return this.frozen_column_tiles[n];if(!i.row&&this.frozen_row_tiles[i.column]===e)return this.frozen_row_tiles[o]}}UpdateTiles(){if(!this.container)throw new Error("invalid container");this.grid_tiles.forEach(w=>{w.forEach(_=>{_.parentElement&&_.parentElement.removeChild(_)})});for(let w of[this.column_header_tiles,this.row_header_tiles,this.frozen_row_tiles,this.frozen_column_tiles])for(let _ of w)_.parentElement&&_.parentElement.removeChild(_);this.frozen_row_tiles=[],this.frozen_column_tiles=[],this.row_header_tiles=[],this.column_header_tiles=[],this.grid_tiles=[];let e=this.view.active_sheet;this.default_row_height=Math.round(e.default_row_height*this.scale),this.default_column_width=Math.round(e.default_column_width*this.scale),this.header_offset={x:Math.round(e.header_offset.x*this.scale),y:Math.round(e.header_offset.y*this.scale)},this.UpdateContainingGrid();let t=this.view.active_sheet.rows,r=this.view.active_sheet.columns;t||(t=100),r||(r=40);let i=0,n=0;for(let w=0;w<t;w++)i+=this.RowHeight(w);for(let w=0;w<r;w++)n+=this.ColumnWidth(w);if(!n||!i)throw"unexpected missing total size";if(i||(i=this.default_row_height*t),n||(n=this.default_column_width*r),this.container.clientWidth>n+this.header_size.width){let w=Math.ceil((this.container.offsetWidth-n)/this.default_column_width);n+=w*this.default_column_width,r+=w}if(this.last_column=r,this.container.clientHeight>i+this.header_size.height){let w=Math.ceil((this.container.offsetHeight-i)/this.default_row_height);i+=w*this.default_row_height,t+=w}this.column_header.style.width=this.contents.style.width=`${n}px`,this.row_header.style.height=this.contents.style.height=`${i}px`;let o=[],a=[],s=0,c=0;for(let w=0;w<r;w++){let _=this.ColumnWidth(w);s&&s+_>this.default_tile_size.width&&(o.push(s),a.push(c),c=w,s=0),s+=_}o.push(s),a.push(c);let d=[],u=[],h=0,m=0;for(let w=0;w<t;w++){let _=this.RowHeight(w);h&&h+_>this.default_tile_size.height&&(d.push(h),u.push(m),h=0,m=w),h+=_}d.push(h),u.push(m);let f=o.length,p=d.length,b=0,g=0,x=0,y=0;for(let w=0;w<this.view.active_sheet.freeze.rows;w++)x+=this.RowHeight(w);for(let w=0;w<this.view.active_sheet.freeze.columns;w++)y+=this.ColumnWidth(w);for(let w=0;w<f;w++){let _=[];b=0;let C=w===f-1?r-a[w]:a[w+1]-a[w];this.column_header_tiles.push(this.CreateTile("column-header-tile",{height:this.header_offset.y,width:o[w]},{row:0,column:w},{row:0,column:a[w]},{rows:0,columns:C},{x:g,y:0},this.column_header)),this.view.active_sheet.freeze.rows&&this.frozen_row_tiles.push(this.CreateTile("frozen-row-tile",{height:x,width:o[w]},{row:1,column:w},{row:0,column:a[w]},{rows:0,columns:C},{x:g,y:0},this.column_header));for(let S=0;S<p;S++){let A=S===p-1?t-u[S]:u[S+1]-u[S];w||(this.row_header_tiles.push(this.CreateTile("row-header-tile",{height:d[S],width:this.header_offset.x},{row:S,column:0},{row:u[S],column:0},{rows:A,columns:1},{x:0,y:b},this.row_header)),this.view.active_sheet.freeze.columns&&this.frozen_column_tiles.push(this.CreateTile("frozen-column-tile",{height:d[S],width:y},{row:S,column:1},{row:u[S],column:0},{rows:A,columns:1},{x:0,y:b},this.row_header))),_.push(this.CreateTile("grid-tile",{height:d[S],width:o[w]},{row:S,column:w},{row:u[S],column:a[w]},{rows:A,columns:C},{x:g,y:b},this.contents)),b+=d[S]}this.grid_tiles.push(_),g+=o[w]}this.total_height=i,this.total_width=n,this.ClearLayoutCaches(),this.UpdateGridTemplates(!0,!0)}ClearLayoutCaches(){this.row_cache=[],this.column_cache=[]}TileIndexForColumn(e){for(let t of this.column_header_tiles)if(t.first_cell.column<=e&&t.last_cell.column>=e)return t.tile_position.column;return-1}TileIndexForRow(e){for(let t of this.row_header_tiles)if(t.first_cell.row<=e&&t.last_cell.row>=e)return t.tile_position.row;return-1}DirtyHeaders(e){if(e){for(let t of this.column_header_tiles){if(t.dirty)continue;let r=new v({row:e.start.row,column:t.first_cell.column},{row:e.start.row,column:t.last_cell.column});(e.entire_row||r.Intersects(e))&&(t.dirty=!0)}for(let t of this.row_header_tiles){if(t.dirty)continue;let r=new v({column:e.start.column,row:t.first_cell.row},{column:e.start.column,row:t.last_cell.row});(e.entire_column||r.Intersects(e))&&(t.dirty=!0)}}}DirtyAll(){for(let e of this.grid_tiles)for(let t of e)t.dirty=!0}DirtyArea(e){if(this.initialized){Array.isArray(e)||(e=[e]);for(let t of e){let r={row:0,column:0},i={row:this.grid_tiles[0].length-1,column:this.grid_tiles.length-1};t.start.column!==1/0&&(r.column=i.column=this.TileIndexForColumn(t.start.column),t.end.column!==t.start.column&&(i.column=this.TileIndexForColumn(t.end.column))),t.start.row!==1/0&&(r.row=i.row=this.TileIndexForRow(t.start.row),t.end.row!==t.start.row&&(i.row=this.TileIndexForRow(t.end.row)));for(let n=r.column;n<=i.column;n++)for(let o=r.row;o<=i.row;o++)this.grid_tiles[n][o].dirty=!0}}}VisibleTiles(){let e=[{row:0,column:0},{row:0,column:0}];if(!this.container||!this.grid_tiles.length||!this.grid_tiles[0].length)return new v(e[0],e[1]);let t=this.scroll_reference_node.scrollLeft,r=t+this.scroll_reference_node.offsetWidth,i=this.scroll_reference_node.scrollTop,n=i+this.scroll_reference_node.offsetHeight;for(let o of this.grid_tiles){let a=o[0];if(a.pixel_start.x<=t&&a.pixel_end.x>=t){for(a of o)if(a.pixel_start.y<=i&&a.pixel_end.y>=i){e[0]=a.tile_position;break}}if(o===this.grid_tiles[this.grid_tiles.length-1]||a.pixel_start.x<=r&&a.pixel_end.x>=r){for(a of o)if(a===o[o.length-1]||a.pixel_start.y<=n&&a.pixel_end.y>=n)return e[1]=a.tile_position,new v(e[0],e[1])}}return new v(e[0],e[1])}UpdateTileHeights(e=!0,t=-1){let r=0;for(let i=0;i<this.row_header_tiles.length;i++){let n=this.row_header_tiles[i];if(t>n.last_cell.row){r+=n.logical_size.height;continue}let o=0;for(let s=n.first_cell.row;s<=n.last_cell.row;s++)o+=this.RowHeight(s);let a=n.logical_size.height===o;if(n.pixel_start.y=r,r+=o,n.pixel_end.y=r,!a){if(n.logical_size.height=o,n.style.height=`${o}px`,n.height=this.dpr*o,this.view.active_sheet.freeze.columns){let s=this.frozen_column_tiles[i];s.logical_size.height=o,s.style.height=`${o}px`,s.height=this.dpr*o}e&&(n.dirty=!0,n.needs_full_repaint=!0)}for(let s of this.grid_tiles){let c=s[i];c.pixel_start.y=n.pixel_start.y,c.pixel_end.y=n.pixel_end.y,a||(c.logical_size.height=o,c.style.height=`${o}px`,c.height=this.dpr*o,e&&(c.dirty=!0,c.needs_full_repaint=!0))}}if(this.view.active_sheet.freeze.rows){let i=0;for(let n=0;n<this.view.active_sheet.freeze.rows;n++)i+=this.RowHeight(n);for(let n of this.frozen_row_tiles)n.style.height=`${i}px`,n.height=i*this.dpr;i+=this.header_offset.y,this.corner_canvas.style.height=`${i}px`,this.corner_canvas.height=i*this.dpr;for(let n of this.grid_tiles)n[0].dirty=!0}this.UpdateGridTemplates(!1,!0),this.row_header.style.height=this.contents.style.height=`${r}px`,this.ClearLayoutCaches()}UpdateTileWidths(e=!0,t=-1){let r=0;for(let i=0;i<this.column_header_tiles.length;i++){let n=this.column_header_tiles[i],o=this.grid_tiles[i];if(t>n.last_cell.column){r+=n.logical_size.width;continue}let a=0;for(let c=n.first_cell.column;c<=n.last_cell.column;c++)a+=this.ColumnWidth(c);let s=n.logical_size.width===a;if(n.pixel_start.x=r,r+=a,n.pixel_end.x=r,!s){if(n.logical_size.width=a,n.style.width=`${a}px`,n.width=this.dpr*a,this.view.active_sheet.freeze.rows){let c=this.frozen_row_tiles[i];c.logical_size.width=a,c.style.width=`${a}px`,c.width=this.dpr*a}e&&(n.dirty=!0,n.needs_full_repaint=!0)}for(let c of o)c.pixel_start.x=n.pixel_start.x,c.pixel_end.x=n.pixel_end.x,s||(c.logical_size.width=a,c.style.width=`${a}px`,c.width=this.dpr*a,e&&(c.dirty=!0,c.needs_full_repaint=!0))}if(this.view.active_sheet.freeze.columns){let i=0;for(let n=0;n<this.view.active_sheet.freeze.columns;n++)i+=this.ColumnWidth(n);for(let n of this.frozen_column_tiles)n.style.width=`${i}px`,n.width=i*this.dpr;i+=this.header_offset.x,this.corner_canvas.style.width=`${i}px`,this.corner_canvas.width=i*this.dpr;for(let n of this.grid_tiles[0])n.dirty=!0}this.UpdateGridTemplates(!0,!1),this.column_header.style.width=this.contents.style.width=`${r}px`,this.ClearLayoutCaches()}ClampToGrid(e){let t=this.PointToAddress_Grid(e),r=this.OffsetCellAddressToRectangle(t);return e.x>r.left+r.width/2?e.x=r.left+r.width-1:e.x=r.left-1,e.y>r.top+r.height/2?e.y=r.top+r.height-1:e.y=r.top-1,e}OffsetCellAddressToRectangle(e){let t=this.CellAddressToRectangle(e);return e.column>=0&&e.column<this.view.active_sheet.freeze.columns&&(t=t.Shift(this.scroll_reference_node.scrollLeft,0)),e.row>=0&&e.row<this.view.active_sheet.freeze.rows&&(t=t.Shift(0,this.scroll_reference_node.scrollTop)),t}CellAddressToRectangle(e){let t=e.row===1/0||e.row<0?0:e.row,r=e.column===1/0||e.column<0?0:e.column;if(this.column_cache.length<=r+1){this.column_cache.length||(this.column_cache[0]=0);for(let o=this.column_cache.length-1;o<=r;o++)this.column_cache[o+1]=this.column_cache[o]+this.ColumnWidth(o)}if(this.row_cache.length<=t+1){this.row_cache.length||(this.row_cache[0]=0);for(let o=this.row_cache.length-1;o<=t;o++)this.row_cache[o+1]=this.row_cache[o]+this.RowHeight(o)}let i=this.column_cache[r],n=this.row_cache[t];return new B(i,n,this.column_cache[r+1]-i,this.row_cache[t+1]-n)}ResizeTileWidth(e,t,r=!0){let i=this.column_header_tiles[e],n=t-i.logical_size.width;i.logical_size.width=t,i.style.width=`${t}px`,i.width=this.dpr*t,i.pixel_end.x+=n,r&&(i.dirty=!0,i.needs_full_repaint=!0);for(let a=e+1;a<this.column_header_tiles.length;a++){this.column_header_tiles[a].pixel_start.x+=n,this.column_header_tiles[a].pixel_end.x+=n;for(let s of this.grid_tiles[a])s.pixel_start.x+=n,s.pixel_end.x+=n}let o=this.grid_tiles[e];for(i of o)i.logical_size.width=t,i.style.width=`${t}px`,i.width=this.dpr*t,i.pixel_end.x+=n,r&&(i.dirty=!0,i.needs_full_repaint=!0);this.UpdateTotalSize(),this.UpdateGridTemplates(!0,!1),this.UpdateContentsSize()}ResizeTileHeight(e,t,r=!0){let i=this.row_header_tiles[e],n=t-i.logical_size.height;i.logical_size.height=t,i.style.height=`${t}px`,i.height=this.dpr*t,i.pixel_end.y+=n,r&&(i.dirty=!0,i.needs_full_repaint=!0);for(let o=e+1;o<this.row_header_tiles.length;o++)i=this.row_header_tiles[o],i.pixel_start.y+=n,i.pixel_end.y+=n;for(let o of this.grid_tiles){i=o[e],i.logical_size.height=t,i.style.height=`${t}px`,i.height=this.dpr*t,i.pixel_end.y+=n,r&&(i.dirty=!0,i.needs_full_repaint=!0);for(let a=e+1;a<o.length;a++)o[a].pixel_start.y+=n,o[a].pixel_end.y+=n}this.UpdateTotalSize(),this.UpdateGridTemplates(!1,!0),this.UpdateContentsSize()}};var Pt=class extends Ye{constructor(e,t){super(e,t,!0)}InitializeInternal(){}UpdateGridTemplates(){}UpdateTileGridPosition(){}UpdateContainingGrid(){}ResizeCursor(){}};var Ot=class extends Ye{constructor(e,t,r){super(e,t,!1,r),this.column_header=r.Div("treb-top-header"),this.row_header=r.Div("treb-left-header"),this.corner=r.Div("treb-corner"),this.corner_canvas=r.Create("canvas"),this.corner.appendChild(this.corner_canvas),this.contents=r.Div("treb-contents"),this.buffer_canvas=r.Create("canvas","treb-buffer-canvas",this.contents),this.grid_selection=r.SVG("svg","treb-grid-selection",this.contents),this.row_header_selection=r.SVG("svg",["frozen-selection","frozen-selection-rows"],this.column_header),this.row_header_annotations=r.Div("frozen-annotation-container frozen-annotation-container-rows",this.column_header),this.column_header_selection=r.SVG("svg",["frozen-selection","frozen-selection-columns"],this.row_header),this.column_header_annotations=r.Div("frozen-annotation-container frozen-annotation-container-columns",this.row_header),this.corner_selection=r.SVG("svg","frozen-selection",this.corner),this.corner_annotations=r.Div("frozen-annotation-container frozen-annotation-container-corner",this.corner),this.annotation_container=r.Div("treb-annotation-container"),this.grid_cover=r.Div("tile-cover grid-cover"),this.column_header_cover=r.Div("tile-cover column-header-cover"),this.row_header_cover=r.Div("tile-cover row-header-cover")}InitializeInternal(e,t){this.container=e,this.scroll_reference_node=this.container,e.appendChild(this.column_header),e.appendChild(this.row_header),e.appendChild(this.corner),e.appendChild(this.contents),e.appendChild(this.annotation_container),e.appendChild(this.grid_cover),e.appendChild(this.column_header_cover),e.appendChild(this.row_header_cover),e.appendChild(this.mock_selection),this.container.addEventListener("scroll",()=>t()),this.ApplyThemeColors()}FocusInLayout(e){return!!(e&&e instanceof Element&&this.container?.contains(e))}ResizeCursor(e){switch(e){case"row":this.row_header_cover.classList.add("resize");break;case"column":this.column_header_cover.classList.add("resize");break;default:this.row_header_cover.classList.remove("resize"),this.column_header_cover.classList.remove("resize");break}}UpdateTileGridPosition(e){e.style.gridColumn=`${e.tile_position.column+1} / ${e.tile_position.column+2}`,e.style.gridRow=`${e.tile_position.row+1} / ${e.tile_position.row+2}`}UpdateContainingGrid(){if(!this.container)throw new Error("missing container");this.header_size.width=this.header_offset.x,this.header_size.height=this.header_offset.y;let e=this.header_offset.x,t=this.header_offset.y;if(this.view.active_sheet.freeze.columns)for(let r=0;r<this.view.active_sheet.freeze.columns;r++)e+=this.ColumnWidth(r);if(this.view.active_sheet.freeze.rows)for(let r=0;r<this.view.active_sheet.freeze.rows;r++)t+=this.RowHeight(r);this.container.style.gridTemplateColumns=`${this.header_offset.x}px auto`,this.container.style.gridTemplateRows=`${this.header_offset.y}px auto`,this.corner_canvas.setAttribute("width",`${this.dpr*e}`),this.corner_canvas.setAttribute("height",`${this.dpr*t}`),this.column_header.style.height=`${t}px`,this.corner_canvas.style.width=`${e}px`,this.corner_canvas.style.height=`${t}px`}UpdateGridTemplates(){let e=0,t=0;this.column_header.style.gridTemplateColumns=this.contents.style.gridTemplateColumns=this.column_header_tiles.map(a=>(e+=a.logical_size.width,`${a.logical_size.width}px`)).join(" "),this.column_header.style.gridTemplateRows=`${this.header_offset.y}px auto`,this.row_header.style.gridTemplateRows=this.contents.style.gridTemplateRows=this.row_header_tiles.map(a=>(t+=a.logical_size.height,`${a.logical_size.height}px`)).join(" ");let r=this.header_offset.y;if(this.view.active_sheet.freeze.rows)for(let a=0;a<this.view.active_sheet.freeze.rows;a++)r+=this.RowHeight(a);this.column_header.style.height=`${r}px`,this.row_header_selection.style.display="block",this.row_header_selection.style.width=`${e}px`,this.corner_selection.style.height=this.row_header_selection.style.height=`${r}px`,this.corner_selection.style.top=this.row_header_selection.style.top="0px",this.row_header_selection.style.left="0px";let i=this.header_offset.x;if(this.view.active_sheet.freeze.columns)for(let a=0;a<this.view.active_sheet.freeze.columns;a++)i+=this.ColumnWidth(a);this.column_header_selection.style.display="block",this.corner_selection.style.width=this.column_header_selection.style.width=`${i}px`,this.column_header_selection.style.height=`${t}px`,this.column_header_selection.style.top="0px",this.corner_selection.style.left=this.column_header_selection.style.left="0px";let n={x:this.view.active_sheet.header_offset.x*this.scale,y:this.view.active_sheet.header_offset.y*this.scale},o=this.view.active_sheet.freeze;o.rows&&o.columns?(this.row_header_annotations.style.display="block",this.column_header_annotations.style.display="block",this.corner_annotations.style.display="block"):o.rows?(this.row_header_annotations.style.display="block",this.column_header_annotations.style.display="none",this.corner_annotations.style.display="none"):o.columns?(this.row_header_annotations.style.display="none",this.column_header_annotations.style.display="block",this.corner_annotations.style.display="none"):(this.row_header_annotations.style.display="none",this.column_header_annotations.style.display="none",this.corner_annotations.style.display="none"),this.row_header_annotations.style.width=`${e}px`,this.corner_annotations.style.height=this.row_header_annotations.style.height=`${r-n.y}px`,this.corner_annotations.style.top=this.row_header_annotations.style.top=`${n.y}px`,this.column_header_annotations.style.width=this.corner_annotations.style.width=`${i-n.x}px`,this.column_header_annotations.style.height=`${t}px`,this.corner_annotations.style.left=this.column_header_annotations.style.left=`${n.x}px`,this.corner_selection.style.display="block",this.grid_selection.style.width=`${e}px`,this.grid_selection.style.height=`${t}px`,this.grid_selection.style.top=`${this.header_offset.y}px`,this.grid_selection.style.left=`${this.header_offset.x}px`,this.annotation_container.style.width=`${e}px`,this.annotation_container.style.height=`${t}px`,this.annotation_container.style.top=`${this.header_offset.y}px`,this.annotation_container.style.left=`${this.header_offset.x}px`}};var Fe=class l extends _e{constructor(t,r,i){super();this.model=t;this.view=r;this.autocomplete=i;this.parser=t.parser}static FormulaChars=("$^&*(-+={[<>/~%@"+F.argument_separator).split("");active_cell;autocomplete_matcher;container_node;active_editor;nodes=[];target_address;assume_formula=!1;text_formula=!1;get selecting(){if(this.assume_formula)return!0;if(!this.text_formula)return!1;if(this.active_editor&&this.active_editor.node===this.active_editor.node.ownerDocument.activeElement){let t=this.active_editor.node.ownerDocument.defaultView,r=t.getSelection();if(r?.rangeCount){let o=r?.getRangeAt(0);if((o?.endContainer instanceof t.HTMLElement?o.endContainer:o.endContainer?.parentElement)?.dataset.reference!==void 0)return!0;if(o?.startContainer instanceof t.Text){let s=(o.startContainer.textContent?.substring(0,o.startOffset)||"").trim();if(s.length&&l.FormulaChars.includes(s[s.length-1]))return!0}else console.info("mark 21",o)}let n=this.SubstringToCaret2(this.active_editor.node)[1].trim();if(n.length){let o=n[n.length-1];return l.FormulaChars.includes(o)}}return!1}composite_dependencies=[];get dependencies(){return this.composite_dependencies}parser;FocusEditor(){this.active_editor&&this.active_editor.node.focus()}RegisterListener(t,r,i){t.node.addEventListener(r,i),t.listeners||(t.listeners=new Map),t.listeners.set(r,i)}SelectAll(t){let i=t.ownerDocument.defaultView.getSelection(),n=t.ownerDocument.createRange();n.selectNode(t),i?.removeAllRanges(),i?.addRange(n)}SetCaret(t,r){let i=t.node.ownerDocument,n=i?.defaultView,o=n.getSelection(),a=i?.createRange(),s=d=>{let u=d;for(;u&&!(u instanceof n.Text)&&u.firstChild;)u=u.firstChild;return u},c=s(t.node);if(r){let d=s(r.node);o&&a&&(a.setStart(c,t.offset),a.setEnd(d,r.offset),o.removeAllRanges(),o.addRange(a))}else o&&a&&(a.setStart(c,t.offset),a.setEnd(c,t.offset),a.collapse(!0),o.removeAllRanges(),o.addRange(a))}InsertReference(t){if(!this.active_editor)return;let r=this.active_editor.node.ownerDocument.defaultView,i=r.getSelection();if(!i)throw new Error("error getting selection");if(i.rangeCount===0)return"";let n=i.getRangeAt(0),o=this.active_editor.node.textContent||"";if(n.startContainer instanceof r.Text)if(!n.collapsed&&n.startOffset<n.endOffset){let a=this.SubstringToCaret2(this.active_editor.node);this.active_editor.node.textContent=a[0]+t+o.substring(a[1].length),this.SetCaret({node:this.active_editor.node,offset:a[0].length},{node:this.active_editor.node,offset:a[0].length+t.length})}else{let a=n.startContainer.parentElement;if(a instanceof r.HTMLElement&&a.dataset.reference)a.textContent=t,this.SetCaret({node:a,offset:t.length});else{let s=this.SubstringToCaret2(this.active_editor.node)[1],c="",d=s.trim();if(d.length){let u=d[d.length-1];l.FormulaChars.includes(u)||(s.length===d.length?c=" +":c="+")}this.active_editor.node.textContent=s+c+t+o.substring(s.length),this.SetCaret({node:this.active_editor.node,offset:s.length+t.length+c.length})}}else n.startContainer instanceof r.HTMLElement?(n.startContainer.textContent=t,this.SetCaret({node:n.startContainer,offset:t.length})):console.warn("unexpected range start container",n.startContainer);this.UpdateText(this.active_editor),this.UpdateColors(),this.active_editor.node.dispatchEvent(new Event("input",{bubbles:!0,cancelable:!0}))}UpdateColors(t=!1,r=!1){let i=new Map,n=new Map;for(let a of this.nodes)for(let s of a.references||[]){let c=this.model.AddressToLabel(s);i.has(c)||(i.set(c,s),n.set(c,n.size))}for(let a of this.nodes){for(let s of Array.from(a.node.childNodes)){let c=s.ownerDocument?.defaultView;if(c&&s instanceof c.HTMLElement&&s.dataset.reference){let d=n.get(s.dataset.reference);s.dataset.highlightIndex=typeof d=="number"?(d%5+1).toString():"?"}}a.check=a.node.innerHTML.length}let o=Array.from(i.values());!t&&JSON.stringify(this.composite_dependencies)===JSON.stringify(o)||(this.composite_dependencies=o,r||this.Publish({type:"update",dependencies:this.composite_dependencies}))}UpdateDependencies(t,r){let i=[];for(let s of r.full_reference_list||[])switch(s.type){case"address":case"range":{let c=s.type==="range"?s.start:s;c.sheet_id||(c.sheet?c.sheet_id=this.model.sheets.Find(c.sheet)?.id||0:c.sheet_id=this.view.active_sheet.id),i.push(s);break}case"structured-reference":if(this.target_address){let c=this.model.ResolveStructuredReference(s,this.target_address);c&&i.push(c)}else console.info("target address not set");break;case"identifier":{let c=this.model.GetName(s.name,this.view.active_sheet.id);c?.type==="range"&&(c.area.count===1?i.push({type:"address",...c.area.start,label:s.name,position:s.position,id:s.id}):i.push({type:"range",start:{type:"address",position:s.position,id:s.id,label:s.name,...c.area.start},end:{type:"address",position:s.position,label:s.name,id:s.id,...c.area.end},label:s.name,position:s.position,id:s.id}));break}}i.sort((s,c)=>s.position-c.position);let n=[],o=new Set,a=new Map;for(let s of i){let c=this.model.AddressToLabel(s),d=N(s)?new v(s):new v(s.start,s.end);o.has(c)||(n.push(d),o.add(c)),a.set(s.label,c)}return this.UpdateReferences(t,n),a}UpdateReferences(t,r=[]){t.node.dataset.references=JSON.stringify(r.map(i=>this.model.AddressToLabel(i))),t.references=r}UpdateText(t,r={}){let i=t.node,n=i.textContent||"",o=O.GetInstance(i.ownerDocument);if(this.text_formula=n[0]==="=",this.active_editor&&!this.assume_formula&&(this.active_editor.node.spellcheck=!this.text_formula,!this.text_formula)||n===t.formatted_text)return;let[a,s]=this.SubstringToCaret2(i),c=a.length,d=s.length;if(c===0&&d===0&&(d=n.length),!n)this.UpdateReferences(t);else{let h=this.parser.Parse(n);if(h.expression){let m=this.UpdateDependencies(t,h),f=n[0]==="="?1:0,p=0,b,g,x=0,y,w=o.Fragment(),_=(C,S="text",A="",E=!1)=>{let R=o.Text(C);if((E||(c>x||c===0&&x===0)&&c<=x+C.length)&&(b={offset:c-x,node:R}),d>x&&d<=x+C.length&&(g={offset:d-x,node:R}),S!=="text"){let z=o.Create("span",S);A&&(z.dataset.reference=A),z.appendChild(R),w.appendChild(z)}else w.appendChild(R);y=R,x+=C.length};this.parser.Walk(h.expression,C=>{if(C.type==="missing"||C.type==="group"||C.type==="dimensioned")return!0;let S=C.position+f,A=n.substring(p,S),E="",R=C.type,z="";switch(C.type){case"identifier":E=n.substring(S,S+C.name.length),z=m.get(C.name)||"";break;case"call":E=n.substring(S,S+C.name.length);break;case"literal":if(typeof C.value=="string")E=n.substring(S,S+C.value.length+2),R="string";else return!1;break;case"address":case"range":case"structured-reference":z=m.get(C.label)||"???",E=r.rewrite_addresses?C.label:n.substring(S,S+C.label.length);break;default:return!0}return _(A),_(E,R,z),p=S+E.length,C.type!=="range"}),p<n.length&&_(n.substring(p)),b||(y?b={node:y,offset:(y.data||"").length}:_("",void 0,"",!0)),i.textContent="",i.appendChild(w),b&&!r.format_only&&i===this.active_editor?.node&&this.SetCaret(b,g)}}t.formatted_text=n;let u=this.autocomplete_matcher;u&&Promise.resolve().then(()=>{let h=u.Exec({text:n,cursor:s.length});this.selecting&&h.completions?.length&&(h.completions=void 0);let m=this.NodeAtIndex(h.completions?.length?h.position||0:h.function_position||0);this.Autocomplete(h,m)})}NodeAtIndex(t){let r=this.active_editor?.node.childNodes||[];for(let i=0;i<r.length;i++){let n=r[i].textContent?.length||0;if(n>t)return r[i];t-=n}}AcceptAutocomplete(t){if(!this.active_editor)return;let r;if(t.data&&t.data.completions){for(let d of t.data.completions)if(d.name.toLowerCase()===t.value?.toLowerCase()){r=d.type;break}}let i=t.data?.position||0,n=i+(t.data?.token?.length||0),o=r==="token"?t.value:t.value+"(",a=this.active_editor.node.textContent||"",s=a.substring(0,i)+o,c=s.length;s+=a.substring(n),this.active_editor.node.textContent=s,this.SetCaret({node:this.active_editor.node,offset:c}),this.autocomplete?.Hide(),this.UpdateText(this.active_editor),this.UpdateColors()}Autocomplete(t,r){if(!this.container_node||!this.autocomplete)return;let i;r?.nodeType===Node.ELEMENT_NODE?i=r.getBoundingClientRect():i=this.container_node.getBoundingClientRect();let n=new B(Math.round(i.left),Math.round(i.top),i.width,i.height);this.autocomplete.Show(this.AcceptAutocomplete.bind(this),t,n)}SubstringToCaret2(t,r=!1){let i=["",""];if(!r&&t!==t.ownerDocument.activeElement||t!==this.active_editor?.node)return i;let o=t.ownerDocument.defaultView,a=[!1,!1],s=(d,u)=>{if(d===u.startContainer&&d===u.endContainer&&!(d instanceof o.Text)){a[0]=a[1]=!0,i[0]+=d.textContent,i[1]+=d.textContent;return}if(d===u.startContainer&&(i[0]+=(d.textContent||"").substring(0,u.startOffset),a[0]=!0),d===u.endContainer&&(i[1]+=(d.textContent||"").substring(0,u.endOffset),a[1]=!0),!(a[0]&&a[1])){if(d instanceof o.Text){let h=d.textContent||"";a[0]||(i[0]+=h),a[1]||(i[1]+=h)}else if(d.hasChildNodes()){for(let h of Array.from(d.childNodes))if(s(h,u),a[0]&&a[1])return}}},c=o.getSelection();if(c?.rangeCount??!1){let d=c?.getRangeAt(0);d&&s(t,d)}return i}};var Qo=typeof navigator>"u"?"":navigator.appVersion,Ee=typeof navigator>"u"?"":navigator.userAgent,Wr=class{is_edge=/Edge/.test(Qo);is_ipad=/iPad|iPhone/.test(Ee);is_iphone=/iPhone/.test(Ee);is_android=/android|samsung/i.test(Ee);is_mobile=this.is_ipad||this.is_android;is_firefox=/firefox/i.test(Ee);is_safari=/safari/i.test(Ee)&&!/edg/i.test(Ee);is_mac=/macintosh/i.test(Ee);is_chrome=/Chrome/i.test(Ee);is_windows=/win64|win32|windows\s+nt/i.test(Ee);is_modern=!this.is_edge&&!(this.is_firefox&&this.is_android)&&/webkit|firefox/i.test(Ee)},Zo={is_edge:!1,is_ipad:!1,is_iphone:!1,is_android:!1,is_firefox:!1,is_safari:!1,is_mac:!1,is_chrome:!1,is_windows:!1,is_modern:!0,is_mobile:!1},j=typeof navigator>"u"?Zo:new Wr;var Ht=class extends Fe{constructor(t,r,i,n,o){super(i,n,o);this.container=t;this.theme=r;this.container_node=t.querySelector(".treb-overlay-container"),this.edit_node=this.container_node.querySelector(".treb-overlay-editor"),j.is_firefox&&this.edit_node.classList.add("firefox"),this.edit_node.inputMode="none";let a={node:this.edit_node};this.nodes=[a],this.active_editor=a,this.RegisterListener(a,"input",s=>{if(s instanceof InputEvent&&s.isComposing)return;if(!s.isTrusted){this.reset_selection=!0;return}this.reset_selection&&this.Publish({type:"reset-selection"});let c=this.edit_node.firstChild;c&&c.tagName==="BR"&&this.edit_node.removeChild(c),this.editing&&(this.UpdateText(a),this.UpdateColors())}),this.RegisterListener(a,"keyup",s=>{s.isComposing||!this.editing||this.autocomplete&&this.autocomplete.HandleKey("keyup",s).handled}),this.edit_inset=this.container_node.querySelector(".treb-overlay-inset"),this.ClearContents()}internal_selection={target:{row:0,column:0},area:new v({row:0,column:0})};get selection(){return this.internal_selection}set selection(t){if(t){let r=t.target||t.area.start;this.internal_selection={target:{row:r.row,column:r.column},area:new v(t.area.start,t.area.end)}}else{let r={row:0,column:0};this.internal_selection={target:r,area:new v(r)}}}edit_style;reset_selection=!1;edit_node;container_node;edit_inset;scale=1;internal_editing=!1;get editing(){return this.internal_editing}set editing(t){this.internal_editing!==t&&(this.internal_editing=t,t?(this.container_node.style.opacity="1",this.container_node.style.pointerEvents="initial"):(this.container_node.style.opacity="0",this.container_node.style.pointerEvents="none"))}UpdateCaption(t=""){this.edit_node.setAttribute("aria-label",t)}Focus(t=""){this.edit_node!==this.edit_node.ownerDocument.activeElement&&(this.container_node.style.top=`${this.container.scrollTop+this.view.active_sheet.header_offset.y}px`,this.container_node.style.left=`${this.container.scrollLeft+this.view.active_sheet.header_offset.x}px`),this.edit_node.focus(),this.UpdateCaption(t)}CloseEditor(){this.editing=!1,this.reset_selection=!1,this.ClearContents(),this.edit_node.spellcheck=!0,this.autocomplete?.Hide(),this.active_cell=void 0}ClearContents(){j.is_firefox?this.edit_node.innerHTML="<span></span>":this.edit_node.textContent=""}Edit(t,r,i,n,o,a){this.Publish({type:"start-editing",editor:"ice"}),this.active_cell=i,this.target_address={...t.target},this.reset_selection=!1;let s=JSON.parse(JSON.stringify(i.style||{}));this.edit_style=a,a?.font_face&&(s.font_face=a.font_face);let c=I.CompositeFont(this.theme.grid_cell_font_size,s,this.scale,this.theme);switch(this.edit_node.style.font=c.font,c.variants?this.edit_node.style.fontVariant=c.variants:this.edit_node.style.fontVariant="",this.edit_node.style.color=D(this.theme,s.text,1),this.edit_inset.style.backgroundColor=D(this.theme,s.fill,0),s.horizontal_align){case"right":this.container_node.classList.remove("align-center","align-left"),this.container_node.classList.add("align-right");break;case"center":this.container_node.classList.remove("align-right","align-left"),this.container_node.classList.add("align-center");break;default:this.container_node.classList.remove("align-right","align-center"),this.container_node.classList.add("align-left");break}this.edit_node.style.paddingBottom=`${Math.max(0,(self.devicePixelRatio||1)-1)}px`;let d=n?.toString()||"";d&&d[0]==="="&&(this.edit_node.spellcheck=!1),r.ApplyStyle(this.container_node);let u=j.is_mac?0:.5;if(this.edit_node.style.bottom=u.toFixed(2)+"px",this.autocomplete?.ResetBlock(),this.selection=t,typeof n<"u"){let h=d[0]!=="="&&d[d.length-1]==="%",m=d.length;this.edit_node.textContent=d,this.SetCaret({node:this.edit_node,offset:m-(h?1:0)})}this.editing=!0,Promise.resolve().then(()=>{this.active_editor&&(this.active_editor.formatted_text=void 0,this.UpdateText(this.active_editor),this.UpdateColors()),!o&&n!==void 0&&this.Publish({type:"update",text:n.toString(),dependencies:this.composite_dependencies})})}GetEditState(){let t=this.active_editor?.node?.textContent||"",r="";return this.active_editor?.node&&(r=this.SubstringToCaret2(this.active_editor.node,!0)[0]),{text:t,substring:r}}HandleKeyDown(t){if(this.editing){if(this.autocomplete){let r=this.autocomplete.HandleKey("keydown",t);if(r.accept&&this.AcceptAutocomplete(r),r.handled)return"handled"}switch(t.key){case"Enter":case"Tab":return"commit";case"Escape":case"Esc":return"discard";case"ArrowUp":case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"Up":case"Down":case"Left":case"Right":return this.selecting?void 0:"commit"}return"handled"}}UpdateScale(t){this.scale=t}};var Wi=new Map,Qe,Ge=(l,e)=>{let t=l,r=Wi.get(t);return r||(r=ea(l,e),Wi.set(t,r),r)};var ea=(l,e)=>{Qe||typeof document<"u"&&(Qe=document.createElement("canvas")),Qe&&(e?Qe.style.fontVariant=e:Qe.style.fontVariant="");let t=Qe?.getContext("2d",{alpha:!1});if(!t)throw new Error("invalid context");t.textBaseline="alphabetic",t.textAlign="center",t.font=l;let r=t.measureText("("),i=r.actualBoundingBoxRight+r.actualBoundingBoxLeft;r=t.measureText("#");let n=r.actualBoundingBoxRight+r.actualBoundingBoxLeft;return r=t.measureText("Mljy!"),{paren:i,hash:n,ascent:r.fontBoundingBoxAscent,descent:r.fontBoundingBoxDescent,height:r.fontBoundingBoxAscent+r.fontBoundingBoxDescent}};var ta=" ",Gt=class{constructor(e,t,r,i,n){this.theme=e;this.layout=t;this.model=r;this.view=i;this.options=n;this.buffer_canvas=t.buffer_canvas,this.buffer_canvas.width=this.buffer_canvas_size.width,this.buffer_canvas.height=this.buffer_canvas_size.height;let o=this.buffer_canvas.getContext("2d",{alpha:!1});if(o){let a=this.layout.dpr;this.buffer_context=o,this.buffer_context.setTransform(a,0,0,a,0,0),this.buffer_context.textAlign="left",this.buffer_context.textBaseline="alphabetic"}}cell_edge_buffer=4;overflow_areas=[];buffer_canvas;buffer_context;buffer_canvas_size={width:256,height:256};FlushOverflows(){let e=this.view.active_sheet.cells;for(let t of e.Iterate())t.renderer_data?.overflowed&&(t.renderer_data=void 0,t.render_clean[this.view.view_index]=!1);for(let t of this.overflow_areas)t.tile.dirty=!0;this.overflow_areas=[]}MeasureText(e,t,r){let i=this.layout.grid_tiles[0][0],n=r??this.layout.scale,o=e.style||{},a=I.CompositeFont(this.theme.grid_cell_font_size,o,n,this.theme),s=Ge(a.font,a.variants),c={base:a.font,strong:I.CompositeFont(this.theme.grid_cell_font_size,{...o,bold:!0},n,this.theme).font,emphasis:I.CompositeFont(this.theme.grid_cell_font_size,{...o,italic:!0},n,this.theme).font,strong_emphasis:I.CompositeFont(this.theme.grid_cell_font_size,{...o,bold:!0,italic:!0},n,this.theme).font};a.variants?i.style.fontVariant=a.variants:i.style.fontVariant="";let d=i.getContext("2d",{alpha:!1});if(!d)throw new Error("context failed");let u=this.PrepText(d,c,e,t),h=u.width,m=s.height*u.strings.length;return{width:h,height:m}}EnsureBuffer(e=0,t=0,r=0){let i=this.layout.dpr;if(e=e*i,t=t*i,r=r*i,e>this.buffer_canvas_size.width||t>this.buffer_canvas_size.height){this.buffer_canvas_size.width=Math.max(Math.ceil(e/256)*256,this.buffer_canvas_size.width),this.buffer_canvas_size.height=Math.max(Math.ceil(t/256)*256,this.buffer_canvas_size.height),this.buffer_canvas.width=this.buffer_canvas_size.width,this.buffer_canvas.height=this.buffer_canvas_size.height;let n=this.buffer_canvas.getContext("2d",{alpha:!1});n&&(this.buffer_context=n,this.buffer_context.textAlign="left",this.buffer_context.textBaseline="alphabetic")}this.buffer_context.setTransform(i,0,0,i,r,0)}OverflowDirty(e=!1){let t=[];for(let r of this.overflow_areas){let i=r.area.start.row,n=e;if(!n)for(let o=r.area.start.column;!n&&o<=r.area.end.column;o++){let a=this.view.active_sheet.cells.GetCell({row:i,column:o},!1);n=!!(a&&!a.render_clean[this.view.view_index])}if(n){for(let o=r.area.start.column;o<=r.area.end.column;o++){let a=this.view.active_sheet.cells.GetCell({row:i,column:o},!1);a&&(a.render_clean[this.view.view_index]=!1,a.renderer_data&&a.renderer_data.overflowed&&(a.renderer_data=void 0))}r.tile.dirty=!0}else t.push(r)}this.overflow_areas=t}RenderCorner(){let t=this.layout.corner_canvas.getContext("2d",{alpha:!1});if(!t)throw new Error("invalid context");let r=I.CompositeFont(this.theme.grid_cell_font_size,this.theme.headers||{},this.layout.scale,this.theme),i=Ge(r.font,r.variants),n=this.layout.dpr,o=this.layout.header_offset,a=o.x;for(let c=0;c<this.view.active_sheet.freeze.columns;c++)a+=this.layout.ColumnWidth(c);let s=o.y;for(let c=0;c<this.view.active_sheet.freeze.rows;c++)s+=this.layout.RowHeight(c);t.setTransform(n,0,0,n,0,0),t.fillStyle=this.theme.headers?.fill?D(this.theme,this.theme.headers.fill):"",t.fillRect(0,0,a,o.y),t.fillRect(0,0,o.x,s),t.strokeStyle=this.theme.headers_grid_color||"",t.beginPath(),t.moveTo(o.x-.5,0),t.lineTo(o.x-.5,o.y),t.moveTo(0,o.y-.5),t.lineTo(o.x,o.y-.5),t.stroke(),!(!this.view.active_sheet.freeze.columns&&!this.view.active_sheet.freeze.rows)&&(t.strokeStyle=this.theme.grid_color||"",t.beginPath(),s!==o.y&&(t.moveTo(o.x-.5,o.y),t.lineTo(o.x-.5,s)),a!==o.x&&(t.moveTo(o.x,o.y-.5),t.lineTo(a,o.y-.5)),t.stroke(),t.strokeStyle=this.theme.headers_grid_color||"",t.textAlign="center",t.textBaseline="middle",t.font=r.font,t.fillStyle=D(this.theme,this.theme.headers?.text),this.view.active_sheet.freeze.rows&&this.layout.header_offset.x>1&&(t.setTransform(n,0,0,n,0,0),t.translate(0,o.y),t.beginPath(),t.moveTo(0,0-.5),t.lineTo(o.x,0-.5),t.stroke(),this.RenderRowLabels(t,0,this.view.active_sheet.freeze.rows-1,i.height)),this.view.active_sheet.freeze.columns&&this.layout.header_offset.y>1&&(t.setTransform(n,0,0,n,0,0),t.translate(o.x,0),t.beginPath(),t.moveTo(0-.5,0),t.lineTo(0-.5,o.y),t.stroke(),this.RenderColumnLabels(t,0,this.view.active_sheet.freeze.columns-1)))}RenderColumnLabels(e,t,r){let i=this.layout.header_offset.y;if(!(i<=1)){for(e.fillStyle=D(this.theme,this.theme.headers?.text,0),e.beginPath();t<=r;t++){let n=this.layout.ColumnWidth(t),o=v.ColumnToLabel(t),a=e.measureText(o);n>a.width&&e.fillText(o,n/2,i/2+1),e.moveTo(n-.5,0),e.lineTo(n-.5,i),e.translate(n,0)}e.stroke()}}RenderRowLabels(e,t,r,i){let n=this.layout.header_offset.x;if(!(n<=1)){for(e.fillStyle=D(this.theme,this.theme.headers?.text,0),e.beginPath();t<=r;t++){let o=this.layout.RowHeight(t);o>=i*1.2&&e.fillText(`${t+1}`,n/2,o/2+1),e.moveTo(0,o-.5),e.lineTo(n,o-.5),e.translate(0,o)}e.stroke()}}RenderHeaders(e,t=!1){let r=this.layout.dpr,i=this.layout.header_offset,n=I.CompositeFont(this.theme.grid_cell_font_size,this.theme.headers||{},this.layout.scale,this.theme),o=Ge(n.font,n.variants);for(let a=e.start.column;a<=e.end.column;a++){let s=this.layout.column_header_tiles[a];if(s.dirty||t){let c=s.getContext("2d",{alpha:!1});if(!c)continue;c.setTransform(r,0,0,r,0,0),c.textAlign="center",c.textBaseline="middle",c.font=n.font,n.variants?s.style.fontVariant=n.variants:s.style.fontVariant="",c.fillStyle=this.theme.headers?.fill?D(this.theme,this.theme.headers.fill):"",c.fillRect(0,0,s.logical_size.width,this.layout.header_offset.y),c.strokeStyle=this.theme.headers_grid_color||"",c.beginPath(),c.moveTo(0,i.y-.5),c.lineTo(s.logical_size.width,i.y-.5),c.stroke(),c.strokeStyle=this.theme.headers_grid_color||"",this.RenderColumnLabels(c,s.first_cell.column,s.last_cell.column),s.dirty=!1}}for(let a=e.start.row;a<=e.end.row;a++){let s=this.layout.row_header_tiles[a];if(s.dirty||t){let c=s.getContext("2d",{alpha:!1});if(!c)continue;c.fillStyle=this.theme.headers?.fill?D(this.theme,this.theme.headers.fill):"",c.setTransform(r,0,0,r,0,0),c.textAlign="center",c.textBaseline="middle",c.font=n.font,n.variants?s.style.fontVariant=n.variants:s.style.fontVariant="",c.fillRect(0,0,this.layout.header_offset.x,s.logical_size.height),c.strokeStyle=this.theme.headers_grid_color||"",c.beginPath(),c.moveTo(i.x-.5,0),c.lineTo(i.x-.5,s.logical_size.height),c.stroke(),c.strokeStyle=this.theme.headers_grid_color||"",this.RenderRowLabels(c,s.first_cell.row,s.last_cell.row,o.height),s.dirty=!1}}(this.view.active_sheet.freeze.rows||this.view.active_sheet.freeze.columns)&&this.RenderCorner()}CopyToAdjacent(e,t,r,i,n,o,a){let s=this.layout.AdjacentTile(e,i,r);if(!s)return;let c=n,d=o;r>0?c=n-(e.pixel_end.x-e.pixel_start.x)*t:r<0&&(c=n+(s.pixel_end.x-s.pixel_start.x)*t),i>0&&(d=o-(e.pixel_end.y-e.pixel_start.y)*t);let u=s.getContext("2d",{alpha:!1});u&&(u.setTransform(t,0,0,t,c,d),u.drawImage(this.buffer_canvas,0,0,(a.width||0)*t,(a.height||0)*t,a.left||0,0,a.width||0,a.height||0))}Render(e){let t=e.getContext("2d",{alpha:!1});if(!t)return;t.textBaseline="alphabetic";let r=this.layout.dpr;t.setTransform(r,0,0,r,0,0);let i=0,n=0;for(let s=e.first_cell.column;s<=e.last_cell.column;s++){let c=this.layout.ColumnWidth(s);if(c){n=0;for(let d=e.first_cell.row;d<=e.last_cell.row;d++){let u=this.layout.RowHeight(d);if(u){t.setTransform(r,0,0,r,i,n);let h=this.view.active_sheet.CellData({row:d,column:s});if(e.needs_full_repaint||!h.render_clean[this.view.view_index]){let m=this.RenderCell(e,h,t,{row:d,column:s},c,u,e.pixel_start.x+i,e.pixel_start.y+n);m.tile_overflow_right&&this.CopyToAdjacent(e,r,1,0,i,n,m),m.tile_overflow_left&&this.CopyToAdjacent(e,r,-1,0,i,n,m),m.tile_overflow_bottom&&this.CopyToAdjacent(e,r,0,1,i,n,m)}}n+=u*r}i+=c*r}}if(!this.view.active_sheet.freeze.rows&&!this.view.active_sheet.freeze.columns)return;let o=0,a=0;if(e.first_cell.row<=this.view.active_sheet.freeze.rows-1)for(let s=e.first_cell.row;s<this.view.active_sheet.freeze.rows&&s<=e.last_cell.row;s++)o+=this.layout.RowHeight(s);if(e.first_cell.column<=this.view.active_sheet.freeze.columns-1)for(let s=e.first_cell.column;s<this.view.active_sheet.freeze.columns&&s<=e.last_cell.column;s++)a+=this.layout.ColumnWidth(s);if(o){let s=this.layout.frozen_row_tiles[e.tile_position.column];if(!s)throw new Error("can't find matching header tile");let c=s.getContext("2d",{alpha:!0});if(!c)throw new Error("header context failed");c.setTransform(r,0,0,r,0,0),c.drawImage(e,0,0,e.logical_size.width*r,o*r,0,0,e.logical_size.width,o)}if(a){let s=this.layout.frozen_column_tiles[e.tile_position.row];if(!s)throw new Error("can't find matching header tile");let c=s.getContext("2d",{alpha:!0});if(!c)throw new Error("header context failed");c.setTransform(r,0,0,r,0,0),c.drawImage(e,0,0,a*r,e.logical_size.height*r,0,0,a,e.logical_size.height)}if(a&&o){let s=this.layout.corner_canvas.getContext("2d",{alpha:"false"});if(!s)throw new Error("corner context failed");s.setTransform(r,0,0,r,this.layout.header_offset.x*r,this.layout.header_offset.y*r),s.drawImage(e,0,0,a*r,o*r,0,0,a,o)}}PrepText(e,t,r,i){let n=[],o=r.style||{},a,s=0;if(r.rendered_type===4){let m=r.calculated_type?r.calculated:r.value;r.formatted=m?this.model.language_model?.boolean_true||"TRUE":this.model.language_model?.boolean_false||"FALSE"}let c,d=r.editing?"":r.formatted;Array.isArray(d)&&(d=d.filter(m=>m.flag!==8));let u="",h;if(o.indent){for(let m=0;m<o.indent;m++)u+=ta;h=o.horizontal_align,h||(h=r.type===3||r.calculated_type===3||r.type===8||r.calculated_type===8?"right":"left")}if(Array.isArray(d)){u&&(h==="right"?d.push({text:u,flag:8}):(h==="left"||typeof h>"u")&&d.unshift({text:u,flag:8}));for(let m of d){if(m.flag===6){c=m.text;continue}let f=e.measureText(m.text).width,p={width:f,text:m.text,hidden:m.flag===1};n.push(p),m.flag===2?a=p:s+=f}if(a){let m=a.text,f=a.width,p=i-s-2*this.cell_edge_buffer;if(a.width=Math.max(0,p),p>0){let b=Math.floor(p/f);for(let g=1;g<b;g++)a.text+=m;s=i-2*this.cell_edge_buffer}else a.text=""}return{strings:[n],format:c,width:s}}else if(d){r.type===2&&d[0]==="'"&&(d=d.slice(1));let m;this.options.markdown?m=Ie.instance.Parse(d):(m=Ie.instance.Dummy(d),e.font=t.base);let f=0,p=i-2*this.cell_edge_buffer,b=[];if(o.wrap){let g=u&&o.horizontal_align!=="center"?e.measureText(u).width:0;p-=g;for(let x of m){for(let w=1;w<x.length;w++){let _=x[w].text.match(/^(\s+)/);_&&(x[w-1].text+=_[1],x[w].text=x[w].text.replace(/^\s+/,""))}let y=[];for(let w of x){this.options.markdown&&(w.strong&&w.emphasis?e.font=t.strong_emphasis:w.strong?e.font=t.strong:w.emphasis?e.font=t.emphasis:e.font=t.base);let _=w.text.match(/\S+\s*/g);if(_&&_.length)for(let C of _){let S=e.measureText(C.trim()).width,A=e.measureText(C).width;y.push({part:w,text:C,trimmed:S,width:A})}}for(;y.length;){let w=y.shift(),_=[w],C=w.trimmed;for(;C<p&&y.length;){let A=y[0],E=C-w.trimmed+w.width+A.trimmed;if(E>=p)break;w=A,_.push(A),C=E,y.shift(),f=Math.max(f,C)}w.text=w.text.trim(),w.width=w.trimmed,f=Math.max(f,w.width);let S=_.map(A=>({...A.part,hidden:!1,width:A.width,text:A.text}));o.indent&&(h==="right"?S.push({text:u,hidden:!1,width:g}):h==="left"&&S.unshift({text:u,hidden:!1,width:g})),b.push(S)}}}else for(let g of m){let x=[];o.indent&&(h==="right"?g.push({text:u}):h==="left"&&g.unshift({text:u}));let y=0;for(let w of g){this.options.markdown&&(w.strong&&w.emphasis?e.font=t.strong_emphasis:w.strong?e.font=t.strong:w.emphasis?e.font=t.emphasis:e.font=t.base);let _=e.measureText(w.text).width;y+=_,x.push({...w,hidden:!1,width:_})}f=Math.max(f,y),b.push(x)}return{strings:b,width:f}}return{strings:[[{text:"",hidden:!1,width:0}]],width:0}}ResolveColors(e){let t={...e};return t.text={text:D(this.theme,e.text,1)},t}RenderCellBorders(e,t,r,i=0,n=0,o=0,a=0){let s=this.view.active_sheet.SurroundingStyle(e,this.theme.table),c=D(this.theme,s[8].fill);c&&(t.fillStyle=c,t.fillRect(i+0,n-1,o,1)),c=D(this.theme,s[4].fill),c&&(t.fillStyle=c,t.fillRect(i-1,n,1,a)),c=D(this.theme,r.fill),c&&(t.fillStyle=c,t.fillRect(i-1,n-1,o+1,a+1)),c=D(this.theme,s[6].fill),c&&(t.fillStyle=c,t.fillRect(i+o-1,n-1,1,a+1)),c=D(this.theme,s[2].fill),c&&(t.fillStyle=c,t.fillRect(i-1,n+a-1,o+1,1)),s[6].border_top&&!s[6].border_left&&(t.fillStyle=D(this.theme,s[6].border_top_fill,1),t.fillRect(i+o-1,n-2+s[6].border_top,1,1)),s[9].border_left&&(t.fillStyle=D(this.theme,s[9].border_left_fill,1),t.fillRect(i+o-1,n-1,1,1)),s[9].border_bottom&&(t.fillStyle=D(this.theme,s[9].border_bottom_fill,1),t.fillRect(i+o-1,n-2+s[9].border_bottom,1,1)),s[4].border_top&&!s[4].border_right&&(t.fillStyle=D(this.theme,s[4].border_right_fill,1),t.fillRect(i-1,n-2+s[4].border_top,1,1)),s[7].border_right&&(t.fillStyle=D(this.theme,s[7].border_right_fill,1),t.fillRect(i-1,n-1,1,1)),s[7].border_bottom&&(t.fillStyle=D(this.theme,s[7].border_bottom_fill,1),t.fillRect(i-1,n-2+s[7].border_bottom,1,1)),s[6].border_bottom&&!s[6].border_left&&(t.fillStyle=D(this.theme,s[6].border_bottom_fill,1),t.fillRect(i+o-1,n+a-s[6].border_bottom,1,1)),s[3].border_left&&(t.fillStyle=D(this.theme,s[3].border_left_fill,1),t.fillRect(i+o-1,n+a-1,1,1)),s[3].border_top&&(t.fillStyle=D(this.theme,s[3].border_top_fill,1),t.fillRect(i+o-1,n+a-s[3].border_top,1,1)),s[4].border_bottom&&!s[4].border_right&&(t.fillStyle=D(this.theme,s[4].border_bottom_fill,1),t.fillRect(i-1,n+a-s[4].border_bottom,1,1)),s[1].border_right&&(t.fillStyle=D(this.theme,s[1].border_right_fill,1),t.fillRect(i-1,n+a-1,1,1)),s[1].border_top&&(t.fillStyle=D(this.theme,s[1].border_top_fill,1),t.fillRect(i-1,n+a-s[1].border_top,1,1)),s[8].border_bottom&&(t.fillStyle=D(this.theme,s[8].border_bottom_fill,1),s[8].border_bottom===2&&(t.fillRect(i-1,n-2,o+1,1),t.fillRect(i-1,n-0,o+1,1),t.fillStyle=D(this.theme,s[8].fill)||D(this.theme,this.theme.grid_cell?.fill,0)||"#fff"),t.fillRect(i-1,n-1,o+1,1)),s[4].border_right&&(t.fillStyle=D(this.theme,s[4].border_right_fill,1),t.fillRect(i-1,n-1,1,a+1)),s[6].border_left&&(t.fillStyle=D(this.theme,s[6].border_left_fill,1),t.fillRect(i+o-1,n-1,1,a+1)),s[2].border_top&&(t.fillStyle=D(this.theme,s[2].border_top_fill,1),s[2].border_top===2&&(t.fillRect(i-1,n+a-2,o+1,1),t.fillRect(i-1,n+a-0,o+1,1),t.fillStyle=D(this.theme,s[2].fill)||D(this.theme,this.theme.grid_cell?.fill,0)||"#fff"),t.fillRect(i-1,n+a-1,o+1,1)),r.border_top&&(t.fillStyle=D(this.theme,r.border_top_fill,1),r.border_top===2&&(t.fillRect(i-1,n-2,o+1,1),t.fillRect(i-1,n+0,o+1,1),t.fillStyle=D(this.theme,r.fill)||D(this.theme,this.theme.grid_cell?.fill,0)||"#fff"),t.fillRect(i-1,n-1,o+1,1)),r.border_left&&(t.fillStyle=D(this.theme,r.border_left_fill,1),t.fillRect(i-1,n-1,1,a+1)),r.border_right&&(t.fillStyle=D(this.theme,r.border_right_fill,1),t.fillRect(i+o-1,n-1,1,a+1)),r.border_bottom&&(t.fillStyle=D(this.theme,r.border_bottom_fill,1),r.border_bottom===2&&(t.fillRect(i-1,n+a-2,o+1,1),t.fillRect(i-1,n+a+0,o+1,1),t.fillStyle=D(this.theme,r.fill)||D(this.theme,this.theme.grid_cell?.fill,0)||"#fff"),t.fillRect(i-1,n+a-1,o+1,1))}PaintBackgroundImage(e,t,r,i,n,o,a=0,s=0,c=0){if(!t.width||!t.height)return;let d=(this.layout.scale||1)*this.layout.dpr,u=r/d%t.width,h=i/d%t.height,m=n/d,f=o/d,p=u+m>t.width,b=h+f>t.height;p&&e.drawImage(t,u-t.width,h,m,f,a,s,n-c,o-c),b&&e.drawImage(t,u,h-t.height,m,f,a,s,n-c,o-c),p&&b&&e.drawImage(t,u-t.width,h-t.height,m,f,a,s,n-c,o-c),e.drawImage(t,u,h,m,f,a,s,n-c,o-c)}RenderCellBackground(e,t,r,i,n,o,a=0,s=0){if(r.fillStyle=this.theme.grid_color,r.fillRect(0,0,n,o),this.view.active_sheet.image)this.PaintBackgroundImage(r,this.view.active_sheet.image,a,s,n,o,0,0,1);else{let c=D(this.theme,i.fill);c?(r.fillStyle=c,r.fillRect(0,0,n-1,o-1)):(r.fillStyle=D(this.theme,this.theme.grid_cell?.fill,0)||"#fff",r.fillRect(0,0,n-1,o-1))}this.RenderCellBorders(t,r,i,0,0,n,o),e&&(r.fillStyle=this.theme.note_marker_color,r.beginPath(),r.moveTo(n-2,1),r.lineTo(n-2-8,1),r.lineTo(n-2,9),r.lineTo(n-2,1),r.fill())}RenderCell(e,t,r,i,n,o,a=0,s=0){let c={},d=!t.render_clean[this.view.view_index];if(t.render_clean[this.view.view_index]=!0,e.needs_full_repaint&&t.renderer_data?.overflowed)return{};let u=t.style?{...t.style}:{};if(t.table&&(u=this.view.active_sheet.CellStyleData(i,t.table.theme||this.theme.table)||{}),t.merge_area)if(i.row===t.merge_area.start.row&&i.column===t.merge_area.start.column){for(let T=t.merge_area.start.column+1;T<=t.merge_area.end.column;T++)n+=this.layout.ColumnWidth(T);for(let T=t.merge_area.start.row+1;T<=t.merge_area.end.row;T++)o+=this.layout.RowHeight(T);if(t.merge_area.count>1){let T=this.view.active_sheet.CellStyleData(t.merge_area.end);T&&(u.border_bottom=T.border_bottom,u.border_right=T.border_right,u.border_bottom_fill=T.border_bottom_fill,u.border_right_fill=T.border_right_fill)}t.merge_area.end.column>e.last_cell.column&&(c.tile_overflow_right=!0),t.merge_area.end.row>e.last_cell.row&&(c.tile_overflow_bottom=!0),(c.tile_overflow_bottom||c.tile_overflow_right)&&this.overflow_areas.push({tile:e,head:{...i},area:new v(t.merge_area.start,t.merge_area.end)})}else return{};let h=!!t.hyperlink;if(t.render_function){this.RenderCellBackground(!!t.note,i,r,u,n,o),r.strokeStyle=r.fillStyle=D(this.theme,u.text,1);let T=this.ResolveColors(u);if(t.render_function.call(void 0,{width:n,height:o,context:r,cell:t,style:T,scale:this.layout.scale||1}).handled)return c}let m=I.CompositeFont(this.theme.grid_cell_font_size,u,this.layout.scale,this.theme),f={base:m.font,strong:I.CompositeFont(this.theme.grid_cell_font_size,{...u,bold:!0},this.layout.scale,this.theme).font,emphasis:I.CompositeFont(this.theme.grid_cell_font_size,{...u,italic:!0},this.layout.scale,this.theme).font,strong_emphasis:I.CompositeFont(this.theme.grid_cell_font_size,{...u,bold:!0,italic:!0},this.layout.scale,this.theme).font};if(m.variants?e.style.fontVariant=m.variants:e.style.fontVariant="",r.font=f.base,d||!t.renderer_data||t.renderer_data.width!==n||t.renderer_data.height!==o){let T=this.PrepText(r,f,t,n);t.renderer_data={text_data:T,width:n,height:o}}let p=t.renderer_data.text_data,b=p.width>n-2*this.cell_edge_buffer,g=n,x=0,y=!1,w=t.type===3||t.calculated_type===3||t.type===8||t.calculated_type===8||t.type===10||t.calculated_type===10,_=u.horizontal_align;_||(_=w?"right":"left");let C=[];if(b)if(t.type!==3&&t.calculated_type!==3&&!u.wrap&&!t.merge_area){let q=p.width-n+this.cell_edge_buffer,le=0,Y=0;_==="center"?le=Y=q/2:_==="right"?le=q:Y=q;let J=i.column,k=i.column;for(;Y>0&&J<this.layout.last_column;){J++;let P={row:i.row,column:J},Z=this.view.active_sheet.CellData(P),be=this.layout.ColumnWidth(J);if(Y-=be,Z&&!Z.type&&!Z.calculated_type)C.push({address:P,cell:Z,grid:new B(g,0,be,o),background:new B(g-1,0,be,o-1),border:new B(g,0,be,o)}),g+=be,Z.render_clean[this.view.view_index]=!0,Z.renderer_data={overflowed:!0};else{y=!0;break}}for(J>e.last_cell.column&&(c.tile_overflow_right=!0);le>0&&k>=1;){k--;let P={row:i.row,column:k},Z=this.view.active_sheet.CellData(P),be=this.layout.ColumnWidth(k);if(le-=be,Z&&!Z.type&&!Z.calculated_type)x-=be,C.push({address:P,cell:Z,grid:new B(x,0,be,o),background:new B(x,0,be,o-1),border:new B(x,0,be,o)});else{y=!0;break}}k<e.first_cell.column&&(c.tile_overflow_left=!0),this.overflow_areas.push({head:{...i},tile:e,area:new v({row:i.row,column:k},{row:i.row,column:J})})}else y=!w;let S=!1,A=r;(c.tile_overflow_bottom||c.tile_overflow_left||c.tile_overflow_right)&&(S=!0,c.width=g-x,c.height=o,c.left=x,this.EnsureBuffer(c.width+1,o+1,-x),r=this.buffer_context,r.font=f.base),this.RenderCellBackground(!!t.note,i,r,u,n,o,a,s);for(let T of C)T.cell.style?.fill&&zi(T.cell.style.fill)&&!this.options.grid_over_background?(r.fillStyle=D(this.theme,T.cell.style.fill,0),r.fillRect(T.grid.left,T.grid.top,T.grid.width,T.grid.height)):(r.fillStyle=this.theme.grid_color||"",r.fillRect(T.grid.left,T.grid.top,T.grid.width,T.grid.height),this.view.active_sheet.image?this.PaintBackgroundImage(r,this.view.active_sheet.image,a+T.background.left,s+T.background.top,T.background.width,T.background.height,T.background.left,T.background.top,0):(r.fillStyle=this.theme.grid_cell?.fill?D(this.theme,this.theme.grid_cell.fill,0):"",r.fillRect(T.background.left,T.background.top,T.background.width,T.background.height))),T.cell.style&&this.RenderCellBorders(T.address,r,T.cell.style,T.border.left,T.border.top,T.border.width,T.border.height);if(u.databar&&o>7&&n>9){let T=u.databar;if(T){let q={x:4,y:3};r.fillStyle=D(this.theme,T.fill);let le=q.y,Y=o-(q.y*2+1),J=q.x,k=0;T.zero>0?(J=J+T.zero*(n-(q.x*2+1)),T.value>T.zero?k=(n-(q.x*2+1))*(T.value-T.zero):(T.negative&&(r.fillStyle=D(this.theme,T.negative)),k=(n-(q.x*2+1))*(T.zero-T.value),J-=k)):k=(n-(q.x*2+1))*T.value,r.fillRect(J,le,k,Y)}}let E=Ge(f.base,m.variants);r.lineWidth=1,r.strokeStyle=r.fillStyle=p.format?p.format:D(this.theme,u.text,1),r.beginPath();let R=this.cell_edge_buffer,z=1,K=p.strings.length,ie=K*E.height*z;y=(y||ie>=o)&&!S,y&&(r.save(),r.beginPath(),r.moveTo(x+1.5,0),r.lineTo(x+1.5,o),r.lineTo(g-1.5,o),r.lineTo(g-1.5,0),r.clip()),r.beginPath();let pe=Math.round(o-E.descent-2+-z*E.height*(K-1));switch(u.vertical_align){case"top":pe=Math.round(2+E.ascent);break;case"middle":pe=Math.round((o-ie)/2+E.ascent)-1.5;break}if(!u.databar?.hide_values)if((t.type===3||t.calculated_type===3||t.type===8||t.calculated_type===8)&&b){let T=Math.floor((n-2*this.cell_edge_buffer)/E.hash),q="";for(let Y=0;Y<T;Y++)q+="#";let le=r.measureText(q).width;_==="center"?R=Math.round((n-le)/2):_==="right"&&(R=n-this.cell_edge_buffer-le),r.fillText(q,R,pe)}else{let T=pe;for(let q of p.strings){let le=0;for(let P of q)le+=P.width;_==="center"?R=Math.round((n-le)/2):_==="right"&&(R=n-this.cell_edge_buffer-le);let Y=T+2.5,J=Math.floor(T-E.ascent*1/3)+.5,k=R;for(let P of q)P.strong&&P.emphasis?r.font=f.strong_emphasis:P.strong?r.font=f.strong:P.emphasis?r.font=f.emphasis:r.font=f.base,P.hidden||(P.text&&r.fillText(P.text,k,T),u.underline&&(r.moveTo(k,Y),r.lineTo(k+P.width,Y)),(u.strike||P.strike)&&(r.moveTo(k,J),r.lineTo(k+P.width,J)),h&&(P.left=k,P.top=T-E.ascent,P.height=E.height)),k+=P.width;T+=z*E.height}}if(r.stroke(),y)r.restore();else if(S){let T=this.layout.dpr;A.drawImage(this.buffer_canvas,0,0,(c.width||0)*T,o*T,x,0,c.width||0,o)}return c}};var Bt=class extends Fe{constructor(t,r,i,n,o){super(r,i,o);this.options=n;let a=O.GetInstance(t.ownerDocument),s=t.querySelector(".treb-formula-bar");s.removeAttribute("hidden"),this.address_label_container=s.querySelector(".treb-address-label"),this.address_label=this.address_label_container.firstElementChild,this.InitAddressLabel(),this.container_node=t.querySelector(".treb-editor-container");let c=this.container_node.firstElementChild,d={node:c};if(this.active_editor=d,this.nodes=[d],c&&this.RegisterListener(d,"input",u=>{u.isTrusted&&(this.UpdateText(d),this.UpdateColors())}),this.active_editor.node.spellcheck=!1,this.RegisterListener(d,"focusin",()=>{let u=this.tolled!==void 0;if(this.tolled=void 0,!this.active_editor)return;let h=this.active_editor.node.textContent||"";if(this.shadow&&(this.shadow=!1,h="",this.active_editor.node.textContent=h,this.active_editor.formatted_text=void 0),h[0]==="{"&&h[h.length-1]==="}"&&(h=h.substring(1,h.length-1),this.active_editor.node.textContent=h,this.active_editor.formatted_text=void 0),this.autocomplete?.ResetBlock(),this.UpdateText(this.active_editor),this.UpdateColors(void 0,!0),u){let m=this.NodeAtIndex(h.length-1);m&&this.SetCaret({node:m,offset:(m.textContent||"").length})}this.committed=!1,this.Publish([{type:"start-editing",editor:"formula-bar"},{type:"update",text:h,cell:this.active_cell,dependencies:this.composite_dependencies}]),this.focused_=!0}),this.RegisterListener(d,"focusout",u=>{let h=u.relatedTarget instanceof HTMLElement&&u.relatedTarget.dataset.tollEditor;this.selecting&&console.info("focusout, but selecting..."),this.autocomplete?.Hide();let m=(this.active_editor?this.GetTextContent(this.active_editor.node).join(""):"").trim();if(h){let f=m;this.active_editor?.node&&(f=this.SubstringToCaret2(this.active_editor.node,!0)[0]),this.committed=!0,this.tolled={text:m,substring:f},this.Publish({type:"toll",value:m})}else this.committed?this.Publish([{type:"stop-editing"}]):(this.committed=!0,this.Publish({type:"commit",value:m}));this.Publish([{type:"stop-editing"}]),this.focused_=!1,this.active_editor&&(this.active_editor.node.spellcheck=!1)}),this.RegisterListener(d,"keydown",this.FormulaKeyDown.bind(this)),this.RegisterListener(d,"keyup",this.FormulaKeyUp.bind(this)),this.options.expand_formula_button){let u;this.expand_button=a.Create("button","expand-button",s,{events:{focus:h=>{u=h.relatedTarget instanceof HTMLElement?h.relatedTarget:void 0},click:h=>{h.stopPropagation(),h.preventDefault(),this.active_editor&&(this.active_editor.node.scrollTop=0),s.hasAttribute("expanded")?s.removeAttribute("expanded"):s.setAttribute("expanded",""),u&&u.focus()}}})}}committed=!1;tolled;shadow_=!1;get shadow(){return this.shadow_}set shadow(t){this.shadow_=t,this.active_editor?.node&&(t?this.active_editor.node.classList.add("treb-editor-shadow"):this.active_editor.node.classList.remove("treb-editor-shadow"))}focused_=!1;get focused(){return this.focused_}address_label_container;address_label;button;expand_button;label_update_timer=0;get formula(){return this.active_editor&&this.active_editor.node.textContent||""}set formula(t){this.active_editor&&(this.active_editor.node.textContent=t,this.active_editor.formatted_text=void 0)}get label(){return this.address_label?.textContent||""}set label(t){t.trim().length?(this.address_label.textContent=t,this.label_update_timer||(this.label_update_timer=requestAnimationFrame(()=>{this.label_update_timer=0,this.address_label.scrollWidth>this.address_label.offsetWidth?this.address_label.setAttribute("title",t):this.address_label.removeAttribute("title")}))):(this.address_label.innerHTML="&nbsp;",this.address_label.removeAttribute("title"))}set editable(t){!this.active_editor||!this.container_node||(t?(this.active_editor.node.setAttribute("contenteditable","true"),this.container_node.removeAttribute("locked")):(this.active_editor.node.removeAttribute("contenteditable"),this.container_node.setAttribute("locked","")))}Restore(){let t=this.container_node?.firstElementChild;t&&t.focus()}Release(){this.tolled=void 0}IsElement(t){return t===this.active_editor?.node}IsExpandButton(t){return this.expand_button&&t===this.expand_button}InitAddressLabel(){this.address_label.contentEditable="true",this.address_label.spellcheck=!1,this.address_label.addEventListener("focusin",()=>{let t=this.address_label.ownerDocument;requestAnimationFrame(()=>{let r=t.defaultView.getSelection(),i=t.createRange();i.selectNodeContents(this.address_label),r?.removeAllRanges(),r?.addRange(i)})}),this.address_label.addEventListener("keydown",t=>{if(!t.isComposing)switch(t.key){case"Enter":t.stopPropagation(),t.preventDefault(),this.Publish({type:"address-label-event",text:this.address_label.textContent||void 0});break;case"Esc":case"Escape":t.stopPropagation(),t.preventDefault(),this.Publish({type:"address-label-event"});break}})}GetTextContent(t){let r=t.childNodes,i=[];for(let n=0;n<r.length;n++){let o=r[n];switch(o.nodeType){case Node.ELEMENT_NODE:i.push(...this.GetTextContent(o)),o instanceof Element&&o.tagName==="DIV"&&i.push(`
7
+ `);break;case Node.TEXT_NODE:o.nodeValue&&i.push(o.nodeValue);break}}return i}FormulaKeyUp(t){t.isComposing||this.autocomplete&&this.autocomplete.HandleKey("keyup",t).handled}FormulaKeyDown(t){if(!t.isComposing){if(this.autocomplete){let r=this.autocomplete.HandleKey("keydown",t);if(r.accept&&this.AcceptAutocomplete(r),r.handled)return}switch(t.key){case"Enter":case"Tab":{let r=t.key==="Enter"&&t.ctrlKey&&t.shiftKey,i=(this.active_editor?this.GetTextContent(this.active_editor.node).join(""):"").trim();this.committed=!0,this.Publish({type:"commit",value:i,event:t,array:r})}break;case"Escape":case"Esc":this.committed=!0,this.Publish({type:"discard"});break;default:return}t.stopPropagation(),t.preventDefault()}}};var ft=class{constructor(e={}){this.options=e;if(this.DOM=O.GetInstance(e.container?.ownerDocument),!this.DOM.doc)throw new Error("invalid context");this.completion_list=this.DOM.Div("treb-cell-editor-ac-list treb-autocomplete",e.container||this.DOM.doc.body,{events:{mousedown:t=>this.ListMouseDown(t),mousemove:t=>this.ListMouseMove(t)}}),this.tooltip=this.DOM.Div("treb-cell-editor-ac-tooltip treb-autocomplete-tooltip",e.container||this.DOM.doc.body)}completion_list_visible=!1;tooltip_visible=!1;last_completion;completion_list;tooltip;selected_index=0;block=!1;autocomplete_data={};callback;active_element;DOM;Hide(){this.tooltip.style.top="-1000px",this.completion_list.style.top="-1000px",this.completion_list_visible=!1,this.tooltip_visible=!1,this.active_element=void 0}SetBlock(){this.block=!0}ResetBlock(){this.block=!1}ListMouseMove(e){let t=e.target;t.tagName==="A"&&t!==this.active_element&&this.active_element&&(this.active_element.classList.remove("selected"),this.active_element=t,this.active_element.classList.add("selected"),this.selected_index=Number(t.dataset.index||"0"),this.last_completion=t.textContent||"")}ListMouseDown(e){e.stopPropagation(),e.preventDefault();let t=e.target;for(;t;){if(t===this.completion_list)return;if(t.tagName==="A")break;t=t.parentElement}t&&(console.info(t),this.callback&&this.callback({handled:!0,accept:!0,value:t.textContent?t.textContent:void 0,data:this.autocomplete_data,click:!0}))}HandleKey(e,t){if(!this.completion_list_visible)return{handled:!1};let r=0,i=!1,n=!1;switch(t.key){case"Up":case"ArrowUp":r=-1;break;case"Down":case"ArrowDown":r=1;break;case"Tab":n=!0;break;case"Escape":case"Esc":i=!0;break;default:return{handled:!1}}if(t.stopPropagation(),t.preventDefault(),e==="keyup")return{handled:!0};if(r){let o=this.completion_list.getBoundingClientRect();this.selected_index+=r,this.selected_index=Math.max(0,this.selected_index);let a=this.completion_list.querySelectorAll("a");this.selected_index=Math.min(this.selected_index,a.length-1);for(let s=0;s<a.length;s++){let c=a[s];if(s===this.selected_index){c.classList.add("selected"),this.active_element=c;let d=c.getBoundingClientRect();d.top<o.top?this.completion_list.scrollBy(0,-d.height):d.bottom>o.bottom&&this.completion_list.scrollBy(0,d.height),this.last_completion=c.textContent||void 0}else c.classList.remove("selected")}return{handled:!0}}else{if(i)return this.block=!0,this.Hide(),{handled:!0};if(n)return{handled:!0,accept:!0,value:this.last_completion,data:this.autocomplete_data}}return{handled:!1}}Show(e,t={},r){if(this.completion_list_visible=!1,this.tooltip_visible=!1,this.autocomplete_data=t,this.callback=e,!this.block)if(t.tooltip?(this.tooltip.innerHTML=t.tooltip+t.arguments+(t.description?`
8
8
  `+t.description:""),this.tooltip.style.left=r.left+"px",this.options.tooltip_prefer_top?this.tooltip.style.top=r.top-this.tooltip.offsetHeight-5+"px":this.tooltip.style.top=r.bottom+5+"px",this.tooltip_visible=!0):this.tooltip.style.top="-1000px",t.completions&&t.completions.length){this.tooltip.style.top="-1000px",this.selected_index=0,this.completion_list.innerHTML='<ul class="notranslate">'+t.completions.map((a,s)=>(a.name===this.last_completion&&(this.selected_index=s),`<li><a data-index="${s}">${a.name}</a></li>`)).join(`
9
- `)+"<ul>";let i=this.completion_list.offsetHeight,n=!1;this.options.autocomplete_prefer_top?n=r.top>=200:this.DOM.doc?.documentElement&&Math.max(this.DOM.doc.documentElement.clientHeight,this.DOM.view?.innerHeight||0)-r.bottom<200&&(n=!0),n?this.completion_list.style.top=r.top-i-5+"px":this.completion_list.style.top=r.bottom+5+"px",this.completion_list.style.left=r.left+"px";let o=this.completion_list.querySelectorAll("a");this.active_element=o[this.selected_index],o[this.selected_index].classList.add("selected"),this.last_completion=o[this.selected_index].textContent||void 0,this.completion_list.scrollTop=this.active_element.offsetTop,this.completion_list_visible=!0}else this.completion_list.style.top="-1000px"}};var pt=(k=>(k[k.Null=0]="Null",k[k.InsertRows=1]="InsertRows",k[k.InsertColumns=2]="InsertColumns",k[k.ResizeRows=3]="ResizeRows",k[k.ResizeColumns=4]="ResizeColumns",k[k.Select=5]="Select",k[k.SetRange=6]="SetRange",k[k.UpdateStyle=7]="UpdateStyle",k[k.UpdateBorders=8]="UpdateBorders",k[k.Indent=9]="Indent",k[k.MergeCells=10]="MergeCells",k[k.UnmergeCells=11]="UnmergeCells",k[k.Clear=12]="Clear",k[k.UpdateTheme=13]="UpdateTheme",k[k.SetNote=14]="SetNote",k[k.SetLink=15]="SetLink",k[k.Freeze=16]="Freeze",k[k.SetName=17]="SetName",k[k.ShowHeaders=18]="ShowHeaders",k[k.AddSheet=19]="AddSheet",k[k.DuplicateSheet=20]="DuplicateSheet",k[k.DeleteSheet=21]="DeleteSheet",k[k.ActivateSheet=22]="ActivateSheet",k[k.RenameSheet=23]="RenameSheet",k[k.ReorderSheet=24]="ReorderSheet",k[k.ShowSheet=25]="ShowSheet",k[k.DataValidation=26]="DataValidation",k[k.Reset=27]="Reset",k[k.SortTable=28]="SortTable",k[k.InsertTable=29]="InsertTable",k[k.RemoveTable=30]="RemoveTable",k[k.AddConditionalFormat=31]="AddConditionalFormat",k[k.RemoveConditionalFormat=32]="RemoveConditionalFormat",k[k.TabColor=33]="TabColor",k[k.CreateAnnotation=34]="CreateAnnotation",k[k.RemoveAnnotation=35]="RemoveAnnotation",k))(pt||{});var Bt=class{function_names=[];argument_separator=F.argument_separator.charCodeAt(0);function_map=new Map;RemoveFunctions(e){Array.isArray(e)||(e=[e]);for(let t of e)this.function_map.delete(t.name.toLowerCase());this.UpdateNameList()}AddFunctions(e){Array.isArray(e)||(e=[e]);for(let t of e)this.function_map.set(t.name.toLowerCase(),t);this.UpdateNameList()}SetFunctions(e){this.function_map.clear();for(let t of e)this.function_map.set(t.name.toLowerCase(),t);this.UpdateNameList()}NormalizeIdentifier(e){return this.function_map.get(e.toLowerCase())?.name}Get(e){return this.function_map.get(e.toLowerCase())}Exec(e){if(e.text[0]!=="=")return{};let t,r={};if(e.cursor===e.text.length&&(t=e.text.match(/(?:^|[^a-zA-Z\u00C0-\u024F_\d])([a-zA-Z\u00C0-\u024F_][\w\d\u00C0-\u024F_.]*)\s*$/),t)){let n=t[1],o=new RegExp("^"+n.replace(".","\\."),"i");r={completions:this.function_names.filter(s=>o.test(s)).map(s=>this.function_map.get(s.toLowerCase())).filter(s=>!!s),token:n,position:e.cursor-n.length}}let i=this.ParseTooltip(e.text.substr(0,e.cursor));if(i.function){let n=this.function_map.get(i.function.toLowerCase());n&&(r.tooltip='<span class="notranslate">'+n.name+"</span>",r.arguments="("+(n.arguments||[]).map((o,a)=>{let s=o.name||"argument";return a===i.argument?`<span class="active-argument">${s}</span>`:s}).join(F.argument_separator+" ")+")",r.description=n.description?`<span class="function-description">${n.description}</span>`:"",r.function_position=i.position||0)}return r}ParseTooltip(e){let t=[],r=0,i="",n=!1,o=0;for(let s of e){let c=s.charCodeAt(0);if(n)c===34&&(n=!1);else switch(c){case 40:t.push({buffer:i.trim(),argument:r,position:o-i.length}),i="",r=0;break;case this.argument_separator:r++;break;case 41:r=t.pop()?.argument||0;break;case 34:i="",n=!0;break;default:c>=97&&c<=122||c>=65&&c<=90||c>=48&&c<=57||c>=192&&c<=591||c===95||c===46?i+=s:i=""}o++}let a=t.pop();return{function:a?.buffer||void 0,position:a?.position||0,argument:r}}UpdateNameList(){this.function_names=[...this.function_map.keys()].sort((e,t)=>e.toLowerCase().localeCompare(t.toLowerCase()))}};var $i={scrollbars:!0,in_cell_editor:!0,formula_bar:!0,add_tab:!1,tab_bar:"auto",expand_formula_button:!1,expand:!0,comment_markdown:!0,repaint_on_cell_change:!0,grid_over_background:!1};var Qo=l=>{console.error("invalid case")},bt=class{grid_events=new ge;command_log=new ge;model;view;get active_sheet(){return this.view.active_sheet}set active_sheet(e){this.view.active_sheet=e}get view_index(){return this.view.view_index}batch=0;batch_paint=!1;batch_events=[];autocomplete_matcher=new Bt;flags={};options;parser;constructor(e={},t){this.model=t,this.view={active_sheet:this.model.sheets.list[0],view_index:this.model.view_count++},this.parser=t.parser,this.options={...$i,...e}}RemoveConditionalFormat(e){this.ExecCommand({key:32,...e})}AddConditionalFormat(e){this.ExecCommand({key:31,format:e})}RemoveTable(e){this.ExecCommand({key:30,table:e})}InsertTable(e,t=!0,r=void 0,i){e.start.sheet_id||(e.start.sheet_id=this.active_sheet.id);let n=this.FindSheet(e);for(let o=e.start.row;o<=e.end.row;o++)for(let a=e.start.column;a<=e.end.column;a++){let s=n.cells.GetCell({row:o,column:a},!1);if(s&&(s.area||s.merge_area||s.table)){this.Error(4);return}}this.ExecCommand({key:29,area:JSON.parse(JSON.stringify(e)),totals:t,sortable:r,theme:i})}ActivateSheet(e,t){let r=typeof e=="number"?e:void 0,i=typeof e=="string"?e:void 0;this.ExecCommand({key:22,index:r,name:i,user:t})}ActivateSheetID(e){this.ExecCommand({key:22,id:e})}DuplicateSheet(e,t,r){let i={key:20,new_name:t,insert_before:r};typeof e>"u"?i.id=this.active_sheet.id:i.index=e,this.ExecCommand(i)}AddSheet(e){this.ExecCommand({key:19,name:e,show:!0})}DeleteSheet(e){if(typeof e>"u"&&!this.model.sheets.list.some((t,r)=>t===this.active_sheet?(e=r,!0):!1))throw new Error("invalid index");this.ExecCommand({key:21,index:e})}InsertSheet(e,t){if(typeof e>"u"&&!this.model.sheets.list.some((r,i)=>r===this.active_sheet?(e=i+1,!0):!1))throw new Error("invalid index");this.ExecCommand({key:19,insert_index:e,name:t,show:!0})}DeleteSheetID(e){this.ExecCommand({key:21,id:e})}Reset(){this.ExecCommand({key:27})}SetLink(e,t){this.ExecCommand({key:15,area:e,reference:t})}ShowAll(){let e=[];for(let t=0;t<this.model.sheets.length;t++)e.push({key:25,index:t,show:!0});this.ExecCommand(e)}ShowSheet(e=0,t=!0){let r={key:25,show:t};typeof e=="string"?r.name=e:r.index=e,this.ExecCommand(r)}SortTable(e,t={}){this.ExecCommand({key:28,table:JSON.parse(JSON.stringify(e)),...qi,...t})}GetFreeze(){return{...this.active_sheet.freeze}}InsertRows(e=0,t=1){this.ExecCommand({key:1,before_row:e,count:t})}GetTableReference(e){return this.model.sheets.Find(e.sheet_id||this.active_sheet.id)?.CellData(e).table||void 0}FromCSV(e){this.parser.Save(),this.parser.SetLocaleSettings(".");let r=Ei(e).map(n=>n.map(o=>{if(o){let a=this.parser.Parse(o);if(a.expression?.type==="complex")return a.expression}return _e.TryParse(o).value}));this.parser.Restore();let i={row:Math.max(0,r.length-1),column:r.reduce((n,o)=>Math.max(n,Math.max(0,o.length-1)),0)};this.ExecCommand([{key:27},{key:6,area:{start:{row:0,column:0},end:i},value:r}])}InsertColumns(e=0,t=1){this.ExecCommand({key:2,before_column:e,count:t})}ReorderSheet(e,t){this.ExecCommand({key:24,index:e,move_before:t})}RenameSheet(e,t){this.ExecCommand({key:23,new_name:t,id:e.id})}Freeze(e=0,t=0,r=!0){this.ExecCommand({key:16,rows:e,columns:t,highlight_transition:r})}SetRowHeight(e,t,r=!0){this.ExecCommand({key:3,row:e,height:t,shrink:r})}SetColumnWidth(e,t){this.ExecCommand({key:4,column:e,width:t})}FilterTable(e,t,r){let i=[];if(!e.area.start.sheet_id)throw new Error("invalid table area");let n=this.model.sheets.Find(e.area.start.sheet_id);if(!n)throw new Error("invalid table sheet");let o=[],a=[],s=e.totals_row?e.area.end.row-1:e.area.end.row;t+=e.area.start.column;for(let c=e.area.start.row+1;c<=s;c++){let d=n.CellData({row:c,column:t}),u=r(d),h=n.GetRowHeight(c);u&&!h?o.push(c):!u&&h&&a.push(c)}o&&i.push({key:3,sheet_id:n.id,row:o,height:n.default_row_height}),a&&i.push({key:3,sheet_id:n.id,row:a,height:0}),i.length&&this.ExecCommand(i)}UpdateSheets(e,t=!1,r){re.Reset();let i=e.map(n=>re.FromJSON(n,this.model.theme_style_properties));if(i.length===0&&i.push(re.Blank(this.model.theme_style_properties)),this.model.sheets.Assign(i),this.ResetMetadata(),this.active_sheet=i[0],r){let n=this.model.sheets.Find(r);n&&(this.active_sheet=n)}}SetAutocompleteFunctions(e){let t=[];for(let i of this.model.named.list)t.push({name:i.name,named:!0,type:"token"});let r=e.slice(0).concat(t);this.autocomplete_matcher.SetFunctions(r)}ResetMetadata(){this.model.document_name=void 0,this.model.user_data=void 0}ResizeColumnsInternal(e){let t=e.sheet_id?this.FindSheet(e.sheet_id):this.active_sheet,r=e.column;if(typeof r>"u"){r=[];for(let i=0;i<t.columns;i++)r.push(i)}if(typeof r=="number"&&(r=[r]),e.width)for(let i of r)t.SetColumnWidth(i,e.width);else console.error("auto size not supported")}RemoveAnnotationInternal(e){for(let t=0;t<e.sheet.annotations.length;t++)if(e.annotation===e.sheet.annotations[t]){e.sheet.annotations.splice(t,1),this.grid_events.Publish({type:"annotation",annotation:e.annotation,event:"delete"});return}}CreateAnnotationInternal(e){}ResizeRowsInternal(e){let t=e.sheet_id?this.FindSheet(e.sheet_id):this.active_sheet,r=e.row;if(typeof r>"u"){r=[];for(let i=0;i<t.rows;i++)r.push(i)}if(typeof r=="number"&&(r=[r]),e.height)for(let i of r)t.SetRowHeight(i,e.height);else console.error("auto size not supported")}ResetInternal(){re.Reset(),this.UpdateSheets([],!0),this.model.named.Reset(),this.model.macro_functions.clear(),this.model.tables.clear()}ValidatePasteAreas(e){for(let t of e){let r=this.active_sheet;if(t.start.sheet_id&&t.start.sheet_id!==r.id&&(r=this.model.sheets.Find(t.start.sheet_id)),!r)return!1;for(let i of r.cells.Iterate(t)){if(i.style?.locked)return console.info("invalid: locked cells"),!1;if(i.merge_area&&(!t.Contains(i.merge_area.start)||!t.Contains(i.merge_area.end)))return console.info("invalid: merge area"),!1;if(i.area&&(!t.Contains(i.area.start)||!t.Contains(i.area.end)))return console.info("invalid: array"),!1}}return!0}SetValidationInternal(e){let t=this.FindSheet(e.area);if(!t)throw new Error("invalid sheet in set validation");let r={start:e.area.start,end:e.area.end};e.range?t.AddValidation({type:"range",error:!!e.error,area:e.range,target:[r]}):e.list?t.AddValidation({type:"list",error:!!e.error,list:JSON.parse(JSON.stringify(e.list)),target:[r]}):t.RemoveValidations(r)}GetValidationRange(e){let t,r=this.FindSheet(e);if(r){t=[],e=r.RealArea(new v(e.start,e.end),!0);for(let i=e.start.row;i<=e.end.row;i++)for(let n=e.start.column;n<=e.end.column;n++){let o=r.CellData({row:i,column:n});o&&o.formatted&&(typeof o.formatted=="string"?t.push(o.formatted):t.push(de.FormatPartsAsText(o.formatted)))}}return t}DeleteSheetInternal(e){let t=!1,r=-1,i="",n=!1,o=e.name?e.name.toLowerCase():"",a=this.model.sheets.list.filter((s,c)=>c===e.index||s.id===e.id||s.name.toLowerCase()===o?(t=s===this.active_sheet,this.model.named.RemoveRangesForSheet(s.id),i=s.name,r=c,!1):!0);if(i&&this.RenameSheetReferences(a,i,"#REF")>0&&(n=!0),!a.length)a.push(re.Blank(this.model.theme_style_properties)),r=0;else if(a.every(s=>!s.visible))a.unshift(re.Blank(this.model.theme_style_properties)),r=0;else for(r>=a.length&&(r=0);!a[r].visible;)r++;return this.model.sheets.Assign(a),t&&this.ActivateSheetInternal({key:22,index:r}),n}RenameSheetInternal(e,t){if(!t||Ri.test(t))throw new Error("invalid sheet name");let r=t.toLowerCase();for(let n of this.model.sheets.list)if(n!==e&&n.name.toLowerCase()===r)throw new Error("sheet name already exists");let i=e.name;e.name=t,this.model.sheets.Assign(this.model.sheets.list),this.RenameSheetReferences(this.model.sheets.list,i,t)}SortTableInternal(e){if(!e.table.area.start.sheet_id)throw new Error("table has invalid area");let t=this.model.sheets.Find(e.table.area.start.sheet_id);if(!t)throw new Error("invalid sheet in table area");let r=[],i=[],n=e.table.area.end.row;e.table.totals_row&&n--;let o=0,a=0;for(let h=e.table.area.start.row+1;h<=n;h++){if(t.GetRowHeight(h))i.push(h);else continue;let m={row:h,number:0,text:"",type:0,data:[]};for(let p=e.table.area.start.column;p<=e.table.area.end.column;p++){let b=t.CellData({row:h,column:p});if(p===e.column+e.table.area.start.column){let g=b.calculated_type||b.type;g===2?o++:g===3&&a++;let x=b.calculated_type?b.calculated:b.value;m.text=x?.toString()||"",m.number=Number(x)||0,m.type=b.calculated_type||b.type}m.data.push({address:{row:h,column:p},data:b.value,type:b.type,style:b.style})}r.push(m)}let s=e.type;s==="auto"&&(a>o?s="numeric":s="text");let c=e.asc?1:-1;switch(s){case"numeric":r.sort((h,f)=>h.type===0?f.type===0?0:1:f.type===0?-1:(h.number-f.number)*c);break;case"text":default:r.sort((h,f)=>h.type===0?f.type===0?0:1:f.type===0?-1:h.text.localeCompare(f.text)*c);break}let d={row:e.table.area.start.row+1,column:e.table.area.start.column};for(let h=0;h<i.length;h++){d.row=i[h];let f=r[h];d.column=e.table.area.start.column;for(let m of f.data){if(m.type===1){let p=m.data,b={columns:0,rows:d.row-f.row},g=this.parser.Parse(p);g.expression&&(p="="+this.parser.Render(g.expression,{offset:b,missing:""})),t.SetCellValue(d,p)}else t.SetCellValue(d,m.data);t.UpdateCellStyle(d,m.style||{},!1),d.column++}}let u=this.model.tables.get(e.table.name.toLowerCase());u&&(u.sort={type:e.type,asc:!!e.asc,column:e.column});{let h=e.table.area.start.row;for(let f=e.table.area.start.column;f<=e.table.area.end.column;f++)t.cells.data[h][f]?.FlushStyle();if(e.table.totals_row){h=e.table.area.end.row;for(let f=e.table.area.start.column;f<=e.table.area.end.column;f++)t.cells.data[h][f]?.FlushStyle()}}return new v(e.table.area.start,e.table.area.end)}UpdateTableColumns(e){if(!e.area.start.sheet_id)throw new Error("invalid area in table");let t=this.model.sheets.Find(e.area.start.sheet_id);if(!t)throw new Error("invalid sheet in table");let r=e.columns?.slice(0)||void 0,i=[],n=e.area.start.row,o=e.area.end.column-e.area.start.column+1,a=e.area.start.column;for(let s=0;s<o;s++,a++){let c=t.CellData({row:n,column:a}),d="";c.type!==2?(typeof c.formatted<"u"?d=c.formatted.toString():typeof c.calculated<"u"?d=c.calculated.toString():typeof c.value<"u"&&(d=c.value.toString()),c.Set(d,2)):d=c.value||"",d||(d=`Column${s+1}`);let u=d,h=!1,f=1;for(;!h;){h=!0;e:for(let m of i)if(m.toLowerCase()===u.toLowerCase()){h=!1,u=`${d}${++f}`;break e}}c.Set(u,2),i.push(u.toLowerCase())}if(r&&r.length===i.length){let s=new Map;for(let c=0;c<r.length;c++){let d=r[c].toLowerCase();d!==i[c]&&s.set(d,i[c])}if(s.size){let c=e.name.toLowerCase();for(let d of this.model.sheets.list)for(let u of d.cells.Iterate())if(u.ValueIsFormula()){let h=!1,f=this.parser.Parse(u.value);f.expression&&(this.parser.Walk(f.expression,m=>{if(m.type==="structured-reference"&&(m.table.toLowerCase()===c||!m.table&&u.table===e))for(let[p,b]of s.entries())m.column.toLowerCase()===p&&(m.column=b,h=!0);return!0}),h&&(console.info("updating value"),u.value="="+this.parser.Render(f.expression,{missing:""})))}}}return e.columns=i,{start:{...e.area.start},end:{row:e.area.start.row,column:e.area.end.column}}}SetRangeInternal(e,t={}){let r=N(e.area)?new v(e.area):new v(e.area.start,e.area.end),i=this.FindSheet(r);if(r.start.sheet_id||(r.start.sheet_id=i.id),!r.entire_row&&!r.entire_column&&(r.end.row>=i.rows||r.end.column>=i.columns)&&(i.cells.EnsureCell(r.end),i===this.active_sheet&&(t.layout=!0)),N(e.area)){let n=i.CellData(e.area);if(n.area&&(n.area.rows>1||n.area.columns>1)){this.Error(2);return}let o=Array.isArray(e.value)?Array.isArray(e.value[0])?e.value[0][0]:e.value[0]:e.value;return e.r1c1&&(o=this.TranslateR1C1(e.area,o)),e.array?i.SetArrayValue(r,o):i.SetCellValue(e.area,o),r}else{if(e.array){let n=Array.isArray(e.value)?Array.isArray(e.value[0])?e.value[0][0]:e.value[0]:e.value;e.r1c1&&(n=this.TranslateR1C1(r.start,n)),i.SetArrayValue(r,n)}else{if(e.r1c1){if(Array.isArray(e.value))for(let n=0;n<e.value.length&&n<r.rows;n++){e.value[n]||(e.value[n]=[]);let o=e.value[n];for(let a=0;a<o.length&&a<r.columns;a++){let s={...r.start,row:r.start.row+n,column:r.start.column+a};o[a]=this.TranslateR1C1(s,o[a])}}else if(typeof e.value=="string"&&e.value[0]==="="){let n=[];for(let o=0;o<r.rows;o++){let a=[];for(let s=0;s<r.columns;s++){let c={...r.start,row:r.start.row+o,column:r.start.column+s};a.push(this.TranslateR1C1(c,e.value))}n.push(a)}e.value=n}}i.SetAreaValues2(r,e.value)}return r}}ActivateSheetInternal(e){let t=this.ResolveSheet(e)||this.model.sheets.list[0];if(this.active_sheet===t&&!e.force)return;if(!t.visible)throw new Error("cannot activate hidden sheet");let r=this.active_sheet;this.active_sheet=t,this.grid_events.Publish({type:"sheet-change",deactivate:r,activate:this.active_sheet})}ShowSheetInternal(e){let t=this.ResolveSheet(e);if(t&&t.visible!==e.show){if(!e.show){let r=0;for(let i of this.model.sheets.list)(!t.visible||i===t)&&r++;if(r>=this.model.sheets.length)throw new Error("can't hide all sheets")}if(t.visible=e.show,t===this.active_sheet){let r=this.model.sheets.list;for(let i=0;i<r.length;i++)if(r[i]===this.active_sheet){for(let n=i+1;n<r.length;n++)if(r[n].visible){this.ActivateSheetInternal({key:22,index:n});return}for(let n=0;n<r.length;n++)if(r[n].visible){this.ActivateSheetInternal({key:22,index:n});return}throw new Error("no visible sheet")}}}}NormalizeCommands(e){Array.isArray(e)||(e=[e]);let t=this.active_sheet.id;for(let r of e)switch(r.key){case 0:case 33:case 18:case 25:case 19:case 20:case 21:case 22:case 23:case 24:case 27:case 34:case 35:break;case 28:case 30:r.table.area.start.sheet_id||(r.table.area.start.sheet_id=t);break;case 31:r.format.area.start.sheet_id||(r.format.area.start.sheet_id=t);break;case 3:case 4:case 2:case 1:case 16:r.sheet_id||(r.sheet_id=t);break;case 12:case 14:case 15:case 9:case 8:case 10:case 11:case 26:case 6:case 7:case 17:case 5:case 29:case 32:r.area&&(N(r.area)?r.area.sheet_id||(r.area.sheet_id=t):r.area.start.sheet_id||(r.area.start.sheet_id=t));break;default:Qo(r)}return e}TabColor(e,t){this.ExecCommand({key:33,sheet:e,color:t})}AddSheetInternal(e=re.default_sheet_name,t=-1){if(!this.options.add_tab){console.warn("add tab option not set or false");return}for(;this.model.sheets.list.some(i=>i.name===e);){let i=e.match(/^(.*?)(\d+)$/);i?e=i[1]+(Number(i[2])+1):e=e+"2"}let r=re.Blank(this.model.theme_style_properties,e);return t>=0?this.model.sheets.Splice(t,0,r):this.model.sheets.Add(r),r.id}ResolveSheet(e){if(typeof e.index<"u")return this.model.sheets.list[e.index];if(typeof e.name<"u")return this.model.sheets.Find(e.name);if(e.id)return this.model.sheets.Find(e.id)}FindSheet(e){if(e===void 0)return this.active_sheet;let t=typeof e=="number"?e:N(e)?e.sheet_id:e.start.sheet_id;if(!t||t===this.active_sheet.id)return this.active_sheet;let r=this.model.sheets.Find(t);return r||this.active_sheet}PatchFormulasInternal(e,t,r,i,n,o,a){let s=this.parser.Parse(e||""),c=!1;if(s.expression&&(this.parser.Walk(s.expression,d=>{if(d.type==="range"||d.type==="address"){let u=[];d.type==="range"?(d.start.sheet&&d.start.sheet.toLowerCase()===o||!d.start.sheet&&a)&&u.push(d.start,d.end):d.type==="address"&&(d.sheet&&d.sheet.toLowerCase()===o||!d.sheet&&a)&&u.push(d);for(let h of u)r&&h.row>=t&&(r<0&&h.row+r<t?h.column=h.row=-1:h.row+=r,c=!0),n&&h.column>=i&&(n<0&&h.column+n<i?h.column=h.row=-1:h.column+=n,c=!0);return!1}return!0}),c))return"="+this.parser.Render(s.expression,{missing:""})}PatchExpressionSheetName(e,t,r){let i=!1,n=this.parser.Parse(e||"");if(n.expression&&(this.parser.Walk(n.expression,o=>(o.type==="address"&&o.sheet&&o.sheet.toLowerCase()===t&&(o.sheet=r,i=!0),!0)),i))return"="+this.parser.Render(n.expression,{missing:""})}RenameSheetReferences(e,t,r){let i=0;t=t.toLowerCase();for(let n of e){for(let o of n.cells.Iterate())if(o.ValueIsFormula()){let a=this.PatchExpressionSheetName(o.value||"",t,r);a&&(o.value=a,i++)}if(n.conditional_formats?.length)for(let o of n.conditional_formats)switch(o.type){case"cell-match":case"expression":{let a=this.PatchExpressionSheetName(o.expression,t,r);a&&(o.expression=a,i++)}break}for(let o of n.annotations)if(o.data.formula){let a=this.PatchExpressionSheetName(o.data.formula,t,r);a&&(o.data.formula=a,i++)}}for(let n of this.model.connected_elements.values())if(n.formula){let o=this.PatchExpressionSheetName(n.formula,t,r);o&&(n.formula=o,i++)}return i}ApplyBordersInternal(e){let t=e.borders,r=e.borders==="none"?0:e.width,i=new v(e.area.start,e.area.end),n=this.FindSheet(i);i.start.sheet_id=n.id;let o={border_top:r},a={border_bottom:r},s={border_left:r},c={border_right:r},d={border_top:0,border_top_fill:{}},u={border_bottom:0,border_bottom_fill:{}},h={border_left:0,border_left_fill:{}},f={border_right:0,border_right_fill:{}};return e.color?(o.border_top_fill={...e.color},a.border_bottom_fill={...e.color},s.border_left_fill={...e.color},c.border_right_fill={...e.color}):(o.border_top_fill={},a.border_bottom_fill={},s.border_left_fill={},c.border_right_fill={}),(t==="none"||t==="all")&&n.UpdateAreaStyle(i,{...o,...a,...s,...c},!0),(t==="top"||t==="outside")&&(i.entire_column||n.UpdateAreaStyle(i.top,{...o},!0)),(t==="none"||t==="all"||t==="outside"||t==="top")&&(i.entire_column||i.start.row&&n.UpdateAreaStyle(new v({row:i.start.row-1,column:i.start.column},{row:i.start.row-1,column:i.end.column}),{...u},!0)),(t==="bottom"||t==="outside")&&(i.entire_column||n.UpdateAreaStyle(i.bottom,{...a},!0)),(t==="none"||t==="all"||t==="outside"||t==="bottom")&&(i.entire_column||n.UpdateAreaStyle(new v({row:i.end.row+1,column:i.start.column},{row:i.end.row+1,column:i.end.column}),{...d},!0)),(t==="left"||t==="outside")&&(i.entire_row||n.UpdateAreaStyle(i.left,{...s},!0)),(t==="none"||t==="all"||t==="outside"||t==="left")&&(i.entire_row||i.start.column&&n.UpdateAreaStyle(new v({row:i.start.row,column:i.start.column-1},{row:i.end.row,column:i.start.column-1}),{...f},!0)),(t==="right"||t==="outside")&&(i.entire_row||n.UpdateAreaStyle(i.right,{...c},!0)),(t==="none"||t==="all"||t==="outside"||t==="right")&&(i.entire_row||n.UpdateAreaStyle(new v({row:i.start.row,column:i.end.column+1},{row:i.end.row,column:i.end.column+1}),{...h},!0)),v.Bleed(i)}TranslateR1C1(e,t){let r=!1,i=this.parser.flags.r1c1;if(this.parser.flags.r1c1=!0,typeof t=="string"&&t[0]==="="){let n=this.parser.Parse(t);n.expression&&(this.parser.Walk(n.expression,o=>(o.type==="address"&&o.r1c1&&(r=!0,o.offset_column?(o.absolute_column=!1,o.column=o.column+e.column):o.absolute_column=!0,o.offset_row?(o.absolute_row=!1,o.row=o.row+e.row):o.absolute_row=!0),!0)),r&&(t="="+this.parser.Render(n.expression,{missing:""})))}return this.parser.flags.r1c1=i,t}ClearAreaInternal(e){let t;if(e.start.sheet_id?t=this.model.sheets.Find(e.start.sheet_id):t=this.active_sheet,!t){console.warn("can't resolve sheet in ClearAreaInternal");return}e=t.RealArea(e);for(let i of t.cells.Iterate(e))if(i.area&&!e.ContainsArea(i.area)){this.Error(2);return}let r=this.model.tables.keys();for(let i of r){let n=this.model.tables.get(i);if(n&&n.area.start.sheet_id===t.id){let o=new v(n.area.start,n.area.end);if(e.ContainsArea(o)){for(let a=o.start.row;a<=o.end.row;a++)for(let s=o.start.column;s<=n.area.end.column;s++){let c=t.cells.GetCell({row:a,column:s},!1);c&&(c.table=void 0)}this.model.tables.delete(i)}}}t.ClearArea(e)}Error(e){this.grid_events.Publish({type:"error",code:e})}DuplicateSheetInternal(e){if(!this.options.add_tab){console.warn("add tab option not set or false");return}let t=this.ResolveSheet(e),r=this.model.sheets.list.reduce((s,c)=>Math.max(s,c.id),0)+1,i=-1;for(let s=0;s<this.model.sheets.length;s++)this.model.sheets.list[s]===t&&(i=s+1);if(!t||i<0)throw new Error("source sheet not found");if(typeof e.insert_before=="number")i=e.insert_before;else if(typeof e.insert_before=="string"){let s=e.insert_before.toLowerCase();for(let c=0;c<this.model.sheets.length;c++)if(this.model.sheets.list[c].name.toLowerCase()===s){i=c;break}}let n={rendered_values:!0},o=re.FromJSON(t.toJSON(n),this.model.theme_style_properties),a=e.new_name||t.name;for(;this.model.sheets.list.some(s=>s.name===a);){let s=a.match(/^(.*?)(\d+)$/);s?a=s[1]+(Number(s[2])+1):a=a+"2"}return o.name=a,o.id=r,this.model.sheets.Splice(i,0,o),o.id}SelectInternal(e){}FreezeInternal(e){let t=this.FindSheet(e.sheet_id||this.active_sheet.id);t.freeze.rows=e.rows,t.freeze.columns=e.columns}PatchExpression(e,t){let r=0,i=this.parser.Parse(e);if(i.expression&&(this.parser.Walk(i.expression,n=>{if(n.type==="range"){if(!n.start.sheet||n.start.sheet.toLowerCase()===t.sheet.name.toLowerCase()){let o=v.PatchArea(n,t);o?(n.start.row=o.start.row,n.start.column=o.start.column,n.end.row=o.end.row,n.end.column=o.end.column):n.start.row=n.end.row=n.start.column=n.end.column=-1}return r++,!1}else if(n.type==="address"){let o=v.PatchArea({start:n,end:n},t);return o?(n.row=o.start.row,n.column=o.start.column):n.row=n.column=-1,r++,!1}return!0}),r))return this.parser.Render(i.expression,{missing:""})}PatchConditionalsAndValidations(e){if(e.sheet.data_validation.length){let t=new Set;for(let r of e.sheet.data_validation){let i=[];for(let n of r.target){let o=v.PatchArea(n,e);o&&i.push(o)}if(i.length>0){if(r.target=i,r.type==="range"&&r.area.start.sheet_id===e.sheet.id){let n=v.PatchArea(r.area,e);n?r.area=n:t.add(r)}}else t.add(r)}t.size&&(e.sheet.data_validation=e.sheet.data_validation.filter(r=>!t.has(r)))}if(e.sheet.conditional_formats?.length){let t=new Set;for(let r of e.sheet.conditional_formats){let i=v.PatchArea(r.area,e);if(i)r.area=JSON.parse(JSON.stringify(i));else{t.add(r);continue}switch(r.type){case"expression":case"cell-match":{let n=this.PatchExpression(r.expression,e);n&&(r.expression=n)}break}}t.size&&(e.sheet.conditional_formats=e.sheet.conditional_formats.filter(r=>!t.has(r)))}}InsertRowsInternal(e){let t=this.FindSheet(e.sheet_id);if(e.count===1/0?e.count=1:e.count===-1/0&&(e.count=-t.rows),!t.InsertRows(e.before_row,e.count))return this.Error(2),{error:!0};this.PatchConditionalsAndValidations({sheet:t,before_column:0,column_count:0,before_row:e.before_row,row_count:e.count});for(let s of this.model.connected_elements.values())if(s.formula){let c=this.PatchFormulasInternal(s.formula,e.before_row,e.count,0,0,t.name.toLowerCase(),!1);c&&(s.formula=c)}let r=Array.from(this.model.tables.values());for(let s of r)if(s.area.start.sheet_id===e.sheet_id)if(e.count>0){if(e.before_row<=s.area.start.row)s.area.start.row+=e.count,s.area.end.row+=e.count;else if(e.before_row<=s.area.end.row){s.area.end.row+=e.count;for(let c=s.area.start.row;c<=s.area.end.row;c++)for(let d=s.area.start.column;d<=s.area.end.column;d++){let u=t.CellData({row:c,column:d});u.table=s}}}else if(e.before_row<=s.area.start.row)if(e.before_row-e.count<=s.area.start.row)s.area.start.row+=e.count,s.area.end.row+=e.count;else if(e.before_row-e.count>=s.area.end.row)this.model.tables.delete(s.name.toLowerCase());else{this.model.tables.delete(s.name.toLowerCase());for(let c=e.before_row;c<=s.area.end.row;c++)for(let d=s.area.start.column;d<=s.area.end.column;d++){let u=t.CellData({row:c,column:d});u.table===s&&(u.table=void 0)}}else e.before_row<=s.area.end.row&&(e.before_row-e.count>s.area.end.row&&(s.totals_row=!1),s.area.end.row=Math.max(0,s.area.end.row+e.count,e.before_row-1));this.model.named.PatchNamedRanges(t.id,0,0,e.before_row,e.count);let i=t.name.toLowerCase();for(let s of this.model.sheets.list){let c=s===t;for(let d of s.cells.Iterate())if(d.ValueIsFormula()){let u=this.PatchFormulasInternal(d.value||"",e.before_row,e.count,0,0,i,c);u&&(d.value=u)}for(let d of s.annotations)if(d.data.formula){let u=this.PatchFormulasInternal(d.data.formula||"",e.before_row,e.count,0,0,i,c);u&&(d.data.formula=u)}}let n=[],o=[],a=[];if(e.count>0){let s=e.before_row;for(let c of t.annotations)if(c.data.layout){let[d,u,h]=[c.data.layout.tl.address.row,c.data.layout.br.address.row,c.data.layout.br.offset.y];if(s<=d)c.data.layout.tl.address.row+=e.count,c.data.layout.br.address.row+=e.count;else if(s<u||s===u&&h>0)c.data.layout.br.address.row+=e.count,o.push(c);else continue;n.push(c)}}else if(e.count<0){let s=e.before_row,c=e.before_row-e.count-1;for(let d of t.annotations)if(d.data.layout){let[u,h,f]=[d.data.layout.tl.address.row,d.data.layout.br.address.row,d.data.layout.br.offset.y];if(s<=u)if(c<u)d.data.layout.tl.address.row+=e.count,d.data.layout.br.address.row+=e.count;else if(c<h-1||c===h-1&&f>0)d.data.layout.tl.address.row=s,d.data.layout.tl.offset.y=0,d.data.layout.br.address.row+=e.count,o.push(d);else{a.push(d);continue}else if(s<h||s===h&&f>0)c<h-1||c===h-1&&f>0?(d.data.layout.br.address.row+=e.count,o.push(d)):(d.data.layout.br.address.row=s,d.data.layout.br.offset.y=0,o.push(d));else continue;n.push(d)}}for(let s of a)t.annotations=t.annotations.filter(c=>c!==s);return{update_annotations_list:n,resize_annotations_list:o,delete_annotations_list:a}}InsertColumnsInternal(e){let t=this.FindSheet(e.sheet_id);if(e.count===1/0?e.count=1:e.count===-1/0&&(e.count=-t.columns),!t.InsertColumns(e.before_column,e.count))return this.Error(2),{error:!0};this.PatchConditionalsAndValidations({sheet:t,before_column:e.before_column,column_count:e.count,before_row:0,row_count:0});for(let s of this.model.connected_elements.values())if(s.formula){let c=this.PatchFormulasInternal(s.formula,0,0,e.before_column,e.count,t.name.toLowerCase(),!1);c&&(s.formula=c)}let r=Array.from(this.model.tables.values());for(let s of r)if(s.area.start.sheet_id===e.sheet_id)if(e.count>0){if(e.before_column<=s.area.start.column)s.area.start.column+=e.count,s.area.end.column+=e.count;else if(e.before_column<=s.area.end.column){s.area.end.column+=e.count;for(let c=s.area.start.row;c<=s.area.end.row;c++)for(let d=s.area.start.column;d<=s.area.end.column;d++){let u=t.CellData({row:c,column:d});u.table=s}this.UpdateTableColumns(s)}}else e.before_column<=s.area.start.column?e.before_column-e.count<=s.area.start.column?(s.area.start.column+=e.count,s.area.end.column+=e.count):e.before_column-e.count>=s.area.end.column?this.model.tables.delete(s.name.toLowerCase()):(s.area.start.column=e.before_column,s.area.end.column+=e.count,this.UpdateTableColumns(s)):e.before_column<=s.area.end.column&&(s.area.end.column=Math.max(0,s.area.end.column+e.count,e.before_column-1),this.UpdateTableColumns(s));this.model.named.PatchNamedRanges(t.id,e.before_column,e.count,0,0);let i=t.name.toLowerCase();for(let s of this.model.sheets.list){let c=s===t;for(let d of s.cells.Iterate())if(d.ValueIsFormula()){let u=this.PatchFormulasInternal(d.value||"",0,0,e.before_column,e.count,i,c);u&&(d.value=u)}for(let d of s.annotations)if(d.data.formula){let u=this.PatchFormulasInternal(d.data.formula,0,0,e.before_column,e.count,i,c);u&&(d.data.formula=u)}}let n=[],o=[],a=[];if(e.count>0){let s=e.before_column;for(let c of t.annotations)if(c.data.layout){let[d,u,h]=[c.data.layout.tl.address.column,c.data.layout.br.address.column,c.data.layout.br.offset.x];if(s<=d)c.data.layout.tl.address.column+=e.count,c.data.layout.br.address.column+=e.count;else if(s<u||s===u&&h>0)c.data.layout.br.address.column+=e.count,o.push(c);else continue;n.push(c)}}else if(e.count<0){let s=e.before_column,c=e.before_column-e.count-1;for(let d of t.annotations)if(d.data.layout){let[u,h,f]=[d.data.layout.tl.address.column,d.data.layout.br.address.column,d.data.layout.br.offset.x];if(s<=u)if(c<u)d.data.layout.tl.address.column+=e.count,d.data.layout.br.address.column+=e.count;else if(c<h-1||c===h-1&&f>0)d.data.layout.tl.address.column=s,d.data.layout.tl.offset.x=0,d.data.layout.br.address.column+=e.count,o.push(d);else{a.push(d);continue}else if(s<h||s===h&&f>0)c<h-1||c===h-1&&f>0?(d.data.layout.br.address.column+=e.count,o.push(d)):(d.data.layout.br.address.column=s,d.data.layout.br.offset.x=0,o.push(d));else continue;n.push(d)}}for(let s of a)t.annotations=t.annotations.filter(c=>c!==s);return{update_annotations_list:n,resize_annotations_list:o,delete_annotations_list:a}}ExecCommand(e,t=!0){let r={pending:[]},i=[];e=this.NormalizeCommands(e),t&&this.command_log.Publish({command:e,timestamp:new Date().getTime()});for(let a of e)switch(a.key){case 27:this.ResetInternal();break;case 12:if(a.area){let s=new v(a.area.start,a.area.end);this.ClearAreaInternal(s),r.data_area=v.Join(s,r.data_area),r.formula=!0}break;case 5:this.SelectInternal(a);break;case 16:this.FreezeInternal(a),r.structure_event=!0;break;case 31:{let s=this.FindSheet(a.format.area);s.conditional_formats.push(a.format),s.Invalidate(new v(a.format.area.start,a.format.area.end)),s===this.active_sheet&&(r.render_area=v.Join(a.format.area,r.render_area)),r.structure_event=!0,r.conditional_formatting_event=!0}break;case 32:{let s,c=0;if(a.format){let d=JSON.stringify(a.format);s=this.FindSheet(a.format.area),s.conditional_formats=s.conditional_formats.filter(u=>JSON.stringify(u)===d?(c++,r.render_area=v.Join(u.area,r.render_area),!1):!0)}else if(a.area){let d=new v(a.area.start,a.area.end);s=this.FindSheet(a.area),s.conditional_formats=s.conditional_formats.filter(u=>{let h=new v(u.area.start,u.area.end);return h.Intersects(d)?(c++,r.render_area=v.Join(h,r.render_area),!1):!0})}s&&c&&(s.FlushConditionalFormats(),r.structure_event=!0,r.conditional_formatting_event=!0)}break;case 29:{let s=this.FindSheet(a.area),c=new v(a.area.start,a.area.end),d=!0;e:for(let u=c.start.row;u<=c.end.row;u++)for(let h=c.start.column;h<=c.end.column;h++){let f=s.cells.GetCell({row:u,column:h},!1);if(f&&(f.area||f.merge_area||f.table)){d=!1;break e}}if(d){let u=this.model.tables.size+1,h="";for(;h=`Table${u++}`,!!this.model.tables.has(h.toLowerCase()););let f={area:a.area,name:h,sortable:a.sortable,theme:a.theme};a.totals&&(f.totals_row=!0),this.model.tables.set(h.toLowerCase(),f);for(let m=c.start.row;m<=c.end.row;m++)for(let p=c.start.column;p<=c.end.column;p++){let b=s.cells.GetCell({row:m,column:p},!0);b.table=f}this.UpdateTableColumns(f),s.Invalidate(new v(f.area.start,f.area.end)),s===this.active_sheet?(r.style_area=v.Join(c,r.style_area),r.render_area=v.Join(c,r.render_area)):r.style_event=!0}}break;case 30:{let s=this.FindSheet(a.table.area),c=new v(a.table.area.start,a.table.area.end);for(let u=c.start.row;u<=c.end.row;u++)for(let h=c.start.column;h<=c.end.column;h++){let f=s.cells.GetCell({row:u,column:h},!1);f&&(f.table=void 0)}this.model.tables.delete(a.table.name.toLowerCase());let d=s.RealArea(c.Clone().Shift(-1,-1).Resize(c.rows+2,c.columns+2));s.Invalidate(d),s===this.active_sheet?(r.style_area=v.Join(c,r.style_area),r.render_area=v.Join(c,r.render_area)):r.style_event=!0}break;case 10:{let s=this.FindSheet(a.area);s.MergeCells(new v(a.area.start,a.area.end)),r.structure_event=!0,r.structure_rebuild_required=!0,s===this.active_sheet?(r.data_area=v.Join(a.area,r.data_area),r.render_area=v.Join(a.area,r.render_area)):(r.data_event=!0,r.pending||(r.pending=[]),r.pending.push(s.id))}break;case 11:{let s=this.FindSheet(a.area),c={},d=new v(a.area.start,a.area.end);for(let h of s.cells.Iterate(d,!1))if(h.merge_area){let f=v.CellAddressToLabel(h.merge_area.start)+":"+v.CellAddressToLabel(h.merge_area.end);c[f]=h.merge_area}let u=Object.keys(c);for(let h=0;h<u.length;h++)s.UnmergeCells(c[u[h]]);s===this.active_sheet?(r.render_area=v.Join(a.area,r.render_area),r.data_area=v.Join(a.area,r.data_area)):(r.data_event=!0,r.pending||(r.pending=[]),r.pending.push(s.id)),r.structure_event=!0,r.structure_rebuild_required=!0}break;case 9:{let s,c=this.FindSheet(a.area);if(N(a.area)){s=new v(a.area);let d=c.GetCellStyle(a.area,!0);c.UpdateCellStyle(a.area,{indent:Math.max(0,(d.indent||0)+a.delta)},!0)}else{s=new v(a.area.start,a.area.end);for(let d of s){let u=c.GetCellStyle(d,!0);c.UpdateCellStyle(d,{indent:Math.max(0,(u.indent||0)+a.delta)},!0)}}c===this.active_sheet?(r.style_area=v.Join(s,r.style_area),r.render_area=v.Join(s,r.render_area)):r.style_event=!0}break;case 7:{let s,c=this.FindSheet(a.area);N(a.area)?(s=new v(a.area),c.UpdateCellStyle(a.area,a.style,!!a.delta)):(s=new v(a.area.start,a.area.end),c.UpdateAreaStyle(s,a.style,!!a.delta)),c===this.active_sheet?(r.style_area=v.Join(s,r.style_area),(!a.delta||a.style.fill||a.style.border_top||a.style.border_left||a.style.border_right||a.style.border_bottom)&&(s=v.Bleed(s),this.active_sheet.Invalidate(s)),r.render_area=v.Join(s,r.render_area)):r.style_event=!0}break;case 26:this.SetValidationInternal(a),(!a.area.start.sheet_id||a.area.start.sheet_id===this.active_sheet.id)&&(r.render_area=v.Join(new v(a.area.start,a.area.end),r.render_area));break;case 17:{let s={type:"token",named:!0,name:a.name,scope:a.scope};a.area||a.expression?(a.area?this.model.named.SetNamedRange(a.name,new v(a.area.start,a.area.end),a.scope):a.expression&&this.model.named.SetNamedExpression(a.name,a.expression,a.scope),this.autocomplete_matcher.AddFunctions(s)):(this.model.named.ClearName(a.name,a.scope),this.autocomplete_matcher.RemoveFunctions(s)),r.structure_event=!0,r.structure_rebuild_required=!0}break;case 8:{let s=this.ApplyBordersInternal(a);s.start.sheet_id===this.active_sheet.id?(r.render_area=v.Join(s,r.render_area),r.style_area=v.Join(s,r.style_area)):r.style_event=!0}break;case 25:this.ShowSheetInternal(a),r.sheets=!0,r.structure_event=!0;break;case 33:a.sheet.tab_color=a.color,r.sheets=!0,r.structure_event=!0;break;case 24:{let s=[],c=this.model.sheets.list[a.index];for(let d=0;d<this.model.sheets.length;d++)d!==a.index&&(d===a.move_before&&s.push(c),s.push(this.model.sheets.list[d]));a.move_before>=this.model.sheets.length&&s.push(c),this.model.sheets.Assign(s),r.sheets=!0,r.structure_event=!0}break;case 23:{let s=this.ResolveSheet(a);s&&(this.RenameSheetInternal(s,a.new_name),r.sheets=!0,r.structure_event=!0)}break;case 35:this.RemoveAnnotationInternal(a),r.structure_event=!0,r.structure_rebuild_required=!0,r.annotation_event=!0;break;case 34:this.CreateAnnotationInternal(a),r.structure_event=!0,r.structure_rebuild_required=!0,r.annotation_event=!0;break;case 3:{let s=this.ResizeRowsInternal(a);if(s)if(s.start.sheet_id===this.active_sheet.id){let c=this.active_sheet.RealArea(new v(s.start,s.end));r.render_area=v.Join(c,r.render_area),r.data_area=v.Join(c,r.data_area),r.data_event=!0}else r.data_event=!0,r.pending||(r.pending=[]),s.start.sheet_id&&r.pending.push(s.start.sheet_id);r.structure_event=!0}break;case 4:this.ResizeColumnsInternal(a),r.structure_event=!0;break;case 18:this.active_sheet.SetHeaderSize(a.show?void 0:1,a.show?void 0:1),this.flags.layout=!0,this.flags.repaint=!0;break;case 1:this.InsertRowsInternal(a),r.structure_event=!0,r.structure_rebuild_required=!0;break;case 2:this.InsertColumnsInternal(a),r.structure_event=!0,r.structure_rebuild_required=!0;break;case 15:case 14:{let s=this.FindSheet(a.area),c=s.cells.GetCell(a.area,!0);if(c){let d;c.merge_area?(d=new v(c.merge_area.start),c=s.cells.GetCell(c.merge_area.start,!0)):d=new v(a.area),a.key===14?c.SetNote(a.note):(c.hyperlink=a.reference||void 0,c.render_clean=[]),s===this.active_sheet?(r.style_area=v.Join(d,r.style_area),r.render_area=v.Join(d,r.render_area)):r.style_event=!0}}break;case 28:{let s=this.SortTableInternal(a);s&&s.start.sheet_id===this.active_sheet.id?(r.data_area=v.Join(s,r.data_area),this.options.repaint_on_cell_change&&(r.render_area=v.Join(s,r.render_area))):r.data_event=!0}break;case 6:{let s=this.SetRangeInternal(a,r);if(s){let d=this.model.sheets.Find(s.start.sheet_id||this.active_sheet.id)?.TablesFromArea(s,!0)||[];for(let u of d)this.UpdateTableColumns(u)}s&&s.start.sheet_id===this.active_sheet.id?(r.data_area=v.Join(s,r.data_area),this.options.repaint_on_cell_change&&(r.render_area=v.Join(s,r.render_area))):r.data_event=!0}break;case 21:this.DeleteSheetInternal(a),r.sheets=!0,r.structure_event=!0,r.structure_rebuild_required=!0;break;case 20:this.DuplicateSheetInternal(a),r.sheets=!0,r.structure_event=!0,r.structure_rebuild_required=!0;break;case 19:{let s=this.AddSheetInternal(a.name,a.insert_index);typeof s=="number"&&a.show&&this.ActivateSheetInternal({key:22,id:s}),r.structure_event=!0,r.sheets=!0,r.structure=!0}break;case 22:this.ActivateSheetInternal(a);break;default:console.warn(`unhandled command: ${pt[a.key]} (${a.key})`)}let n,o;return r.data_area?(r.data_area.start.sheet_id||r.data_area.SetSheetID(this.active_sheet.id),n={type:"data",area:r.data_area}):r.data_event&&(n={type:"data"}),r.style_area?(r.style_area.start.sheet_id||r.style_area.SetSheetID(this.active_sheet.id),o={type:"style",area:r.style_area}):r.style_event&&(o={type:"style"}),n&&o?i.push({type:"composite",data_area:n.area,style_area:o.area}):(n&&i.push(n),o&&i.push(o)),r.structure_event&&i.push({type:"structure",rebuild_required:r.structure_rebuild_required,conditional_format:r.conditional_formatting_event,update_annotations:r.annotation_event}),this.batch>0?this.batch_events.push(...i):this.grid_events.Publish(i),r}};var $t=class extends Fe{get active(){return this.nodes.length>0}Reset(){this.AttachNodes()}AttachNodes(e=[],t=!0){this.assume_formula=t;let r=[];r=e.map(i=>{for(let n of this.nodes)if(n.node===i)return n;return{node:i}});for(let i of this.nodes)if(i.listeners){for(let[n,o]of i.listeners.entries())i.node.removeEventListener(n,o);i.listeners.clear()}this.nodes=r;for(let i of this.nodes){if(i.formatted_text===i.node.textContent){let n=i.node.innerHTML.length;i.check!==n&&(i.formatted_text=void 0)}i.node.ownerDocument.activeElement===i.node&&(this.active_editor=i),this.UpdateText(i,{toll_events:!0}),this.RegisterListener(i,"focusin",()=>{this.active_editor=i}),this.RegisterListener(i,"focusout",()=>{this.active_editor=void 0}),this.RegisterListener(i,"input",n=>{n.isTrusted&&(this.UpdateText(i),this.UpdateColors())})}this.UpdateColors(!0)}};var gt=class extends bt{hide_selection=!1;headless=!1;edit_state={};get scale(){return this.layout.scale}set scale(e){this.layout.scale=e,this.UpdateLayout(),this.UpdateAnnotationLayout(),this.layout.UpdateAnnotation(this.active_sheet.annotations,this.theme),this.layout.ApplyTheme(this.theme),this.overlay_editor?.UpdateScale(e),this.tab_bar?.UpdateScale(e),this.grid_events.Publish({type:"scale",scale:e});for(let t of this.model.sheets.list)for(let r of t.annotations)r.dirty=!0}theme;selected_annotation;hover_data={};editing_state=0;editing_cell={row:-1,column:-1,sheet_id:0};editing_selection;editing_annotation;pending_reset_selection=!1;view_node;container;layout;tile_update_pending=!1;scroll_offset_pending;pending_layout_update=new Set;decimal_separator_code=46;overlay_editor;autocomplete;formula_bar;RESIZE_PIXEL_BUFFER=5;external_editor_config;external_editor;cell_resize={row:-1,column:-1};render_tiles=new v({row:0,column:0});primary_selection={target:{row:0,column:0},area:new v({row:0,column:0}),empty:!0};spill_selection={target:{row:0,column:0},area:new v({row:0,column:0}),empty:!0};active_selection={target:{row:0,column:0},area:new v({row:0,column:0}),empty:!0};nub_select_flag=!1;additional_selections=[];double_click_data={};layout_token=0;render_token=0;tile_renderer;selection_renderer;tab_bar;DOM=O.GetInstance();constructor(e={},t,r=jt,i=!0,n){if(super(e,t),this.decimal_separator_code=F.decimal_separator.charCodeAt(0),this.theme=JSON.parse(JSON.stringify(r)),!i){this.headless=!0,this.layout=new Nt(this.model,this.view);return}this.DOM=n,this.layout=new Pt(this.model,this.view,n),e.initial_scale&&(typeof e.initial_scale=="string"&&(e.initial_scale=Number(e.initial_scale)),this.layout.scale=e.initial_scale),this.tile_renderer=new Ht(this.theme,this.layout,this.model,this.view,this.options),this.selection_renderer=new Lt(this.theme,this.layout,this.model,this.view,this.primary_selection,this.additional_selections)}CopyArea(e,t="copy"){let r=(e.start.sheet_id?this.model.sheets.Find(e.start.sheet_id):this.active_sheet)||this.active_sheet,i=r.GetCellStyle(e,!1),n=t!=="cut",o=[];for(let{cell:a,row:s,column:c}of r.cells.IterateRC(e)){let d=a.value;n&&d&&a.type===1&&(d=this.FormatR1C1(d,{row:s,column:c})[0][0]);let u=s-e.start.row,h=c-e.start.column;o[u]||(o[u]=[]);let f;a.area&&(f={start:{row:a.area.start.row-e.start.row,column:a.area.start.column-e.start.column},end:{row:a.area.end.row-e.start.row,column:a.area.end.column-e.start.column}}),o[u][h]={value:d,calculated:a.calculated,style:i[u][h],area:f}}return t==="cut"&&this.SetRange(e,void 0,{recycle:!0}),o}PasteArea(e,t,r={}){if(!t)throw new Error("no clipboad data");let i=t.length,n=t[0]?.length||0;e.Resize(Math.max(1,Math.floor(e.rows/i))*i,Math.max(1,Math.floor(e.columns/n))*n);let o=(e.start.sheet_id?this.model.sheets.Find(e.start.sheet_id):this.active_sheet)||this.active_sheet,a=[];if(r.values)for(let[d,u]of t.entries()){a[d]=[];for(let h of u)a[d].push(typeof h.calculated>"u"?h.value:h.calculated)}let s=t,c=this.Batch(()=>{if(r.values)this.SetRange(e,a,{r1c1:!0,recycle:!0});else{this.SetRange(e,void 0,{recycle:!0});for(let d of e){let u=(d.row-e.start.row)%i,h=(d.column-e.start.column)%n,f=s[u][h];if(f.area){if(f.area.start.row===u&&f.area.start.column===h){let m=new v(f.area.start,f.area.end);m.Shift(e.start.row,e.start.column),this.SetRange(m,f.value,{r1c1:!0,array:!0})}}else f.value&&this.SetRange(new v(d),f.value,{r1c1:!0})}}if(r.formatting==="number-formats")for(let d of e){let u=(d.row-e.start.row)%i,h=(d.column-e.start.column)%n,f=(s[u][h].style||{}).number_format;o.UpdateCellStyle(d,{number_format:f},!0)}else if(r.formatting!=="target")for(let d of e){let u=(d.row-e.start.row)%i,h=(d.column-e.start.column)%n;o.UpdateCellStyle(d,s[u][h].style||{},!1)}},!0);this.grid_events.Publish(c)}Reselect(){this.primary_selection.empty||this.Select(this.primary_selection,this.primary_selection.area,this.primary_selection.target)}SetNote(e,t){if(!e){if(this.primary_selection.empty)return;e=this.primary_selection.target}this.ExecCommand({key:14,area:e,note:t})}FindAnnotation(e){for(let t of this.active_sheet.annotations)if((t.view[this.view_index]||{}).node===e)return t}CreateAnnotation(e={},t=this.active_sheet,r=!0,i=!1,n,o){this.ExecCommand({key:34,properties:e,add_to_sheet:r,offset:i,target:n,focus:o,sheet:t})}CreateAnnotationInternal(e){let t=new Ne(e.properties);if(e.offset)if(!t.data.layout&&t.scaled_rect&&(t.data.layout=this.layout.RectToAnnotationLayout(t.scaled_rect)),!t.data.layout)console.warn("can't offset annotation without layout");else{let r=this.layout.AnnotationLayoutToRect(t.data.layout).Shift(20,20),i=!0;for(;i;){i=!1;for(let n of e.sheet.annotations)if(n!==t&&n.scaled_rect&&n.scaled_rect.top===r.top&&n.scaled_rect.left===r.left){r=r.Shift(20,20),i=!0;break}}t.data.layout=this.layout.RectToAnnotationLayout(r)}if(e.target&&(B.IsRectangle(e.target)?(t.data.layout=void 0,t.rect=B.Create(e.target)):e.target.start&&(t.rect=void 0,t.data.layout=this.layout.AddressToAnnotationLayout(e.target.start,e.target.end||e.target.start))),e.add_to_sheet&&(e.sheet.annotations.some(r=>r===t)||e.sheet.annotations.push(t),this.AddAnnotation(t)),e.focus){let r=t.view[this.view_index];if(r&&r.node){let i=r.node;setTimeout(()=>{i.focus()},1)}}}UpdateAnnotationLayout(){}AddAnnotation(e,t=!1,r=!0){let i=e.view[this.view_index];if(i||(i={},e.view[this.view_index]=i),!i.node){let n=this.DOM.Div("annotation",void 0,{data:{scale:this.layout.scale.toString()},style:{fontSize:`${10*this.layout.scale}pt`},attrs:{tabindex:"-1"},events:{mousedown:s=>{s.button===0&&this.layout.AnnotationMouseDown(e,n,s,o,a).then(c=>{c?this.grid_events.Publish(c):this.selected_annotation!==e&&this.grid_events.Publish({type:"annotation",annotation:e,event:"select"}),e.data.layout&&this.EnsureAddress(e.data.layout.br.address,1)})},focusin:()=>{for(let s of this.layout.GetFrozenAnnotations(e))s.classList.add("clone-focus");this.selected_annotation=e,this.primary_selection.empty=!0,this.primary_selection.target={row:-1,column:-1,sheet_id:this.active_sheet.id},this.HideGridSelection()},focusout:s=>{for(let c of this.layout.GetFrozenAnnotations(e))c.classList.remove("clone-focus");this.formula_bar&&this.formula_bar.IsElement(s.relatedTarget)?(this.primary_selection.empty=!0,this.RenderSelections(),this.editing_annotation=e,this.layout.ShowSelections(!0)):this.formula_bar?.IsExpandButton(s.relatedTarget)||this.layout.FocusInLayout(s.relatedTarget||void 0)&&(this.selected_annotation===e&&(this.selected_annotation=void 0),this.ShowGridSelection())}}});i.node=n,i.content_node=this.DOM.Div("annotation-content",n);let o=this.DOM.Div("annotation-move-target",n),a=this.DOM.Div("annotation-resize-target",n);n.addEventListener("keydown",s=>{let c=e.scaled_rect;if(!c){console.info("missing scaled rect!");return}let d=[n,...this.layout.GetFrozenAnnotations(e)];if(s.ctrlKey||j.is_mac&&s.metaKey){let h=e.data.style?{...e.data.style}:{},f=!0;switch(s.key){case"b":this.ApplyAnnotationStyle({bold:!h.bold});break;case"i":this.ApplyAnnotationStyle({italic:!h.italic});break;case"u":this.ApplyAnnotationStyle({underline:!h.underline});break;default:f=!1}if(f){s.stopPropagation(),s.preventDefault();return}}let u={x:c.left,y:c.top};switch(s.key){case"ArrowUp":case"Up":s.ctrlKey?(this.layout.AnnotationLayoutOrder(e,1)&&this.grid_events.Publish({type:"annotation",event:"move",annotation:e}),n.focus()):u.y--;break;case"ArrowLeft":case"Left":if(s.ctrlKey)return;u.x--;break;case"ArrowRight":case"Right":if(s.ctrlKey)return;u.x++;break;case"ArrowDown":case"Down":s.ctrlKey?(this.layout.AnnotationLayoutOrder(e,-1)&&this.grid_events.Publish({type:"annotation",event:"move",annotation:e}),n.focus()):u.y++;break;case"Escape":case"Esc":this.Focus();break;case"Backspace":s.metaKey&&j.is_mac&&(this.Focus(),this.RemoveAnnotation(e));break;case"Delete":case"Del":this.Focus(),this.RemoveAnnotation(e);break;default:return}if(s.stopPropagation(),s.preventDefault(),u.x=Math.max(u.x,0),u.y=Math.max(u.y,0),c.left!==u.x||c.top!==u.y){c.left=Math.round(u.x),c.top=Math.round(u.y);for(let h of d)h.style.top=c.top+"px",h.style.left=c.left+"px";e.data.extent=void 0,this.grid_events.Publish({type:"annotation",event:"move",annotation:e}),e.data.layout=this.layout.RectToAnnotationLayout(c)}})}r&&(this.layout.AddAnnotation(e,this.theme),e.data.layout&&this.EnsureAddress(e.data.layout.br.address,1,t)),t||this.grid_events.Publish({type:"annotation",annotation:e,event:"create"})}AnnotationUpdated(e){this.layout.CloneFrozenAnnotation(e)}RemoveAnnotation(e,t=this.active_sheet){this.ExecCommand({key:35,annotation:e,sheet:t})}RemoveAnnotationInternal(e){super.RemoveAnnotationInternal(e),this.layout.RemoveAnnotation(e.annotation)}RemoveAnnotationNodes(){this.headless||this.layout.RemoveAnnotationNodes()}ShowHeaders(e=!0){this.ExecCommand({key:18,show:e})}FromImportData(e,t=!1){this.RemoveAnnotationNodes();let r=e.sheets,i=r.map(()=>re.Blank(this.model.theme_style_properties).toJSON()),n;if(typeof e.active_tab=="number")n=i[e.active_tab]?.id;else for(let a=0;a<e.sheets.length;a++)if(!e.sheets[a].hidden){n=i[a].id;break}this.UpdateSheets(i,!0,n);let o={};this.model.macro_functions.clear(),this.ClearSelection(this.primary_selection),this.model.tables.clear();for(let a=0;a<r.length;a++){let s=this.model.sheets.list[a];s.ImportData(r[a]),o[s.name]=s.id;for(let c of r[a].cells)c.table&&(c.table.area.start.sheet_id=s.id,this.model.tables.set(c.table.name.toLowerCase(),c.table));for(let c of this.model.tables.values())this.UpdateTableColumns(c)}this.model.sheets.UpdateIndexes(),this.model.named.Reset(),e.named&&this.model.UnserializeNames(e.named,this.active_sheet,!0);for(let a of this.active_sheet.annotations)this.AddAnnotation(a,!0);this.ActivateSheetTasks(),this.QueueLayoutUpdate(),this.StyleDefaultFromTheme(),t&&this.Repaint(!1,!1),this.tab_bar&&this.tab_bar.Update(!1)}NextSheet(e=1,t=!1){if(this.model.sheets.length===1)return;let r=this.model.sheets.list.map((i,n)=>({sheet:i,index:n})).filter(i=>i.sheet.visible);if(r.length!==1){for(let i=0;i<r.length;i++)if(r[i].sheet===this.active_sheet){let n=(i+e)%r.length;for(;n<0;)n+=r.length;this.ActivateSheet(r[n].index,t);return}}}UpdateSheets(e,t=!1,r){if(super.UpdateSheets(e,t,r),this.RemoveAnnotationNodes(),this.ClearSelection(this.primary_selection),e[0]&&e[0].primary_selection){let i=e[0].primary_selection;i.empty||this.Select(this.primary_selection,new v(i.area.start,i.area.end),i.target)}else if(!this.active_sheet.selection.empty){let i=this.active_sheet.selection;this.Select(this.primary_selection,new v(i.area.start,i.area.end),i.target)}this.layout.ClearLayoutCaches();for(let i of this.model.sheets.list)for(let n of i.annotations)this.AddAnnotation(n,!0,i===this.active_sheet);this.ActivateSheetTasks(),this.QueueLayoutUpdate(JSON.parse(JSON.stringify(this.active_sheet.scroll_offset))),this.StyleDefaultFromTheme(),t&&this.Repaint(!1,!1),this.tab_bar&&this.tab_bar.Update(!1)}UpdateLayout(){this.layout.UpdateTiles(),this.layout.UpdateContentsSize(),this.render_tiles=this.layout.VisibleTiles(),this.Repaint(!0)}UpdateTabBar(){this.tab_bar&&this.tab_bar.Update(!0)}UpdateTheme(e=!1,t){if(!e)for(let i of Object.keys(this.theme))delete this.theme[i];let r=JSON.parse(JSON.stringify(jt));this.view_node&&(r={...Ji(this.view_node,this.options.support_font_stacks)}),r={...this.theme,...r,...t},Object.assign(this.theme,r),this.StyleDefaultFromTheme(),this.active_sheet.UpdateDefaultRowHeight(this.theme),this.active_sheet.FlushCellStyles(),this.layout.ApplyTheme(this.theme),this.tab_bar&&this.tab_bar.UpdateTheme(),e||(this.UpdateLayout(),this.overlay_editor?.UpdateScale(this.layout.scale),this.Repaint(!0,!0,!0))}SetScale(e){e=Math.round(e*1e3)/1e3,e=Math.min(2,Math.max(e,.5)),this.options.persist_scale_key&&localStorage.setItem(this.options.persist_scale_key,JSON.stringify({scale:e})),this.scale=e}Initialize(e,t=!1){if(!this.tile_renderer||!this.selection_renderer)return;this.view_node=e,this.UpdateTheme(!0);let i=e.querySelector(".treb-spreadsheet-body").querySelector("div");this.options.formula_bar&&(this.autocomplete||(this.autocomplete=new mt({theme:this.theme,container:i})),this.InitFormulaBar(e,this.autocomplete)),this.options.tab_bar&&(this.tab_bar=new Ft(this.layout,this.model,this.view,this.options,this.theme,e),this.tab_bar.Subscribe(n=>{switch(n.type){case"cancel":break;case"scale":{let o=this.layout.scale;if(o=Math.round(n.value*1e3)/1e3,o=Math.min(2,Math.max(o,.5)),this.options.persist_scale_key&&localStorage.setItem(this.options.persist_scale_key,JSON.stringify({scale:o})),this.scale=o,n.keep_focus)return}break;case"reorder-sheet":this.ReorderSheet(n.index,n.move_before);break;case"delete-sheet":this.DeleteSheet();break;case"add-sheet":this.AddSheet();break;case"rename-sheet":this.RenameSheet(n.sheet,n.name);break;case"activate-sheet":this.ActivateSheetID(n.sheet.id);break}this.SelectingArgument()||this.Focus()})),this.container=i,this.container.classList.add("treb-grid"),j.is_mac&&j.is_safari&&this.container.classList.add("safari"),this.container.setAttribute("tabindex","-1"),this.layout.Initialize(i,{scroll:()=>this.OnScroll(),dropdown:n=>this.OnDropdownSelect(n),sort:(n,o,a)=>{let s=this.model.tables.get(n.toLowerCase());s&&this.SortTable(s,{column:o,asc:a})},focus:()=>this.Focus()},this.options.scrollbars),this.selection_renderer.Initialize(),this.layout.UpdateTiles(),this.autocomplete||(this.autocomplete=new mt({theme:this.theme,container:i})),this.InitOverlayEditor(this.autocomplete),this.AttachListeners(),this.render_tiles=this.layout.VisibleTiles(),t||(this.tab_bar?.Update(!1),this.Repaint(!0))}MergeCells(e){!e&&this.primary_selection.empty||(this.layout.HideDropdownCaret(),this.ExecCommand({key:10,area:e||this.primary_selection.area}))}UnmergeCells(e){!e&&this.primary_selection.empty||(this.layout.HideDropdownCaret(),this.ExecCommand({key:11,area:e||this.primary_selection.area}))}GetAnnotationStyle(){if(this.selected_annotation)return this.selected_annotation.data?.style?JSON.parse(JSON.stringify(this.selected_annotation.data.style)):{}}ApplyAnnotationStyle(e={},t=!0){if(this.selected_annotation){let r=this.selected_annotation;r.data.style=JSON.parse(JSON.stringify(t?I.Composite([r.data.style||{},e]):e));let i=r.view[this.view_index]?.node;this.layout.UpdateAnnotation(r,this.theme),i&&i.focus(),this.grid_events.Publish({type:"annotation",event:"update",annotation:r}),this.DelayedRender()}}AnnotationSelected(){return!!this.selected_annotation}Focus(e="",t=!1){if(this.selected_annotation)if(t)this.editing_annotation===this.selected_annotation?this.pending_reset_selection=!0:(this.selected_annotation=void 0,this.ShowGridSelection());else{this.selected_annotation.view[this.view_index].node?.focus();return}j.is_mobile?this.container?.focus():this.overlay_editor?.Focus(e)}SetValidation(e,t,r){if(!e){if(this.primary_selection.empty)throw new Error("invalid target in set validation");e=this.primary_selection.area}let i=new v(e.start,e.end),n={key:26,area:{start:i.start,end:i.end},error:r};t&&(Array.isArray(t)?n.list=t:typeof t=="object"&&t.start&&t.end&&N(t.start)&&N(t.end)&&(n.range=t)),this.ExecCommand(n),!this.primary_selection.empty&&(!e.start.sheet_id||e.start.sheet_id===this.active_sheet.id)&&i.Contains(this.primary_selection.target)&&requestAnimationFrame(()=>this.Select(this.primary_selection,this.primary_selection.area,this.primary_selection.target))}SetName(e,t,r,i,n=!1){let o=this.model.named.ValidateNamed(e);if(!o)throw new Error("invalid name");if(e=o,this.autocomplete_matcher){let s=this.autocomplete_matcher.Get(e);if(s&&(!s.named||!n)&&(t||r))throw new Error("name already defined")}let a={key:17,name:e,scope:i};if(t)N(t)&&(t=new v(t)),t.start.sheet_id||(t=new v({...t.start,sheet_id:this.active_sheet.id},t.end)),a.area=new v(t.start,t.end);else if(r){let s=this.parser.Parse(r);if(s.valid&&s.expression)this.parser.Walk(s.expression,c=>{if(c.type==="address"||c.type==="range"){if(c.type==="range"&&(c=c.start),!c.sheet_id&&c.sheet){let d=this.model.sheets.Find(c.sheet);d&&(c.sheet_id=d.id)}return c.sheet_id||(c.sheet_id=this.active_sheet.id),!1}return!0}),a.expression=s.expression;else throw console.info({expression:r,parse_result:s}),new Error("invalid expression")}this.ExecCommand(a)}SelectAll(){this.Select(this.primary_selection,new v({row:1/0,column:1/0}),void 0,!0),this.RenderSelections()}ExternalEditor(e){if(this.external_editor_config=e,e){let t=(e.dependencies||[]).filter(r=>!!r).map(r=>N(r)?new v(r):new v(r.start,r.end));if(e.nodes?.length){if(!this.external_editor){let r=new $t(this.model,this.view);this.external_editor=r,r.Subscribe(()=>this.HighlightDependencies(r.dependencies))}this.external_editor.AttachNodes(e.nodes,e.assume_formula??!0)}else this.external_editor&&this.external_editor.Reset();e.dependencies&&this.HighlightDependencies(t)}else this.external_editor&&this.external_editor.Reset(),this.ClearAdditionalSelections(),this.RenderSelections(!0)}SelectRange(e){this.Select(this.primary_selection,e),this.RenderSelections()}GetRangeStyle(e,t=!1){let r=0;if(N(e)?r=e.sheet_id||this.active_sheet.id:r=e.start.sheet_id||this.active_sheet.id,r)return this.model.sheets.Find(r)?.GetCellStyle(e,t)||void 0}FormatR1C1(e,t){ut(t)&&(t=t.start),Array.isArray(e)||(e=[[e]]);let r={type:"address",label:"",row:t.row,column:t.column,sheet:t.sheet_id?this.model.sheets.Name(t.sheet_id):this.active_sheet.name,position:0,id:0};for(let i=0;i<e.length;i++){let n=e[i];for(let o=0;o<n.length;o++){let a=n[o];if(typeof a=="string"&&a[0]==="="){let s=this.parser.Parse(a);s.expression&&(n[o]="="+this.parser.Render(s.expression,{missing:"",r1c1:!0,r1c1_base:{...r,row:t.row+i,column:t.column+o}}))}}}return e}GetRange(e,t){if(N(e)){let i=this.model.sheets.Find(e.sheet_id||this.active_sheet.id);if(i){if(t==="A1"||t==="R1C1"){let n=i.cells.RawValue(e);return t==="R1C1"?this.FormatR1C1(n,e):n}return t==="formatted"?i.GetFormattedRange(e):i.cells.GetRange(e)}return}let r=this.model.sheets.Find(e.start.sheet_id||this.active_sheet.id);if(r){if(t==="A1"||t==="R1C1"){let i=r.cells.RawValue(e.start,e.end);return t==="R1C1"?this.FormatR1C1(i,e):i}return t==="formatted"?r.GetFormattedRange(e.start,e.end):r.cells.GetRange(e.start,e.end)}}SetRange(e,t,r={}){let{recycle:i,transpose:n,array:o,r1c1:a}=r;if(r.argument_separator){let s={argument_separator:this.parser.argument_separator,decimal_mark:this.parser.decimal_mark};this.parser.Save();let c=!1;if(r.argument_separator===","&&this.parser.argument_separator!==","&&(this.parser.SetLocaleSettings("."),c=!0),r.argument_separator===";"&&this.parser.argument_separator!==";"&&(this.parser.SetLocaleSettings(","),c=!0),c){this.parser.flags.r1c1=a;let d=u=>{if(typeof u=="string"&&u[0]==="="){let h=this.parser.Parse(u);h.expression&&(u="="+this.parser.Render(h.expression,{missing:"",convert_decimal:s.decimal_mark,convert_argument_separator:s.argument_separator,pass_through_addresses:!0}))}return u};Array.isArray(t)?t=t.map(u=>Array.isArray(u)?u.map(h=>d(h)):d(u)):t=d(t)}this.parser.Restore()}if(t=this.model.UntranslateData(t,{r1c1:a}),!Array.isArray(t))i||o?this.ExecCommand({key:6,area:e,value:t,array:o,r1c1:a}):this.ExecCommand({key:6,area:e.start,value:t,array:o,r1c1:a});else{if(Tt(t)){if(i){if(e.rows>t.length){let c=Math.floor(e.rows/t.length);if(c>1){let d=[...t];for(let u=0;u<c;u++){let h=JSON.parse(JSON.stringify(d));t.push(...h)}}}let s=0;for(let c of t)s=Math.max(s,c.length);if(e.columns>s){let c=Math.floor(e.columns/s);if(c>1)for(let d of t){for(;d.length<s;)d.push(void 0);let u=[...d];for(let h=0;h<c;h++){let f=JSON.parse(JSON.stringify(u));d.push(...f)}}}}}else if(i){let s=e.entire_column?this.active_sheet.rows:e.rows,c=e.entire_row?this.active_sheet.columns:e.columns,d=s*c;if(d>t.length){let h=t.slice(0),f=Math.ceil(d/h.length);for(let m=1;m<f;m++)h=h.concat(t.slice(0));t=h}let u=[];for(let h=0,f=0;h<c;h++,f+=s)u[h]=t.slice(f,f+s);t=u}else t=[t];n&&(t=this.Transpose(t)),this.ExecCommand({key:6,area:e,value:t,array:o,r1c1:a})}!this.primary_selection.empty&&e.Contains(this.primary_selection.target)&&this.UpdateFormulaBarFormula()}ApplyStyle(e,t={},r=!0){if(!e){if(this.primary_selection.empty)return;e=this.primary_selection.area}re.UpdateStyle(t),this.ExecCommand({key:7,area:e,style:t,delta:r}),this.UpdateFormulaBarFormula()}GetSelection(){return this.primary_selection}Update(e=!1,t){this.DelayedRender(e,t)}UpdateAnnotations(){this.active_sheet.annotations.length&&this.layout.UpdateAnnotation(this.active_sheet.annotations,this.theme)}Indent(e,t=0){if(!e){if(this.primary_selection.empty)return;e=this.active_sheet.RealArea(this.primary_selection.area)}this.ExecCommand({key:9,area:e,delta:t})}ApplyBorders2(e,t="none",r,i=1){if(!e){if(this.primary_selection.empty)return;e=this.primary_selection.area}t==="none"&&(i=0),this.ExecCommand({key:8,color:r,area:e,borders:t,width:i})}Batch(e,t=!0){if(this.batch===0?this.batch_paint=t:this.batch_paint=this.batch_paint||t,this.batch++,e(),this.batch--,this.batch===0){let r=this.batch_events.slice(0);return this.batch_events=[],this.batch_paint&&this.DelayedRender(!1),r}return[]}ScrollTo(e,t=!0,r=!0,i=!1){this.layout.ScrollTo(e,t,r,i)}ScrollIntoView(e,t=!1){this.options.scrollbars&&this.layout.ScrollIntoView(e,t)}GetScrollOffset(){return this.layout.GetScrollOffset()}ScrollOffset(e){if(e)this.layout.scroll_offset=e;else return this.layout.scroll_offset}RenameSheetInternal(e,t){super.RenameSheetInternal(e,t),this.tab_bar?.Update(!1)}StyleDefaultFromTheme(){this.model.theme_style_properties.font_face=this.theme.grid_cell?.font_face||"",this.model.theme_style_properties.font_size=this.theme.grid_cell?.font_size||{unit:"pt",value:10}}AutoSizeRow(e,t,r=!0){if(!this.tile_renderer)return;let i=e.GetRowHeight(t),n=0,o=6;for(let a=0;a<e.cells.columns;a++){let s=e.CellData({row:t,column:a}),{height:c}=this.tile_renderer.MeasureText(s,e.GetColumnWidth(a),1);n=Math.max(n,c+o)}r||(n=Math.max(i,n)),n>o+2&&e.SetRowHeight(t,n)}AutoSizeColumn(e,t,r=!0){if(!this.tile_renderer)return;let i=e.GetColumnWidth(t),n=0,o=14;for(let a=0;a<e.cells.rows;a++){let s=e.CellData({row:a,column:t}),{width:c}=this.tile_renderer.MeasureText(s,i,1);n=Math.max(n,c+o)}r||(n=Math.max(i,n)),n>o+2&&e.SetColumnWidth(t,n)}EnsureActiveSheet(e=!1){for(let t of this.model.sheets.list)if(t===this.active_sheet){e&&this.ActivateSheetInternal({key:22,id:t.id,force:!0});return}this.ActivateSheetInternal({key:22,index:0})}RefreshAnnotations(){this.RemoveAnnotationNodes();for(let e of this.active_sheet.annotations)this.AddAnnotation(e,!0,!0)}ActivateSheetInternal(e){let t=this.SelectingArgument(),r=this.ResolveSheet(e)||this.model.sheets.list[0];if(this.active_sheet===r&&!e.force)return;if(!r.visible)throw new Error("cannot activate hidden sheet");this.HideHoverInfo(),this.active_sheet.selection=JSON.parse(JSON.stringify(this.primary_selection)),this.active_sheet.scroll_offset=this.layout.scroll_offset;let i=this.active_sheet;this.RemoveAnnotationNodes(),this.active_sheet=r,t?this.RenderSelections():(this.ClearSelection(this.primary_selection),r.selection&&!r.selection.empty&&this.Select(this.primary_selection,new v(r.selection.area.start,r.selection.area.end),r.selection.target));let n=this.active_sheet.annotations;for(let o of n)this.AddAnnotation(o,!0);this.ActivateSheetTasks(),this.QueueLayoutUpdate(),this.pending_layout_update.has(this.active_sheet.id)?(this.Repaint(!0,!0),this.pending_layout_update.delete(this.active_sheet.id)):this.Repaint(!1,!1),this.grid_events.Publish({type:"sheet-change",deactivate:i,activate:this.active_sheet}),this.tab_bar&&this.tab_bar.Update(!!e.user),this.layout.scroll_offset=this.active_sheet.scroll_offset,this.formula_bar?.selecting&&requestAnimationFrame(()=>this.formula_bar?.FocusEditor())}ActivateSheetTasks(){if(this.active_sheet.Activate(this.DOM),this.active_sheet.image&&!this.active_sheet.image.complete){let e=this.active_sheet.image,t=0,r=()=>{e.complete?this.UpdateLayout():t++<5&&setTimeout(()=>r(),10)};r()}}HighlightFreezeArea(){for(let e of[this.layout.corner_selection,this.layout.row_header_selection,this.layout.column_header_selection])e.classList.add("highlight-area"),setTimeout(()=>{e.classList.remove("highlight-area")},400)}QueueLayoutUpdate(e){this.tile_update_pending=!0,e&&(this.scroll_offset_pending=e)}HandleAddressLabelEvent(e){if(e){let t=(o="")=>{let a=o.toLowerCase();for(let s of this.model.sheets.list)if(s.name.toLowerCase()===a)return s.id;return this.active_sheet.id},r=o=>{for(let a of this.model.sheets.list)if(a.id===o)return a;return this.active_sheet},i,n=this.parser.Parse(e);if(n.expression)switch(n.expression.type){case"address":n.expression.sheet_id=t(n.expression.sheet),i=new v(n.expression);break;case"range":n.expression.start.sheet_id=t(n.expression.start.sheet),i=new v(n.expression.start,n.expression.end);break;case"identifier":{let o=this.model.GetName(n.expression.name,this.active_sheet.id);o?.type==="range"&&(i=o.area),i||this.primary_selection.empty||this.SetName(n.expression.name.toUpperCase(),this.primary_selection.area)}break;default:break}if(i){let o=r(i.start.sheet_id);if(o.columns>=i.end.column&&o.rows>=i.end.row){this.ExecCommand({key:5,area:i});return}else console.warn("address out of range")}}this.UpdateAddressLabel(),this.Focus()}InitFormulaBar(e,t){this.formula_bar=new Gt(e,this.model,this.view,this.options,t),this.formula_bar.autocomplete_matcher=this.autocomplete_matcher,this.formula_bar.Subscribe(r=>{switch(r.type){case"address-label-event":this.HandleAddressLabelEvent(r.text);break;case"stop-editing":this.pending_reset_selection&&this.ShowGridSelection(),this.pending_reset_selection=!1,this.editing_state=0;break;case"start-editing":this.editing_state=2,this.editing_cell={...this.primary_selection.target},this.editing_selection={...this.primary_selection};break;case"toll":this.editing_state=0,this.ClearAdditionalSelections(),this.ClearSelection(this.active_selection),this.DelayedRender();break;case"discard":if(this.editing_state=0,this.editing_annotation){this.ClearAdditionalSelections(),this.ClearSelection(this.active_selection);let i=this.editing_annotation.view[this.view_index]?.node;i&&i.focus(),this.editing_annotation=void 0,this.UpdateFormulaBarFormula(),this.DelayedRender();return}this.container&&this.Focus(),this.ClearAdditionalSelections(),this.ClearSelection(this.active_selection),this.UpdateFormulaBarFormula(),this.DelayedRender();break;case"commit":if(this.active_sheet.id!==this.editing_cell.sheet_id&&this.editing_cell.sheet_id&&this.ActivateSheetID(this.editing_cell.sheet_id),this.editing_state=0,this.editing_annotation){let i=this.editing_annotation;if(this.ClearAdditionalSelections(),this.ClearSelection(this.active_selection),i.data.formula=r.value?this.FixFormula(r.value):"",!this.pending_reset_selection){let n=this.editing_annotation.view[this.view_index]?.node;n&&n.focus()}this.grid_events.Publish({type:"annotation",event:"update",annotation:i}),this.editing_annotation=void 0,this.DelayedRender();return}this.container&&this.Focus(),r.event?this.SetInferredType(this.primary_selection,r.value,r.array):this.editing_selection&&this.SetInferredType(this.editing_selection,r.value,r.array),this.ClearAdditionalSelections(),this.ClearSelection(this.active_selection),this.options.repaint_on_cell_change&&this.DelayedRender(!1,this.primary_selection.area),r.event&&this.OverlayKeyDown(r.event);break;case"update":r.dependencies&&this.HighlightDependencies(r.dependencies);break}})}InitOverlayEditor(e){this.container&&(this.overlay_editor=new Ot(this.container,this.theme,this.model,this.view,e),this.overlay_editor.UpdateScale(this.layout.scale),this.overlay_editor.autocomplete_matcher=this.autocomplete_matcher,this.overlay_editor.Subscribe(t=>{switch(t.type){case"stop-editing":this.editing_state=0;break;case"start-editing":this.editing_state=1,this.editing_cell={...this.primary_selection.target};break;case"update":t.dependencies&&this.HighlightDependencies(t.dependencies);break;case"end-selection":case"reset-selection":this.ClearSelection(this.active_selection),this.overlay_editor?.target_address?.sheet_id&&this.active_sheet.id!==this.overlay_editor.target_address.sheet_id&&this.ActivateSheetID(this.overlay_editor.target_address.sheet_id),this.DelayedRender();break}}))}DelayedRender(e=!1,t,r=!1){!this.tile_update_pending&&t?this.layout.DirtyArea(t):!this.tile_update_pending&&e&&this.layout.DirtyAll(),this.render_token||(this.render_token=1,Promise.resolve().then(()=>{this.render_token=0,this.Repaint(e,r)}))}Repaint(e=!1,t=!1,r=!1){if(this.headless||!this.tile_renderer)return;if(this.tile_update_pending&&(this.tile_update_pending=!1,this.layout.UpdateTiles(),this.scroll_offset_pending&&(this.layout.scroll_offset=this.scroll_offset_pending,this.scroll_offset_pending=void 0),this.render_tiles=this.layout.VisibleTiles(),this.layout.UpdateAnnotation(this.active_sheet.annotations,this.theme)),this.layout_token=0,this.tile_renderer.OverflowDirty(t),e)for(let s of this.layout.grid_tiles)for(let c of s)c.dirty=!0;let i=this.render_tiles.start,n=this.render_tiles.end,o=[];for(let s=i.row;s<=n.row;s++)o.push(s);let a=[];for(let s=i.column;s<=n.column;s++)a.push(s);i.row>0&&this.active_sheet.freeze.rows&&o.push(0),i.column>0&&this.active_sheet.freeze.columns&&a.push(0);for(let s of a)for(let c of o){let d=this.layout.grid_tiles[s][c];(e||d.dirty||d.needs_full_repaint)&&(this.tile_renderer.Render(d),d.dirty=d.needs_full_repaint=!1)}this.tile_renderer.RenderHeaders(this.render_tiles,r),this.tile_renderer.RenderCorner(),this.RenderSelections()}MouseMove_RowHeader(e){let t=this.layout.CoordinateToRowHeader(e.offsetY),r=this.layout.OffsetCellAddressToRectangle({row:t.row,column:0});this.hover_data.address&&(this.hover_data.address.row!==-1||this.hover_data.address.column!==-1)&&this.HoverCell({row:-1,column:-1});let i=-1;e.offsetY-r.top<=this.RESIZE_PIXEL_BUFFER&&t.row>0?i=t.row-1:r.bottom-e.offsetY<=this.RESIZE_PIXEL_BUFFER&&(i=t.row),i>=0?this.layout.ResizeCursor("row"):this.cell_resize.row&&(this.cell_resize.row=-1,this.layout.ResizeCursor()),this.cell_resize.row=i}MouseMove_ColumnHeader(e){let t=this.layout.CoordinateToColumnHeader(e.offsetX),r=this.layout.OffsetCellAddressToRectangle({row:0,column:t.column});this.hover_data.address&&(this.hover_data.address.row!==-1||this.hover_data.address.column!==-1)&&this.HoverCell({row:-1,column:-1});let i=-1;e.offsetX-r.left<=this.RESIZE_PIXEL_BUFFER&&t.column>0?i=t.column-1:r.right-e.offsetX<=this.RESIZE_PIXEL_BUFFER&&(i=t.column),i>=0?this.layout.ResizeCursor("column"):this.cell_resize.column&&(this.cell_resize.column=-1,this.layout.ResizeCursor()),this.cell_resize.column=i}MouseDown_RowHeader(e){if(e.button!==0)return;e.stopPropagation(),e.preventDefault();let t=this.layout.CoordinateToRowHeader(e.offsetY),r=this.layout.row_header_cover.getBoundingClientRect(),i={x:r.left,y:r.top};if(this.cell_resize.row>=0){let n=this.cell_resize.row,o=i.y+e.offsetY;if(this.layout.HideDropdownCaret(),this.IsDoubleClick({row:n,column:-1})){let f=[n];if(!this.primary_selection.empty&&this.primary_selection.area.rows>1&&this.primary_selection.area.start.column===1/0&&this.primary_selection.area.ContainsRow(n)){let m=this.active_sheet.RealArea(this.primary_selection.area);f=[];for(let p=m.start.row;p<=m.end.row;p++)f.push(p)}this.ExecCommand({key:3,row:f});return}let a=this.layout.RowHeight(n),s=a,c=this.layout.OffsetCellAddressToRectangle({row:n,column:0}),d=i.y+c.bottom;this.layout.ShowTooltip({left:!0,text:`${s}px`,x:Math.round(r.right+10),y:d});let u=[],h=[];for(let f of this.active_sheet.annotations){let m=c.bottom-1;if(!f.scaled_rect||f.scaled_rect.bottom<m)continue;let p=[...this.layout.GetFrozenAnnotations(f)],b=f.view[this.view_index]?.node;b&&p.push(b),m<=f.scaled_rect.top&&f.data.move_with_cells?u.push({annotation:f,y:f.scaled_rect.top,nodes:p}):m>f.scaled_rect.top&&f.data.resize_with_cells&&h.push({annotation:f,height:f.scaled_rect.height,nodes:p})}Ae(this.layout.mask,"row-resize",f=>{let m=Math.max(-a,Math.round(f.offsetY-o));if(m+a!==s){s=m+a,this.layout.SetRowHeight(n,s),this.layout.UpdateTooltip({text:`${s}px`,y:d+m});for(let{annotation:p,y:b}of u)p.scaled_rect&&(p.scaled_rect.top=b+m);for(let{annotation:p,height:b}of h)p.scaled_rect&&(p.scaled_rect.height=b+m);requestAnimationFrame(()=>{for(let{annotation:p,nodes:b}of h)if(p.scaled_rect)for(let g of b)p.scaled_rect.ApplyStyle(g);for(let{annotation:p,nodes:b}of u)if(p.scaled_rect)for(let g of b)p.scaled_rect.ApplyStyle(g);this.layout.UpdateTileHeights(!0,n),this.Repaint(!1,!0),this.layout.UpdateAnnotation(this.active_sheet.annotations,this.theme)})}},()=>{this.layout.HideTooltip(),requestAnimationFrame(()=>{let f=[n];if(!this.primary_selection.empty&&this.primary_selection.area.rows>1&&this.primary_selection.area.start.column===1/0&&this.primary_selection.area.ContainsRow(n)){let m=this.active_sheet.RealArea(this.primary_selection.area);f=[];for(let p=m.start.row;p<=m.end.row;p++)f.push(p)}this.layout.SetRowHeight(n,a),this.ExecCommand({key:3,row:f,height:s/this.scale});for(let{annotation:m}of u)m.scaled_rect&&(m.data.layout=this.layout.RectToAnnotationLayout(m.scaled_rect));for(let{annotation:m}of h){m.scaled_rect&&(m.data.layout=this.layout.RectToAnnotationLayout(m.scaled_rect));let p=m.view[this.view_index];p&&p.resize_callback&&p.resize_callback.call(void 0)}})})}else{let n=this.SelectingArgument()?this.active_selection:this.primary_selection;if(this.SelectingArgument()||this.Focus(void 0,!0),e.shiftKey&&!n.empty){let o=n.target;this.Select(n,new v(n.target,t,!0),void 0,!0),t=o}else this.Select(n,new v(t),{column:0,row:t.row});this.RenderSelections(),Ae(this.layout.mask,[],o=>{let a=this.layout.CoordinateToRowHeader(o.offsetY-i.y),s=new v(a,t,!0);(n.empty||!s.Equals(n.area))&&(this.Select(n,s,void 0,!0),this.RenderSelections())},()=>{})}}MouseDown_ColumnHeader(e){if(e.button!==0)return;e.stopPropagation(),e.preventDefault();let t=this.layout.CoordinateToColumnHeader(e.offsetX),r=this.layout.column_header_cover.getBoundingClientRect(),i={x:r.left,y:r.top};if(this.cell_resize.column>=0){let n=this.cell_resize.column,o=i.x+e.offsetX;if(this.layout.HideDropdownCaret(),this.IsDoubleClick({row:-1,column:n})){let f=[n];if(!this.primary_selection.empty&&this.primary_selection.area.columns>1&&this.primary_selection.area.start.row===1/0&&this.primary_selection.area.ContainsColumn(n)){let m=this.active_sheet.RealArea(this.primary_selection.area);f=[];for(let p=m.start.column;p<=m.end.column;p++)f.push(p)}this.ExecCommand({key:4,column:f});return}let a=this.layout.ColumnWidth(n),s=a,c=this.layout.OffsetCellAddressToRectangle({row:0,column:n}),d=i.x+c.right;this.layout.ShowTooltip({up:!0,text:`${s}px`,x:d,y:Math.round(r.bottom+10)});let u=[],h=[];for(let f of this.active_sheet.annotations){let m=c.right-1;if(!f.scaled_rect||f.scaled_rect.right<m)continue;let p=[...this.layout.GetFrozenAnnotations(f)],b=f.view[this.view_index]?.node;b&&p.push(b),m<=f.scaled_rect.left&&f.data.move_with_cells?u.push({annotation:f,x:f.scaled_rect.left,nodes:p}):m>f.scaled_rect.left&&f.data.resize_with_cells&&h.push({annotation:f,width:f.scaled_rect.width,nodes:p})}Ae(this.layout.mask,"column-resize",f=>{let m=Math.max(-a,Math.round(f.offsetX-o));if(m+a!==s){s=m+a,this.layout.UpdateTooltip({text:`${s}px`,x:d+m}),this.layout.SetColumnWidth(n,s);for(let{annotation:p,x:b}of u)p.scaled_rect&&(p.scaled_rect.left=b+m);for(let{annotation:p,width:b}of h)p.scaled_rect&&(p.scaled_rect.width=b+m);requestAnimationFrame(()=>{for(let{annotation:p,nodes:b}of h)if(p.scaled_rect)for(let g of b)p.scaled_rect.ApplyStyle(g);for(let{annotation:p,nodes:b}of u)if(p.scaled_rect)for(let g of b)p.scaled_rect.ApplyStyle(g);this.layout.UpdateTileWidths(!0,n),this.Repaint(!1,!0)})}},()=>{this.layout.HideTooltip(),requestAnimationFrame(()=>{let f=[n];if(!this.primary_selection.empty&&this.primary_selection.area.columns>1&&this.primary_selection.area.start.row===1/0&&this.primary_selection.area.ContainsColumn(n)){let m=this.active_sheet.RealArea(this.primary_selection.area);for(let p=m.start.column;p<=m.end.column;p++)f.push(p)}this.ExecCommand({key:4,column:f,width:s});for(let{annotation:m}of u)m.scaled_rect&&(m.data.layout=this.layout.RectToAnnotationLayout(m.scaled_rect));for(let{annotation:m}of h){m.scaled_rect&&(m.data.layout=this.layout.RectToAnnotationLayout(m.scaled_rect));let p=m.view[this.view_index];p&&p.resize_callback&&p.resize_callback.call(void 0)}})})}else{let n=this.SelectingArgument()?this.active_selection:this.primary_selection;if(this.SelectingArgument()||this.Focus(void 0,!0),e.shiftKey&&!n.empty){let o=n.target;this.Select(n,new v(n.target,t,!0),void 0,!0),t=o}else this.Select(n,new v(t),{row:0,column:t.column});this.RenderSelections(),Ae(this.layout.mask,[],o=>{let a=this.layout.CoordinateToColumnHeader(o.offsetX-i.x),s=new v(a,t,!0);(n.empty||!s.Equals(n.area))&&(this.Select(n,s,void 0,!0),this.RenderSelections())})}}HoverCell(e,t){let r=this.active_sheet.cells.GetCell(e,!1);if(r?.table&&r.table.area.start.row===e.row&&r.table.sortable!==!1?(this.hover_data.table_header=!0,this.layout.ShowTableSortButton(r.table,e.column-r.table.area.start.column,e)):(this.hover_data.table_header&&this.layout.HideTableSortButton(),this.hover_data.table_header=!1),r?.merge_area){let i=r.merge_area;e=i.start,r=this.active_sheet.cells.GetCell(e,!1),e={row:i.start.row,column:i.end.column}}if(r?.note){let i=Ie.instance.Parse(r.note),n=this.options.comment_markdown?Ie.instance.HTML(i,{br:!1}):void 0;this.layout.ShowNote(r.note,e,t,n),this.hover_data.note=!0}else this.hover_data.note&&(this.layout.HideNote(),this.hover_data.note=!1);r?.hyperlink?(this.layout.ShowTitle("Link: "+r.hyperlink,e),this.hover_data.link=!0,this.hover_data.cell=r):this.hover_data.link&&(this.layout.HideTitle(),this.hover_data.cell=void 0),this.hover_data.address={...e}}HideHoverInfo(){this.layout.HideTitle(),this.layout.HideTooltip(),this.hover_data.note=this.hover_data.link=!1,this.hover_data.cell=void 0,this.hover_data.pointer&&this.layout.grid_cover.classList.remove("link-pointer"),this.hover_data.pointer=!1}MouseMove_Grid(e){if(e.stopPropagation(),e.preventDefault(),!this.selection_renderer)return;(this.cell_resize.row>=0||this.cell_resize.column>=0)&&this.layout.ResizeCursor();let t={x:e.offsetX,y:e.offsetY},r;if(this.overlay_editor?.editing||(r=this.layout.PointToAddress_Grid(t),(!this.hover_data.address||this.hover_data.address.row!==r.row||this.hover_data.address.column!==r.column)&&this.HoverCell(r,e)),this.hover_data.link&&r&&(this.hover_data.point=t,this.hover_data.handler||(this.hover_data.handler=requestAnimationFrame(()=>{let n=this.hover_data.address&&this.hover_data.point&&this.hover_data.cell&&this.PointInTextPart(this.hover_data.address,this.hover_data.point,this.hover_data.cell);n!==!!this.hover_data.pointer&&(this.hover_data.pointer=n,n?this.layout.grid_cover.classList.add("link-pointer"):this.layout.grid_cover.classList.remove("link-pointer")),this.hover_data.handler=void 0}))),this.primary_selection.empty||!this.selection_renderer.nub_rectangle){this.nub_select_flag&&(this.layout.grid_cover.classList.remove("nub-select"),this.nub_select_flag=!1);return}let i=this.selection_renderer.nub_rectangle.Contains(e.offsetX,e.offsetY);i!==this.nub_select_flag&&(i?this.layout.grid_cover.classList.add("nub-select"):this.layout.grid_cover.classList.remove("nub-select"),this.nub_select_flag=i)}ClearDoubleClick(){this.double_click_data.address=void 0}IsDoubleClick(e,t=300){if(this.double_click_data.address&&this.double_click_data.address.row===e.row&&this.double_click_data.address.column===e.column)return clearTimeout(this.double_click_data.timeout),this.double_click_data.address=void 0,this.double_click_data.timeout=void 0,!0;this.double_click_data.timeout&&clearTimeout(this.double_click_data.timeout),this.double_click_data.address={...e},this.double_click_data.timeout=window.setTimeout(()=>{this.double_click_data.address=void 0,this.double_click_data.timeout=void 0},t)}PointInTextPart(e,t,r){let i=this.layout.CellAddressToRectangle(e);r.merge_area&&(i=i.Combine(this.layout.CellAddressToRectangle(r.merge_area.end)));let n=t.x-i.left,o=t.y-i.top,a=r.renderer_data?.text_data?.strings||[];for(let s of a)for(let c of s)if(typeof c.left=="number"&&typeof c.top=="number"&&typeof c.width=="number"&&typeof c.height=="number"&&n>=c.left&&o>=c.top&&n<=c.left+c.width&&o<=c.top+c.height)return!0;return!1}MouseDown_Grid(e){if(e.button!==0)return;e.stopPropagation(),e.preventDefault();let t=this.SelectingArgument();if(!t&&this.additional_selections.length&&this.ClearAdditionalSelections(),(!t||!this.formula_bar?.selecting&&!this.external_editor?.selecting)&&this.Focus(void 0,!0),this.overlay_editor?.editing&&!this.overlay_editor?.selecting){if(this.overlay_editor?.selection){let u=this.overlay_editor?.edit_node.textContent||void 0;this.SetInferredType(this.overlay_editor.selection,u,!1)}this.DismissEditor()}let r={x:e.offsetX,y:e.offsetY},i=this.layout.PointToAddress_Grid(r),n=t?this.active_selection:this.primary_selection;if(!t&&this.IsDoubleClick(i)){j.is_mobile&&this.overlay_editor?.edit_node?.focus(),this.OverlayEditCell({target:i,area:new v(i)},!1);return}let o=this.layout.grid_cover.getBoundingClientRect(),a={x:o.left,y:o.top},s=[],c;if(e.shiftKey&&!n.empty){let u=n.target;this.Select(n,new v(i,n.target,!0),void 0,!0),i=u}else if(this.nub_select_flag)i=n.area.TopLeft(),s.push("nub-select"),c=this.active_sheet.RealArea(n.area);else{let u=i,h=this.active_sheet.CellData(u);if(h.merge_area&&(u=h.merge_area.start,h=this.active_sheet.CellData(h.merge_area.start)),h.hyperlink&&this.PointInTextPart(u,r,h)){let f=h.hyperlink;Promise.resolve().then(()=>{this.grid_events.Publish({type:"cell-event",data:{type:"hyperlink",reference:f}})}),this.ClearDoubleClick();return}if(h.click_function){let f=this.layout.CellAddressToRectangle(u);h.merge_area&&(f=f.Combine(this.layout.CellAddressToRectangle(h.merge_area.end)));let m=h.click_function.call(this,{cell:h,x:r.x-f.left,y:r.y-f.top,width:f.width,height:f.height,scale:this.layout.scale});if(m.value&&this.ExecCommand({key:6,value:m.value,area:u}),m.block_selection){this.ClearDoubleClick(),!this.primary_selection.empty&&this.primary_selection.target.row===u.row&&this.primary_selection.target.column===u.column&&this.UpdateFormulaBarFormula();return}}this.Select(n,new v(i),i)}this.RenderSelections(),t&&this.UpdateSelectedArgument(n);let d=this.layout.CellAddressToRectangle({row:0,column:0}).Combine(this.layout.CellAddressToRectangle({row:this.active_sheet.rows-1,column:this.active_sheet.columns-1})).Expand(-1,-1);Ae(this.layout.mask,s,u=>{let h={x:u.offsetX-a.x,y:u.offsetY-a.y},f=d.Clamp(h.x,h.y),m=this.layout.PointToAddress_Grid(f),p=this.layout.scroll_reference_node,b=!1;this.container&&this.options.scrollbars&&(h.x<p.scrollLeft?(p.scrollLeft-=25,b=!0):h.x>p.scrollLeft+this.container.clientWidth&&(p.scrollLeft+=25,b=!0),h.y<p.scrollTop?(p.scrollTop-=25,b=!0):h.y>p.scrollTop+this.container.clientHeight&&(p.scrollTop+=25,b=!0),b&&(o=this.layout.grid_cover.getBoundingClientRect(),a.x=o.left+document.body.scrollLeft,a.y=o.top+document.body.scrollTop));let g=new v(m,i,!0);if(c&&(g=c.Clone(),g.ConsumeAddress(m),g.rows!==c.rows&&g.columns!==c.columns)){let x={rows:m.row>c.end.row?m.row-c.end.row:c.start.row-m.row,columns:m.column>c.end.column?m.column-c.end.column:c.start.column-m.column};x.rows>=x.columns?g=new v({row:g.start.row,column:c.start.column},{row:g.end.row,column:c.end.column}):g=new v({row:c.start.row,column:g.start.column},{row:c.end.row,column:g.end.column})}(n.empty||!g.Equals(n.area))&&(this.Select(n,g,void 0,!0),this.RenderSelections(),t?this.UpdateSelectedArgument(n):this.UpdateAddressLabelArea(n))},()=>{this.UpdateAddressLabel(),t?this.overlay_editor?.editing||(this.external_editor_config?(this.external_editor?.active&&this.external_editor.FocusEditor(),this.external_editor_config.update):this.formula_bar&&this.formula_bar.FocusEditor()):c&&this.RecycleNubArea(n.area,c)})}Transpose(e){let t=[],r=e.length,i=e[0].length;for(let n=0;n<i;n++){t[n]=[];for(let o=0;o<r;o++)t[n][o]=e[o][n]}return t}RecycleNubArea(e,t){if(e.Equals(t))return;let r=[];for(let u=0;u<t.rows;u++){r[u]=[];for(let h=0;h<t.columns;h++){let f={row:t.start.row+u,column:t.start.column+h};r[u][h]=this.active_sheet.CellData(f)}}if(r[0][0].area&&r[0][0].area.Equals(t)){this.ExecCommand({key:6,value:r[0][0].value,array:!0,area:e});return}if(r[0][0].table&&t.Equals(new v(r[0][0].table.area.start,r[0][0].table.area.end))){let u=r[0][0].table,h=u.sortable,f=u.totals_row,m=u.theme;this.ExecCommand([{key:30,table:u},{key:29,area:e,sortable:h,totals:f,theme:m}]);return}let i=[],n=[],o=t.columns,a=e.rows,s=!1,c=!1;e.columns===t.columns?s=e.start.row<t.start.row:(o=t.rows,a=e.columns,s=e.start.column<t.start.column,r=this.Transpose(r),c=!0);for(let u=0;u<a;u++)i[u]=[],n[u]=[];for(let u=0;u<o;u++){let h=0;if(r.length>1){h=1;let f=[],m=[];for(let p=0;p<r.length;p++){let b=r[p][u];b.ValueIsNumber()&&(m.push(p),f.push(b.value))}if(f.length>1){let p=f.slice(1).map((b,g)=>b-f[g]);p.every(b=>b===p[0])&&(h=p[0])}f.length&&(h+=f[f.length-1]-f[0])}for(let f=0;f<r.length;f++){let m,p=r[f][u];if(p.ValueIsFormula()){let _=this.parser.Parse(p.value);_.expression&&_.full_reference_list?.length&&(m=_.expression)}let b=0,g=f,x=r.length,y=0,w=h;s&&(g=a-r.length+f,x=-r.length,w=-h);for(let _=g;_>=0&&_<a;_+=x,b+=x,y+=w){let C={offset:c?{rows:0,columns:b}:{rows:b,columns:0}};if(m)i[_][u]="="+this.parser.Render(m,C);else{let S=r[f][u];S.ValueIsNumber()?i[_][u]=S.value+y:i[_][u]=S.value}n[_][u]=r[f][u].style||{}}}}let d=[{key:6,value:c?this.Transpose(i):i,array:!1,area:e}];c&&(n=this.Transpose(n));for(let u=0;u<n.length;u++)for(let h=0;h<n[u].length;h++)d.push({key:7,area:{row:u+e.start.row,column:h+e.start.column},style:n[u][h],delta:!1});this.ExecCommand(d)}UpdateSelectedArgument(e){let t=this.active_sheet.CellData(e.area.start),r=new v(t.merge_area?t.merge_area.start:e.target),i=this.model.named.MatchSelection(e.area,r);if(!i&&(i=e.area.spreadsheet_label,t.merge_area&&t.merge_area.Equals(e.area)&&(i=v.CellAddressToLabel(t.merge_area.start)),this.external_editor_config||this.active_sheet.id!==this.editing_cell.sheet_id)){let n=this.active_sheet.name;Ce.test(n)?i=`'${n}'!${i}`:i=`${n}!${i}`}if(this.overlay_editor?.editing&&this.overlay_editor.selecting)this.overlay_editor.InsertReference(i);else if(this.formula_bar&&this.formula_bar.selecting)this.formula_bar.InsertReference(i);else if(this.external_editor_config&&(this.external_editor?.active&&(this.external_editor.FocusEditor(),this.external_editor.InsertReference(i)),this.external_editor_config.update)){let n=this.external_editor_config.update.call(0,i);n&&Array.isArray(n)&&this.HighlightDependencies(n.filter(o=>!!o).map(o=>N(o)?new v(o):new v(o.start,o.end)))}}SelectingArgument(){return this.overlay_editor?.editing&&this.overlay_editor?.selecting||this.formula_bar&&this.formula_bar.selecting||!!this.external_editor_config}ReleaseOverlayEditor(){this.editing_state=0,this.DismissEditor(),this.DelayedRender()}RestoreOverlayEditor(){this.overlay_editor?.FocusEditor()}OverlayKeyDown(e){let t=!1;if(this.overlay_editor&&this.overlay_editor.editing)switch(t=!0,this.overlay_editor.HandleKeyDown(e)){case"handled":return;case"discard":this.editing_state=0,this.DismissEditor(),this.DelayedRender();return;case"commit":if(this.active_sheet.id!==this.editing_cell.sheet_id&&this.editing_cell.sheet_id&&this.ActivateSheetID(this.editing_cell.sheet_id),this.editing_state=0,this.overlay_editor?.selection){let c=this.overlay_editor?.edit_node.textContent||void 0,d=e.key==="Enter"&&(e.ctrlKey||j.is_mac&&e.metaKey)&&e.shiftKey;this.SetInferredType(this.overlay_editor.selection,c,d,void 0,this.overlay_editor.edit_style)}this.DismissEditor(),this.options.repaint_on_cell_change&&this.DelayedRender(!1,this.overlay_editor?.selection.area||void 0);break}let r=this.SelectingArgument();if(this.formula_bar&&this.formula_bar.focused&&!r||this.selected_annotation&&!r)return;let i=r?this.active_selection:this.primary_selection,n={rows:0,columns:0},o=!1,a=!1;if(e.ctrlKey||j.is_mac&&e.metaKey){switch(e.key){case"ArrowDown":case"Down":n.rows++;break;case"ArrowUp":case"Up":n.rows--;break;case"ArrowLeft":case"Left":n.columns--;break;case"ArrowRight":case"Right":n.columns++;break;case"Backspace":e.metaKey&&j.is_mac&&(i.empty||this.DeleteSelection(i));break;case"Delete":case"Del":{e.stopPropagation(),e.preventDefault();for(let s=0;s<this.model.sheets.length;s++)if(this.model.sheets.list[s]===this.active_sheet){this.DeleteSheet(s);break}return}break;case"/":e.stopPropagation(),e.preventDefault(),this.SelectArrayOrTable();break;default:if(e.shiftKey)return}if(n.columns||n.rows)if(e.stopPropagation(),e.preventDefault(),!i.empty&&(n.columns||n.rows)){if(this.BlockSelection(i,!!e.shiftKey,n.columns,n.rows)){e.shiftKey&&!r&&this.UpdateAddressLabelArea(i);return}}else return;else{let s={},c=this.primary_selection.empty?{}:this.active_sheet.CellData(this.primary_selection.target).style||{};switch(e.key.toLowerCase()){case"b":s.bold=!c.bold;break;case"i":s.italic=!c.italic;break;case"u":s.underline=!c.underline;break;case"a":this.SelectAll();break;case"0":if(!e.altKey)return;this.ClearSelection(this.primary_selection),this.RenderSelections();break;default:e.key;return}Object.keys(s).length&&this.ApplyStyle(void 0,s)}}else{if(/^F\d+$/.test(e.key))return;switch(e.key){case"Tab":e.shiftKey?n.columns--:n.columns++,o=!0;break;case"Enter":e.shiftKey?n.rows--:n.rows++,o=!0;break;case"ArrowDown":case"Down":n.rows++,a=e.shiftKey;break;case"ArrowUp":case"Up":n.rows--,a=e.shiftKey;break;case"ArrowLeft":case"Left":n.columns--,a=e.shiftKey;break;case"ArrowRight":case"Right":n.columns++,a=e.shiftKey;break;case"Delete":case"Del":i.empty||this.DeleteSelection(i);break;case"PageUp":case"PageDown":if(e.shiftKey){this.NextSheet(e.key==="PageUp"?-1:1,!0);break}return;case"Control":case"Shift":case"Alt":return;default:i.empty||e.key!=="Escape"&&this.OverlayEditCell(i,!0,e);return}}e.stopPropagation(),e.preventDefault(),(n.rows||n.columns)&&(this.AdvanceSelection(n,i,o,a,!t),e.shiftKey&&!r&&this.UpdateAddressLabelArea(i))}SelectArrayOrTable(){if(this.primary_selection.empty)return;let e=this.active_sheet.CellData(this.primary_selection.target);if(!(!e||!e.area&&!e.table&&!e.spill)){if(e.area&&this.Select(this.primary_selection,e.area,e.area.start),e.spill&&this.Select(this.primary_selection,e.spill,e.spill.start),e.table){let t=new v(e.table.area.start,e.table.area.end);this.Select(this.primary_selection,t,t.start)}this.RenderSelections()}}RenderSelections(e=!0){let t=this.hide_selection?!1:!this.editing_state||this.editing_cell.sheet_id===this.active_sheet.id,r=this.primary_selection.empty?void 0:this.active_sheet.CellData(this.primary_selection.target);this.layout.ShowSpillBorder(r?.spill),this.selection_renderer?.RenderSelections(t,e)}BlockSelection(e,t,r,i,n=!0){if(e.empty)return!1;let o={...e.target};i>0?o.row=Math.max(o.row,e.area.end.row):i<0&&(o.row=Math.min(o.row,e.area.start.row)),r>0?o.column=Math.max(o.column,e.area.end.column):r<0&&(o.column=Math.min(o.column,e.area.start.column));let a=this.active_sheet.cells,s=a.GetCell(e.target,!1);if(!s||s.type===0&&!s.area&&!s.spill)return!1;let c={...o};for(;;){let d={row:c.row+i,column:c.column+r};if(d.column<0||d.row<0||d.column>=this.active_sheet.columns||d.row>=this.active_sheet.rows)break;let u=!1;if(i)for(let h=e.area.start.column;!u&&h<=e.area.end.column;h++)s=a.GetCell({row:d.row,column:h},!1),u=u||!!s&&(s.type!==0||!!s.area||!!s.spill),!u&&s&&s.merge_area&&(s=a.GetCell(s.merge_area.start,!1),u=u||!!s&&(s.type!==0||!!s.area||!!s.spill));else for(let h=e.area.start.row;!u&&h<=e.area.end.row;h++)s=a.GetCell({row:h,column:d.column},!1),u=u||!!s&&(s.type!==0||!!s.area||!!s.spill),!u&&s&&s.merge_area&&(s=a.GetCell(s.merge_area.start,!1),u=u||!!s&&(s.type!==0||!!s.area||!!s.spill));if(!u)break;c=d}if(t){i?(o.row=e.target.row,o.column=e.area.start.column,c.column=e.area.end.column):(o.column=e.target.column,o.row=e.area.start.row,c.row=e.area.end.row);let d=new v(o,c,!0);this.Select(e,d,e.target,!0)}else this.Select(e,new v(c));return this.ScrollIntoView(c),this.SelectingArgument()&&this.UpdateSelectedArgument(e),n&&this.DelayedRender(),!0}DeleteSelection(e){if(e.empty)return;let t=this.active_sheet.RealArea(e.area);this.ExecCommand({key:12,area:t})}SetInferredType(e,t,r=!1,i=!0,n){let o=e.target||e.area.start,a=this.active_sheet.CellData(o);if(a.area){if(!r&&a.area.count>1||!e.area||!e.area.Equals(a.area)){this.Error(2);return}}else if(r){for(let f of this.active_sheet.cells.Iterate(e.area,!1))if(f.area){this.Error(2);return}}let s=this.active_sheet.GetValidation(o)[0];if(s&&s.error){let f;if(s.type==="list"?f=s.list:s.type==="range"&&(f=this.GetValidationRange(s.area)),f&&f.length){let m=!1;if(t){let p=t.toUpperCase();for(let b of f)if(b&&b.toString().toUpperCase()===p){t=b.toString(),m=!0;break}}if(!m){this.Error(3);return}}}a.merge_area&&(o=a.merge_area.start);let c=[];n&&c.push({key:7,style:n,delta:!0,area:r?e.area:e.target});let d=typeof t=="string"&&t.trim()[0]==="=";if(d&&(t=this.FixFormula(t||""),!this.active_sheet.HasCellStyle(o))){let f=this.parser.Parse(t);if(f){if(f.expression?.type==="call"&&(!a.style||!a.style.number_format||L.Equals(a.style.number_format,"General"))){let m=f.expression.name.toLowerCase(),p;switch(m){case"today":p="Short Date";break;case"now":p="Timestamp";break}p&&c.push({key:7,area:r?e.area:o,style:{number_format:p},delta:!0})}if(f.expression){let m,p=(x,y=this.active_sheet)=>{if(y.HasCellStyle({...x})){let w=y.CellData({...x});if(w.style&&w.style.number_format&&(!m||/%/.test(m))&&(m=L.Translate(w.style.number_format),!/%/.test(m)))return!0}return!1},b=!1,g=this.active_sheet;if(this.parser.Walk(f.expression,x=>{if(b)return!1;switch(x.type){case"address":this.model.ResolveSheetID(x),g=this.model.sheets.Find(x.sheet_id||0),b=b||p(x,g);break;case"range":this.model.ResolveSheetID(x),g=this.model.sheets.Find(x.start.sheet_id||0);for(let y of new v(x.start,x.end))if(b=b||p(y,g),b)break;break}return!b}),m){let x={number_format:L.SymbolicName(m)||m};c.push({key:7,area:r?e.area:o,style:x,delta:!0})}}}}let u=this.parser.Parse(t||"").expression;u?.type==="group"&&u.elements.length===1&&u.elements[0].type==="complex"&&(u=u.elements[0]);let h;if(u?.type==="complex"?h={type:8,value:{real:u.real,imaginary:u.imaginary}}:u?.type==="literal"&&typeof u.value=="boolean"?h={type:4,value:u.value}:h=_e.TryParse(t),!d&&h.type===3){let f="",m=h.hints||{};(!a.style||!a.style.number_format||L.Equals(a.style.number_format,"General"))&&(m.Date?f="Short Date":m.Exponential?f="Exponential":m.Percent?f="Percent":m.Currency?f="Currency":(m.Grouping||m.Parens)&&(f="Accounting")),f&&c.push({key:7,area:r?e.area:o,style:{number_format:f},delta:!0})}if(c.push({key:6,area:r?e.area:o,array:r,value:d?this.model.UntranslateFunction(t||""):h.value}),i)this.ExecCommand(c);else return c}FixFormula(e){if(e.trim()[0]!=="=")return e;e=e.replace(/^\s+/,"");let t=!1,r=!1,i=0,n=!1,o=e.length;for(let a=0;a<o;a++){let s=e[a];if(!n)switch(s){case'"':t?e[a+1]==='"'?a++:t=!1:r||(t=!0);break;case"'":r?r=!1:t||(r=!0);break;case"\\":n=!0;break;case"(":!t&&!r&&i++;break;case")":!t&&!r&&i--;break}}for(t?e+='"':r&&(e+="'");i>0;)e+=")",i--;return e=this.NormalizeFormula(e),e}NormalizeFormula(e){let t=this.parser.Parse(e);return t.error&&console.warn(t.error),t&&t.expression&&(this.parser.Walk(t.expression,r=>{switch(r.type){case"call":r.name=this.autocomplete_matcher.NormalizeIdentifier(r.name)||r.name;break;case"identifier":this.model.GetName(r.name,this.active_sheet.id)?.type==="range"&&(r.name=r.name.toUpperCase());break}return!0}),e="="+this.parser.Render(t.expression,{missing:""})),e}DismissEditor(){this.overlay_editor?.active_cell&&(this.overlay_editor.active_cell.editing=!1,this.overlay_editor.active_cell.render_clean=[],this.DelayedRender(void 0,this.overlay_editor.selection.area)),this.editing_state=0,this.Focus(),this.overlay_editor?.CloseEditor(),this.ClearAdditionalSelections(),this.ClearSelection(this.active_selection)}NormalizeCellValue(e){let t=e.value;if(e.ValueIsNumber()&&e.style&&e.style.number_format)if(L.Get(e.style.number_format).date_format){let i=Re(e.value),n=i.getUTCHours()||i.getUTCMinutes()||i.getUTCSeconds()?"Timestamp":"Short Date";t=L.Get(n).Format(t)}else if(/(?:%|percent)/i.test(e.style.number_format)){let i=0,n=e.value.toString().match(/\.(.*?)$/);n&&n[1]&&(i=Math.max(0,n[1].length-2)),t=(e.value*100).toFixed(i)+"%",F.decimal_separator===","&&(t=t.replace(/\./,","))}else t&&F.decimal_separator===","&&(t=e.value.toString().replace(/\./,","));else{if(e.ValueIsBoolean())return e.value?this.model.language_model?.boolean_true||"TRUE":this.model.language_model?.boolean_false||"FALSE";e.ValueIsNumber()?t&&F.decimal_separator===","&&(t=e.value.toString().replace(/\./,",")):e.ValueIsComplex()?(e.value.imaginary?e.value.real?t=`${e.value.real.toString()}${e.value.imaginary<0?" - ":" + "}${e.value.imaginary===1||e.value.imaginary===-1?"":Math.abs(e.value.imaginary).toString()}i`:e.value.imaginary===1?t="i":e.value.imaginary===-1?t="-i":t=e.value.imaginary.toString()+"i":t=e.value.real.toString(),F.decimal_separator===","&&(t=t.replace(/\./,","))):e.ValueIsFormula()&&(t=this.model.TranslateFunction(e.value))}return t}IsNumeric(e){return e>=48&&e<=57||e===this.decimal_separator_code||e===45||e===43}OverlayEditCell(e,t=!0,r){if(!this.options.in_cell_editor)return;let i=e.target||e.area.start,n=this.active_sheet.CellData(i),o;if(this.HideHoverInfo(),n.merge_area?(o=this.layout.OffsetCellAddressToRectangle(n.merge_area.start).Combine(this.layout.OffsetCellAddressToRectangle(n.merge_area.end)),i=n.merge_area.start,n=this.active_sheet.CellData(i)):o=this.layout.OffsetCellAddressToRectangle(i),n.style?.locked){console.info("cell is locked for editing");return}o=o.Shift(this.layout.header_size.width,this.layout.header_size.height);let a=n.value,s;typeof a>"u"&&!n.style?.font_face&&(s=this.edit_state),t?(n.type===3||n.rendered_type===3)&&n.style&&n.style.number_format&&/(?:%|percent)/i.test(n.style.number_format)&&(!r||this.IsNumeric(r.key.charCodeAt(0)))?a="%":a=void 0:a=this.NormalizeCellValue(n),this.overlay_editor?.Edit(e,o.Expand(-1,-1),n,a,r,s),n.editing=!0,n.render_clean=[],this.DelayedRender(!1,e.area)}BoundAddressArea(e,t){e.column>t.end.column?(e.row=this.StepVisibleRows(e.row,1),e.row>t.end.row&&(e.row=t.start.row),e.column=t.start.column):e.column<t.start.column?(e.row=this.StepVisibleRows(e.row,-1),e.row<t.start.row&&(e.row=t.end.row),e.column=t.end.column):e.row>t.end.row?(e.column=this.StepVisibleColumns(e.column,1),e.column>t.end.column&&(e.column=t.start.column),e.row=t.start.row):e.row<t.start.row&&(e.column=this.StepVisibleColumns(e.column,-1),e.column<t.start.column&&(e.column=t.end.column),e.row=t.end.row)}StepVisibleRows(e,t){if(t>0)for(let r=0;r<t;r++)this.layout.RowHeight(++e)||r--;else if(t<0)for(let r=0;r>t;r--)--e>=0&&!this.layout.RowHeight(e)&&r++;return e}StepVisibleColumns(e,t){if(t>0)for(let r=0;r<t;r++)this.layout.ColumnWidth(++e)||r--;else if(t<0)for(let r=0;r>t;r--)--e>=0&&!this.layout.ColumnWidth(e)&&r++;return e}EnsureAddress(e,t=8,r=!1){let i=!1;if(this.options.expand){if(e.row!==1/0&&e.row>=this.active_sheet.rows){let n=this.active_sheet.rows;for(;e.row>=n;)n+=t;this.active_sheet.cells.EnsureRow(n),i=!0}if(e.column!==1/0&&e.column>=this.active_sheet.columns){let n=this.active_sheet.columns;for(;e.column>=n;)n+=t;this.active_sheet.cells.EnsureColumn(n),i=!0}i&&!r&&(this.layout.UpdateTiles(),this.layout.UpdateContentsSize(),this.Repaint(!0,!0))}return i}AdvanceSelection(e,t,r=!1,i=!1,n=!0){let o=this.SelectingArgument();if(t.empty)if(o){let a={row:Math.max(0,this.StepVisibleRows(this.primary_selection.target.row,e.rows)),column:Math.max(0,this.StepVisibleColumns(this.primary_selection.target.column,e.columns))};this.Select(t,new v(a))}else this.Select(t,new v({row:0,column:0}));else{let a=this.active_sheet.CellData(t.target);if(a.merge_area&&r&&(r=!a.merge_area.Equals(t.area)),r&&t.area.count>1){let s=this.active_sheet.RealArea(t.area),c=t.target;for(;;){c.row=this.StepVisibleRows(c.row,e.rows),c.column=this.StepVisibleColumns(c.column,e.columns),this.BoundAddressArea(c,s);let d=this.active_sheet.CellData(c);if(!d.merge_area||d.merge_area.start.row===c.row&&d.merge_area.start.column===c.column)break}this.Select(t,s,c)}else if(i&&t&&t.target){let s=t.area,c=t.target,d=s.start,u=s.end,h={row:1/0,column:1/0};if(e.columns&&(s.columns===1?e.columns>0?(u.column=this.StepVisibleColumns(u.column,1),h.column=u.column):(d.column=this.StepVisibleColumns(d.column,-1),h.column=d.column):s.end.column>c.column?(u.column=this.StepVisibleColumns(u.column,e.columns),h.column=u.column):s.start.column<c.column&&(d.column=this.StepVisibleColumns(d.column,e.columns),h.column=d.column),u.column=Math.max(0,u.column),d.column=Math.max(0,d.column)),e.rows&&(s.rows===1?e.rows>0?(u.row=this.StepVisibleRows(u.row,1),h.row=u.row):(d.row=this.StepVisibleRows(d.row,-1),h.row=d.row):s.end.row>c.row?(u.row=this.StepVisibleRows(u.row,e.rows),h.row=u.row):s.start.row<c.row&&(d.row=this.StepVisibleRows(d.row,e.rows),h.row=d.row),u.row=Math.max(0,u.row),d.row=Math.max(0,d.row)),this.options.expand){for(let f of[d,u,h])f.row!==1/0&&(f.row=Math.max(0,f.row)),f.column!==1/0&&(f.column=Math.max(0,f.column));this.EnsureAddress(u)&&(n=!0),this.ScrollIntoView(h),this.Select(t,new v(d,u),void 0,!0)}else{for(let f of[d,u,h])f.row!==1/0&&(f.row=Math.max(0,Math.min(f.row,this.active_sheet.rows-1))),f.column!==1/0&&(f.column=Math.max(0,Math.min(f.column,this.active_sheet.columns-1)));this.ScrollIntoView(h),this.Select(t,new v(d,u),void 0,!0)}}else{let s=t.target;a.merge_area?(e.columns<0?s.column=this.StepVisibleColumns(a.merge_area.start.column,-1):e.columns>0&&(s.column=this.StepVisibleColumns(a.merge_area.end.column,1)),e.rows<0?s.row=this.StepVisibleRows(a.merge_area.start.row,-1):e.rows>0&&(s.row=this.StepVisibleRows(a.merge_area.end.row,1))):(s.row=this.StepVisibleRows(s.row,e.rows),s.column=this.StepVisibleColumns(s.column,e.columns)),this.EnsureAddress(s)&&(n=!0),this.Select(t,new v({row:Math.min(Math.max(0,s.row),this.active_sheet.rows-1),column:Math.min(Math.max(0,s.column),this.active_sheet.columns-1)})),this.RenderSelections(),this.ScrollIntoView(t.target)}}this.SelectingArgument()&&this.UpdateSelectedArgument(t),n&&this.DelayedRender()}HighlightDependencies(e,t=!0){let r=0;e:for(let i of e)if((i.start.row===1/0||i.start.row<this.active_sheet.rows)&&(i.start.column===1/0||i.start.column<this.active_sheet.columns)){if(i.start.spill&&i.end.row===i.start.row&&i.end.column===i.start.column){let a=this.model.sheets.Find(i.start.sheet_id||-1)?.CellData(i.start);a?.spill&&a.spill.start.row===i.start.row&&a.spill.start.column===i.start.column&&i.ConsumeArea(a.spill)}i=this.active_sheet.RealArea(i);let n=i.spreadsheet_label;if(this.additional_selections[r]&&this.additional_selections[r].area.spreadsheet_label===n)r++;else{for(let o=0;o<r;o++)if(this.additional_selections[o].area.spreadsheet_label===n&&this.additional_selections[o].area.start.sheet_id===i.start.sheet_id)continue e;this.additional_selections[r++]={target:i.start,area:i}}}this.additional_selections.splice(r),t&&this.RenderSelections(!1)}ClearAdditionalSelections(){this.additional_selections.splice(0,this.additional_selections.length)}ClearSelection(e){this.Select(e)}HideGridSelection(){this.UpdateAddressLabel(void 0,"");let e=this.selected_annotation&&this.selected_annotation.data.formula?this.selected_annotation.data.formula:"";this.UpdateFormulaBarFormula(e),this.layout.ShowSelections(!1)}ShowGridSelection(){this.UpdateAddressLabel(),this.UpdateFormulaBarFormula(),this.layout.ShowSelections(!0)}Select(e,t,r,i=!1){if(e.empty||i&&(r=e.target),t){let n=this.active_sheet.RealArea(t);r||(r=n.start);e:for(;;){for(let s of this.active_sheet.cells.Iterate(n,!1))if(s.merge_area&&!n.ContainsArea(s.merge_area)){t.ConsumeArea(s.merge_area),n=this.active_sheet.RealArea(t);continue e}break}e.area=new v({...t.start,sheet_id:this.active_sheet.id},t.end),r&&(e.target={...r,sheet_id:this.active_sheet.id}),e.empty=!1;let o=this.active_sheet.CellData(e.target),a="";o.formatted&&(typeof o.formatted=="string"?a=o.formatted:a=o.formatted.map(s=>s.flag===1||s.flag===6?"":s.text).join("")),this.overlay_editor?.UpdateCaption(a)}else e.empty=!0;e===this.primary_selection&&(j.is_edge&&this.Focus(),this.grid_events.Publish({type:"selection",selection:this.primary_selection}),this.UpdateAddressLabel(),this.UpdateFormulaBarFormula(),this.formula_bar&&(this.formula_bar.target_address={...this.primary_selection.target}),this.options.stats&&this.UpdateStats())}UpdateFormulaBarFormula(e){if(this.layout.HideDropdownCaret(),e){this.formula_bar&&(this.formula_bar.shadow=!1,this.formula_bar.formula=e);return}if(this.primary_selection.empty)this.formula_bar&&(this.formula_bar.shadow=!1,this.formula_bar.formula="");else{let t=this.active_sheet.CellData(this.primary_selection.target),r=t.merge_area||t.area||t.spill,i=!1;r&&(r.start.column!==this.primary_selection.target.column||r.start.row!==this.primary_selection.target.row)&&(t=this.active_sheet.CellData(r.start),t.spill&&(i=!0)),this.formula_bar&&(this.formula_bar.editable=!t.style?.locked);let n=this.NormalizeCellValue(t),o=this.active_sheet.GetValidation(this.primary_selection.target)[0];if(o&&!t.style?.locked){let a;o.type==="list"?a=o.list:o.type==="range"&&(a=this.GetValidationRange(o.area)),a&&a.length&&this.layout.ShowDropdownCaret(t.merge_area||new v(this.primary_selection.target),a,t.value)}this.formula_bar&&(this.formula_bar.shadow=i,t.area?this.formula_bar.formula="{"+(n||"")+"}":this.formula_bar.formula=(n??"").toString())}}RenderStats(e){if(!Array.isArray(e))return[];let t=0,r=0,i={real:0,imaginary:0};for(let o of e)for(let a of o)typeof a=="number"?(i.real+=a,r++):he(a)&&(i.real+=a.real,i.imaginary+=a.imaginary,r++),typeof a<"u"&&t++;let n=o=>{let a=Math.floor(Math.log10(o));return a<-6||a>10?L.Get("Exponential"):a<=-1?L.Get("General"):L.Get("Number")};if(t>1)if(r>0){let o=L.Get("General");if(i.imaginary){let a={real:i.real/r,imaginary:i.imaginary/r};return[{label:"Count",value:t.toString()},{label:"Sum",value:de.FormatPartsAsText(o.FormatComplex(i))},{label:"Average",value:de.FormatPartsAsText(o.FormatComplex(a))}]}else return[{label:"Count",value:t.toString()},{label:"Sum",value:n(i.real).Format(i.real)},{label:"Average",value:n(i.real/r).Format(i.real/r)}]}else return[{label:"Count",value:t.toString()}];return[]}UpdateStats(){if(this.tab_bar){let e=[];typeof this.options.stats=="function"?this.primary_selection.empty||(e=this.options.stats.call(void 0,this.GetRange(this.primary_selection.area))):!this.primary_selection.empty&&this.primary_selection.area.count>1&&(e=this.RenderStats(this.GetRange(this.primary_selection.area))),this.tab_bar.stats_data=e}}UpdateAddressLabelArea(e){!e.empty&&!e.area.entire_sheet&&(e.area.entire_column?this.UpdateAddressLabel(void 0,e.area.columns+"C"):e.area.entire_row?this.UpdateAddressLabel(void 0,e.area.rows+"R"):e.area.count>1?this.UpdateAddressLabel(void 0,e.area.rows+"R x "+e.area.columns+"C"):this.UpdateAddressLabel(e))}UpdateAddressLabel(e=this.primary_selection,t){if(this.formula_bar)if(typeof t<"u")this.formula_bar.label=t;else if(e.empty)this.formula_bar.label="";else{let r=this.active_sheet.CellData(this.primary_selection.target),i=new v(r.merge_area?r.merge_area.start:e.target);this.formula_bar.label=this.model.named.MatchSelection(e.area,i)||v.CellAddressToLabel(i.start)}}OnDropdownSelect(e){if(typeof e<"u"){let i=_e.TryParse(e.toString());i.type===3&&(e=i.value)}let t=this.active_sheet.CellData(this.primary_selection.target),r=t.merge_area?t.merge_area.start:this.primary_selection.target;this.ExecCommand({key:6,area:r,value:e}),this.UpdateFormulaBarFormula()}OnScroll(){let e=this.layout.VisibleTiles();e.Equals(this.render_tiles)||(this.render_tiles=e,this.layout_token||(this.layout_token=requestAnimationFrame(()=>this.Repaint())))}AttachListeners(){if(!this.container)throw new Error("invalid container");this.container.addEventListener("copy",this.HandleCopy.bind(this)),this.container.addEventListener("cut",this.HandleCut.bind(this)),this.container.addEventListener("paste",this.HandlePaste.bind(this)),this.layout.grid_cover.addEventListener("mousedown",e=>this.MouseDown_Grid(e)),this.layout.column_header_cover.addEventListener("mousedown",e=>this.MouseDown_ColumnHeader(e)),this.layout.row_header_cover.addEventListener("mousedown",e=>this.MouseDown_RowHeader(e)),this.layout.column_header_cover.addEventListener("mousemove",e=>this.MouseMove_ColumnHeader(e)),this.layout.row_header_cover.addEventListener("mousemove",e=>this.MouseMove_RowHeader(e)),this.layout.grid_cover.addEventListener("mousemove",e=>this.MouseMove_Grid(e)),this.overlay_editor?.edit_node.addEventListener("keydown",e=>this.OverlayKeyDown(e)),this.layout.corner.addEventListener("dblclick",()=>{this.SelectAll()}),window.addEventListener("resize",()=>{this.layout.UpdateDPR()&&(this.QueueLayoutUpdate(),this.Repaint(!0,!0,!0))})}HandleCopy(e){if(e.stopPropagation(),e.preventDefault(),this.primary_selection.empty){if(e.clipboardData&&e.clipboardData.clearData(),this.selected_annotation&&e.clipboardData){let t=JSON.stringify({data:this.selected_annotation,source:this.active_sheet.id});e.clipboardData.setData("text/x-treb-annotation",t);let r=this.selected_annotation.view[this.view_index];if(r&&r.node){let i=r.node.firstChild?.firstChild;if(i){let n=Vi(i).outerHTML;e.clipboardData.setData("text/uri-list","data:image/svg+xml;base64,"+btoa(n)),e.clipboardData.setData("text/html",n),e.clipboardData.setData("text/plain",n)}}}}else{let t=this.active_sheet.RealArea(this.primary_selection.area),r=[],i=[];if(this.primary_selection.area.entire_column)for(let d=t.start.column;d<=t.end.column;d++){let u=this.active_sheet.GetColumnWidth(d);u!==this.active_sheet.default_column_width&&(r[d-t.start.column]=u)}if(this.primary_selection.area.entire_row)for(let d=t.start.row;d<=t.end.row;d++){let u=this.active_sheet.GetRowHeight(d);u!==this.active_sheet.default_row_height&&(i[d-t.start.row]=u)}let n=t.columns,o=t.rows,a=[],s=[];for(let d=0;d<o;d++){let u=[];for(let h=0;h<n;h++){let f={row:t.start.row+d,column:t.start.column+h},m=this.active_sheet.CellData(f),p="";m.calculated!==void 0?m.calculated_type===8?p=Xe(m.calculated):p=m.calculated.toString():m.type===8?p=Xe(m.value):p=m.value?.toString()||"",u.push(p);let b={address:f,data:m.value,type:m.type,style:this.active_sheet.GetCopyStyle(f)};m.area&&m.area.start.row===f.row&&m.area.start.column===f.column&&(b.array={rows:m.area.rows,columns:m.area.columns}),s.push(JSON.parse(JSON.stringify(b)))}a.push(u)}let c=a.map(d=>d.join(" ")).join(`
10
- `);e.clipboardData&&(e.clipboardData.clearData(),e.clipboardData.setData("text/plain",c),e.clipboardData.setData("text/x-treb",JSON.stringify({source:t,data:s,column_width:r,row_height:i})))}}HandleCut(e){if(e.stopPropagation(),e.preventDefault(),this.HandleCopy(e),this.primary_selection.empty)this.selected_annotation&&this.RemoveAnnotation(this.selected_annotation);else{let t=this.active_sheet.RealArea(this.primary_selection.area);this.ExecCommand({key:12,area:t})}}RecyclePasteAreas(e,t){let r=[];if(e.count===1)for(let i=t.start.row;i<=t.end.row;i++)for(let n=t.start.column;n<=t.end.column;n++)r.push(new v({row:i,column:n}));else if(e.columns===t.columns&&t.rows>=e.rows&&t.rows%e.rows===0)for(let i=t.start.row;i<=t.end.row;i+=e.rows)r.push(new v({row:i,column:t.start.column},{row:i+e.rows-1,column:t.end.column}));else if(e.rows===t.rows&&t.columns>=e.columns&&t.columns%e.columns===0)for(let i=t.start.column;i<=t.end.column;i+=e.columns)r.push(new v({column:i,row:t.start.row},{column:i+e.columns-1,row:t.end.row}));else r.push(t.Clone().Resize(e.rows,e.columns));return r}HandlePaste(e){if(this.overlay_editor?.editing||(e.stopPropagation(),e.preventDefault(),!e.clipboardData))return;let t=e.clipboardData.getData("text/x-treb-annotation");if(t){try{let o=JSON.parse(t);if(o.source&&o.source!==this.active_sheet.id&&o.data&&o.data.formula){let a="",s=this.model.sheets.Find(o.source);if(s&&(a=s.name),a){let c=this.parser.Parse(o.data.formula);c.expression&&(this.parser.Walk(c.expression,d=>d.type==="range"?(!d.start.sheet_id&&!d.start.sheet&&(d.start.sheet=a),!1):(d.type==="address"&&!d.sheet_id&&!d.sheet&&(d.sheet=a),!0)),o.data.formula="="+this.parser.Render(c.expression,{missing:""}))}}this.CreateAnnotation(o.data,void 0,!0,!0,void 0,!0)}catch(o){console.error(o)}return}if(this.primary_selection.empty)return;let r=this.active_sheet.RealArea(this.primary_selection.area),i=[],n=e.clipboardData.getData("text/x-treb");if(n)try{let o=JSON.parse(n),a=new v(o.source.start,o.source.end),s=this.RecyclePasteAreas(a,r);if(s.length===1&&r.Resize(s[0].rows,s[0].columns),!this.ValidatePasteAreas(s)){this.Error(5);return}let c=[];for(let d of s){this.active_sheet.cells.EnsureCell(d.end),i.push({key:12,area:d});let u={rows:d.start.row-a.start.row,columns:d.start.column-a.start.column};if(o.data.forEach(h=>{let f=h.data,m={row:h.address.row-a.start.row+d.start.row,column:h.address.column-a.start.column+d.start.column};if(h.type===1){let p=this.parser.Parse(f);p.expression&&(f="="+this.parser.Render(p.expression,{offset:u,missing:""}))}if(h.array){let p={start:{...m},end:{row:m.row+h.array.rows-1,column:m.column+h.array.columns-1}},b={key:6,value:f,array:!0,area:p};c.push(new v(p.start,p.end)),i.push(b)}else{let p=!1;for(let b of c)if(b.Contains(m)){p=!0;break}p||i.push({key:6,value:f,area:m})}i.push({key:7,style:h.style||{},area:m})}),o.column_width?.length){for(let[h,f]of o.column_width.entries())if(typeof f=="number"){let m=h+d.start.column;i.push({key:4,column:m,width:f})}}if(o.row_height?.length){for(let[h,f]of o.row_height.entries())if(typeof f=="number"){let m=h+d.start.row;i.push({key:3,row:m,height:f})}}}}catch(o){console.error("invalid treb data on clipboard"),console.info(o);return}else{let o=e.clipboardData.getData("text/plain");if(!o)return!0;let s=o.trim().split(`
11
- `).map(d=>d.split(" ").map(u=>u.trim())),c=this.RecyclePasteAreas(new v({row:0,column:0},{row:s.length-1,column:s[0].length-1}),r);if(c.length===1&&(r.Resize(s.length,s[0].length),r.Resize(c[0].rows,c[0].columns)),!this.ValidatePasteAreas(c)){this.Error(5);return}for(let d of c)for(let u=0;u<s.length;u++)for(let h=0;h<s[0].length;h++){let f=new v({row:u+d.start.row,column:h+d.start.column});if(this.active_sheet.cells.EnsureCell(f.end),s[u][h]){let m=this.SetInferredType({area:f,target:f.start,empty:!1},s[u][h],!1,!1);if(m)for(let p of m)i.push(p)}else{let m=this.active_sheet.cells.GetCell(f.start,!1);m&&m.type!==0&&i.push({key:12,area:f.Clone()})}}}this.ExecCommand(i),this.Select(this.primary_selection,r)}AllSelections(e=!1){let t=[this.primary_selection,this.active_selection].concat(this.additional_selections);return e?t:t.filter(r=>!r.empty)}InsertRowsInternal(e){let t=super.InsertRowsInternal(e);if(t.error)return t;let r=this.FindSheet(e.sheet_id);if(r===this.active_sheet){if(e.count<0)for(let i of this.AllSelections())i.empty=!0;else for(let i of this.AllSelections())i.target.row>=e.before_row&&(i.target.row+=e.count),i.area.entire_column||(i.area.start.row>=e.before_row?i.area.Shift(e.count,0):i.area.end.row>=e.before_row&&i.area.ConsumeAddress({row:i.area.end.row+e.count,column:i.area.end.column}));for(let i of t.delete_annotations_list||[])this.layout.RemoveAnnotation(i);if(this.QueueLayoutUpdate(),this.Repaint(),t.update_annotations_list?.length){this.layout.UpdateAnnotation(t.update_annotations_list,this.theme);for(let i of t.resize_annotations_list||[]){let n=i.view[this.view_index];n?.resize_callback&&n.resize_callback.call(void 0)}}}else this.pending_layout_update.add(r.id);return t}InsertColumnsInternal(e){let t=super.InsertColumnsInternal(e);if(t.error)return t;let r=this.FindSheet(e.sheet_id);if(r===this.active_sheet){if(e.count<0)for(let i of this.AllSelections())i.empty=!0;else for(let i of this.AllSelections())i.target.column>=e.before_column&&(i.target.column+=e.count),i.area.entire_row||(i.area.start.column>=e.before_column?i.area.Shift(0,e.count):i.area.end.column>=e.before_column&&i.area.ConsumeAddress({row:i.area.end.row,column:i.area.end.column+e.count}));for(let i of t.delete_annotations_list||[])this.layout.RemoveAnnotation(i);if(this.tile_renderer?.FlushOverflows(),this.QueueLayoutUpdate(),this.DelayedRender(!0,void 0,!0),t.update_annotations_list?.length){this.layout.UpdateAnnotation(t.update_annotations_list,this.theme);for(let i of t.resize_annotations_list||[]){let n=i.view[this.view_index];n?.resize_callback&&n.resize_callback.call(void 0)}}}else this.pending_layout_update.add(r.id);return t}ResetInternal(){super.ResetInternal(),this.RemoveAnnotationNodes(),this.ClearSelection(this.primary_selection),this.ScrollIntoView({row:0,column:0}),this.QueueLayoutUpdate(),this.layout.HideNote()}ResizeColumnsInternal(e){if(this.headless)return super.ResizeColumnsInternal(e);let t=e.sheet_id?this.FindSheet(e.sheet_id):this.active_sheet,r=e.column;if(typeof r>"u"){r=[];for(let o=0;o<t.columns;o++)r.push(o)}typeof r=="number"&&(r=[r]);let i=typeof e.width!="number",n=Math.round((e.width||0)/this.scale);if(i)for(let o of r)this.AutoSizeColumn(t,o,!0);else for(let o of r)t.SetColumnWidth(o,n);t===this.active_sheet?(this.layout.UpdateTotalSize(),this.layout.container&&this.layout.container.offsetWidth&&this.layout.container.offsetWidth>this.layout.total_width?this.UpdateLayout():(this.layout.UpdateTileWidths(!0),this.render_tiles=this.layout.VisibleTiles(),this.Repaint(!1,!0)),this.layout.UpdateAnnotation(this.active_sheet.annotations,this.theme),this.RenderSelections()):this.pending_layout_update.add(t.id)}ResizeRowsInternal(e){let t,r=e.sheet_id?this.FindSheet(e.sheet_id):this.active_sheet,i=e.row;if(typeof i>"u"){i=[];for(let s=0;s<r.rows;s++)i.push(s)}typeof i=="number"&&(i=[i]);let n=typeof e.shrink=="boolean"?e.shrink:!0,o=typeof e.height!="number",a=Math.round(e.height||0/this.scale);if(o)for(let s of i)r.GetRowHeight(s)||(t?t.ConsumeAddress({row:s,column:1}):t=new v({row:s,column:1/0,sheet_id:r.id})),this.AutoSizeRow(r,s,n);else for(let s of i){let c=r.GetRowHeight(s);(!c&&a||c&&!a)&&(t?t.ConsumeAddress({row:s,column:1}):t=new v({row:s,column:1/0,sheet_id:r.id})),r.SetRowHeight(s,a)}return r===this.active_sheet?(this.layout.UpdateTotalSize(),this.layout.container&&this.layout.container.offsetHeight&&this.layout.container.offsetHeight>this.layout.total_height?this.UpdateLayout():(this.layout.UpdateTileHeights(!0),this.render_tiles=this.layout.VisibleTiles(),this.Repaint(!1,!0)),this.layout.UpdateAnnotation(this.active_sheet.annotations,this.theme),this.RenderSelections()):this.pending_layout_update.add(r.id),t?{start:t.start,end:t.end}:void 0}SelectInternal(e){e.area?(e.area.start.sheet_id&&e.area.start.sheet_id!==this.active_sheet.id&&this.ActivateSheetInternal({key:22,id:e.area.start.sheet_id}),this.Select(this.primary_selection,new v(e.area.start,e.area.end)),this.RenderSelections()):this.ClearSelection(this.primary_selection)}FreezeInternal(e){let t=this.FindSheet(e.sheet_id||this.active_sheet.id),r=(typeof e.highlight_transition=="boolean"?e.highlight_transition:!0)&&t===this.active_sheet;if(e.rows===t.freeze.rows&&e.columns===t.freeze.columns){r&&this.HighlightFreezeArea();return}t.freeze.rows=e.rows,t.freeze.columns=e.columns,t===this.active_sheet?(this.QueueLayoutUpdate(),this.Repaint(),r&&this.HighlightFreezeArea(),e.rows||e.columns?this.layout.CloneFrozenAnnotations():this.layout.ClearFrozenAnnotations()):this.pending_layout_update.add(t.id)}ExecCommand(e,t=!0){let r=super.ExecCommand(e,t);this.batch||r.render_area&&this.DelayedRender(!1,r.render_area),r.repaint&&this.Repaint();for(let i of r.pending||[])this.pending_layout_update.add(i);return r.layout&&this.QueueLayoutUpdate(),r.sheets&&this.tab_bar&&this.tab_bar.Update(),r.formula&&this.UpdateFormulaBarFormula(),r}};var Xi=["default","old-style","transitional","handwritten","monospace","industrial","ui"],qt={default:"Sans-serif","old-style":"Old style",transitional:"Serif",handwritten:"Handwritten",monospace:"Monospace",industrial:"Industrial sans",ui:"System UI"},Wi=new Map,Wr=(l,e)=>{let t=e.fontFamily,r="",i=t.split(/,/);for(let u of i){u=u.replace(/'"/g,"").trim();let h=u.toLowerCase();if(j.is_firefox&&/sitka text/i.test(h))continue;let f=Wi.get(h);if(typeof f>"u"&&(f=ae.FontLoaded(u),Wi.set(h,f)),f){r=u;break}}r||console.warn("no font found for font stack",l);let n=r.toLowerCase().replace(/['"]/g,"").replace(/\W+/g,"-"),o=e.getPropertyValue("--treb-font-stack-default-size"),a=e.getPropertyValue(`--treb-font-stack-${n}-size`),s=e.getPropertyValue(`--treb-font-stack-${n}-variant`),c=I.ParseFontSize(a||o||"10pt").font_size||{unit:"pt",value:10};return{family:t,font:r,variants:s,size:c}};var jt={grid_color:"#ccc",note_marker_color:"#d2c500",mode:"light",offset_cache:{},offset_light:"#fff",offset_dark:"#000",font_stacks:{},grid_cell_font_size:{value:10,unit:"pt"}},Zo=(l,e)=>{let t=Pr(e),r=e.tint||0;l.mode==="dark"&&(r=-r),l.tint_cache||(l.tint_cache=[]),l.tint_cache[t]||(l.tint_cache[t]={});let i=l.tint_cache[t][r];if(!i){let n=(l.theme_colors_rgb?l.theme_colors_rgb[t]:[0,0,0])||[0,0,0],o;r>0?o=W.Lighten(n[0],n[1],n[2],r*100,!0):o=W.Darken(n[0],n[1],n[2],-r*100,!0),i=`rgb(${o.r},${o.g},${o.b})`,l.tint_cache[t][r]=i}return i},D=(l,e,t)=>{if(e&&e.offset){if(e.offset.offset)return console.warn("invalid offset color"),"";let r="";if(ee(e.offset)){let n=ae.MeasureColor(e.offset.text);r=`rgb(${n[0]}, ${n[1]}, ${n[2]})`}else r=D(l,e.offset,void 0);if(l.offset_cache&&l.offset_cache[r])return l.offset_cache[r];let i=l.offset_light;if(r){let n=r.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(n){let o=[Number(n[1]),Number(n[2]),Number(n[3])],a=Array.from(ae.MeasureColor(l.offset_dark)),s=Array.from(ae.MeasureColor(l.offset_light)),c=W.GetTextColor(o,a,s);i=`rgb(${c[0]}, ${c[1]}, ${c[2]})`}else console.warn("can't offset against color",r,"(1)");l.offset_cache||(l.offset_cache={}),l.offset_cache[r]=i}else console.warn("can't resolve offset color",e.offset,"(2)");return i}return ee(e)?e.text==="none"?"":e.text:Ke(e)?e.tint?Zo(l,e):l.theme_colors?l.theme_colors[Pr(e)]:"":(t||t===0)&&l.theme_colors?l.theme_colors[t]:""},ea=l=>{let e=10,t="pt",r=l.match(/^([\d.]+)(\D.*)$/);return r&&(e=Number(r[1]),t=r[2]),{value:e,unit:t}},Ki=(l,e=!1)=>{let t={fill:{text:l.backgroundColor},text:{text:l.color},font_size:{unit:"em",value:1}};return e&&(t.font_face=l.fontFamily),/italic/i.test(l.font)&&(t.italic=!0),l.fontWeight==="700"&&(t.bold=!0),t},ta=(l,e)=>{let t=l.grid_cell?.text,r=l.grid_cell?.fill;e.fillStyle=ee(t)?t.text:"",e.fillRect(0,0,3,3);let i=W.RGBToHSL(...Array.from(e.getImageData(1,1,1,1).data));e.fillStyle=ee(r)?r.text:"",e.fillRect(0,0,3,3);let n=W.RGBToHSL(...Array.from(e.getImageData(1,1,1,1).data));return i.l>n.l?"dark":"light"},Jt=(l,e=.7)=>{let t={border_top:1,border_top_fill:{theme:l},border_bottom:1,border_bottom_fill:{theme:l}};return{header:{text:{offset:{theme:l}},fill:{theme:l},bold:!0,...t},odd:{fill:{theme:l,tint:e},...t},even:{...t},total:{...t,border_top:2}}},Ji=(l,e=!1)=>{let t=JSON.parse(JSON.stringify(jt)),r=O.GetInstance(l.ownerDocument),i=(h,f)=>r.Div(f,h),n=(h,f)=>r.view?.getComputedStyle(i(h,f)),o=i(l,""),a=n.bind(0,o),s=a("grid-cells");if(t.grid_cell=Ki(s,!1),t.grid_color=s.stroke||"",t.grid_cell_font_size=ea(s.fontSize||""),e)for(let h of Xi)s=a(`treb-font-stack-${h}`),t.font_stacks[h]=Wr(h,s);else s=a("treb-font-stack-default"),t.font_stacks.default=Wr("default",s);s=a("grid-headers"),t.headers=Ki(s,!0),t.headers_grid_color=s.stroke,(!t.headers_grid_color||t.headers_grid_color==="none")&&(t.headers_grid_color=t.grid_color),s=a("treb-offset-dark"),s.color&&(t.offset_dark=s.color),s=a("treb-offset-light"),s.color&&(t.offset_light=s.color),s=a("note-marker"),t.note_marker_color=s.backgroundColor,o.style.color="rgba(1,2,3,.4)",s=a("");let c=s.color;t.theme_colors=[ee(t.grid_cell.fill)?t.grid_cell.fill.text:"rgb(255, 255, 255)",ee(t.grid_cell.text)?t.grid_cell.text.text:"rgb(51, 51, 51)"];for(let h=1;h<32&&(s=a(`theme-color-${h}`),!(!s.color||s.color===c));h++)t.theme_colors.push(s.color);let d=r.Create("canvas");d.width=3,d.height=3;let u=d.getContext("2d",{willReadFrequently:!0});return u&&(t.mode=ta(t,u)),u&&(t.theme_colors_rgb=t.theme_colors.map(h=>{u.fillStyle=h,u.fillRect(0,0,3,3);let f=u.getImageData(1,1,1,1);return Array.from(f.data)})),t.table=Jt(4),o.parentElement?.removeChild(o),t};var qi={column:0,type:"auto",asc:!0};var Wt=class{constructor(e,t,r="RGB"){this.color_space=r;this.mapped=e.map(i=>{if(i.value<0||i.value>1)throw new Error("invalid stop value");let n=ae.MeasureColor(D(t,i.color)),o=[];if(r==="HSL"){let a=W.RGBToHSL(n[0],n[1],n[2]);o=[a.h,a.s,a.l]}else o=[...n];return{...i,resolved:o}}),this.mapped.sort((i,n)=>i.value-n.value),this.mapped[0].value>0&&this.mapped.unshift({...this.mapped[0],value:0}),this.mapped[this.mapped.length-1].value<1&&this.mapped.push({...this.mapped[this.mapped.length-1],value:1})}mapped;RenderColor(e){return this.color_space==="RGB"?{text:`rgb(${e})`}:{text:`hsl(${e[0]},${e[1]*100}%,${e[2]*100}%)`}}Interpolate(e){e=Math.min(1,Math.max(0,e));for(let[t,r]of this.mapped.entries()){if(e===r.value)return this.RenderColor(r.resolved);if(e<r.value){let i=this.mapped[t-1],n=r,o=n.value-i.value,a=e-i.value,s=[0,1,2].map(c=>i.resolved[c]+(n.resolved[c]-i.resolved[c])/o*a);return this.RenderColor(s)}}return{text:""}}};var Xt={};co(Xt,{Iterate:()=>ra});function*ra(l){if(l.start.row===1/0||l.end.row===1/0)throw new Error("don't iterate infinite area");let e=l.start.sheet_id;for(let t=l.start.row;t<=l.end.row;t++)for(let r=l.start.column;r<=l.end.column;r++)yield{row:t,column:r,sheet_id:e}}var Kt=class{constructor(e){this.parser=e}named=new Map;get list(){return this.named.values()}SetNamedExpression(e,t,r){return this.SetName({type:"expression",name:e,expression:t,scope:r})}SetNamedRange(e,t,r){return this.SetName({type:"range",name:e,area:new v(t.start,t.end),scope:r})}SetName(e){let t=e.name;return this.ValidateNamed(t)?(this.named.set(this.ScopedName(t,e.scope),e),!0):(console.warn("invalid name",{name:t}),!1)}ScopedName(e,t){return typeof t=="number"?t+":"+e.toLowerCase():e.toLowerCase()}ClearName(e,t){typeof t=="number"?this.named.delete(this.ScopedName(e,t)):this.named.delete(e.toLowerCase())}RemoveRangesForSheet(e){let t=[];for(let[r,i]of this.named)(i.type==="range"&&i.area.start.sheet_id===e||i.scope===e)&&t.push(r);for(let r of t)this.named.delete(r)}Reset(){this.named.clear()}Get_(e,t,r=!1){return r?this.named.get(this.ScopedName(e,t)):this.named.get(this.ScopedName(e,t))??this.named.get(e.toLowerCase())}ValidateNamed(e){return e=e.trim().toUpperCase(),!e.length||/[^A-Z\d_.?]/.test(e)||/^[^A-Z_]/.test(e)||e==="R"||e==="C"||/^[A-Z]{1,3}[1-9]\d*$/.test(e)||/^R[[\]\d]+C/.test(e)?!1:e}MatchSelection(e,t){if(!e.start.sheet_id)throw new Error("match selection without sheet id");let r;for(let i of this.named.values())if(i.type==="range"&&i.area.start.sheet_id===e.start.sheet_id&&(e.Equals(i.area)&&(r=i.name),t?.Equals(i.area)))return i.name;return r}PatchNamedRanges(e,t,r,i,n){let o=[...this.list];for(let a of o){if(a.type==="expression")continue;let s=a.name,c=a.area;if(c.start.sheet_id!==e){console.info("skipping name",s);continue}if(r&&t<=c.end.column){if(r>0)t<=c.start.column?c.Shift(0,r):t>c.start.column&&t<=c.end.column?c.ConsumeAddress({row:c.end.row,column:c.end.column+r}):console.warn("PNR X case 1",t,r,JSON.stringify(c));else if(r<0)if(t-r<=c.start.column)c.Shift(0,r);else if(t<=c.start.column&&t-r>c.end.column)this.ClearName(s);else if(t<=c.start.column){let d=t-r-1;this.SetName({type:"range",area:new v({row:c.start.row,column:d+1+r,sheet_id:e},{row:c.end.row,column:c.end.column+r}),name:s})}else t<=c.end.column?t-r-1>=c.end.column?this.SetName({type:"range",area:new v({row:c.start.row,column:c.start.column,sheet_id:e},{row:c.end.row,column:t-1}),name:s}):this.SetName({type:"range",name:s,area:new v({row:c.start.row,column:c.start.column,sheet_id:e},{row:c.end.row,column:c.start.column+c.columns+r-1})}):console.warn("PNR X case 2",t,r,JSON.stringify(c))}if(n&&i<=c.end.row){if(n>0)i<=c.start.row?c.Shift(n,0):i>c.start.row&&i<=c.end.row?c.ConsumeAddress({row:c.end.row+n,column:c.end.column}):console.warn("PNR X case 3",i,n,JSON.stringify(c));else if(n<0)if(i-n<=c.start.row)c.Shift(n,0);else if(i<=c.start.row&&i-n>c.end.row)this.ClearName(s);else if(i<=c.start.row){let d=i-n-1;this.SetNamedRange(s,new v({column:c.start.column,row:d+1+n,sheet_id:e},{column:c.end.column,row:c.end.row+n}))}else i<=c.end.row?i-n-1>=c.end.row?this.SetNamedRange(s,new v({column:c.start.column,row:c.start.row,sheet_id:e},{column:c.end.column,row:i-1})):this.SetNamedRange(s,new v({column:c.start.column,row:c.start.row,sheet_id:e},{column:c.end.column,row:c.start.row+c.rows+n-1})):console.warn("PNR X case 4",i,n,JSON.stringify(c))}}}};var _t=class{parser=new We;language_model;document_name;user_data;sheets=new St;named=new Kt(this.parser);macro_functions=new Map;view_count=0;theme_style_properties=JSON.parse(JSON.stringify(I.DefaultProperties));tables=new Map;GetName(e,t){let r=e.split(/!/);if(r.length===1)return this.named.Get_(e,t);let i=r[0];/^'.*?'$/.test(i)&&(i=i.substring(1,i.length-1));let n=this.sheets.ID(i);return this.named.Get_(r[1],n||0,!1)}UnserializeNames(e,t,r=!1){this.parser.Save(),r&&this.parser.SetLocaleSettings(".",",");for(let i of e){if(!i.expression)continue;let n=this.parser.Parse(i.expression);if(n.expression){let o=typeof i.scope=="string"?this.sheets.ID(i.scope):void 0;if(n.expression.type==="address"||n.expression.type==="range"){let[a,s]=n.expression.type==="range"?[n.expression.start,n.expression.end]:[n.expression,n.expression];if(a.sheet)if(/^\[\d+\]/.test(a.sheet))console.warn("named range refers to an external file");else{let c=new v({...a,sheet_id:this.sheets.ID(a.sheet)},s);c.start.sheet_id?this.named.SetNamedRange(i.name,c,o):console.warn("missing sheet ID?",a)}else console.warn("missing sheet name?",a)}else this.parser.Walk(n.expression,a=>a.type==="address"||a.type==="range"?(a.type==="range"&&(a=a.start),a.sheet_id||a.sheet&&(a.sheet_id=this.sheets.ID(a.sheet)),a.sheet_id||(a.sheet_id=t?.id),!1):!0),this.named.SetNamedExpression(i.name,n.expression,o)}}this.parser.Restore()}SerializeNames(e){let t=[];for(let r of this.named.list){let i={name:r.name,expression:"",type:r.type};if(r.scope&&(i.scope=this.sheets.Name(r.scope)),r.type==="expression")this.parser.Walk(r.expression,n=>{if(n.type==="address"||n.type==="range"){let o=n.type==="range"?n.start:n;return o.absolute_column=o.absolute_row=!0,o.sheet||(o.sheet_id&&(o.sheet=this.sheets.Name(o.sheet_id)),o.sheet||(o.sheet=e?.name)),n.type==="range"&&(n.end.absolute_column=n.end.absolute_row=!0),!1}return!0}),i.expression=this.parser.Render(r.expression,{missing:""});else{let n={start:{...r.area.start,absolute_column:!0,absolute_row:!0},end:{...r.area.end,absolute_column:!0,absolute_row:!0}};i.expression=this.AddressToLabel(n)}t.push(i)}return t}ResolveStructuredReference(e,t){let r;if(e.table?r=this.tables.get(e.table.toLowerCase()):t.sheet_id&&(r=this.sheets.Find(t.sheet_id)?.CellData(t)?.table),!r)return;let i=e.column.toLowerCase(),n=-1;if(r.columns){for(let o=0;o<r.columns.length;o++)if(i===r.columns[o]){n=r.area.start.column+o;break}}if(!(n<0))if(e.scope==="row"){let o=t.row;return o<r.area.start.row||o>r.area.end.row?void 0:{label:e.label,type:"address",row:o,column:n,sheet_id:r.area.start.sheet_id,id:e.id,position:e.position}}else{let o=r.area.start.row,a=r.area.end.row;return e.scope==="column"&&(o++,r.totals_row&&a--),{label:e.label,type:"range",position:e.position,id:e.id,start:{type:"address",row:o,column:n,sheet_id:r.area.start.sheet_id,label:e.label,position:e.position,id:0},end:{type:"address",row:a,column:n,label:e.label,position:e.position,id:0}}}}AddressToLabel(e){let t=N(e)?e:e.start,r=N(e)?[v.CellAddressToLabel(e)]:[v.CellAddressToLabel(e.start),v.CellAddressToLabel(e.end)],i=this.sheets.Find(t.sheet_id||0),n=i?.name?Ce.test(i.name)?`'${i.name}'`:i.name:"";return n+(n?"!":"")+(r[0]===r[1]?r[0]:r.join(":"))}ResolveSheetID(e,t,r){let i=e.type==="address"?e:e.start;if(i.sheet_id)return!0;if(i.sheet){let n=this.sheets.Find(i.sheet);if(n)return i.sheet_id=n.id,!0}else{if(t?.sheet_id)return i.sheet_id=t.sheet_id,!0;if(r?.id)return i.sheet_id=r.id,!0}return!1}ResolveArea(e,t,r){let i=this.ResolveAddress(e,t,r);return N(i)?new v(i):new v(i.start,i.end)}ResolveAddress(e,t,r){if(typeof e=="string"){r?.r1c1&&(this.parser.Save(),this.parser.flags.r1c1=!0);let i=this.parser.Parse(e);if(r?.r1c1&&this.parser.Restore(),i.expression&&i.expression.type==="address")return this.ResolveSheetID(i.expression,void 0,t),{row:i.expression.row,column:i.expression.column,sheet_id:i.expression.sheet_id};if(i.expression&&i.expression.type==="range")return this.ResolveSheetID(i.expression,void 0,t),{start:{row:i.expression.start.row,column:i.expression.start.column,sheet_id:i.expression.start.sheet_id},end:{row:i.expression.end.row,column:i.expression.end.column}};if(i.expression&&i.expression.type==="identifier"){let n=this.GetName(i.expression.name,t.id);if(n?.type==="range")return n.area}return{row:0,column:0}}return e}AddConnectedElement(e){let t=this.connected_element_id++;return this.connected_elements.set(t,e),t}RemoveConnectedElement(e){let t=this.connected_elements.get(e);return this.connected_elements.delete(e),t}connected_element_id=100;connected_elements=new Map;language_map;reverse_language_map;SetLanguageMap(e){if(!e)this.language_map=this.reverse_language_map=void 0;else{let t=Object.keys(e);this.language_map={};for(let r of t)this.language_map[r.toUpperCase()]=e[r];this.reverse_language_map={};for(let r of t){let i=e[r];this.reverse_language_map[i.toUpperCase()]=r}}}TranslateFunction(e,t){return this.language_map?this.TranslateInternal(e,this.language_map,this.language_model?.boolean_true,this.language_model?.boolean_false,t):e}UntranslateFunction(e,t){return this.reverse_language_map?this.TranslateInternal(e,this.reverse_language_map,"TRUE","FALSE",t):e}UntranslateData(e,t){return Array.isArray(e)?Tt(e)?e.map(r=>r.map(i=>i&&typeof i=="string"&&i[0]==="="?this.UntranslateFunction(i,t):i)):e.map(r=>r&&typeof r=="string"&&r[0]==="="?this.UntranslateFunction(r,t):r):(e&&typeof e=="string"&&e[0]==="="&&(e=this.UntranslateFunction(e,t)),e)}TranslateInternal(e,t,r,i,n){this.parser.Save(),this.parser.flags.r1c1=n?.r1c1;let o=this.parser.Parse(e);if(o.expression){let a=!1;if(this.parser.Walk(o.expression,s=>{if(s.type==="call"){let c=t[s.name.toUpperCase()];c&&(a=!0,s.name=c)}else s.type==="literal"&&typeof s.value=="boolean"&&(a=!0);return!0}),a)return"="+this.parser.Render(o.expression,{missing:"",boolean_true:r,boolean_false:i,r1c1:n?.r1c1})}return this.parser.Restore(),e}SetLanguage(e){if(this.language_model=e,!e)this.SetLanguageMap(),this.parser.flags.boolean_true="TRUE",this.parser.flags.boolean_false="FALSE";else{let t={};if(e.functions)for(let r of e.functions||[])t[r.base.toUpperCase()]=r.name;this.SetLanguageMap(t),e.boolean_false||(e.boolean_false=t.FALSE),e.boolean_true||(e.boolean_true=t.TRUE),this.parser.flags.boolean_true=e.boolean_true||"TRUE",this.parser.flags.boolean_false=e.boolean_false||"FALSE"}for(let t of this.sheets.list)t.FlushCellStyles()}};var Yi=()=>({target:{row:0,column:0},area:new v({row:0,column:0}),empty:!0});var ia=100,Qi={move_with_cells:!0,resize_with_cells:!0,movable:!0,resizable:!0,removable:!0,selectable:!0},Ne=class{data={...Qi};get key(){return this.key_}rect;scaled_rect;temp={};view=[];dirty;key_=ia++;constructor(e={}){this.data={...Qi,...JSON.parse(JSON.stringify(e))},e.rect&&(this.rect=B.Create(e.rect))}toJSON(){return{...this.data,rect:this.rect}}};var na=100,Zi=60,re=class l{static base_id=100;static default_sheet_name="Sheet1";default_style_properties;annotations=[];freeze={rows:0,columns:0};visible=!0;default_column_width=100;default_row_height=25;cells=new Et;selection=Yi();scroll_offset={x:0,y:0};name=l.default_sheet_name;tab_color;background_image;_image=void 0;flush_conditional_formats=!1;get image(){return this._image}conditional_formats=[];data_validation=[];outline;id_;row_height_map=new Map;column_width_=[];row_headers=[];column_headers=[];row_header_width=100;column_header_height=25;style_map=[];style_json_map=[];sheet_style={};row_styles={};column_styles={};row_pattern=[];cell_style=[];conditional_format_cache=[];conditional_format_checklist=[];get header_offset(){return{x:this.row_header_width,y:this.column_header_height}}get rows(){return this.cells.rows}get columns(){return this.cells.columns}get id(){return this.id_}set id(e){this.id_=e,this.id>=l.base_id&&(l.base_id=this.id+1)}constructor(e){this.default_style_properties=e,this.default_column_width=na,this.row_header_width=Zi,this.id_=l.base_id++}static Reset(){this.base_id=100}static Blank(e,t,r=30,i=20,n){let o=new l(e);return n&&o.UpdateDefaultRowHeight(n),t&&(o.name=t),r=Math.max(r,1),i=Math.max(i,1),o.cells.EnsureCell({row:r-1,column:i-1}),o}static UpdateStyle(e){if(typeof e.horizontal_align=="number"){let t=["","left","center","right"];e.horizontal_align=t[e.horizontal_align]||void 0}if(typeof e.vertical_align=="number"){let t=["","top","bottom","middle"];e.vertical_align=t[e.vertical_align]||void 0}}static FromJSON(e,t,r){let i=typeof e=="string"?JSON.parse(e):e,n=(c,d)=>{Object.keys(d).forEach(u=>{let h=Number(u)||0;c[h]=d[u]})};r||(r=new l(t)),i.default_column_width&&(r.default_column_width=i.default_column_width),i.default_row_height&&(r.default_row_height=i.default_row_height),i.conditional_formats&&(r.conditional_formats=i.conditional_formats),r.data_validation=(i.data_validations||[]).map(c=>({...c,target:(c.target||[]).map(d=>new v(d.start,d.end))})),i.id&&(r.id=i.id),i.name&&(r.name=i.name),i.tab_color&&(r.tab_color=i.tab_color),i.background_image&&(r.background_image=i.background_image);let o=c=>{let d=c;this.UpdateStyle(d),(d.font_size_value||d.font_size_unit)&&(d.font_size={unit:d.font_size_unit||"pt",value:d.font_size_value||10},d.font_size_unit=void 0,d.font_size_value=void 0),d.font_bold&&(d.bold=!0,d.font_bold=void 0),d.font_italic&&(d.italic=!0,d.font_italic=void 0),d.font_underline&&(d.underline=!0,d.font_underline=void 0),d.font_strike&&(d.strike=!0,d.font_strike=void 0),d.text_color&&(d.text_color!=="none"&&(d.text={text:d.text_color}),d.text_color=void 0),d.background&&(d.background!=="none"&&(d.fill={text:d.background}),d.background=void 0),d.border_top_color&&(d.border_top_color!=="none"&&(d.border_top_fill={text:d.border_top_color}),d.border_top_color=void 0),d.border_left_color&&(d.border_left_color!=="none"&&(d.border_left_fill={text:d.border_left_color}),d.border_left_color=void 0),d.border_bottom_color&&(d.border_bottom_color!=="none"&&(d.border_bottom_fill={text:d.border_bottom_color}),d.border_bottom_color=void 0),d.border_right_color&&(d.border_right_color!=="none"&&(d.border_right_fill={text:d.border_right_color}),d.border_right_color=void 0)},a=i.styles||i.cell_style_refs||[];for(let c of a)o(c);if(r.cell_style=[],a&&(i.cell_styles||[]).forEach(c=>{typeof c.ref=="number"&&(c.style=JSON.parse(JSON.stringify(a[c.ref])))}),r.cells.FromJSON(i.data),i.rows&&r.cells.EnsureRow(i.rows-1),i.columns&&r.cells.EnsureColumn(i.columns-1),i.data)if(ht(i.data))for(let c of i.data)c.style_ref&&(r.cell_style[c.column]||(r.cell_style[c.column]=[]),r.cell_style[c.column][c.row]=JSON.parse(JSON.stringify(a[c.style_ref])));else if(Nr(i.data))for(let c of i.data){let d=c.row;for(let u of c.cells){let h=u.column;u.style_ref&&(r.cell_style[h]||(r.cell_style[h]=[]),r.cell_style[h][d]=JSON.parse(JSON.stringify(a[u.style_ref])))}}else for(let c of i.data){let d=c.column;for(let u of c.cells){let h=u.row;u.style_ref&&(r.cell_style[d]||(r.cell_style[d]=[]),r.cell_style[d][h]=JSON.parse(JSON.stringify(a[u.style_ref])))}}r.freeze.rows=0,r.freeze.columns=0,i.freeze&&(r.freeze.rows=i.freeze.rows||0,r.freeze.columns=i.freeze.columns||0),r.scroll_offset=i.scroll?{...i.scroll}:{x:0,y:0};for(let c of i.cell_styles||[])if(c.style&&(r.cell_style[c.column]||(r.cell_style[c.column]=[]),r.cell_style[c.column][c.row]=c.style,c.rows))for(let d=1;d<c.rows;d++)r.cell_style[c.column][c.row+d]=JSON.parse(JSON.stringify(c.style));r.sheet_style=i.sheet_style||{},r.column_styles={},r.row_styles={};let s=(c,d)=>{for(let u of Object.keys(c)){let h=Number(u),f=c[h];if(typeof f=="number"){let m=a[f];m&&(d[h]=JSON.parse(JSON.stringify(m)),o(d[h]))}else f&&(d[h]=f,o(d[h]))}};s(i.row_style,r.row_styles),s(i.column_style,r.column_styles),r.row_pattern=i.row_pattern||[],o(r.sheet_style||{});for(let c of r.row_pattern)o(c);if(r.row_height_map=new Map,i.row_height)for(let[c,d]of Object.entries(i.row_height))r.row_height_map.set(Number(c),d);if(r.row_height_map.size>0){let c=Math.max(...r.row_height_map.keys());r.cells.EnsureRow(c)}return r.column_width_=[],n(r.column_width_,i.column_width||{}),r.column_width_.length&&r.cells.EnsureColumn(r.column_width_.length-1),r.annotations=(i.annotations||[]).map(c=>new Ne(c)),i.selection&&(r.selection=JSON.parse(JSON.stringify(i.selection))),r.visible=!0,typeof i.visible<"u"&&(r.visible=!!i.visible),r}AddValidation(e){this.data_validation.push({...e,target:(e.target||[]).map(t=>new v(t.start,t.end))})}RemoveValidations(e){let t=new v(e.start,e.end);this.data_validation=this.data_validation.filter(r=>(r.target=r.target.filter(i=>!t.Equals2(i)),r.target.length>0))}GetValidation(e){let t=[];for(let r of this.data_validation)for(let i of r.target)if(i.Contains(e)){t.push(r);break}return t}Activate(e){if(this.background_image){let t=Mt(this.background_image);t&&(this._image=e.Create("img"),this._image.src=t)}}MergeCells(e){e=e.Clone();let t=[...this.cells.Iterate(e,!0)];for(let[r,i]of t.entries())i.merge_area=e,i.render_clean=[],r&&i.Reset()}UnmergeCells(e){for(let t of this.cells.Iterate(e,!1))if(!t.merge_area||!e.Equals(t.merge_area)){console.warn("area mismatch");return}for(let t of this.cells.Iterate(e,!1))t.merge_area=void 0,t.render_clean=[]}UpdateDefaultRowHeight(e,t=1){if(typeof window<"u"){let r=I.Composite([this.default_style_properties,this.sheet_style]),i=I.CompositeFont(e.grid_cell_font_size,r,t,e),o=Ge(i.font,i.variants).height*1.25;this.default_row_height<o&&(this.default_row_height=o)}}SetRowHeaders(e){this.row_headers=e.map(t=>t===void 0?"":t.toString()),this.row_headers&&this.cells.EnsureRow(this.row_headers.length-1)}SetColumnHeaders(e){this.column_headers=e.map(t=>t===void 0?"":t.toString()),e&&this.cells.EnsureColumn(e.length-1)}RowHeader(e){return this.row_headers?this.row_headers.length>e?this.row_headers[e]:"":e+1}ColumnHeader(e){let t="";if(this.column_headers)return this.column_headers.length>e?this.column_headers[e]:"";for(;;){let r=e%26;if(t=String.fromCharCode(65+r)+t,e=Math.floor(e/26),e)e--;else break}return t}GetRowHeight(e){let t=this.row_height_map.get(e);return typeof t>"u"?this.default_row_height:t}SetRowHeight(e,t){return this.row_height_map.set(e,t),this.cells.EnsureRow(e),t}GetColumnWidth(e){let t=this.column_width_[e];return typeof t>"u"?this.default_column_width:t}SetColumnWidth(e,t){return this.column_width_[e]=t,this.cells.EnsureColumn(e),t}Delta(e,t){let r={},i=[...Object.keys(e),...Object.keys(t)];for(let n of i){let o=e[n],a=t[n];typeof o=="object"&&typeof a=="object"?JSON.stringify(o)!==JSON.stringify(a)&&(r[n]=a):o!==a&&(r[n]=a)}return r}UpdateCellStyle(e,t,r=!0){let{row:i,column:n}=e;this.cell_style[n]||(this.cell_style[n]=[]);let o=this.CompositeStyleForCell(e,!1,!1,void 0,!1),a=I.Composite([this.default_style_properties,o,I.Merge(this.cell_style[n][i]||{},t,r)]),s=this.Delta(o,a);this.cell_style[n][i]=s,this.BleedFlush({start:e,end:e})}Invalidate(e){for(let t of this.cells.Iterate(this.RealArea(e),!1))t.render_clean=[]}UpdateAreaStyle(e,t={},r=!0){if(e)if(e.entire_sheet)this.UpdateSheetStyle(t,r);else if(e.entire_column)for(let i=e.start.column;i<=e.end.column;i++)this.UpdateColumnStyle(i,t,r);else if(e.entire_row)for(let i=e.start.row;i<=e.end.row;i++)this.UpdateRowStyle(i,t,r);else for(let i of e)this.UpdateCellStyle(i,t,r)}HasCellStyle(e){return!!(this.cell_style[e.column]&&this.cell_style[e.column][e.row]||this.row_styles[e.row]||this.column_styles[e.column]||this.row_pattern.length)}NextVisibleColumn(e){for(++e;this.column_width_[e]===0;e++);return e}PreviousVisibleColumn(e){for(--e;e>=0&&this.column_width_[e]===0;e--);return e}NextVisibleRow(e){for(++e;this.GetRowHeight(e)===0;e++);return e}PreviousVisibleRow(e){for(--e;e>=0&&this.GetRowHeight(e)===0;e--);return e}TableRow(e,t){let r={alternate:!1,header:t===e.area.start.row,last:!1,totals:e.totals_row&&t===e.area.end.row};if(r.header||r.totals)return r;if(!(e.totals_row&&this.GetRowHeight(e.area.end.row)>0)){let a=e.area.end.row;for(;a>=e.area.start.row;a--)if(this.GetRowHeight(a)){r.last=a===t;break}}let n=e.area.start.row+1,o=t-n;for(let[a,s]of this.row_height_map.entries())if(!(a<n)){if(a>e.area.end.row)break;s||o--}return r.alternate=o%2===1,r}SurroundingStyle(e,t){let r=[{},{},{},{},{},{},{},{},{},{}],i=e.column+1,n=e.column-1,o=e.row+1,a=e.row-1;for(;this.column_width_[i]===0;i++);for(;this.GetRowHeight(o)===0;o++);for(;n>=0&&this.column_width_[n]===0;n--);for(;a>=0&&this.GetRowHeight(a)===0;a--);return n>=0&&a>=0&&(r[7]=this.CellStyleData({row:a,column:n},t)||{}),n>=0&&(r[4]=this.CellStyleData({row:e.row,column:n},t)||{},r[1]=this.CellStyleData({row:o,column:n},t)||{}),a>=0&&(r[8]=this.CellStyleData({row:a,column:e.column},t)||{},r[9]=this.CellStyleData({row:a,column:i},t)||{}),r[6]=this.CellStyleData({row:e.row,column:i},t)||{},r[2]=this.CellStyleData({row:o,column:e.column},t)||{},r[3]=this.CellStyleData({row:o,column:i},t)||{},r}CellStyleData(e,t){let r=this.cells.GetCell(e);if(r){if(!r.style){let i=this.GetStyleIndex(this.CompositeStyleForCell(e));r.style=this.style_map[i]}if(r.table){let i=r.table.theme||t;if(i){let n=JSON.parse(JSON.stringify(r.style)),o=this.TableRow(r.table,e.row);return o.header?i.header&&(n=I.Composite([n,i.header])):o.totals?i.total&&(n=I.Composite([n,i.total])):o.alternate?i.odd&&(n=I.Composite([n,i.odd])):i.even&&(n=I.Composite([n,i.even])),n}}return r.style}}GetCopyStyle(e){return this.CompositeStyleForCell(e,!0,!1,void 0,!1)}CellData(e){let t=this.cells.EnsureCell(e);if(t.rendered_type)return t;let r,i;if(t.calculated_type?(i=t.calculated,r=t.calculated_type):(i=t.value,r=t.type),!t.style){let n=this.GetStyleIndex(this.CompositeStyleForCell(e));t.style=this.style_map[n]}if(!r||i===null||typeof i>"u")t.formatted="",t.rendered_type=2;else if(r===3)isNaN(i)?t.formatted=typeof t.style.nan>"u"?"NaN":t.style.nan:t.formatted=this.FormatNumber(i,t.style.number_format),t.rendered_type=3;else if(r===7)t.formatted="#"+(i||"ERR?"),t.rendered_type=7;else if(r===4)t.formatted=i.toString().toUpperCase(),t.rendered_type=4;else if(r===1&&t.calculated===void 0)t.formatted="",t.rendered_type=2;else if(r===8){let n=i;if(isNaN(n.real)||isNaN(n.imaginary))t.formatted=typeof t.style.nan>"u"?"NaN":t.style.nan;else{let o=L.Get(t.style.number_format||"",!0);t.formatted=o.FormatComplex(n)}t.rendered_type=8}else if(r===10){if(isNaN(i.value))t.formatted=typeof t.style.nan>"u"?"NaN":t.style.nan,t.formatted+=" "+i.unit;else{let n=L.Get(t.style.number_format||"",!0);t.formatted=n.FormatDimensionedQuantity(i)}t.rendered_type=10}else r===6?(t.formatted="\u{1D453}()",t.rendered_type=2):(t.formatted=this.FormatNumber(i,t.style.number_format),t.rendered_type=2);return t}FormatNumber(e,t=""){let r=L.Get(t).FormatParts(e);return r.length?r.length===1&&!r[0].flag?r[0].text||"":r:""}SetHeaderSize(e=Zi,t=this.default_row_height){this.row_header_width=e,this.column_header_height=t}GetStyle(e){return this.style_map[e]}InsertRows(e=0,t=1){if(e)for(let c=0;c<this.cells.columns;c++){let d=this.cells.GetCell({row:e-1,column:c},!1);if(d&&d.area){let u=this.cells.GetCell({row:e,column:c},!1);if(u&&u.area&&u.area.Equals(d.area))return!1}}t<0?this.cells.DeleteRows(e,-t):this.cells.InsertRows(e,t);let r={},i={};for(let c=e;c<this.cells.rows;c++)for(let d=0;d<this.cells.columns;d++){let u=this.cells.GetCell({row:c,column:d},!1);u&&(u.area&&!i[u.area.spreadsheet_label]&&(i[u.area.spreadsheet_label]=u.area),u.merge_area&&!r[u.merge_area.spreadsheet_label]&&(r[u.merge_area.spreadsheet_label]=u.merge_area))}for(let c of Object.keys(i)){let d=i[c],u=new v({row:d.start.row+t,column:d.start.column},{row:d.end.row+t,column:d.end.column});for(let h of u){let f=this.cells.GetCell(h,!0);f.area=u}}for(let c of Object.keys(r)){let d=r[c],u={row:d.start.row,column:d.start.column};d.start.row>=e&&(u.row+=t);let h=new v(u,{row:d.end.row+t,column:d.end.column});for(let f of h){let m=this.cells.GetCell(f,!0);m.merge_area=h}}let n=Object.keys(this.row_styles),o={};n.forEach(c=>{let d=Number(c);d<e?o[d]=this.row_styles[d]:t<0&&d<e-t||(o[d+t]=this.row_styles[d])}),this.row_styles=o;let a=[];if(t<0)a=[e,-t];else{a=[e,0];for(let c=0;c<t;c++)a.push(void 0)}this.cell_style.forEach(c=>{c&&c.length>=e&&c.splice.apply(c,a)});let s=new Map;if(t>0)for(let[c,d]of this.row_height_map)c>=e?s.set(c+t,d):s.set(c,d);else if(t<0)for(let[c,d]of this.row_height_map)c>=e?c>=e-t&&s.set(c+t,d):s.set(c,d);return this.row_height_map=s,this.FlushCellStyles(),!0}InsertColumns(e=0,t=1){if(e)for(let s=0;s<this.cells.rows;s++){let c=this.cells.GetCell({row:s,column:e-1},!1);if(c&&c.area){let d=this.cells.GetCell({row:s,column:e},!1);if(d&&d.area&&d.area.Equals(c.area))return!1}}t<0?this.cells.DeleteColumns(e,-t):this.cells.InsertColumns(e,t);let r={},i={};for(let s=e;s<this.cells.columns;s++)for(let c=0;c<this.cells.rows;c++){let d=this.cells.GetCell({row:c,column:s},!1);d&&(d.area&&!i[d.area.spreadsheet_label]&&(i[d.area.spreadsheet_label]=d.area),d.merge_area&&!r[d.merge_area.spreadsheet_label]&&(r[d.merge_area.spreadsheet_label]=d.merge_area))}for(let s of Object.keys(i)){let c=i[s],d=new v({row:c.start.row,column:c.start.column+t},{row:c.end.row,column:c.end.column+t});for(let u of d){let h=this.cells.GetCell(u,!0);h.area=d}}for(let s of Object.keys(r)){let c=r[s],d={row:c.start.row,column:c.start.column};c.start.column>=e&&(d.column+=t);let u=new v(d,{row:c.end.row,column:c.end.column+t});for(let h of u){let f=this.cells.GetCell(h,!0);f.merge_area=u}}let n=Object.keys(this.column_styles),o={};n.forEach(s=>{let c=Number(s);c<e?o[c]=this.column_styles[c]:t<0&&c<e-t||(o[c+t]=this.column_styles[c])}),this.column_styles=o;let a=[];if(t<0)a=[e,-t];else{a=[e,0];for(let s=0;s<t;s++)a.push(void 0)}return this.cell_style.splice.apply(this.cell_style,a),this.column_width_.splice.apply(this.column_width_,a),this.FlushCellStyles(),!0}ClearArea(e){for(let t of this.cells.Iterate(this.RealArea(e),!1))t.Reset()}SetAreaValues2(e,t){e=this.RealArea(e),this.cells.SetArea(e,t)}SetArrayValue(e,t){e=this.RealArea(e);for(let i of this.cells.Iterate(e,!0))i.SetArray(e);this.cells.GetCell(e.start,!0).SetArrayHead(e,t)}SetCellValue(e,t){this.cells.GetCell(e,!0).Set(t)}TablesFromArea(e,t=!1){if(N(e)){let i=this.cells.GetCell(e,!1);return i?.table&&(!t||e.row===i.table.area.start.row)?[i.table]:[]}let r=new Set;for(let i=e.start.row;i<=e.end.row;i++)for(let n=e.start.column;n<=e.end.column;n++){let o=this.cells.GetCell({row:i,column:n},!1);o?.table&&!r.has(o.table)&&(!t||i===o.table.area.start.row)&&r.add(o.table)}return Array.from(r.values())}RealArea(e,t=!1){let r=e.start,i=e.end;return e.entire_row&&(r.column=0,r.absolute_column=!1,i.column=this.cells.columns-1,i.absolute_column=!1),e.entire_column&&(r.row=0,r.absolute_row=!1,i.row=this.cells.rows-1,i.absolute_row=!1),t&&(i.row>=this.rows&&(i.row=this.rows-1,i.absolute_row=!1),i.column>=this.columns&&(i.column=this.columns-1,i.absolute_column=!1)),new v(r,i)}GetCellStyle(e,t=!1){if(N(e))return this.CompositeStyleForCell(e,!0,!1,t);if(e.start.row===e.end.row&&e.start.column===e.end.column)return[[this.CompositeStyleForCell(e.start,!0,!1,t)]];let r=[];for(let i=e.start.row;i<=e.end.row;i++){let n=[];for(let o=e.start.column;o<=e.end.column;o++)n.push(this.CompositeStyleForCell({row:i,column:o},!0,!1,t));r.push(n)}return r}FormattedCellValue(e){let t=this.CellData(e);if(t)return typeof t.formatted=="string"?t.formatted:t.formatted?t.formatted.map(r=>{switch(r.flag){case 1:return" ";case 2:return" ";default:return r.text}}).join(""):t.value}GetFormattedRange(e,t=e){if(e.row===t.row&&e.column===t.column)return this.FormattedCellValue(e);let r=[];for(let i=e.row;i<=t.row;i++){let n=[];for(let o=e.column;o<=t.column;o++)n.push(this.FormattedCellValue({row:i,column:o}));r.push(n)}return r}NumberFormatsAndColors(e,t){let r=i=>{i.number_format&&(t[i.number_format]=1),ee(i.text)&&(e[i.text.text]=1),ee(i.fill)&&(e[i.fill.text]=1),ee(i.border_top_fill)&&(e[i.border_top_fill.text]=1),ee(i.border_left_fill)&&(e[i.border_left_fill.text]=1),ee(i.border_right_fill)&&(e[i.border_right_fill.text]=1),ee(i.border_bottom_fill)&&(e[i.border_bottom_fill.text]=1)};r(this.sheet_style);for(let i in this.row_styles)r(this.row_styles[i]);for(let i in this.column_styles)r(this.column_styles[i]);for(let i of this.row_pattern)r(i);for(let i of this.cell_style)if(i)for(let n of i)n&&r(n)}CompressCellStyles(e){let t=[];for(let r=0;r<e.length;r++){let i=e[r];if(i)for(let n=0;n<i.length;n++){let o=i[n];if(o){let a=n+1;for(;a<i.length&&i[a]===o;a++);a>n+1?t.push({row:n,column:r,ref:o,rows:a-n}):t.push({row:n,column:r,ref:o}),n=a-1}}}return t}toJSON(e={}){let t=(S,A)=>{let E={};for(let R=0;R<S.length;R++)typeof S[R]<"u"&&S[R]!==A&&(E[R]=S[R]);if(Object.keys(E).length)return E},r=[{}],i={},n=[],o=JSON.stringify({});for(let S=0;S<this.cell_style.length;S++){let A=this.cell_style[S];if(A){n[S]=[];for(let E=0;E<A.length;E++)if(A[E]){let R=I.Serialize(A[E]);if(R!==o){let z=i[R];typeof z!="number"&&(i[R]=z=r.length,r.push(A[E])),n[S][E]=z}}}}let a=S=>{let A=I.Serialize(S);if(A===o)return 0;let E=i[A];return typeof E!="number"&&(i[A]=E=r.length,r.push(S)),E};r=JSON.parse(JSON.stringify(r));let s=JSON.parse(JSON.stringify(this.sheet_style)),c=JSON.parse(JSON.stringify(this.row_pattern)),d={},u={};for(let S of Object.keys(this.column_styles)){let A=Number(S),E=this.column_styles[A];if(E){let R=a(E);R&&(d[A]=R)}}if(this.row_pattern&&this.row_pattern.length&&e.apply_row_pattern){let S=this.rows+1;for(let A of Object.keys(this.row_styles)){let E=Number(A);!isNaN(E)&&E>=S&&(S=E+1)}for(let A=0;A<S;A++){let E=this.row_pattern[A%this.row_pattern.length],R=this.row_styles[A]||{},z=I.Composite([E,R]),K=a(z);K&&(u[A]=K)}}else for(let S of Object.keys(this.row_styles)){let A=Number(S),E=this.row_styles[A];if(E){let R=a(E);R&&(u[A]=R)}}let h=(S={},A={})=>{let E={...A,...S};if(ee(E))return E.text=ae.MeasureColorARGB(E.text),E;if(Ke(E))return E};if(e.export_colors){let S=[];for(let A of[r,[s],c])if(Array.isArray(A))for(let E of A)S.push(E);else for(let E of Object.keys(A))S.push(A[E]);for(let A of S){let E=h(A.border_top_fill,I.DefaultProperties.border_top_fill);E!==void 0&&(A.border_top_fill=E),E=h(A.border_left_fill,I.DefaultProperties.border_left_fill),E!==void 0&&(A.border_left_fill=E),E=h(A.border_right_fill,I.DefaultProperties.border_right_fill),E!==void 0&&(A.border_right_fill=E),E=h(A.border_bottom_fill,I.DefaultProperties.border_bottom_fill),E!==void 0&&(A.border_bottom_fill=E),ee(A.fill)&&(A.fill.text=ae.MeasureColorARGB(A.fill.text)),ee(A.text)&&(A.text.text=ae.MeasureColorARGB(A.text.text))}}let f={calculated_value:!!e.rendered_values,preserve_type:!!e.preserve_type,expand_arrays:!!e.expand_arrays,decorated_cells:!!e.decorated_cells,nested:!0,cell_style_refs:n,tables:!!e.tables},m=this.cells.toJSON(f),p=m.data,{rows:b,columns:g}=m;e.shrink?(b+=2,g+=1):(b=this.rows,g=this.columns);for(let S of this.annotations)S.data.extent||this.CalculateAnnotationExtent(S),S.data.extent&&(b=Math.max(b,S.data.extent.row+1),g=Math.max(g,S.data.extent.column+1));let x=this.CompressCellStyles(n),y=this.conditional_formats.length?JSON.parse(JSON.stringify(this.conditional_formats.map(S=>({...S,internal:void 0})))):void 0,w=this.data_validation.length?JSON.parse(JSON.stringify(this.data_validation)):void 0,_={};for(let[S,A]of this.row_height_map.entries())_[S]=A;let C={id:this.id,name:this.name,tab_color:this.tab_color,data:p,sheet_style:s,rows:b,columns:g,cell_styles:x,styles:r,row_style:u,column_style:d,conditional_formats:y,data_validations:w,row_pattern:c.length?c:void 0,default_row_height:this.default_row_height,default_column_width:this.default_column_width,row_height:_,column_width:t(this.column_width_,this.default_column_width),selection:JSON.parse(JSON.stringify(this.selection)),annotations:JSON.parse(JSON.stringify(this.annotations))};return this.visible||(C.visible=this.visible),(this.scroll_offset.x||this.scroll_offset.y)&&(C.scroll=this.scroll_offset),this.background_image&&(C.background_image=this.background_image),(this.freeze.rows||this.freeze.columns)&&(C.freeze=this.freeze),C}FlushCellStyles(){this.style_map=[],this.style_json_map=[],this.cells.FlushCellStyles()}ImportData(e){let t=e.styles;e.outline&&(this.outline=e.outline);let r=e.sheet_style;r&&this.UpdateAreaStyle(new v({row:1/0,column:1/0},{row:1/0,column:1/0}),t[r]);let i=e.column_styles;if(i)for(let o=0;o<i.length;o++)i[o]&&this.UpdateAreaStyle(new v({row:1/0,column:o},{row:1/0,column:o}),t[i[o]]);if(e.row_styles)for(let[o,a]of e.row_styles.entries())a&&this.UpdateAreaStyle(new v({row:o,column:1/0}),t[a]);this.cells.FromJSON(e.cells),e.name&&(this.name=e.name||"");for(let o of this.cells.Iterate())o.spill&&(o.spill.start.sheet_id||o.spill.SetSheetID(this.id));e.tab_color&&(this.tab_color=e.tab_color);let n=this.cell_style;for(let o of e.cells)o.style_ref&&(n[o.column]||(n[o.column]=[]),n[o.column][o.row]=t[o.style_ref]);for(let o=0;o<e.column_widths.length;o++)typeof e.column_widths[o]<"u"&&this.SetColumnWidth(o,e.column_widths[o]);for(let o=0;o<e.row_heights.length;o++)typeof e.row_heights[o]<"u"&&this.SetRowHeight(o,e.row_heights[o]);for(let o of e.annotations||[])this.annotations.push(new Ne(o));for(let o of e.conditional_formats||[])this.conditional_formats.push(o);for(let o of e.data_validations||[])this.AddValidation(o);e.hidden&&(this.visible=!1)}CalculateAnnotationExtent(e){if(e.data.layout){e.data.extent={...e.data.layout.br.address};return}let t=1e3;e.data.extent={row:0,column:0};let r=e.rect?.right;if(r&&this.default_column_width){for(let n=0;r>=0&&n<t;n++)if(r-=this.GetColumnWidth(n),r<0){e.data.extent.column=n;break}}let i=e.rect?.bottom;if(i&&this.default_row_height){for(let n=0;i>=0&&n<t;n++)if(i-=this.GetRowHeight(n),i<0){e.data.extent.row=n;break}}}UpdateSheetStyle(e,t=!0){this.sheet_style=I.Merge(this.sheet_style,e,t);let r=Object.keys(e);for(let i of this.cell_style)if(i)for(let n of i)n&&r.forEach(o=>delete n[o]);for(let i of Object.keys(this.row_styles))r.forEach(n=>delete this.row_styles[i][n]);for(let i of Object.keys(this.column_styles))r.forEach(n=>delete this.column_styles[i][n]);this.FlushCellStyles()}UpdateRowStyle(e,t,r=!0){this.row_styles[e]=I.Merge(this.row_styles[e]||{},t,r);let i=Object.keys(t);for(let n of this.cell_style)n&&n[e]&&i.forEach(o=>delete n[e][o]);for(let n=0;n<this.cells.columns;n++)if(this.column_styles[n]){let o=this.column_styles[n],a=this.cell_style[n]?this.cell_style[n][e]||{}:{};for(let s of i)typeof o[s]<"u"&&(a[s]=t[s]);Object.keys(a).length&&(this.cell_style[n]||(this.cell_style[n]=[]),this.cell_style[n][e]=JSON.parse(JSON.stringify(a)))}for(let n of this.cells.Iterate(this.RealArea(v.FromRow(e))))n.FlushStyle()}UpdateColumnStyle(e,t,r=!0){this.column_styles[e]=I.Merge(this.column_styles[e]||{},t,r);let i=Object.keys(t);if(this.cell_style[e])for(let n of this.cell_style[e])n&&i.forEach(o=>delete n[o]);for(let n of this.cells.Iterate(this.RealArea(v.FromColumn(e))))n.FlushStyle()}BleedFlush(e){let t=[Math.max(0,e.start.row-1),e.end.row+1],r=[Math.max(0,e.start.column-1),e.end.column+1];for(let i=t[0];i<=t[1];i++)for(let n=r[0];n<=r[1];n++)this.cells.GetCell({row:i,column:n},!1)?.FlushStyle()}FlushConditionalFormats(){this.flush_conditional_formats=!0}ApplyConditionalFormats(){let e=this.flush_conditional_formats;for(let i of this.conditional_formats)if(i.internal?.vertex?.updated){e=!0;break}if(!e)return;this.flush_conditional_formats=!1;let t=[],r=[...this.conditional_format_checklist];this.conditional_format_checklist=[];for(let i of this.conditional_formats){i.internal?.vertex?.updated&&(i.internal.vertex.updated=!1);let n=JSON.parse(JSON.stringify(i.area));(n.start.row===null||n.end.row===null)&&(n.start.row=0,n.end.row=this.cells.rows-1),(n.start.column===null||n.end.column===null)&&(n.start.column=0,n.end.column=this.cells.columns-1);let o=i.internal?.vertex?.result;if(i.type==="gradient"){if(o&&i.internal?.gradient){let a=i.property??"fill";if(o.type===9)for(let s=n.start.row;s<=n.end.row;s++)for(let c=n.start.column;c<=n.end.column;c++){let d=o.value[c-n.start.column][s-n.start.row];if(d.type===3){t[s]||(t[s]=[]),t[s][c]||(t[s][c]=[]);let u=i.internal.gradient.Interpolate(d.value);t[s][c].push({[a]:u})}}else if(o.type===3){let s=i.internal.gradient.Interpolate(o.value);for(let c=n.start.row;c<=n.end.row;c++){t[c]||(t[c]=[]);for(let d=n.start.column;d<=n.end.column;d++)t[c][d]||(t[c][d]=[]),t[c][d].push({[a]:s})}}r.push(n),this.conditional_format_checklist.push(n)}}else if(i.type==="data-bar"){if(o){if(o.type===9)for(let a=n.start.row;a<=n.end.row;a++)for(let s=n.start.column;s<=n.end.column;s++){let c=o.value[s-n.start.column][a-n.start.row];if(c.type===9){let[d,u]=c.value[0];d.type===3&&u.type===3&&(t[a]||(t[a]=[]),t[a][s]||(t[a][s]=[]),t[a][s].push({databar:{value:d.value,zero:u.value,fill:i.fill,negative:i.negative,hide_values:i.hide_values}}))}}r.push(n),this.conditional_format_checklist.push(n)}}else if(o){if(o.type===9)for(let a=n.start.row;a<=n.end.row;a++)for(let s=n.start.column;s<=n.end.column;s++){let c=o.value[s-n.start.column][a-n.start.row];c&&(c.type===4||c.type===3)&&c.value&&(t[a]||(t[a]=[]),t[a][s]||(t[a][s]=[]),t[a][s].push(i.style))}else if((o.type===4||o.type===3)&&o.value)for(let a=n.start.row;a<=n.end.row;a++){t[a]||(t[a]=[]);for(let s=n.start.column;s<=n.end.column;s++)t[a][s]||(t[a][s]=[]),t[a][s].push(i.style)}r.push(n),this.conditional_format_checklist.push(n)}}for(let i of r)this.BleedFlush(i);this.conditional_format_cache=t}ConditionalFormatForCell(e){return this.conditional_format_cache[e.row]?this.conditional_format_cache[e.row][e.column]||[]:[]}CompositeStyleForCell(e,t=!0,r=!0,i=!0,n=!0){let{row:o,column:a}=e,s=[];return i&&s.push(this.default_style_properties),s.push(this.sheet_style),r&&this.row_pattern.length&&s.push(this.row_pattern[o%this.row_pattern.length]),this.row_styles[o]&&s.push(this.row_styles[o]),this.column_styles[a]&&s.push(this.column_styles[a]),t&&this.cell_style[a]&&this.cell_style[a][o]&&s.push(this.cell_style[a][o]),n&&s.push(...this.ConditionalFormatForCell(e)),I.Composite(s)}GetStyleIndex(e){let t=JSON.stringify(e);for(let i=0;i<this.style_json_map.length;i++)if(t===this.style_json_map[i])return i;let r=this.style_map.length;return this.style_map.push(JSON.parse(t)),this.style_json_map.push(t),r}};var en={"red-green":{color_space:"RGB",stops:[{value:0,color:{theme:5,tint:.5}},{value:1,color:{theme:9,tint:.5}}]},"red-yellow-green":{color_space:"RGB",stops:[{value:0,color:{theme:5,tint:.5}},{value:.5,color:{theme:7,tint:.5}},{value:1,color:{theme:9,tint:.5}}]},"green-red":{color_space:"RGB",stops:[{value:0,color:{theme:9,tint:.5}},{value:1,color:{theme:5,tint:.5}}]},"green-yellow-red":{color_space:"RGB",stops:[{value:0,color:{theme:9,tint:.5}},{value:.5,color:{theme:7,tint:.5}},{value:1,color:{theme:5,tint:.5}}]}};var Yt=class l{static type="vertex";type=l.type;color=0;edges_in=new Set;edges_out=new Set;get has_inbound_edges(){return this.edges_in.size>0}get has_outbound_edges(){return this.edges_out.size>0}Reset(){for(let e of this.edges_out)e.RemoveDependency(this);for(let e of this.edges_in)e.RemoveDependent(this);this.edges_out.clear(),this.edges_in.clear()}ClearDependencies(){for(let e of this.edges_in)e.RemoveDependent(this);this.edges_in.clear()}AddDependent(e){e!==this&&(this.edges_out.has(e)||this.edges_out.add(e))}RemoveDependent(e){this.edges_out.delete(e)}AddDependency(e){e!==this&&(this.edges_in.has(e)||this.edges_in.add(e))}RemoveDependency(e){this.edges_in.delete(e)}LinkTo(e){this.AddDependent(e),e.AddDependency(this)}DependsOn(e){this.AddDependency(e),e.AddDependent(this)}LoopCheck(){let e=[this];for(;e.length;){let t=e[e.length-1],r=!0;if(t.color!==2){t.color=1;for(let i of t.edges_out){if(i.color===1)return this.color=0,!0;i.color===0&&i.edges_out.size&&(e.push(i),r=!1)}}r&&(t.color=2,e.pop())}return this.color=2,!1}};var Ze=class extends Yt{dirty=!1};var tn={error:"NOTIMPL"},we=()=>({type:7,value:"N/A"}),fe=()=>({type:7,value:"EXPR"});var ye=()=>({type:7,value:"DIV/0"}),U=()=>({type:7,value:"ARG"}),M=()=>({type:7,value:"VALUE"}),$=()=>({type:7,value:"REF"}),Xr=()=>({type:7,value:"NAME"}),rn=()=>({type:7,value:"SPILL"}),Qt=()=>({type:7,value:"UNK"});var ze=class l extends Ze{static type="spreadsheet-vertex";reference;error=0;address;result={type:0};expression={type:"missing",id:-1};expression_error=!1;short_circuit=!1;type=l.type;get array_head(){return this.address?!!this.reference&&!!this.reference.area&&this.reference.area.start.column===this.address.column&&this.reference.area.start.row===this.address.row:!1}TakeReferenceValue(){this.reference&&(this.result=Q(this.reference.GetValue()))}Calculate(e){if(this.dirty){if(this.color===0&&this.LoopCheck()&&(this.dirty=!1,this.edges_in.size)){this.reference&&(this.array_head||this.reference.type===1)&&this.reference.SetCalculationError("LOOP");for(let t of this.edges_out)t.Calculate(e);return}for(let t of this.edges_in)if(t.dirty)return;if(this.reference){if(this.reference.type===1){this.short_circuit=!1;let t=e.CalculationCallback.call(e,this);if(this.result=t.value,this.short_circuit)return;t.volatile&&e.volatile_list.push(this)}else this.result=this.reference.GetValue4();if(this.array_head)e.SpreadCallback.call(e,this,this.result);else if(this.reference.type===1)if(this.result.type===9){let t=e.SpillCallback.call(e,this,this.result);if(t)for(let r of t)for(let i of r.edges_out)i.dirty=!0,i.Calculate(e)}else this.reference.SetCalculatedValue(this.result.value,this.result.type)}else console.info("skip dirty constant? [or dangling...]");this.dirty=!1;for(let t of this.edges_out)t.dirty&&e.calculation_list.push(t)}}};var Be=class l extends Ze{static type="array-vertex";static list=[];type=l.type;area;static GetVertex(e){for(let t of this.list)if(t.area.start.sheet_id===e.start.sheet_id&&t.area.Equals(e))return[t,!1];return[new l(e),!0]}static Clear(){this.list=[]}static GetContainingArrays(e){let t=[];for(let r of this.list)r.area.start.sheet_id===e.sheet_id&&r.area.Contains(e)&&t.push(r);return t}static CreateImplicitEdges(e,t){for(let r of this.list)r.area.start.sheet_id===t.sheet_id&&r.area.Contains(t)&&r.DependsOn(e)}constructor(e){super(),this.area=e.Clone(),l.list.push(this)}RemoveDependent(e){super.RemoveDependent(e),this.edges_out.size||(this.Reset(),l.list=l.list.filter(t=>t!==this))}Calculate(e){if(this.dirty){if(this.color===0&&this.LoopCheck()&&(this.dirty=!1,this.edges_in.size)){for(let t of this.edges_out)t.Calculate(e);return}for(let t of this.edges_in)if(t.dirty)return;this.dirty=!1;for(let t of this.edges_out)t.Calculate(e)}}};var er=class{vertices=[[]];volatile_list=[];calculation_list=[];spill_data=[];loop_hint;leaf_vertices=new Set;dirty_list=[];loop_check_required=!1;IsSpreadsheetVertex(e){return e.type===ze.type}FlushTree(){this.dirty_list=[],this.volatile_list=[],this.vertices=[[]],this.leaf_vertices.clear(),Be.Clear()}ResolveArrayHead(e){if(!e.sheet_id)throw new Error("resolve array head with no sheet id");let t=this.model.sheets.Find(e.sheet_id)?.cells;if(!t)throw new Error("no cells? sheet id "+e.sheet_id);let r=t.data[e.row];if(r){let i=r[e.column];if(i&&i.area){let n={row:i.area.start.row,column:i.area.start.column,sheet_id:e.sheet_id};return console.info("array head",e,n),n}}return e}*IterateVertices(e,t=!1){for(let r of Xt.Iterate(e)){let i=this.GetVertex(r,t);i&&(yield i)}}GetVertex(e,t){if(!e.sheet_id)throw console.info(JSON.stringify({address:e,create:t})),console.trace(),new Error("getvertex with no sheet id");let r=this.model.sheets.Find(e.sheet_id)?.cells;if(!r)throw new Error("no cells? sheet id "+e.sheet_id);if(!this.vertices[e.sheet_id]){if(!t)return;this.vertices[e.sheet_id]=[]}if(this.vertices[e.sheet_id][e.column]){let n=this.vertices[e.sheet_id][e.column][e.row];if(n)return n;if(!t)return}else{if(!t)return;this.vertices[e.sheet_id][e.column]=[]}let i=new ze;return i.address={row:e.row,column:e.column,absolute_row:e.absolute_row,absolute_column:e.absolute_column,sheet_id:e.sheet_id},i.reference=r.EnsureCell(e),this.vertices[e.sheet_id][e.column][e.row]=i,Be.CreateImplicitEdges(i,e),i}RemoveVertex(e){if(!e.sheet_id)throw new Error("removevertex with no sheet id");let t=this.GetVertex(e,!1);t&&(t.Reset(),this.vertices[e.sheet_id][e.column][e.row]=void 0)}ResetVertex(e){let t=this.GetVertex(e,!1);t&&t.Reset()}RIBcount=0;ResetInbound(e,t=!1,r=!0,i=!1){this.RIBcount++;let n=this.GetVertex(e,r);if(!n){if(t){let a=Be.GetContainingArrays(e);for(let s of a)this.SetVertexDirty(s)}return}let o=[];if(i&&(o=Array.from(n.edges_in)),n.ClearDependencies(),t&&this.SetVertexDirty(n),i){n.has_outbound_edges||this.RemoveVertex(e);for(let a of o)if(!a.has_inbound_edges&&!a.has_outbound_edges){let s=a;s.address&&this.RemoveVertex(s.address)}}}ResetLoopState(){for(let e of this.vertices)if(e){for(let t of e)if(t)for(let r of t)r&&(r.color=r.edges_out.size?0:2)}for(let e of this.leaf_vertices)e.color=2}LoopCheck(e=!1){if(!this.loop_check_required&&!e)return!1;let t=[];for(let i of this.vertices)if(i){for(let n of i)if(n)for(let o of n)o&&(o.color=o.edges_out.size?0:2,t.push(o))}let r=[];for(let i of t)if(i.color===0){for(i.color=1,r.push(i);r.length;){let n=r[r.length-1],o=!0;if(n.color!==2)for(let a of n.edges_out){if(a.color===1)return this.loop_hint=this.RenderAddress(i.address),console.info("loop detected @",this.loop_hint),!0;a.color===0&&(r.push(a),o=!1)}o&&(r.pop(),n.color=2)}i.color=2}return this.loop_check_required=!1,this.loop_hint=void 0,!1}RenderAddress(e){if(!e)return"undefined";let t="";if(e.sheet_id){let i=this.model.sheets.Find(e.sheet_id);i&&(t=i.name+"!")}let r=new v(e);return t+r.spreadsheet_label}CompositeAddArrayEdge(e,t){if(!e.start.sheet_id)throw new Error("AddArrayEdge called without sheet ID");let[r,i]=Be.GetVertex(e);if(t.DependsOn(r),this.loop_check_required=!0,!i)return;let n=this.vertices[e.start.sheet_id];if(n){if(e.entire_row){for(let o=0;o<n.length;o++)if(n[o])for(let a=e.start.row;a<=e.end.row;a++){let s=n[o][a];s&&r.DependsOn(s)}}else if(e.entire_column){for(let o=e.start.column;o<=e.end.column;o++)if(n[o])for(let a of n[o])a?.address&&r.DependsOn(a)}else for(let o=e.start.row;o<=e.end.row;o++)for(let a=e.start.column;a<=e.end.column;a++)if(n[a]){let s=n[a][o];s&&r.DependsOn(s)}}}AddLeafVertexArrayEdge(e,t){this.CompositeAddArrayEdge(e,t)}AddArrayEdge(e,t){if(!e.start.sheet_id)throw new Error("AddArrayEdge called without sheet ID");let r=this.GetVertex(t,!0);this.CompositeAddArrayEdge(e,r)}AddEdge(e,t){let r=this.GetVertex(e,!0);this.GetVertex(t,!0).DependsOn(r),r.reference&&r.reference.area&&!r.array_head&&this.AddEdge({...e,row:r.reference.area.start.row,column:r.reference.area.start.column},t),this.loop_check_required=!0}RemoveEdge(e,t){let r=this.GetVertex(e,!1),i=this.GetVertex(t,!1);!r||!i||(r.RemoveDependent(i),i.RemoveDependency(r))}SetAreaDirty(e){if(e.start.column===1/0||e.end.column===1/0||e.start.row===1/0||e.end.row===1/0)throw new Error("don't iterate over infinite area");let t=e.start.sheet_id;if(!t)throw new Error("invalid area, missing sheet id");for(let r=e.start.column;r<=e.end.column;r++)for(let i=e.start.row;i<=e.end.row;i++){let n={row:i,column:r,sheet_id:t};this.GetVertex(n,!1)&&this.SetDirty(n)}}SetVertexDirty(e){if(!e.dirty){this.dirty_list.push(e),e.dirty=!0;for(let t of e.edges_out)this.SetVertexDirty(t)}}SetDirty(e){let t=this.GetVertex(e,!0);this.SetVertexDirty(t)}AddLeafVertex(e){this.leaf_vertices.add(e)}RemoveLeafVertex(e){this.leaf_vertices.delete(e)}AddLeafVertexEdge(e,t){let r=this.GetVertex(e,!0);return t.DependsOn(r),0}RemoveLeafVertexEdge(e,t){let r=this.GetVertex(e,!1);r&&(r.RemoveDependent(t),t.RemoveDependency(r))}InitializeGraph(){for(let e of this.dirty_list)this.IsSpreadsheetVertex(e)&&(e.TakeReferenceValue(),this.CheckVolatile(e)&&this.volatile_list.push(e)),e.dirty=!1;this.dirty_list=[]}Recalculate(){for(let e of this.volatile_list)this.SetVertexDirty(e);this.spill_data=this.spill_data.filter(({area:e,vertex:t})=>{if(t.dirty){t.Reset();let r=e.start.sheet_id?this.model.sheets.Find(e.start.sheet_id)?.cells:void 0;if(r)for(let{cell:i,row:n,column:o}of r.IterateRC(new v(e.start,e.end)))i.spill&&(i.spill=void 0,typeof i.value>"u"&&i.Reset()),this.SetDirty({row:n,column:o,sheet_id:e.start.sheet_id});return!1}return!0}),this.calculation_list=this.dirty_list.slice(0),this.volatile_list=[],this.dirty_list=[],this.loop_check_required&&(this.ResetLoopState(),this.loop_check_required=!1);for(let e=0;e<this.calculation_list.length;e++)this.calculation_list[e].Calculate(this);this.calculation_list=[]}};var oa=l=>{let e={m:l,n:l,array:[]};for(let t=0;t<l;t++){let r=[];for(let i=0;i<l;i++)r.push({real:0,imaginary:0});e.array.push(r)}return e};var aa=l=>{let{r:e,theta:t}=l,r=e*Math.cos(t),i=e*Math.sin(t);return{real:r,imaginary:i}},tr=l=>{let e=Math.sqrt(l.real*l.real+l.imaginary*l.imaginary),t=Math.atan2(l.imaginary,l.real);return{r:e,theta:t}},on=l=>{let e={real:Math.sinh(l.real)*Math.cos(l.imaginary),imaginary:Math.cosh(l.real)*Math.sin(l.imaginary)},t={real:Math.cosh(l.real)*Math.cos(l.imaginary),imaginary:Math.sinh(l.real)*Math.sin(l.imaginary)};return Pe(e,t)},an=l=>Pe({real:Math.tan(l.real),imaginary:Math.tanh(l.imaginary)},{real:1,imaginary:-(Math.tan(l.real)*Math.tanh(l.imaginary))}),sn=l=>({real:Math.cosh(l.real)*Math.cos(l.imaginary),imaginary:Math.sinh(l.real)*Math.sin(l.imaginary)}),ln=l=>({real:Math.cos(l.real)*Math.cosh(l.imaginary),imaginary:Math.sin(l.real)*Math.sinh(l.imaginary)}),cn=l=>({real:Math.sinh(l.real)*Math.cos(l.imaginary),imaginary:Math.cosh(l.real)*Math.sin(l.imaginary)}),rr=l=>({real:Math.sin(l.real)*Math.cosh(l.imaginary),imaginary:Math.cos(l.real)*Math.sinh(l.imaginary)}),Yr=l=>{if(l.imaginary===0)return{real:Math.asin(l.real),imaginary:0};let e=Math.hypot(l.real+1,l.imaginary)/2,t=Math.hypot(l.real-1,l.imaginary)/2,r=e+t,i=e-t,n={real:Math.asin(i),imaginary:Math.log(r+Math.sqrt(r*r-1))};return(l.imaginary<0||l.imaginary===0&&l.real>1)&&(n.imaginary=-n.imaginary),n},dn=l=>{if(l.imaginary===0)return{real:Math.acos(l.real),imaginary:0};let e=Yr(l);return{real:Math.PI/2-e.real,imaginary:e.imaginary}},un=l=>{let{real:e,imaginary:t}=l;if(e===0){if(t>1)return{real:Math.PI/2,imaginary:.5*Math.log((t-1)/(t+1))};if(t<-1)return{real:-Math.PI/2,imaginary:.5*Math.log((1-t)/(-1-t))}}let r=e*e,i=t*t,n=.5*Math.atan2(2*e,1-r-i),o=.25*Math.log((r+(t+1)*(t+1))/(r+(t-1)*(t-1)));return{real:n,imaginary:o}},hn=(l,e)=>{if(e.real===0&&e.imaginary===0&&l.real===0&&l.imaginary===0)return!1;let t=e.real*e.real+e.imaginary*e.imaginary,r={real:(l.real*e.real+l.imaginary*e.imaginary)/t,imaginary:(l.imaginary*e.real-l.real*e.imaginary)/t},i=r.real*r.real,n=r.imaginary*r.imaginary,o={real:.5*Math.atan2(2*r.real,1-i-n),imaginary:.25*Math.log((i+(r.imaginary+1)*(r.imaginary+1))/(i+(r.imaginary-1)*(r.imaginary-1)))};return e.real<0&&(o.real+=l.real>=0||l.imaginary>=0?Math.PI:-Math.PI),o},fn=(...l)=>{let e=l.shift();if(!e)return{real:0,imaginary:0};for(let t of l)e=ne(e,t);return e},ne=(l,e)=>({real:l.real*e.real-l.imaginary*e.imaginary,imaginary:l.real*e.imaginary+l.imaginary*e.real}),sa=(l,e)=>{let t=[];for(let r=0;r<l.m;r++){let i=[];for(let n=0;n<l.n;n++)i.push(l.array[r][n]+e.array[r][n]);t.push(i)}return{m:l.m,n:l.n,array:t}},Kr=(l,e)=>{let t=[];for(let r=0;r<l.m;r++){let i=[];for(let n=0;n<e.n;n++){let o=0;for(let a=0;a<l.n;a++)o+=l.array[r][a]*e.array[a][n];i.push(o)}t.push(i)}return{array:t,m:l.m,n:e.n}},mn=(l,e)=>{let t=[];for(let r=0;r<l.m;r++){let i=[];for(let n=0;n<e.n;n++){let o={real:0,imaginary:0};for(let a=0;a<l.n;a++)o.real+=l.array[r][a].real*e.array[a][n].real-l.array[r][a].imaginary*e.array[a][n].imaginary,o.imaginary+=l.array[r][a].real*e.array[a][n].imaginary+l.array[r][a].imaginary*e.array[a][n].real;i.push(o)}t.push(i)}return t},ir=l=>{let e={real:0,imaginary:0},t=l.n;if(t==2){let i=ne(l.array[0][0],l.array[1][1]),n=ne(l.array[1][0],l.array[0][1]);return{real:i.real-n.real,imaginary:i.imaginary-n.imaginary}}let r=oa(l.n);for(let i=0;i<t;i++){let n=0;for(let s=1;s<t;s++){let c=0;for(let d=0;d<t;d++)d!=i&&(r.array[n][c]={...l.array[s][d]},c++);n++}r.m=r.n=t-1;let o=Math.pow(-1,i),a=ne({real:l.array[0][i].real*o,imaginary:l.array[0][i].imaginary*o},ir(r));e.real+=a.real,e.imaginary+=a.imaginary}return e};var la=l=>{let e={real_values:!1,imaginary_values:!1,square:l.m===l.n,unit_diagonal:!0},t={m:l.m,n:l.n,array:[]},r={m:l.m,n:l.n,array:[]};for(let i=0;i<l.m;i++){let n=l.array[i],o=[],a=[];for(let s=0;s<l.n;s++)n[s].real&&(e.real_values=!0),n[s].imaginary&&(e.imaginary_values=!0),s===i&&e.unit_diagonal&&(n[s].real!==1||n[s].imaginary!==0)&&(e.unit_diagonal=!1),o.push(n[s].real),a.push(n[s].imaginary);t.array.push(o),r.array.push(a)}return{real:t,imaginary:r,flags:e}},ca=l=>{let e=l.array.map(t=>t.slice(0));return{m:l.m,n:l.n,array:e}},nn=l=>{if(l.m!==l.n)return;let e=ca(l),t=e.array,r=0,i=0,n=0,o=0,a=l.m;for(i=1;i<a;i++)t[0][i]/=t[0][0];for(i=1;i<a;i++){for(n=i;n<a;n++){for(r=0,o=0;o<i;o++)r+=t[n][o]*t[o][i];t[n][i]-=r}if(i!=a-1)for(n=i+1;n<a;n++){for(r=0,o=0;o<i;o++)r+=t[i][o]*t[o][n];t[i][n]=(t[i][n]-r)/t[i][i]}}for(i=0;i<a;i++)for(n=i;n<a;n++){let s=1;if(i!=n)for(s=0,o=i;o<n;o++)s-=t[n][o]*t[o][i];t[n][i]=s/t[n][n]}for(i=0;i<a;i++)for(n=i;n<a;n++)if(i!=n){for(r=0,o=i;o<n;o++)r+=t[o][n]*(i==o?1:t[i][o]);t[i][n]=-r}for(i=0;i<a;i++)for(n=0;n<a;n++){for(r=0,o=i>n?i:n;o<a;o++)r+=(n==o?1:t[n][o])*t[o][i];t[n][i]=r}return e},pn=l=>{let e=[];if(l.m!==l.n)return;let{real:t,imaginary:r,flags:i}=la(l),n=nn(t);if(!n)return;if(!i.imaginary_values){for(let u=0;u<l.m;u++){let h=[];for(let f=0;f<l.n;f++)h.push({real:n.array[u][f],imaginary:0});e.push(h)}return e}let o=Kr(n,r),a=Kr(r,o),s=sa(t,a),c=nn(s);if(!c)return;let d=Kr(o,c);for(let u=0;u<l.m;u++){let h=[];for(let f=0;f<l.n;f++)h.push({real:c.array[u][f],imaginary:-d.array[u][f]});e.push(h)}return e},Pe=(l,e)=>{let t={real:e.real,imaginary:-e.imaginary},r=ne(l,t),i=ne(e,t);return{real:r.real/i.real,imaginary:r.imaginary/i.real}},yt=l=>{let e=l.real||0,t=l.imaginary||0;return ne({real:Math.exp(e),imaginary:0},{real:Math.cos(t),imaginary:Math.sin(t)})},Qr=l=>{let e=tr(l);return{real:Math.log(e.r),imaginary:e.theta}},ve=(l,e)=>{if(e.imaginary)return yt(ne(e,Qr(l)));{let t=tr(l);return aa({r:Math.pow(t.r,e.real),theta:t.theta*e.real})}};var bn=(l,e=0)=>l&&l.type===8?l:{type:8,value:{real:e,imaginary:0}},$e=l=>l.imaginary?{type:8,value:l}:{type:3,value:l.real},je=(l,e)=>{if(l.type===7)return[0,0,l];if(e.type===7)return[0,0,e];let t=[0,0];switch(l.type){case 3:t[0]=l.value;break;case 4:t[0]=l.value?1:0;break;case 0:break;case 8:t[3]=l;break;default:return[0,0,M()]}switch(e.type){case 3:t[1]=e.value;break;case 4:t[1]=e.value?1:0;break;case 0:break;case 8:t[4]=e;break;default:return[0,0,M()]}return(t[3]||t[4])&&(t[3]=bn(t[3],t[0]),t[4]=bn(t[4],t[1])),t},da=(l,e)=>{let[t,r,i,n,o]=je(l,e);return i||(n&&o?$e({real:n.value.real+o.value.real,imaginary:n.value.imaginary+o.value.imaginary}):{value:t+r,type:3})},ti=(l,e)=>{let[t,r,i,n,o]=je(l,e);return i||(n&&o?$e({real:n.value.real-o.value.real,imaginary:n.value.imaginary-o.value.imaginary}):{value:t-r,type:3})},ua=(l,e)=>{let[t,r,i,n,o]=je(l,e);if(i)return i;if(n&&o)return $e(ve(n.value,o.value));let a=Math.pow(t,r);return isNaN(a)?M():{type:3,value:a}},ha=(l,e)=>{let[t,r,i,n,o]=je(l,e);if(i)return i;if(n&&o)return $e(ve(n.value,o.value));if(t<0&&r!==0&&Math.abs(r)<1)return $e(ve({real:t,imaginary:0},{real:r,imaginary:0}));let a=Math.pow(t,r);return isNaN(a)?M():{type:3,value:a}},Zr=ua,fa=(l,e)=>{let[t,r,i,n,o]=je(l,e);return i||(n&&o?$e(ne(n.value,o.value)):{value:t*r,type:3})},ma=(l,e)=>{let[t,r,i,n,o]=je(l,e);return i||(n&&o?o.value.real===0&&o.value.imaginary===0?ye():$e(Pe(n.value,o.value)):r===0?ye():{value:t/r,type:3})},pa=(l,e)=>{let[t,r,i]=je(l,e);return i||(r===0?ye():{value:t%r,type:3})},ei=(l,e)=>l.type===7?l:e.type===7?e:l.type===0&&(e.value===""||e.value===0||e.type===8&&e.value.real===0&&e.value.imaginary===0)||e.type===0&&(l.value===""||l.value===0||l.type===8&&l.value.real===0&&l.value.imaginary===0)?{type:4,value:!0}:l.type===8?e.type===8?{type:4,value:l.value.imaginary===e.value.imaginary&&l.value.real===e.value.real}:{type:4,value:!l.value.imaginary&&l.value.real===e.value}:e.type===8?{type:4,value:!e.value.imaginary&&l.value===e.value.real}:l.type===2&&e.type===2?{type:4,value:l.value.toLowerCase()===e.value.toLowerCase()}:{type:4,value:l.value==e.value},gn=(l,e)=>{let t=ei(l,e);return t.type===7?t:{type:4,value:!t.value}},ba=(l,e)=>l.type===7?l:e.type===7?e:l.type===8||e.type===8?M():{type:4,value:(l.value||0)>(e.value||0)},ri=(l,e)=>!(l.type===8||l.type===9||l.type===10||l.type===5||e.type===8||e.type===9||e.type===10||e.type===5),ga=(l,e)=>l.type===7?l:e.type===7?e:ri(l,e)?{type:4,value:(l.value||0)>=(e.value||0)}:M(),_a=(l,e)=>l.type===7?l:e.type===7?e:ri(l,e)?{type:4,value:(l.value||0)<(e.value||0)}:M(),ya=(l,e)=>l.type===7?l:e.type===7?e:ri(l,e)?{type:4,value:(l.value||0)<=(e.value||0)}:M(),_n=()=>{Zr=ha},yn=l=>{switch(l){case"+":return da;case"-":return ti;case"*":return fa;case"/":return ma;case"^":return Zr;case"**":return Zr;case"%":return pa;case"=":return ei;case"==":return ei;case"!=":return gn;case"<>":return gn;case">":return ba;case">=":return ga;case"<":return _a;case"<=":return ya}};var ii=l=>!Array.isArray(l)&&l.type===5&&!!l.value.type,ue=l=>l.type===5&&l.key==="metadata",or=class{constructor(e,t,r){this.data_model=e;this.library=t;this.parser=r}context={address:{row:-1,column:-1},volatile:!1,bindings:[]};Calculate(e,t,r,i=!1){return i||(this.context.address=t,this.context.volatile=!1,this.context.area=r),{value:this.CalculateExpression(e),volatile:this.context.volatile}}CellFunction2(e){if(!e.sheet_id)if(e.sheet)e.sheet_id=this.data_model.sheets.ID(e.sheet)||0;else return()=>$();let t=this.data_model.sheets.Find(e.sheet_id)?.cells;if(!t)return console.warn("missing cells reference @ "+e.sheet_id),()=>$();let r=t.GetCell(e);return r?e.spill&&r.spill&&r.spill.start.row===e.row&&r.spill.start.column===e.column?()=>r.spill?t.GetRange4(r.spill.start,r.spill.end,!0)||$():rn():()=>r.GetValue4():()=>({type:3,value:0})}CellFunction4(e,t){return e.sheet_id?this.data_model.sheets.Find(e.sheet_id)?.cells?.GetRange4(e,t,!0)||$():$()}GetMetadata(e,t){let r,i;switch(e.type){case"address":if(e.spill){let n;if(e.sheet_id&&(n=this.data_model.sheets.Find(e.sheet_id)),!n)return console.error("missing sheet [da6]"),$();let o=n.CellData(e);o.spill&&(i=o.spill)}else r=e;break;case"range":i=e;break;case"structured-reference":{let n=this.data_model.ResolveStructuredReference(e,this.context.address);n&&(n.type==="address"?r=n:n.type==="range"&&(i=n))}break;case"identifier":{let n=this.data_model.GetName(e.name,this.context.address.sheet_id||0);n?.type==="range"&&(n.area.count===1?r=n.area.start:i=n.area)}break;case"call":{let n=this.CalculateExpression(e,!0);if(ii(n))if(n.value.type==="address")r=n.value;else if(n.value.type==="range")i=n.value;else return n;else return n}break;default:return this.CalculateExpression(e)}if(r){let n;if(r.sheet_id&&(n=this.data_model.sheets.Find(r.sheet_id)),!n)return console.error("missing sheet [ac8]"),$();let o=n.CellData(r),a=o.calculated_type?o.calculated:o.value,s={type:"metadata",address:{...r,position:0,id:0,type:"address",label:new v(r).spreadsheet_label},value:a,format:o.style?o.style.number_format:void 0,...t(o,r)};return{type:5,value:s,key:"metadata"}}else if(i){if(i.start.row===1/0||i.start.column===1/0)return $();let n;if(i.start.sheet_id&&(n=this.data_model.sheets.Find(i.start.sheet_id)),!n)throw new Error("missing sheet [ac9]");let o=[];for(let a=i.start.column;a<=i.end.column;a++){let s=[];for(let c=i.start.row;c<=i.end.row;c++){let d=n.CellData({row:c,column:a});r={...i.start,row:c,column:a};let u=d.calculated_type?d.calculated:d.value,h={type:"metadata",address:r,value:u,format:d.style?d.style.number_format:void 0,...t(d,r)};s.push({type:5,value:h,key:"metadata"})}o.push(s)}return{type:9,value:o}}return this.CalculateExpression(e)}RewriteMacro(e,t){let r;switch(e.type){case"identifier":if(r=t[e.name.toUpperCase()],r)return JSON.parse(JSON.stringify(r));break;case"binary":e.left=this.RewriteMacro(e.left,t),e.right=this.RewriteMacro(e.right,t);break;case"unary":e.operand=this.RewriteMacro(e.operand,t);break;case"group":e.elements=e.elements.map(i=>this.RewriteMacro(i,t));break;case"call":e.args=e.args.map(i=>this.RewriteMacro(i,t));break}return e}CallMacro(e,t){if(!t.expression)return()=>fe();let r=JSON.stringify(t.expression),i={},n=t.argument_names?.map(o=>o.toUpperCase())||[];return o=>{let a=JSON.parse(r);for(let s=0;s<n.length;s++)i[n[s]]=o.args[s]||{type:"missing",id:0};return this.CalculateExpression(this.RewriteMacro(a,i))}}ImplicitCallTail(e,t){let r=e.value;if(!r.func||!r.bindings)return fe();let i={};for(let o=0;o<r.bindings.length;o++){let a=r.bindings[o];if(a?.type==="identifier")i[a.name.toUpperCase()]=t[o]||{type:"missing"};else return fe()}let n=JSON.parse(JSON.stringify(r.func));return this.parser.Walk2(n,o=>{if(o.type==="identifier"){let a=o.name.toUpperCase(),s=i[a];if(s)return JSON.parse(JSON.stringify(s))}return!0}),this.CalculateExpression(n)}Apply(e,t){let r=t.map(i=>{switch(i.type){case 3:case 4:case 2:return{type:"literal",value:i.value,id:0,position:0};case 7:return{type:"literal",value:"#"+i.value,id:0,position:0};case 9:{let n=[];for(let o=0;o<i.value.length;o++){let a=i.value[o],s=[];for(let c=0;c<a.length;c++){let d=a[c];switch(d.type){case 4:case 3:case 2:s.push(d.value||void 0);break;default:console.warn("unhandled array value",d),s.push(void 0)}}n.push(s)}return{type:"array",values:n,id:0,position:0}}case 0:return{type:"missing",id:0};default:console.warn("unhandled parameter value",i)}return{type:"missing",id:0}});return this.ImplicitCallTail(e,r)}ImplicitCall(){return e=>{e.type==="call"&&(e={type:"implicit-call",args:e.args,call:{type:"identifier",name:e.name,position:e.position,id:0},position:e.position,id:0});let t=this.CalculateExpression(e.call);return t.type===6?this.ImplicitCallTail(t,e.args):fe()}}NormalizeBindings(e){let t={};for(let[r,i]of Object.entries(e))t[r.toUpperCase()]=i;return t}CallExpression(e,t=!1){let r=this.library.Get(e.name);if(!r){let i=e.name.toUpperCase();return this.LookupBinding(i)?this.ImplicitCall():this.data_model.GetName(i,this.context.address.sheet_id||0)?this.ImplicitCall():()=>Xr()}return i=>{this.context.volatile=this.context.volatile||!!r.volatile;let n=e.name.toLowerCase()==="if",o=-1,a,s=i.args,c=r.arguments||[],d;r.create_binding_context&&(d=r.create_binding_context.call(0,{args:i.args,descriptors:c}),d?(s=d.args,d.argument_descriptors&&(c=d.argument_descriptors),this.context.bindings.unshift(this.NormalizeBindings(d.context))):a=U());let u=s.map((m,p)=>{if(a)return;let b=c[Math.min(p,c.length-1)]||{};if(b.passthrough)return m;if(p===o)return b.boxed?{type:0}:void 0;if(typeof m>"u")return n&&p===0&&(o=1),b.boxed?{type:0}:void 0;if(b.address)return b.boxed?{type:2,value:this.parser.Render(m).replace(/\$/g,"")}:this.parser.Render(m).replace(/\$/g,"");if(b.metadata)return this.GetMetadata(m,()=>({}));{let g=this.CalculateExpression(m);if(g.type===7){if(b.allow_error)return g;a=g;return}if(n&&p===0&&g.type!==9){let x=!1;if(g.type===2){let y=g.value.toLowerCase().trim();x=y!=="false"&&y!=="f"}else x=!!g.value;o=x?2:1}return b.boxed?g:g.type===9?g.value.map(x=>x.map(y=>y.value)):g.value}});if(d&&this.context.bindings.shift(),a)return a;let h={address:{...this.context.address},area:this.context.area?{start:{...this.context.area.start},end:{...this.context.area.end}}:void 0,apply:r.fp?this.Apply.bind(this):void 0},f=r.fn.apply(h,u);if(r.return_type==="reference"){if(t)return f;if(ii(f)){if(f.value.type==="address")return this.CellFunction2(f.value)();if(f.value.type==="range")return this.CellFunction4(f.value.start,f.value.end)}return f}return f}}ResolveStructuredReference(e){let t=this.data_model.ResolveStructuredReference(e,this.context.address);if(t){if(t.type==="address")return this.CellFunction2(t);if(t.type==="range")return()=>this.CellFunction4(t.start,t.end)}return()=>$()}ResolveDimensionedQuantity(){return e=>{let t=this.CalculateExpression(e.expression);return{type:10,value:{value:t.value,unit:e.unit.name}}}}UnaryExpression(e,t=!1){switch(e.operator){case"+":return r=>this.CalculateExpression(r.operand);case"-":{let r=ti,i={type:3,value:0};return n=>{let o=this.CalculateExpression(n.operand);return o.type===9?{type:9,value:o.value.map(a=>a.map(s=>r(i,s)))}:r(i,o)}}case"@":return r=>{let i;switch(r.operand.type){case"address":if(r.operand.spill){let o=this.CellFunction2(r.operand)();if(o.type===9){let a=this.context.address.row??-1,s=this.context.address.column??-1;if(a>=r.operand.row&&a<r.operand.row+o.value[0]?.length&&o.value.length===1){if(!t)return o.value[0][a-r.operand.row];i={...r.operand,row:a,spill:!1}}else if(s>=r.operand.column&&s<r.operand.column+o.value.length&&o.value[0]?.length===1){if(!t)return o.value[s-r.operand.column][0];i={...r.operand,column:s,spill:!1}}else return M()}}break;case"range":{let o=this.context.address.row??-1,a=this.context.address.column??-1;if(o>=r.operand.start.row&&o<=r.operand.end.row&&r.operand.start.column===r.operand.end.column)i={...r.operand.start,row:o,spill:!1};else if(a>=r.operand.start.column&&a<=r.operand.end.column&&r.operand.start.row===r.operand.end.row)i={...r.operand.start,column:a,spill:!1};else return M()}}if(i)return t?{type:5,value:i}:this.CellFunction2(i)();let n=this.CalculateExpression(r.operand);return n.type===9?n.value[0][0]:n};default:return()=>(console.warn("unexpected unary operator:",e.operator),fe())}}RecycleArray(e,t,r){if(e[0].length<r){let i=e[0].length;for(let n of e)for(let o=i;o<r;o++)n[o]=n[o%i]}if(e.length<t){let i=e.length;for(let n=i;n<t;n++)e[n]=e[n%i].slice(0)}return e}ElementwiseBinaryExpression(e,t,r){let i=Math.max(t.value.length,r.value.length),n=Math.max(t.value[0].length,r.value[0].length),o=this.RecycleArray(t.value,i,n),a=this.RecycleArray(r.value,i,n),s=[];for(let c=0;c<i;c++){let d=[];for(let u=0;u<n;u++)d[u]=e(o[c][u]||{type:0},a[c][u]||{type:0});s.push(d)}return{type:9,value:s}}AsReference(e){switch(e.type){case"address":return e;case"range":if(e.start.row===e.end.row&&e.start.column===e.end.column)return e.start;break;default:{let t=this.CalculateExpression(e,!0);if(ii(t)){if(t.value.type==="address")return t.value;if(t.value.type==="range"&&t.value.start.row===t.value.end.row&&t.value.start.column===t.value.end.column)return t.value.start}}break}}BinaryExpression(e){let t=e.operator==="&"?(r,i)=>{if(r.type===7)return r;if(i.type===7)return i;let n=[r,i].map(o=>o.type===0?"":o.type===4?o.value?this.data_model.language_model?.boolean_true||"TRUE":this.data_model.language_model?.boolean_false||"FALSE":o.value);return{type:2,value:`${n[0]}${n[1]}`}}:yn(e.operator);return t?r=>{let i=this.CalculateExpression(r.left),n=this.CalculateExpression(r.right);return i.type===9?n.type===9?this.ElementwiseBinaryExpression(t,i,n):this.ElementwiseBinaryExpression(t,i,{type:9,value:[[n]]}):n.type===9?this.ElementwiseBinaryExpression(t,{type:9,value:[[i]]},n):t(i,n)}:e.operator===":"?r=>{let i=this.AsReference(r.left),n=this.AsReference(r.right);return i&&n?this.CellFunction4(i,n):fe()}:()=>(console.info(`(unexpected binary operator: ${e.operator})`),fe())}Identifier(e){let t=e.name;if(t[0]==="#")return()=>$();let r=t.toUpperCase();switch(r){case"FALSE":return()=>({value:!1,type:4});case"TRUE":return()=>({value:!0,type:4});case"UNDEFINED":return()=>({value:void 0,type:0})}return()=>{let i=this.LookupBinding(r);if(i)return this.CalculateExpression(i);let n=this.data_model.GetName(r,this.context.address.sheet_id||0);switch(n?.type){case"range":return n.area.count===1?this.CellFunction4(n.area.start,n.area.start):this.CellFunction4(n.area.start,n.area.end);case"expression":return this.CalculateExpression(n.expression)}return Xr()}}LookupBinding(e){e=e.toUpperCase();for(let t of this.context.bindings){let r=t[e];if(r)return r}}GroupExpression(e){return!e.elements||e.elements.length!==1?(console.warn("Can't handle group !== 1"),()=>fe()):t=>this.CalculateExpression(t.elements[0])}CalculateExpression(e,t=!1){if(e.fn)return e.fn(e);switch(e.type){case"implicit-call":return(e.fn=this.ImplicitCall())(e);case"call":{let r=this.data_model.macro_functions.get(e.name.toUpperCase());return r?(e.fn=this.CallMacro(e,r))(e):(e.fn=this.CallExpression(e,t))(e)}case"address":return(e.fn=this.CellFunction2(e))();case"range":return(e.fn=r=>this.CellFunction4(r.start,r.end))(e);case"binary":return(e.fn=this.BinaryExpression(e))(e);case"unary":return(e.fn=this.UnaryExpression(e,t))(e);case"identifier":return(e.fn=this.Identifier(e))();case"missing":return(e.fn=()=>({value:void 0,type:0}))();case"dimensioned":return(e.fn=this.ResolveDimensionedQuantity())(e);case"literal":{let r={value:e.value,type:be(e.value)};return(e.fn=()=>r)()}case"group":return(e.fn=this.GroupExpression(e))(e);case"complex":{let r={value:{real:e.real,imaginary:e.imaginary},type:8};return(e.fn=()=>r)()}case"structured-reference":return(e.fn=this.ResolveStructuredReference(e))();case"array":return(e.fn=()=>({type:9,value:e.values.map(r=>(Array.isArray(r)?r:[r]).map(i=>({type:be(i),value:i})))}))();default:return console.warn("Unhandled parse expr:",e),Qt()}}};var wu=1e3*60*60*24;var ar=l=>{let e=[],t=l.length,r=l[0].length;for(let i=0;i<r;i++){e[i]=[];for(let n=0;n<t;n++)e[i][n]=l[n][i]}return e},ni=l=>{if(!l)return[];if(typeof l[0]>"u")return[];let e=[],t=l.length,r=l[0].length;for(let i=0;i<r;i++){e[i]=[];for(let n=0;n<t;n++)e[i][n]=l[n][i]}return e};var oe=l=>{let e=[];for(let t of l)if(t?.type===9)for(let r of t.value)e=e.concat(oe(r));else e.push(t);return e},X=(l,e=!1)=>Array.isArray(l)?l.reduce((t,r)=>typeof r>"u"&&!e?t:Array.isArray(r)?t.concat(X(r,e)):r instanceof Float32Array||r instanceof Float64Array?t.concat(Array.from(r)):t.concat([r]),[]):[l],te=l=>X(l).filter(e=>typeof e=="number"),oi=(l,e=!1)=>e?l.map(t=>{switch(typeof t){case"number":case"undefined":case"string":case"boolean":return t}}):l.filter(t=>{switch(typeof t){case"number":case"undefined":case"string":case"boolean":return!0}return!1}),va=l=>!!l&&typeof l=="object"&&l.type===9,wn=(l,e)=>(...t)=>{let r=[],i=[];for(let[n,o]of t.entries())if(o&&l[n]){let a=Array.isArray(o)?o:va(o)?o.value:void 0;a&&(r[n]=a,i.length||(i=a))}return r.length?{type:9,value:i.map((n,o)=>n.map((a,s)=>{let c=t.map((d,u)=>r[u]?r[u][o][s]??{type:0}:d);return e(...c)}))}:e(...t)},vt=l=>{let e=[],t=l.length,r="[\\^$.|?*+()";for(let i=0;i<t;i++){let n=l[i];switch(n){case"*":e.push(".","*");break;case"?":e.push(".");break;case"~":n=l[++i]||"";default:for(let o=0;o<r.length;o++)if(n===r[o]){e.push("\\");break}e.push(n);break}}return e.join("")},xn=l=>({type:2,value:l});var lr=class{functions={};Register(...e){for(let t of e)for(let r of Object.keys(t)){if(/[^a-zA-Z0-9._]/.test(r))throw new Error("invalid function name (invalid character)");if(r.length>255)throw new Error("invalid function name (too long, > 255)");if(/^[^a-zA-Z]/.test(r))throw new Error("invalid function name (start with an ascii letter)");let i=r.toLowerCase();if(this.functions[i])throw new Error(`function name (${i}) is already in use`);let n=t[r];if(n.canonical_name=r,!n.unrolled){let o=n.arguments?.map(a=>!!a.unroll);o?.some(a=>!!a)&&(n.fn=wn(o,n.fn),n.unrolled=!0)}this.functions[i]=n}}Get(e){let t=e.toLowerCase();return this.functions[t]}List(e=!0){let t={};for(let r of Object.keys(this.functions))e&&this.functions[r].visibility==="internal"||(t[r]=this.functions[r]);return t}Alias(e,t){let r=this.Get(t);if(!r)throw new Error(`referenced function ${t} does not exist`);this.Register({[e]:{...r}})}};var wt=class{static default_color="#888";static UnpackValues(e){if(Array.isArray(e)){let t=e[0];return Array.isArray(t)||t instanceof Float64Array||t instanceof Float32Array?e.reduce((r,i)=>r.concat(this.UnpackValues(i)),[]):e.map(r=>isNaN(r)?void 0:r)}else{if(e instanceof Float32Array||e instanceof Float64Array)return Array.prototype.slice.call(e);if(e&&typeof e=="object"){let r=Object.keys(e).length;if(typeof e[0]<"u"&&typeof e[(r-1).toString()]<"u"){let i=[];for(let n=0;n<r;n++)i[n]=e[n.toString()];return i}}}return[]}static SparklineCommon(e,t){let r=[],i=ee(t.text)?t.text.text:this.default_color,n=[i,i];return Array.isArray(e.calculated)&&(r=this.UnpackValues(e.calculated[0]),typeof e.calculated[1]=="string"&&(n[0]=e.calculated[1]),typeof e.calculated[2]=="string"&&(n[1]=e.calculated[2])),{values:r,colors:n}}static RenderLine(e,t,r,i,n){let{values:o,colors:a}=this.SparklineCommon(i,n),s=.05,c=.1,d=1;Array.isArray(i.calculated)&&typeof i.calculated[2]=="number"&&(d=i.calculated[2]);let u=0,h=0,f=-1;for(let m=0;m<o.length;m++){let p=o[m];typeof p=="number"&&(f>=0?(u=Math.min(u,p),h=Math.max(h,p)):(f=m,u=h=p))}if(u===h&&(u&&(u-=1),h+=1),u!==h){let m=e*(1-2*s)/(o.length-1),p=h-u,b=t*(1-2*c),g=t*c;r.strokeStyle=a[0],r.lineWidth=d,r.lineCap="round",r.lineJoin="round",r.beginPath();let x=0;for(let y=f;y<o.length;y++){let w=o[y];if(typeof w=="number"){let _=e*s+m*y,C=t-(w-u)*b/p-g;x===0?(r.moveTo(_,C),x=1):r.lineTo(_,C)}else x=0}r.stroke()}}static RenderColumn(e,t,r,i,n){let{values:o,colors:a}=this.SparklineCommon(i,n),s=3,c=2.5,d=0,u=0,h=!1;for(let f of o)typeof f=="number"&&(h?(d=Math.min(d,f),u=Math.max(u,f)):(h=!0,d=u=f));if(d===u&&(d&&(d-=1),u+=1),o.length){let f=(e-2*s-2)/(o.length-0),m=t-2*c,p=c;if(d!==u)if(d<0&&u>0){let b=u-d,g=p+u/b*m;for(let x=0;x<o.length;x++){let y=o[x];if(typeof y=="number"){let w=s+x*f,_=Math.abs(y)/b*m;if(y>=0){r.fillStyle=a[0];let C=g-_;r.fillRect(w+2,C,f-2,_)}else{r.fillStyle=a[1];let C=g;r.fillRect(w+2,C,f-2,_)}}}}else if(u>0){r.fillStyle=a[0];let b=u-d;for(let g=0;g<o.length;g++){let x=o[g];if(typeof x=="number"){let y=s+g*f,w=Math.max(1,(x-d)/b*m),_=t-p-w;r.fillRect(y+2,_,f-2,w)}}}else{r.fillStyle=a[1];let b=u-d;for(let g=0;g<o.length;g++){let x=o[g];if(typeof x=="number"){let y=s+g*f,w=Math.max(1,Math.abs(u-x)/b*m),_=p;r.fillRect(y+2,_,f-2,w)}}}}}};var Cn=l=>{let{x:e,y:t,width:r,height:i,cell:n}=l,o={},a=3,s=Math.round(16*(l.scale||1));if(n&&r&&i&&e&&t){let c={x:a,y:i-a-s};if(n.style){switch(n.style.vertical_align){case"top":c.y=a;break;case"middle":c.y=Math.round((i-s)/2);break}switch(n.style.horizontal_align){case"right":c.x=Math.round(r-a-s);break;case"center":c.x=Math.round((r-s)/2);break}}e>=c.x&&e<=c.x+s&&t>=c.y&&t<=c.y+s&&(o.value=`=Checkbox(${n.calculated?"FALSE":"TRUE"})`,o.block_selection=!0)}return o},Sn=l=>{let{context:e,width:t,height:r,cell:i}=l,n=l.scale||1;e.lineJoin="round",e.lineCap="round";let o=3*n,a=16*n,s=o,c=r-o-a;if(i.style){switch(i.style.vertical_align){case"top":c=o;break;case"middle":c=(r-a)/2;break}switch(i.style.horizontal_align){case"right":s=t-o-a;break;case"center":s=(t-a)/2;break}}s=Math.floor(s)+.5,c=Math.floor(c)+.5;let d=Math.floor(s+a)+.5,u=Math.floor(c+a)+.5;if(i&&i.calculated){e.lineWidth=.5,e.fillStyle=e.strokeStyle,e.beginPath(),e.moveTo(s,c),e.lineTo(s+16*n,c),e.lineTo(s+16*n,c+16*n),e.lineTo(s,c+16*n),e.closePath(),e.moveTo(s+15*n,c+4*n);for(let h of[[13.59,2.58],[6,10.17],[2.41,6.59],[1,8],[6,13]])e.lineTo(s+h[0]*n,c+h[1]*n);e.closePath(),e.fill()}else e.lineWidth=1,e.lineJoin="round",e.beginPath(),e.moveTo(s,c),e.lineTo(d,c),e.lineTo(d,u),e.lineTo(s,u),e.closePath(),e.stroke();return{handled:!0}};var Oe=l=>{switch(l.type){case 8:return l.value;case 3:return{real:l.value,imaginary:0};case 4:return{real:l.value?1:0,imaginary:0};case 0:return{real:0,imaginary:0}}return!1};var An=(l,e,t)=>{let r=new Date;return r.setMilliseconds(0),r.setSeconds(0),r.setMinutes(0),r.setHours(0),l<0||l>1e4||(l<1899&&(l+=1900),r.setFullYear(l),e<1||e>12)||(r.setMonth(e-1),t<1||t>31)?!1:(r.setDate(t),Se(r.getTime()))};var kn=(l,e)=>{let t=new Date(Re(l)),r=t.getUTCMonth()+e,i=t.getUTCFullYear();for(t.setUTCHours(12),t.setUTCMinutes(0),t.setUTCSeconds(0),t.setUTCMilliseconds(0);r<0;)r+=12,i--;for(;r>11;)r-=12,i++;if(t.setUTCMonth(r),t.setUTCFullYear(i),t.getUTCMonth()!==r){let o=t.getUTCDate();t=new Date(t.getTime()-o*86400*1e3)}return t},Rn=[{name:"Lookup value"},{name:"Table"},{name:"Result index"},{name:"Inexact",default:!0}],En=(l,e,t,r=!0,i=!1)=>{if(i&&(e=ni(e)),t=Math.max(0,t-1),r){let n=e[t][0];if(typeof l=="number"){let o=Number(e[0][0]);if(isNaN(o)||o>l)return we();for(let a=1;a<e[0].length&&(o=Number(e[0][a]),!(isNaN(o)||o>l));a++)n=e[t][a]}else{l=(l||"").toString().toLowerCase();let o=(e[0][0]||"").toString().toLowerCase();if(o.localeCompare(l)>0)return we();for(let a=1;a<e[0].length&&(o=(e[0][a]||"").toString().toLowerCase(),!(o.localeCompare(l)>0));a++)n=e[t][a]}return Q(n)}else{for(let n=0;n<e[0].length;n++)if(e[0][n]==l)return Q(e[t][n]);return we()}},cr=(l,e=!1)=>{if(!l)return e;switch(l.type){case 3:return l.value;case 0:return e}return!1},Le=(l,e,t)=>({description:t,arguments:[{name:"number",boxed:!0,unroll:!0}],fn:r=>r.type===3?{type:3,value:l(r.value)}:r.type===8?{type:8,value:e(r.value)}:U()}),ai={Sqrt:{description:"Returns the square root of the argument",arguments:[{boxed:!0,unroll:!0}],fn:l=>{if(l.type===8){let e=ve(l.value,{real:.5,imaginary:0});return ce(e)}else{if(l.type===0||!l.value)return{type:3,value:0};if(l.type===3&&l.value<0){let e=ve({real:l.value,imaginary:0},{real:.5,imaginary:0});return{type:8,value:e}}else if(l.type===3){let e=Math.sqrt(l.value);return isNaN(e)?M():{type:3,value:e}}else return M()}}},Power:{description:"Returns base raised to the given power",arguments:[{name:"base",boxed:!0,unroll:!0},{name:"exponent",boxed:!0,unroll:!0}],fn:(l,e)=>{if(l.type===3&&e.type===3&&(l.value>=0||e.value===0||Math.abs(e.value)>=1)){let i=Math.pow(l.value,e.value);return isNaN(i)?M():{type:3,value:i}}let t=Oe(l),r=Oe(e);if(t&&r){let i=ve(t,r);return ce(i)}return M()}}},et={True:{fn:()=>({type:4,value:!0})},False:{fn:()=>({type:4,value:!1})},Int:{fn:l=>({type:3,value:Math.floor(l)})},Rand:{volatile:!0,fn:()=>({type:3,value:Math.random()})},RandArray:{volatile:!0,arguments:[{name:"rows"},{name:"columns"},{name:"min"},{name:"max"},{name:"integer"}],description:"Returns an array of uniformly-distributed random numbers",fn:(l=1,e=1,t=0,r=1,i=!1)=>{let n=[];if(i){let o=r-t+1;for(let a=0;a<e;a++){let s=[];for(let c=0;c<l;c++)s.push({type:3,value:Math.floor(Math.random()*o+t)});n.push(s)}}else{let o=r-t;for(let a=0;a<e;a++){let s=[];for(let c=0;c<l;c++)s.push({type:3,value:Math.random()*o+t});n.push(s)}}return{type:9,value:n}}},RandBetween:{arguments:[{name:"min"},{name:"max"}],volatile:!0,fn:(l=0,e=1)=>{if(l>e){let t=l;l=e,e=t}return{type:3,value:Math.floor(Math.random()*(e+1-l)+l)}}},Sum:{description:"Adds arguments and ranges",arguments:[{boxed:!0,name:"values or ranges",repeat:!0}],fn:(...l)=>{let e={real:0,imaginary:0},t=oe(l);for(let r of t)switch(r.type){case 3:e.real+=r.value;break;case 4:break;case 8:e.real+=r.value.real,e.imaginary+=r.value.imaginary;break;case 7:return r}return ce(e)}},SumSQ:{description:"Returns the sum of the squares of all arguments",arguments:[{boxed:!0,name:"values or ranges",repeat:!0}],fn:(...l)=>{let e={real:0,imaginary:0},t=oe(l);for(let r of t)switch(r.type){case 3:e.real+=r.value*r.value;break;case 4:break;case 8:{let i=ne(r.value,r.value);e.real+=i.real,e.imaginary+=i.imaginary}break;case 7:return r}return ce(e)}},EDate:{arguments:[{name:"Start date",unroll:!0},{name:"Months",unroll:!0}],fn:(l,e=0)=>{if(typeof l!="number"||typeof e!="number")return U();let t=kn(l,e);return{type:3,value:Se(t.getTime(),!1)}}},EOMonth:{arguments:[{name:"Start date",unroll:!0},{name:"Months",unroll:!0}],fn:(l,e=0)=>{if(typeof l!="number"||typeof e!="number")return U();let t=kn(l,e);switch(t.getUTCMonth()){case 1:{let i=t.getUTCFullYear();i%4===0&&(i===1900||i%400===0||i%100!==0)?t.setUTCDate(29):t.setUTCDate(28)}break;case 0:case 2:case 4:case 6:case 7:case 9:case 11:t.setUTCDate(31);break;default:t.setUTCDate(30);break}return{type:3,value:Se(t.getTime(),!1)}}},Now:{description:"Returns current time",volatile:!0,fn:()=>({type:3,value:Se(new Date().getTime())})},YearFrac:{description:"Returns the fraction of a year between two dates",arguments:[{name:"Start"},{name:"End"},{name:"Basis",default:0}],fn:(l,e,t)=>{if(e<l){let n=l;l=e,e=n}let r=Math.max(0,e-l),i=360;if(t&&t<0||t>4)return U();switch(t){case 1:break;case 2:break;case 3:i=365;break}return{type:3,value:r/i}}},Date:{description:"Constructs a date from year/month/day",arguments:[{name:"year",unroll:!0},{name:"month",unroll:!0},{name:"day",unroll:!0}],fn:(l,e,t)=>{let r=An(l,e,t);return r===!1?U():{type:3,value:r}}},Today:{description:"Returns current day",volatile:!0,fn:()=>{let l=new Date;return l.setMilliseconds(0),l.setSeconds(0),l.setMinutes(0),l.setHours(12),{type:3,value:Se(l.getTime())}}},IfError:{description:"Returns the original value, or the alternate value if the original value contains an error",arguments:[{name:"original value",allow_error:!0,boxed:!0},{name:"alternate value"}],fn:(l,e=0)=>l&&l.type===7?{value:e,type:be(e)}:l},IsNA:{description:"Checks if another cell contains a #NA error",arguments:[{name:"reference",allow_error:!0,boxed:!0}],fn:(...l)=>{let e=oe(l);for(let t of e)if(t.type===7&&t.value==="N/A")return{type:4,value:!0};return{type:4,value:!1}}},IsErr:{description:"Checks if another cell contains an error",arguments:[{name:"reference",allow_error:!0,boxed:!0}],fn:(...l)=>{let e=oe(l);for(let t of e)if(t.type===7&&t.value!=="N/A")return{type:4,value:!0};return{type:4,value:!1}}},IsError:{description:"Checks if another cell contains an error",arguments:[{name:"reference",allow_error:!0,boxed:!0}],fn:(...l)=>{let e=oe(l);for(let t of e)if(t.type===7)return{type:4,value:!0};return{type:4,value:!1}}},Year:{description:"Returns year from date",arguments:[{name:"date",unroll:!0}],fn:l=>Q(new Date(Re(l)).getUTCFullYear())},Month:{description:"Returns month from date",arguments:[{name:"date",unroll:!0}],fn:l=>Q(new Date(Re(l)).getUTCMonth()+1)},Day:{description:"Returns day of month from date",arguments:[{name:"date",unroll:!0}],fn:l=>Q(new Date(Re(l)).getUTCDate())},Radians:{description:"Converts degrees to radians",arguments:[{name:"Degrees",description:"Angle in degrees",unroll:!0}],fn:l=>Q(l*Math.PI/180)},Degrees:{description:"Converts radians to degrees",arguments:[{name:"Radians",description:"Angle in radians",unroll:!0}],fn:l=>Q(l/Math.PI*180)},CountA:{description:"Counts cells that are not empty",fn:(...l)=>Q(X(l).reduce((e,t)=>typeof t>"u"?e:e+1,0))},Count:{description:"Counts cells that contain numbers",fn:(...l)=>Q(X(l).reduce((e,t)=>typeof t=="number"||he(t)?e+1:e,0))},Or:{fn:(...l)=>{let e=!1;l=X(l);for(let t of l)e=e||!!t;return Q(e)}},And:{fn:(...l)=>{let e=!0;l=X(l);for(let t of l)e=e&&!!t;return Q(e)}},Not:{arguments:[{unroll:!0,boxed:!0}],fn:l=>{let e=!1;if(l)switch(l.type){case 0:e=!1;break;case 2:case 4:case 3:e=!!l.value;break;case 7:return l}return Q(!e)}},If:{arguments:[{name:"test value",boxed:!0},{name:"value if true",boxed:!0,allow_error:!0},{name:"value if false",boxed:!0,allow_error:!0}],fn:(l,e={type:4,value:!0},t={type:4,value:!1})=>{let r=e.type===9,i=t.type===9;return l.type===9?{type:9,value:l.value.map((o,a)=>o.map((s,c)=>(s.type===2?s.value.toLowerCase()!=="false"&&s.value.toLowerCase()!=="f":!!s.value)?r?e.value[a][c]:e:i?t.value[a][c]:t))}:(l.type===2?l.value.toLowerCase()!=="false"&&l.value.toLowerCase()!=="f":!!l.value)?e:t}},Fact:{description:"Returns the factorial of a number",arguments:[{name:"number",unroll:!0}],fn:l=>{l=Math.round(l);let e=1;for(;l>1;)e*=l,l--;return{type:3,value:e}}},Factdouble:{description:"Returns the double factorial of a number",arguments:[{name:"number",unroll:!0}],fn:l=>{l=Math.round(l);let e=1;for(;l>1;)e*=l,l-=2;return{type:3,value:e}}},Power:{description:"Returns base raised to the given power",arguments:[{name:"base",boxed:!0,unroll:!0},{name:"exponent",boxed:!0,unroll:!0}],fn:(l,e)=>{let t=Oe(l),r=Oe(e);if(!t||!r)return M();if(l.type===8||e.type===8)return ce(ve(t,r));{let i=Math.pow(t.real,r.real);return isNaN(i)?M():{type:3,value:i}}}},Mod:{arguments:[{unroll:!0},{unroll:!0}],fn:(l,e)=>e?Q(l%e):ye()},Large:{description:"Returns the nth numeric value from the data, in descending order",arguments:[{name:"values"},{name:"index",unroll:!0}],fn:(l,e)=>{if(e<=0)return U();let t=te(l);return t.sort((r,i)=>i-r),e<=t.length?{type:3,value:t[e-1]}:U()}},Small:{description:"Returns the nth numeric value from the data, in ascending order",arguments:[{name:"values"},{name:"index",unroll:!0}],fn:(l,e)=>{if(e<=0)return U();let t=te(l);return t.sort((r,i)=>r-i),e<=t.length?{type:3,value:t[e-1]}:U()}},Filter:{description:"Filter an array using a second array.",arguments:[{name:"source",description:"Source array"},{name:"filter",description:"Filter array"}],fn:(l,e)=>{if(typeof l>"u"||typeof e>"u")return U();Array.isArray(l)||(l=[[l]]),Array.isArray(e)||(e=[[e]]);let t=l.length,r=l[0].length,i=e.length,n=e[0].length;if(r===n){let o=[];for(let a=0;a<t;a++)o.push([]);for(let[a,s]of e[0].entries())if(s)for(let c=0;c<t;c++)o[c].push(Q(l[c][a]));return{type:9,value:o}}else if(t===i){let o=[];for(let[a,[s]]of e.entries())s&&o.push(l[a].map(c=>Q(c)));return{type:9,value:o}}return U()}},Sort:{arguments:[{name:"values"}],fn:(...l)=>(l=X(l),l.every(e=>typeof e=="number")?l.sort((e,t)=>e-t):l.sort(),{type:9,value:[l.map(e=>Q(e))]})},Transpose:{description:"Returns transpose of input matrix",arguments:[{name:"matrix",boxed:!0}],fn:l=>l.type===9?{type:9,value:ar(l.value)}:l},Max:{fn:(...l)=>({type:3,value:Math.max.apply(0,te(l))})},Min:{fn:(...l)=>({type:3,value:Math.min.apply(0,te(l))})},SumProduct:{description:"Returns the sum of pairwise products of two or more ranges",fn:(...l)=>{let e=l.map(i=>X(i)),t=Math.max.apply(0,e.map(i=>i.length)),r=0;for(let i=0;i<t;i++)r+=e.reduce((n,o)=>{let a=o[i];return a===!0&&(a=1),typeof a=="number"?n*a:0},1);return{type:3,value:r}}},Row:{arguments:[{name:"reference",metadata:!0}],fn:function(l){if(!l)if(this?.area){let e=[];for(let t=this.area.start.column;t<=this.area.end.column;t++){let r=[];for(let i=this.area.start.row;i<=this.area.end.row;i++)r.push({type:3,value:i+1});e.push(r)}return{type:9,value:e}}else return{type:3,value:this?this.address.row+1:-1};if(l.type===9){let e=l.value,t=e[0][0];if(ue(t))return{type:9,value:[e[0].map((r,i)=>({type:3,value:i+t.value.address.row+1}))]}}else if(ue(l))return{type:3,value:l.value.address.row+1};return U()}},Column:{arguments:[{name:"reference",metadata:!0}],fn:function(l){if(!l)if(this?.area){let e=[];for(let t=this.area.start.column;t<=this.area.end.column;t++){let r=[];for(let i=this.area.start.row;i<=this.area.end.row;i++)r.push({type:3,value:t+1});e.push(r)}return{type:9,value:e}}else return{type:3,value:this?this.address.column+1:-1};if(l.type===9){let e=l.value,t=e[0][0];if(ue(t))return{type:9,value:e.map((r,i)=>[{type:3,value:i+t.value.address.column+1}])}}else if(ue(l))return{type:3,value:l.value.address.row+1};return U()}},Choose:{arguments:[{name:"Selected index"},{name:"Choice 1...",metadata:!0}],return_type:"reference",description:"Returns one of a list of choices",fn:(l,...e)=>{if(l<1||l>e.length)return M();let t=e[l-1];if(ue(t))return{type:5,value:t.value.address};if(t.type===9){let r=t.value,i=r.length,n=r[0].length,o=r[0][0],a=r[i-1][n-1];if(i===1&&n===1){if(ue(o))return{type:5,value:o.value.address}}else if(ue(o)&&ue(a))return{type:5,value:{type:"range",position:0,id:0,label:"",start:o.value.address,end:a.value.address}}}return{...t}}},XLOOKUP:{arguments:[{name:"Lookup value"},{name:"Lookup array"},{name:"Return array",metadata:!0},{name:"Not found",boxed:!0},{name:"Match mode",default:0},{name:"Search mode",default:1}],return_type:"reference",xlfn:!0,fn:(l,e,t,r,i=0,n=1)=>{if(!t)return U();let o;if(t.type===9){let d=t.value,u=d.length,h=d[0].length,f=d[0][0],m=d[u-1][h-1];ue(f)&&ue(m)&&(o=new v(f.value.address,m.value.address))}if(!o)return console.info("invalid range"),$();if(!Array.isArray(e))return console.info("lookup is not an array"),M();let a=e[0];if(!Array.isArray(a))return console.info("lookup is not a 2d array"),M();if(e.length!==1&&a.length!==1)return console.info("lookup array has invalid dimensions"),M();let s=e.length===1;s&&(e=ni(e)),n<0&&e.reverse();let c=(d,u)=>{let h,f;if(s?(n<0&&(u=d.rows-1-u),u>=0&&u<d.rows&&(h={type:"address",position:0,id:1,label:"",row:d.start.row+u,column:d.start.column,sheet_id:d.start.sheet_id},f={type:"address",position:0,id:2,label:"",row:d.start.row+u,column:d.end.column,sheet_id:d.start.sheet_id})):(n<0&&(u=d.columns-1-u),u>=0&&u<d.columns&&(h={type:"address",position:0,id:1,label:"",row:d.start.row,column:d.start.column+u,sheet_id:d.start.sheet_id},f={type:"address",position:0,id:2,label:"",row:d.end.row,column:d.start.column+u,sheet_id:d.start.sheet_id})),h&&f){let m={type:"range",position:0,id:0,label:"",start:h,end:f};return{type:5,value:m}}return{type:0}};if(i===2&&typeof l!="string"&&(i=0),(i===1||i===-1)&&typeof l=="number"){let d=0,u=-1;for(let h=0;h<e.length;h++){let f=e[h][0];if(typeof f=="number"){if(f===l)return c(o,h);let m=Math.abs(f-l);(i===1&&f>l||i===-1&&f<l)&&(u<0||m<d)&&(d=m,u=h)}}if(u>=0)return c(o,u)}switch(i){case 2:{let d=vt(l?.toString()||""),u=new RegExp("^"+d+"$","i");for(let h=0;h<e.length;h++){let f=e[h][0];if(typeof f=="string"&&u.exec(f))return c(o,h)}}break;case 0:typeof l=="string"&&(l=l.toLowerCase());for(let d=0;d<e.length;d++){let u=e[d][0];if(typeof u=="string"&&(u=u.toLowerCase()),u===l)return c(o,d)}break}return r&&r.type!==0?r:we()}},HLookup:{arguments:[...Rn],fn:(l,e,t,r=!0)=>En(l,e,t,r,!0)},VLookup:{arguments:[...Rn],fn:(l,e,t,r=!0)=>En(l,e,t,r,!1)},Product:{arguments:[{boxed:!0}],fn:(...l)=>{let e={real:1,imaginary:0};l=oe(l);for(let t of l)t.type===8?e=ne(e,t.value):t.type===3&&(e.real*=t.value,e.imaginary*=t.value);return ce(e)}},Log:{arguments:[{name:"number",unroll:!0},{name:"base",unroll:!0}],fn:(l,e=10)=>({type:3,value:Math.log(l)/Math.log(e)})},Log10:{arguments:[{name:"number",unroll:!0}],fn:l=>({type:3,value:Math.log(l)/Math.log(10)})},Ln:{arguments:[{name:"number",unroll:!0}],fn:l=>({type:3,value:Math.log(l)})},"Ceiling.Math":{arguments:[{name:"number",unroll:!0},{name:"significance",unroll:!0},{name:"away from zero",unroll:!0}],fn:(l,e=1,t)=>{let r=0;return t&&l<0?r=-Math.ceil(-l/e)*e:r=Math.ceil(l/e)*e,{type:3,value:r}}},"Floor.Math":{arguments:[{name:"number",unroll:!0},{name:"significance",unroll:!0},{name:"away from zero",unroll:!0}],fn:(l,e=1,t)=>{let r=0;return t&&l<0?r=-Math.floor(-l/e)*e:r=Math.floor(l/e)*e,{type:3,value:r}}},Floor:{arguments:[{name:"number",unroll:!0},{name:"significance",unroll:!0}],fn:(l,e=1)=>({type:3,value:Math.floor(l/e)*e})},Ceiling:{arguments:[{name:"number",unroll:!0},{name:"significance",unroll:!0}],fn:(l,e=1)=>({type:3,value:Math.ceil(l/e)*e})},Round:{arguments:[{unroll:!0},{unroll:!0}],fn:(l,e=0)=>{let t=Math.pow(10,e);return{type:3,value:Math.round(t*l)/t}}},RoundDown:{arguments:[{unroll:!0},{unroll:!0}],fn:(l,e=0)=>{let t=Math.pow(10,e),r=l>=0;return{type:3,value:r?Math.floor(t*l)/t:Math.ceil(t*l)/t}}},RoundUp:{arguments:[{unroll:!0},{unroll:!0}],fn:(l,e=0)=>{let t=Math.pow(10,e),r=l>=0;return{type:3,value:r?Math.ceil(t*l)/t:Math.floor(t*l)/t}}},Reverse:{arguments:[{boxed:!0}],fn:l=>l.type===9?(l.value.length===1?l.value[0].reverse():l.value.reverse(),l):{type:2,value:(l.value??"").toString().split("").reverse().join("")}},Exp:{arguments:[{boxed:!0,unroll:!0}],fn:l=>{if(l.type===8){let e=yt(l.value);return ce(e)}return l.type!==3?M():{type:3,value:Math.exp(l.value)}}},Abs:{arguments:[{boxed:!0,unroll:!0}],fn:l=>l.type===8?{type:3,value:Math.sqrt(l.value.real*l.value.real+l.value.imaginary*l.value.imaginary)}:l.type!==3?M():{type:3,value:Math.abs(l.value||0)}},Simplify:{arguments:[{name:"value",unroll:!0},{name:"significant digits",unroll:!0}],fn:(l,e=2)=>{if(e=e||2,l===0)return{type:3,value:l};let t=l<0?-1:1;l*=t;let r=Math.pow(10,Math.floor(Math.log10(l))+1-e);return{type:3,value:Math.round(l/r)*r*t}}},Sqrt:{description:"Returns the square root of the argument",arguments:[{boxed:!0,unroll:!0}],fn:l=>{if(l.type===8){let e=ve(l.value,{real:.5,imaginary:0});return ce(e)}else{if(l.type===0||!l.value)return{type:3,value:0};if(l.type===3)return{type:3,value:Math.sqrt(l.value)}}return M()}},HexToDec:{arguments:[{description:"hexadecimal string",unroll:!0}],fn:l=>({type:3,value:parseInt(l,16)})},DecToHex:{arguments:[{description:"number",unroll:!0}],fn:l=>({type:2,value:l.toString(16)})},Checkbox:{arguments:[{name:"checked"}],click:Cn,render:Sn,fn:l=>({value:!!l,type:4})},"Sparkline.Column":{arguments:[{name:"data"},{name:"color"},{name:"negative color"}],render:l=>(wt.RenderColumn(l.width,l.height,l.context,l.cell,l.style),{handled:!0}),fn:(...l)=>({type:5,value:l,key:"sparkline-data"})},"Sparkline.Line":{arguments:[{name:"data"},{name:"color"},{name:"line width"}],render:l=>(wt.RenderLine(l.width,l.height,l.context,l.cell,l.style),{handled:!0}),fn:(...l)=>({type:5,value:l,key:"sparkline-data"})},UniqueValues:{arguments:[{name:"range",boxed:!0}],visibility:"internal",fn:l=>{if(l.type===9){let e=n=>{if(n)switch(n.type){case 2:case 3:case 4:return n.value;case 0:return"";default:return console.info("check",n,n.value),n.value?.toString()||""}else return""},t=new Set,r=new Set;for(let n of l.value)for(let o of n){let a=e(o);t.has(a)?r.add(a):t.add(a)}let i=[];for(let n of l.value){let o=[];for(let a of n){let s=e(a);o.push({type:4,value:!r.has(s)})}i.push(o)}return{type:9,value:i}}return{type:4,value:!0}}},Between:{arguments:[{name:"target",boxed:!0,unroll:!0},{name:"min"},{name:"max"}],visibility:"internal",fn:(l,e=0,t=1)=>({type:4,value:l.type===3&&l.value>=e&&l.value<=t})},Gradient:{arguments:[{name:"range",boxed:!0},{name:"min"},{name:"max"},{name:"parameters"}],visibility:"internal",fn:(l,e,t,r)=>{let i=oe([l]),n=0,o=0,a=0;for(let u of i){if(u.type===7)return u;u.type===3&&(n===0&&!r?(o=u.value,a=u.value):(o=Math.min(o,u.value),a=Math.max(a,u.value)),n++)}typeof t=="number"&&(a=t),typeof e=="number"&&(o=e);let s=a-o,c=1,d=1;if(l.type===9){c=l.value.length,d=l.value[0]?.length||0;let u=[];for(let h=0;h<c;h++){let f=[];for(let m=0;m<d;m++){let p=l.value[h][m];if(p.type===3){let b=0;a===o?p.value>a?b=1:p.value<a?b=0:b=.5:s>0&&(b=(p.value-o)/s),r?f.push({type:9,value:[[{type:3,value:b},{type:3,value:(0-o)/s}]]}):f.push({type:3,value:b})}else f.push({type:0})}u.push(f)}return{type:9,value:u}}else return U()}},ATan2:{arguments:[{name:"y",boxed:!0,unroll:!0},{name:"x",boxed:!0,unroll:!0}],fn:(l,e)=>{if(l.type===3&&e.type===3)return{type:3,value:Math.atan2(l.value,e.value)};if(l.type===3&&(l={type:8,value:{real:l.value,imaginary:0}}),e.type===3&&(e={type:8,value:{real:e.value,imaginary:0}}),l.type===8&&e.type===8){let t=hn(l.value,e.value);return t===!1?U():{type:8,value:t}}return U()}},Sin:Le(Math.sin,rr),SinH:Le(Math.sinh,cn),ASin:Le(Math.asin,Yr),Cos:Le(Math.cos,ln),CosH:Le(Math.cosh,sn),ACos:Le(Math.acos,dn),Tan:Le(Math.tan,an),TanH:Le(Math.tanh,on),ATan:Le(Math.atan,un),E:{fn:()=>({type:3,value:Math.E})},PI:{fn:()=>({type:3,value:Math.PI})},SQRT2:{fn:()=>({type:3,value:Math.SQRT2})},SQRT1_2:{fn:()=>({type:3,value:Math.SQRT1_2})},Sequence:{arguments:[{name:"rows",boxed:!0},{name:"columns",default:1,boxed:!0},{name:"start",default:1,boxed:!0},{name:"step",default:1,boxed:!0}],fn:(l,e,t,r)=>{let i=cr(l,1),n=cr(e,1),o=cr(r,1),a=cr(t,1);if(i===!1||n===!1||o===!1||a===!1)return U();let s=[];for(let c=0;c<n;c++){let d=[];for(let u=0;u<i;u++)d.push({type:3,value:a+u*o*n+c*o});s.push(d)}return{type:9,value:s}}}},Tn={};for(let l of Object.keys(et))Tn[l.toLowerCase()]=l;var wa=["ceil","pow","ln10","ln2","log10","log10e","log1p","log2","log2e","random","imul","clz32","fround","f16round"],Mn={};for(let l of wa)Mn[l.toLowerCase()]=l;for(let l of Object.getOwnPropertyNames(Math)){let e=l.toLowerCase();if(Tn[e]||Mn[e])continue;let t=Object.getOwnPropertyDescriptor(Math,l);if(!t)continue;let r=t.value,i=typeof r;switch(i){case"number":et[l]={fn:()=>({type:3,value:r}),category:["Math Functions"]};break;case"function":et[l]={fn:(...n)=>Q(r(...n)),category:["Math Functions"]};break;default:console.info("unexpected type:",i,l);break}}Math.log10||(Math.log10=l=>Math.log(l)/Math.log(10));var xt=(l,e,t=0,r=0,i=0)=>i?-(t*(l/(1-Math.pow(1+l,-e))))/(1+l)-r*(1/((1+l)*((Math.pow(1+l,e)-1)/l))):-(t*l*Math.pow(1+l,e)+r*l)/(Math.pow(1+l,e)-1),Vn=(l,e,t,r=0,i=0)=>i?(1+l)*-t/l*(Math.pow(1+l,e)-1)-r*Math.pow(1+l,e):-t/l*(Math.pow(1+l,e)-1)-r*Math.pow(1+l,e),si=(l,e,t,r=0,i=0,n=0)=>{if(e<1)return NaN;if(e===1&&n)return 0;let o=xt(l,t,r,i,n),a=Vn(l,e-1,o,r,n)*l;return n?a/(1+l):a},Un=(l,e,t,r=0,i=0,n=0)=>xt(l,t,r,i,n)-si(l,e,t,r,i,n),Dn={NPV:{description:"Returns the present value of a series of future cashflows",arguments:[{name:"Rate"},{name:"Cashflow"}],fn:(l=0,...e)=>{let t=0,r=X(e);for(let i=0;i<r.length;i++){let n=r[i];typeof n=="number"&&(t+=Math.pow(1+l,-(i+1))*n)}return{type:3,value:t}}},XNPV:{description:"returns the NPV of a nonperiodic stream of payments at a given rate",arguments:[{name:"Discount rate"},{name:"Values"},{name:"Dates"}],fn:(l,e,t)=>{if(typeof l!="number")return U();if(e=X(e),t=X(t),e.length!==t.length)return U();let r=[];for(let o of e){if(typeof o!="number")return U();r.push(o)}let i=[];for(let o of t){if(typeof o!="number")return U();i.push(Math.floor(o))}let n=0;for(let o=0;o<r.length;o++)n+=(r[o]||0)/Math.pow(1+l,(i[o]-i[0])/365);return{type:3,value:n}}},XIRR:{description:"returns the internal rate of return of a nonperiodic stream of payments",arguments:[{name:"Values"},{name:"Dates"},{name:"Guess",default:.1}],fn:(l,e,t=.1)=>{if(l=X(l),e=X(e),l.length!==e.length)return U();let r=0,i=0,n=[];for(let u of l){if(typeof u!="number")return U();u>0&&r++,u<0&&i++,n.push(u)}if(r<=0||i<=0)return U();let o=[];for(let u of e){if(typeof u!="number")return U();o.push(Math.floor(u))}let a=o[0];for(let u of o)if(u<a)return U();let s=.1,c=[{found:!1,value:0},{found:!1,value:0}],d=n.length;for(let u=0;u<100;u++){let h=0;for(let f=0;f<d;f++)h+=(n[f]||0)/Math.pow(1+t,(o[f]-o[0])/365);if(Math.abs(h)<=1e-6)return{type:3,value:t};if(h>0){if(c[0].value=c[0].found?Math.max(c[0].value,t):t,c[0].found=!0,!c[1].found){t+=s;continue}}else if(c[1].value=c[1].found?Math.min(c[1].value,t):t,c[1].found=!0,!c[0].found){t-=s;continue}t=c[0].value+(c[1].value-c[0].value)/2}return M()}},IRR:{description:"Calculates the internal rate of return of a series of cashflows",arguments:[{name:"Cashflows"},{name:"Guess",default:.1}],fn:(l,e=.1)=>{let t=X(l).map(n=>typeof n=="number"?n:0),r=.1,i=[{found:!1,value:0},{found:!1,value:0}];for(let n=0;n<50;n++){let o=0;for(let a=0;a<t.length;a++)o+=Math.pow(1+e,-(a+1))*t[a];if(Math.abs(o)<=.00125)return{type:3,value:e};if(o>0){if(i[0].value=i[0].found?Math.max(i[0].value,e):e,i[0].found=!0,!i[1].found){e+=r;continue}}else if(i[1].value=i[1].found?Math.min(i[1].value,e):e,i[1].found=!0,!i[0].found){e-=r;continue}e=i[0].value+(i[1].value-i[0].value)/2}return{type:7,value:"NUM"}}},CUMPRINC:{description:"Returns cumulative principal paid on a loan between two periods",arguments:[{name:"Rate"},{name:"Periods"},{name:"Present Value"},{name:"Start Period"},{name:"End Period"},{name:"Type",default:0}],fn:(l,e,t,r,i,n=0)=>{let o=0;for(let a=r;a<=i;a++)o+=Un(l,a,e,t,0,n);return{type:3,value:o}}},CUMIPMT:{description:"Returns cumulative interest paid on a loan between two periods",arguments:[{name:"Rate"},{name:"Periods"},{name:"Present Value"},{name:"Start Period"},{name:"End Period"},{name:"Type",default:0}],fn:(l,e,t,r,i,n=0)=>{let o=0;for(let a=r;a<=i;a++)o+=si(l,a,e,t,0,n);return{type:3,value:o}}},IPMT:{description:"Returns the interest portion of a payment",arguments:[{name:"Rate"},{name:"Period"},{name:"Periods"},{name:"Present Value",default:0},{name:"Future Value",default:0},{name:"Type",default:0}],fn:(l,e,t,r=0,i=0,n=0)=>({type:3,value:si(l,e,t,r,i,n)})},PPMT:{description:"Returns the principal portion of a payment",arguments:[{name:"Rate"},{name:"Period"},{name:"Periods"},{name:"Present Value",default:0},{name:"Future Value",default:0},{name:"Type",default:0}],fn:(l,e,t,r=0,i=0,n=0)=>({type:3,value:Un(l,e,t,r,i,n)})},Rate:{description:"Returns the interest rate of a loan",arguments:[{name:"Periods"},{name:"Payment"},{name:"Present Value",default:0},{name:"Future Value",default:0},{name:"Type",default:0}],fn:(l,e,t=0,r=0,i=0)=>{let n=.25,o=[-1,1],a=32,s=1e-6;for(let c=0;c<a;c++){let d=xt(n,l,t,r,i);if(Math.abs(d-e)<=s)return{type:3,value:n};let u=xt(o[1],l,t,r,i);e>=d&&e<=u||e>=u&&e<=d?o[0]=n:o[1]=n,n=o[0]+(o[1]-o[0])/2}return{type:3,value:n}}},FV:{description:"Returns the future value of an investment",arguments:[{name:"Rate"},{name:"Periods"},{name:"Payment"},{name:"Present Value",default:0},{name:"Type",default:0}],fn:(l,e,t,r=0,i=0)=>({type:3,value:Vn(l,e,t,r,i)})},PV:{description:"Returns the present value of an investment",arguments:[{name:"Rate"},{name:"Periods"},{name:"Payment"},{name:"Future Value",default:0},{name:"Type",default:0}],fn:(l,e,t,r=0,i=0)=>i?(t+=r*(1/((1+l)*((Math.pow(1+l,e)-1)/l))),{type:3,value:-(t+t/l*(1-Math.pow(1+l,-(e-1))))}):{type:3,value:-(r+t/l*(Math.pow(1+l,e)-1))/Math.pow(1+l,e)}},NPER:{description:"Returns the number of periods of an investment",arguments:[{name:"Rate"},{name:"Payment"},{name:"Present Value"},{name:"Future Value",default:0},{name:"Type",default:0}],fn:(l,e,t=0,r=0,i=0)=>i?{type:3,value:1+(-Math.log(1+l*(1-t/-e))+Math.log(1+r*l/(-e*(1+l))))/Math.log(1+l)}:{type:3,value:(Math.log(Math.pow(1-t*l/-e,-1))+Math.log(1+r*l/-e))/Math.log(1+l)}},PMT:{description:"Returns the periodic payment of a loan",arguments:[{name:"Rate"},{name:"Periods"},{name:"Present Value"},{name:"Future Value",default:0},{name:"Type",default:0}],fn:(l,e,t,r=0,i=0)=>({type:3,value:xt(l,e,t,r,i)})}};var zn={Char:{arguments:[{name:"number"}],fn:l=>({type:2,value:String.fromCodePoint(l||32)}),category:["text"]},Code:{arguments:[{name:"string"}],fn:l=>({type:3,value:l.codePointAt(0)||0}),category:["text"]},Value:{arguments:[{name:"text"}],fn:l=>{let e=_e.TryParse(l);return e.type===3?{type:3,value:e.value}:U()},category:["text"]},Text:{arguments:[{name:"value"},{name:"number format"}],fn:(l,e="0.00####")=>({type:2,value:L.Get(e).Format(l||0)}),category:["text"]},WildcardMatch:{visibility:"internal",arguments:[{name:"text",unroll:!0},{name:"text",unroll:!0},{name:"invert"}],fn:(l,e,t=!1)=>{if(typeof l=="string"&&typeof e=="string"){let r=vt(e),i=new RegExp("^"+r+"$","i").exec(l);return{type:4,value:t?!i:!!i}}return{type:4,value:l===e||l?.toString()===e?.toString()}}},Exact:{arguments:[{name:"text",boxed:!0,unroll:!0},{name:"text",boxed:!0,unroll:!0}],category:["text"],fn:(l,e)=>({type:4,value:l?.value?.toString()===e?.value?.toString()})},Len:{arguments:[{name:"string",unroll:!0}],fn:l=>({type:3,value:l.toString().length})},Substitute:{arguments:[{name:"text"},{name:"search"},{name:"replacement"},{name:"index"}],fn:(l,e,t,r)=>{if(typeof r=="number"){if(r<1)return M();let i=1;return{type:2,value:l.replaceAll(e,(...n)=>(console.info(n),i++===r?t:e))}}else return{type:2,value:l.replaceAll(e,t)}}},Left:{arguments:[{name:"string"},{name:"count"}],fn:(l,e=1)=>({type:2,value:l.substr(0,e)}),category:["text"]},Right:{arguments:[{name:"string"},{name:"count"}],fn:(l,e=1)=>({type:2,value:l.slice(-e)}),category:["text"]},Mid:{arguments:[{name:"string"},{name:"left"},{name:"count"}],fn:(l,e=0,t=1)=>({type:2,value:l.substr(Math.max(0,e-1),t)}),category:["text"]},Search:{description:"Find a string (needle) in another string (haystack). Case-insensitive.",arguments:[{name:"Needle"},{name:"Haystack"},{name:"Start",default:1}],fn:(l,e,t=1)=>{if(t>=1){if(!l)return{type:3,value:t};let r=vt(l),i=new RegExp(r,"i").exec(e.substr(t-1));if(i)return{type:3,value:i.index+t}}return M()}},Find:{description:"Find a string (needle) in another string (haystack). Case-sensitive.",arguments:[{name:"Needle"},{name:"Haystack"},{name:"Start",default:1}],fn:(l,e,t=1)=>{if(t>=1){if(!l)return{type:3,value:t};l=l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");let r=new RegExp(l).exec(e.substr(t-1));if(r)return{type:3,value:r.index+t}}return M()}},Upper:{description:"Converts text to upper case",arguments:[{name:"text",unroll:!0}],fn:l=>l==null?{type:0}:{type:2,value:l.toString().toUpperCase()}},Lower:{description:"Converts text to lower case",arguments:[{name:"text",unroll:!0}],fn:l=>l==null?{type:0}:{type:2,value:l.toString().toLowerCase()}},Concat:{description:"Pastes strings together",fn:(...l)=>{let t=X(l).map(r=>{let i=r?.toString()||"";return typeof r=="number"&&F.decimal_separator===","?i.replace(/\./,","):i}).join("");return{type:2,value:t}}}},li={Concatenate:"Concat"};var dr=(l,e)=>({type:4,value:typeof e.value?.value===l}),ur=[{name:"Reference",metadata:!0,unroll:!0}],Ln={IsBlank:{description:"Returns true if the reference is blank",arguments:ur,fn:dr.bind(0,"undefined")},IsNumber:{description:"Returns true if the reference is a number",arguments:ur,fn:dr.bind(0,"number")},IsLogical:{description:"Returns true if the reference is a logical TRUE or FALSE",arguments:ur,fn:dr.bind(0,"boolean")},IsText:{description:"Returns true if the reference is text",arguments:ur,fn:dr.bind(0,"string")}};var Fn=2220446049250313e-31,xa=l=>{let e=1+l;return Math.log(e)-(e-1-l)/e},In=(l,e,t,r)=>{let i=2*Number.MIN_VALUE,n=0,o=1,a=1-(l+e)*t/(l+1);Math.abs(a)<i&&(a=Number.NaN),a=1/a,n=a;for(let s=1;s<=512;s++){let c=s*(e-s)*t/((l-1+2*s)*(l+2*s)),d=0;if(a=1+c*a,o=1+c/o,Math.abs(a)<i&&(a=Number.NaN),Math.abs(o)<i&&(o=Number.NaN),a=1/a,d=a*o,n*=d,c=-(l+s)*(l+e+s)*t/((l+2*s)*(l+2*s+1)),a=1+c*a,o=1+c/o,Math.abs(a)<i&&(a=Number.NaN),Math.abs(o)<i&&(o=Number.NaN),a=1/a,d=a*o,n*=d,Math.abs(d-1)<2*Fn||n*Math.abs(d-1)<r)return n}return Number.NaN},ci=(l,e,t)=>{if(e<0||t<0)return Number.NaN;if(l<=0)return 0;if(l>=1)return 1;if(l>.5)return 1-ci(1-l,t,e);let r=e/(e+t),i=0;if(l<.1){let n=(Math.log(e)+ke(e)+ke(t)-ke(e+t)+Math.log(l))/e;n<=0?(i=Math.exp(n),i*=Math.pow(1-i,-(t-1)/e)):i=r,i>r&&(i=r)}else i=r;for(let n=0;n<64;n++){let o=l-ui(i,e,t),a=di(i,e,t);if(o===0)return i;let s=o/Math.max(2*Math.abs(o/i),a),c=s,d=-((e-1)/i-(t-1)/(1-i))*s*s/2,u=c;if(Math.abs(d)<Math.abs(c)?u+=d:u*=2*Math.abs(c/d),i+u>0&&i+u<1?i+=u:i=Math.sqrt(i)*Math.sqrt(r),Math.abs(c)<=1e-10*i)return i}return i},ke=l=>{let e=l-1,t=e+5.5;t-=(e+.5)*Math.log(t);let r=1,i=[76.18009173,-86.50532033,24.01409822,-1.231739516,.00120858003,-536382e-11];for(let n of i)r+=n/++e;return-t+Math.log(2.50662827465*r)},di=(l,e,t)=>l<0||l>1?0:Math.exp(ke(e+t)-ke(e)-ke(t))*Math.pow(l,e-1)*Math.pow(1-l,t-1),ui=(l,e,t)=>{if(l<=0)return 0;if(l>=1)return 1;let i=-(ke(e)+ke(t)-ke(e+t))+e*Math.log(l)+t*xa(-l),n=Math.exp(i);if(l<(e+1)/(e+t+2)){let o=In(e,t,l,0);return n*o/e}else{let o=Math.abs(t/n)*Fn,a=In(t,e,1-l,o);return 1-n*a/t}};var Nn=l=>{let e=l-1,t=e+5.5;t-=(e+.5)*Math.log(t);let r=1,i=[76.18009173,-86.50532033,24.01409822,-1.231739516,.00120858003,-536382e-11];for(let n of i)r+=n/++e;return-t+Math.log(2.50662827465*r)},Ca=(l,e)=>{let t=Nn(l);if(e===0)return 0;let r=l,i=1/l,n=i;for(let o=1;o<1e3;o++)if(++r,n*=e/r,i+=n,Math.abs(n)<Math.abs(i)*3e-9)return i*Math.exp(-e+l*Math.log(e)-t);return console.error("too many iterations"),!1},Sa=(l,e)=>{let t=Nn(l),r=e+1-l,i=1/1e-30,n=1/r,o=n;for(let a=1;a<=1e3;a++){let s=-a*(a-l);r+=2,n=s*n+r,Math.abs(n)<1e-30&&(n=1e-30),i=r+s/i,Math.abs(i)<1e-30&&(i=1e-30),n=1/n;let c=n*i;if(o*=c,Math.abs(c-1)<3e-9)return Math.exp(-e+l*Math.log(e)-t)*o}return console.error("too many iterations"),!1},hr=(l,e)=>{if(e<0||l<=0)return console.error("invalid parameter"),!1;if(e<l+1)return Ca(l,e);{let t=Sa(l,e);return t===!1?!1:1-t}};var Hn=l=>{let e=.254829592,t=-.284496736,r=1.421413741,i=-1.453152027,n=1.061405429,o=.3275911;l=Math.abs(l);let a=1/(1+o*l);return 1-((((n*a+i)*a+r)*a+t)*a+e)*a*Math.exp(-1*l*l)},Aa=Math.sqrt(2*Math.PI),hi=(l,e,t,r)=>{let i=0;return r?i=.5*(1+(l<e?-1:1)*Hn(Math.abs(l-e)/(t*Math.sqrt(2)))):i=Math.exp(-1/2*Math.pow((l-e)/t,2))/(t*Aa),i},Pn=l=>{if(l===.5)return 0;let e=l<1&&l>.5?1-l:l,t=Math.sqrt(Math.log(1/Math.pow(e,2))),r=t-(2.515517+.802853*t+.010328*Math.pow(t,2))/(1+1.432788*t+.189269*Math.pow(t,2)+.001308*Math.pow(t,3));return l>.5?r:-r},fi=l=>{let e=l.length;return e%2?l[Math.floor(e/2)]:(l[e/2]+l[e/2-1])/2},On=(l,e=!0)=>{l.sort((i,n)=>i-n);let t=l.length,r=(i,n,o)=>{let a=n*i+o,s=a%1;if(s){let c=l[Math.floor(a)],d=l[Math.ceil(a)];return c+(d-c)*s}else return l[a]};return e?[l[0],r(.25,t-1,0),fi(l),r(.75,t-1,0),l[t-1]]:t%1?[l[0],r(.25,t-2,0),fi(l),r(.75,t-2,1),l[t-1]]:[l[0],r(.25,t-3,0),fi(l),r(.75,t-3,2),l[t-1]]},fr=l=>{let e=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,15056327351493116e-23],t=Math.PI,r=rr,i=Pe,n=ne,o=m=>({real:m,imaginary:0}),a=(m,p)=>({real:m.real+p.real,imaginary:m.imaginary+p.imaginary}),s=ve,c=yt,d=m=>({real:-m.real,imaginary:-m.imaginary}),u=fn;if(l.real<.5)return i(o(t),n(r(n(o(t),l)),fr({real:1-l.real,imaginary:-l.imaginary})));l.real-=1;let h=o(e[0]);for(let m=1;m<e.length;m++)h=a(h,i(o(e[m]),a(l,o(m))));let f=a(l,o(7.5));return u(o(Math.sqrt(2*t)),s(f,a(l,o(.5))),c(d(f)),h)},ka=(l,e,t)=>{let r=fr({real:e,imaginary:0}).real;return Math.pow(l,e-1)*Math.exp(-l/t)/(r*Math.pow(t,e))},Ra=(l,e,t)=>{let r=0,i=e*10,n=1e-6,o=0;for(;i-r>n;){o++;let a=(i+r)/2,s=hr(e,r/t),c=hr(e,a/t);if(s===!1||c===!1)return!1;(c-l)*(s-l)<0?i=a:r=a}return(r+i)/2},Te=(l,e=!1)=>{let t=l.length,r=0,i=0;for(let n=0;n<t;n++)r+=l[n];r/=t;for(let n=0;n<t;n++){let o=l[n]-r;i+=o*o}return e?i/(t-1):i/t},Gn={Slope:{arguments:[{name:"known_y"},{name:"known_x"}],fn:(l,e)=>{let t=te(e),r=te(l);if(t.length!==r.length)return U();let i=0,n=0,o=0,a=0;for(let c=0;c<t.length;c++){let d=t[c],u=r[c];o+=d*u,i+=d,n+=u,a+=d*d}let s=(t.length*o-i*n)/(t.length*a-i*i);return{type:3,value:s}}},Intercept:{arguments:[{name:"known_y"},{name:"known_x"}],fn:(l,e)=>{let t=te(e),r=te(l);if(t.length!==r.length)return U();let i=t.length,n=0,o=0,a=0,s=0;for(let d=0;d<i;d++){let u=t[d],h=r[d];a+=u*h,n+=u,o+=h,s+=u*u}let c=i*a-n*o;return c/=i*s-n*n,{type:3,value:(o-c*n)/i}}},Phi:{arguments:[{name:"x",boxed:!0,unroll:!0}],fn:l=>l.type===3?{type:3,value:1/Math.sqrt(Math.PI*2)*Math.exp(-l.value*l.value/2)}:U()},"Z.Test":{arguments:[{name:"Array",boxed:!0},{name:"x",boxed:!0,unroll:!0},{name:"Sigma",boxed:!0,unroll:!0}],fn:(l,e,t)=>{let r=[];if(l.type===9)for(let i of l.value)for(let n of i)n.type===3&&r.push(n.value);else l.type===3&&r.push(l.value);if(r.length&&e.type===3){let i=0,n=r.length;for(let a of r)i+=a;i/=n;let o=t?.type===3?t.value:Math.sqrt(Te(r,!0));return{type:3,value:1-hi((i-e.value)/(o/Math.sqrt(n)),0,1,!0)}}return U()}},"Beta.Dist":{description:"beta distribution",arguments:[{name:"x",unroll:!0},{name:"a"},{name:"b"},{name:"cumulative"}],fn:(l,e,t,r)=>e<0||t<0?U():r?{type:3,value:ui(l,e,t)}:{type:3,value:di(l,e,t)}},"Beta.Inv":{description:"Inverse of the beta distribution",arguments:[{name:"probability",unroll:!0},{name:"a"},{name:"b"}],fn:(l,e,t)=>e<0||t<0?U():{type:3,value:ci(l,e,t)}},Erf:{fn:l=>({type:3,value:Hn(l)})},"Norm.Inv":{description:"Inverse of the normal cumulative distribution",arguments:[{name:"probability"},{name:"mean",default:0},{name:"standard deviation",default:1}],xlfn:!0,fn:(l,e=0,t=1)=>({type:3,value:Pn(l)*t+e})},"Norm.S.Inv":{description:"Inverse of the standard normal cumulative distribution",arguments:[{name:"probability",unroll:!0}],xlfn:!0,fn:l=>({type:3,value:Pn(l)})},"Norm.Dist":{description:"Cumulative normal distribution",arguments:[{name:"value"},{name:"mean",default:0},{name:"standard deviation",default:1},{name:"cumulative",default:!0}],xlfn:!0,fn:(l,e=0,t=1,r=!0)=>({type:3,value:hi(l,e,t,r)})},"Norm.S.Dist":{description:"Cumulative normal distribution",arguments:[{name:"value"},{name:"cumulative",default:!0}],xlfn:!0,fn:(l,e=!0)=>({type:3,value:hi(l,0,1,e)})},"StDev.P":{description:"Returns the standard deviation of a set of values, corresponding to a population",arguments:[{name:"data"}],fn:(...l)=>({type:3,value:Math.sqrt(Te(te(l),!1))})},"StDev.S":{description:"Returns the standard deviation of a set of values, corresponding to a sample of a population",arguments:[{name:"data"}],fn:(...l)=>({type:3,value:Math.sqrt(Te(te(l),!0))})},"Var.P":{description:"Returns the variance of a set of values, corresponding to a population",arguments:[{name:"data"}],fn:(...l)=>({type:3,value:Te(te(l),!1)})},"Var.S":{description:"Returns the variance of a set of values, corresponding to a sample of a population",arguments:[{name:"data"}],fn:(...l)=>({type:3,value:Te(te(l),!0)})},Covar:{description:"Returns the covariance between two ranges of values",arguments:[{name:"A"},{name:"B"}],fn:(l,e)=>{if(!Array.isArray(l)||!Array.isArray(e))return M();if(!Array.isArray(l[0])||!Array.isArray(e[0]))return M();if(l.length!==e.length)return U();let t=0,r=0,i={x:0,y:0},n={x:[],y:[]};for(let o=0;o<l.length;o++){if(!l[o]||!e[o])continue;if(l[o].length!==e[o].length)return U();let a=l[o].length;r+=a;for(let s=0;s<a;s++)i.x+=l[o][s]||0,i.y+=e[o][s]||0,n.x.push(l[o][s]||0),n.y.push(e[o][s]||0)}if(r===0)return we();i.x/=r,i.y/=r;for(let o=0;o<r;o++)t+=(n.x[o]-i.x)*(n.y[o]-i.y);return{type:3,value:t/r}}},Correl:{description:"Returns the correlation between two ranges of values",arguments:[{name:"A"},{name:"B"}],fn:(l,e)=>{if(!Array.isArray(l)||!Array.isArray(e))return M();if(!Array.isArray(l[0])||!Array.isArray(e[0]))return M();let t=0,r=0,i=0,n=0,o=0,a=0,s=0;for(let c=0;c<l.length;c++){if(!l[c]||!e[c])continue;let d=l[c].length;for(let u=0;u<d;u++){let h=Number(l[c][u]),f=Number(e[c][u]);isNaN(h)||isNaN(f)||(r+=h*f,i+=h,n+=f,o+=h*h,a+=f*f,s++)}}return t=s*r-i*n,t&&(t/=Math.sqrt((s*o-i*i)*(s*a-n*n))),{type:3,value:t}}},GeoMean:{description:"Returns the geometric mean of all numeric arguments",arguments:[{boxed:!0}],fn:(...l)=>{l=oe(l);let e=0,t={real:1,imaginary:0},r=!1,i=!1;for(let n of l)n.type===8?(r=!0,t=ne(t,n.value),e++):n.type===3&&(n.value<0&&(i=!0),e++,t.real*=n.value,t.imaginary*=n.value);if(r){let n=ve(t,{real:1/e,imaginary:0});return n.imaginary?{type:8,value:n}:{type:3,value:n.real}}else return i?M():{type:3,value:Math.pow(t.real,1/e)}}},LCM:{description:"Retuns the least common mulitple of the arguments",arguments:[{boxed:!0}],fn:(...l)=>{l=oe(l);let e=[];for(let i of l){if(i.type===7)return i;if(i.type===3)e.push(i.value);else if(i.type!==0)return console.info("RT",i.type),U()}let t=(i,n)=>i%n==0?n:t(n,i%n);if(e.length===0)return{type:3,value:0};let r=e[0];for(let i=1;i<e.length;i++)r=r*e[i]/t(r,e[i]);return{type:3,value:r}}},"Gamma.Inv":{description:"Returns the inverse of the gamma distribution",arguments:[{name:"probability",unroll:!0},{name:"alpha"},{name:"beta"}],fn:(l,e,t)=>{if(l<0||l>1)return U();let r=Ra(l,e,t);return r===!1?M():{type:3,value:r}}},"Gamma.Dist":{fn:(l,e,t,r)=>{if(l<0||e<=0||t<=0)return U();let i=r?hr(e,l/t):ka(l,e,t);return i===!1?M():{type:3,value:i}}},GammaLn:{description:"Returns the natural log of the gamma function",arguments:[{name:"value",boxed:!0,unroll:!0}],fn:l=>l.type===3?{type:3,value:ke(l.value)}:U()},"GammaLn.Precise":{description:"Returns the natural log of the gamma function",arguments:[{name:"value",boxed:!0,unroll:!0}],fn:l=>{let e;if(l.type===3?e={real:l.value,imaginary:0}:l.type===8&&(e=l.value),e){let t=fr(e);return ce(Qr(t))}return U()}},Gamma:{description:"Returns the gamma function for the given value",arguments:[{name:"value",boxed:!0,unroll:!0}],fn:l=>{let e={real:0,imaginary:0};if(l.type===8)e={...l.value};else if(l.type===3)e.real=l.value;else return U();if(e.imaginary===0&&e.real%1===0&&e.real<=0)return M();let t=fr(e);return Math.abs(t.imaginary)<=1e-7?{type:3,value:t.real}:{type:8,value:t}}},Delta:{arguments:[{name:"number"},{name:"number",default:0}],fn:(l,e=0)=>typeof l!="number"||typeof e!="number"?M():{type:3,value:l===e?1:0}},GCD:{description:"Finds the greatest common divisor of the arguments",arguments:[{boxed:!0}],fn:(...l)=>{l=oe(l);let e=[];for(let i of l){if(i.type===7)return i;if(i.type===3)e.push(i.value);else if(i.type!==0)return console.info("RT",i.type),U()}let t=(i,n)=>i%n==0?n:t(n,i%n);if(e.length===0)return M();if(e.length===1)return{type:3,value:e[0]};let r=e[0];for(let i=1;i<e.length;i++)r=t(r,e[i]);return{type:3,value:r}}},HarMean:{description:"Returns the harmonic mean of the arguments",arguments:[{boxed:!0}],fn:(...l)=>{l=oe(l);let e={real:0,imaginary:0},t=0;for(let r of l){if(r.type===7)return r;if(r.type===3&&(e.real+=1/r.value,t++),r.type===8){let i=Pe({real:1,imaginary:0},r.value);e.real+=i.real,e.imaginary+=i.imaginary,t++}}return e.imaginary?{type:8,value:Pe({real:t,imaginary:0},e)}:{type:3,value:t/e.real}}},Average:{description:"Returns the arithmetic mean of all numeric arguments",arguments:[{boxed:!0}],fn:(...l)=>{l=oe(l);let e={real:0,imaginary:0},t=0;for(let r of l){if(r.type===7)return r;r.type===3&&(e.real+=r.value,t++),r.type===8&&(e.real+=r.value.real,e.imaginary+=r.value.imaginary,t++)}return e.real/=t,e.imaginary/=t,e.imaginary?{type:8,value:e}:{type:3,value:e.real}}},Percentile:{description:"Returns the kth percentile value from the range of data",arguments:[{name:"range"},{name:"percentile"}],fn:(l,e)=>{let t=te(l);t.sort((s,c)=>s-c);let r=t.length,i=Math.pow(10,8),n=Math.round((1+(r-1)*e)*i)/i,o=Math.floor(n),a=Math.ceil(n);return{type:3,value:(t[o-1]+t[a-1])/2}}},"Quartile.Inc":{description:"Returns the interpolated quartile of the data set (including median)",arguments:[{name:"range"},{name:"quartile"}],xlfn:!0,fn:(l,e)=>{if(typeof e!="number"||e<0||e>4||e%1)return U();let t=te(l),r=On(t,!0);return{type:3,value:r[e]}}},"Quartile.Exc":{description:"Returns the interpolated quartile of the data set (excluding median)",arguments:[{name:"range"},{name:"quartile"}],xlfn:!0,fn:(l,e)=>{if(typeof e!="number"||e<1||e>3||e%1)return U();let t=te(l),r=On(t,!1);return{type:3,value:r[e]}}},Median:{description:"Returns the median value of the range of data",arguments:[{name:"range"}],fn:(...l)=>{let e=te(l);e.sort((o,a)=>o-a);let r=1+(e.length-1)*.5,i=Math.floor(r),n=Math.ceil(r);return{type:3,value:(e[i-1]+e[n-1])/2}}},Rank:{arguments:[{name:"Value"},{name:"Source"},{name:"Order"}],fn:(l,e,t=0)=>{if(typeof l!="number")return U();let r=te(e);r.sort(t?(i,n)=>i-n:(i,n)=>n-i);for(let i=0;i<r.length;i++)if(r[i]===l)return{type:3,value:i+1};return M()}}},mi={Mean:"Average",StDev:"StDev.S",StDevA:"StDev.S",StDevPA:"StDev.P",Var:"Var.S",Quartile:"Quartile.Inc",NormSInv:"Norm.S.Inv",NormSDist:"Norm.S.Dist",NormDist:"Norm.Dist"};var Bn={IsComplex:{description:"Returns true if the reference is a complex number",arguments:[{name:"Reference",metadata:!0,unroll:!0}],fn:l=>({type:4,value:!!l?.value&&he(l.value.value)})},Real:{description:"Returns the real part of a complex number",arguments:[{boxed:!0,unroll:!0}],fn:l=>l.type===3?{...l}:l.type===8?{type:3,value:l.value.real||0}:l.type===0||l.type===2&&l.value===""?{type:3,value:0}:M()},Imaginary:{description:"Returns the imaginary part of a complex number (as real)",arguments:[{boxed:!0,unroll:!0}],fn:l=>l.type===8?{type:3,value:l.value.imaginary||0}:l.type===3||l.type===0||l.type===2&&l.value===""?{type:3,value:0}:M()},Conjugate:{description:"Returns the conjugate of a complex number",arguments:[{boxed:!0,unroll:!0}],fn:l=>{let e=Oe(l);return e?e.imaginary?{type:8,value:{real:e.real,imaginary:-e.imaginary}}:{type:3,value:e.real}:M()}},Arg:{description:"Returns the principal argument of a complex number (in radians)",arguments:[{boxed:!0,unroll:!0}],fn:l=>l.type===8?{type:3,value:Math.atan2(l.value.imaginary,l.value.real)}:l.type===3||l.type===0||l.type===2&&l.value===""?{type:3,value:Math.atan2(0,l.value||0)}:M()},Rectangular:{description:"Converts a complex number in polar form to rectangular form",arguments:[{name:"r"},{name:"\u03B8 in radians"}],fn:(l=0,e=0)=>({type:8,value:{real:l*Math.cos(e),imaginary:l*Math.sin(e)}})},Complex:{description:"Ensures that the given value will be treated as a complex number",arguments:[{boxed:!0,unroll:!0}],fn:l=>{let e=Oe(l);return e?{type:8,value:e}:M()}},ComplexLog:{description:"Returns the principal value Log(z) of a complex number z",arguments:[{boxed:!0,unroll:!0}],fn:l=>{if(l.type===3){if(!l.value)return M();l={type:8,value:{real:l.value,imaginary:0}}}else if(l.type===0||l.type===2&&l.value==="")return M();if(l.type===8){let e=tr(l.value),t={real:Math.log(e.r),imaginary:e.theta};return t.imaginary?{type:8,value:t}:{type:3,value:t.real}}return M()}}};var mr=l=>{let e=[];l.type===9?e=l.value:e=[[l]];let t=e.length,r=t?e[0].length:0,i=[];if(!t||!r)return{m:t,n:r,array:i};for(let n=0;n<t;n++){let o=[];for(let a=0;a<r;a++){let s=e[n][a];if(s.type===8)o.push({...s.value});else if(s.type===3)o.push({real:s.value,imaginary:0});else if(s.type===0||s.value==="")o.push({real:0,imaginary:0});else return{m:t,n:r,error:!0,array:[]}}i.push(o)}return{m:t,n:r,array:i}},$n={MDeterm:{description:"Returns the determinant of a matrix",arguments:[{name:"matrix",boxed:!0}],fn:l=>{let e=mr(l);if(!e.array||!e.m||!e.n||e.m!==e.n||e.error)return M();let t=ir(e);return t?ce(t):M()}},MInverse:{description:"Returns the inverse matrix",arguments:[{name:"matrix",boxed:!0}],fn:l=>{let e=mr(l);if(!e.array||!e.m||!e.n||e.m!==e.n||e.error)return M();let t=ir(e);if(t&&t.real===0&&t?.imaginary===0)return M();let r=pn(e);return r?{type:9,value:r.map(i=>i.map(n=>ce(n)))}:M()}},MMult:{description:"Returns the dot product A \u22C5 B",arguments:[{name:"A",boxed:!0},{name:"B",boxed:!0}],fn:(l,e)=>{let t=mr(l),r=mr(e);if(!t.array||t.error||!r.array||r.error)return M();if(t.m!==r.n)return M();let i=mn(r,t);return{type:9,value:i.map(n=>n.map(o=>ce(o)))}}}};var jn={RegexExtract:{description:"Extract text using a regular expression",arguments:[{name:"text",unroll:!0},{name:"pattern",unroll:!0},{name:"return mode",unroll:!0,default:0},{name:"case insensitive",unroll:!0,default:!1}],fn:(l,e,t=0,r=!1)=>{let i=[];r&&i.push("i"),t===1&&i.push("g");let n=new RegExp(e,i.length?i.join(""):void 0);switch(t){case 0:{let o=l.match(n);return{type:2,value:o===null?"":o[0]??""}}case 1:{let o=Array.from(l.matchAll(n));return console.info({result:o}),{type:9,value:[o.map(a=>({type:2,value:a[0]||""}))]}}case 2:{let o=l.match(n);if(o===null)return{type:2,value:""};let a=Array.from(o).slice(1);return{type:9,value:[a.map(s=>({type:2,value:s}))]}}default:return U()}}},RegexReplace:{arguments:[{name:"text",unroll:!0},{name:"pattern",unroll:!0},{name:"replacement",unroll:!0},{name:"occurrence",unroll:!0,default:0},{name:"case insensitive",unroll:!0,default:!1}],description:"Replace text in a string using a regex",fn:(l,e,t,r=0,i=!1)=>{let n=["g"];i&&n.push("i");let o=new RegExp(e,n.length?n.join(""):void 0);if(r===0)return{type:2,value:l.replaceAll(o,t)};if(r<0){let s=Array.from(l.matchAll(o)).length;r+=s+1}let a=l.replace(o,s=>--r===0?t:s);return{type:2,value:a}}},RegexTest:{arguments:[{name:"text",unroll:!0},{name:"pattern",unroll:!0},{name:"case insensitive",unroll:!0,default:!1}],description:"Match text against a regular expression",fn:(l,e,t=!1)=>{let r=new RegExp(e,t?"i":void 0);return{type:4,value:r.test(l)}}}};var qn={Lambda:{description:"Creates a function",arguments:[{name:"Argument",repeat:!0,boxed:!0,passthrough:!0},{name:"Function",boxed:!0,passthrough:!0}],fn:(...l)=>({type:6,value:{bindings:l.slice(0,l.length-1),func:l[l.length-1],alt:"LAMBDA",type:"function"}})},Let:{description:"Binds values to names for a calculation",arguments:[{name:"Name",repeat:!0},{name:"Value",repeat:!0},{name:"Calculation",boxed:!0}],create_binding_context:({args:l,descriptors:e})=>{if(l.length%2!==1)return;let t={};for(let r=0;r<l.length-1;r+=2){let i=l[r],n=l[r+1];if(i.type==="identifier")t[i.name]=n;else return}return{context:t,args:l.slice(-1),argument_descriptors:e.slice(-1)}},fn:l=>l||{type:0}}};var Jn={MakeArray:{description:"Create an array using a function",arguments:[{name:"rows"},{name:"columns"},{name:"lambda",description:"Function to apply",boxed:!0}],fp:!0,fn:function(l,e,t){if(l>0&&e>0&&t?.type===6){let r=this?.apply;if(!r)return M();let i=[];for(let n=0;n<e;n++){let o=[];for(let a=0;a<l;a++)o.push(r(t,[{type:3,value:a+1},{type:3,value:n+1}]));i.push(o)}return{type:9,value:i}}return U()}},Reduce:{description:"Accumulates a value by applying a function to a set of values",arguments:[{name:"initial value",boxed:!0},{name:"data",description:"Input data",boxed:!0},{name:"lambda",description:"Function to apply",boxed:!0}],fp:!0,fn:function(l,e,t){if(!this?.apply)return M();if(t.type!==6)return U();e.type!==9&&(e={type:9,value:[[e]]});let r=e.value.length,i=e.value[0].length;for(let n=0;n<i;n++)for(let o=0;o<r;o++){let a=[l,e.value[o][n]];l=this.apply(t,a)}return l}},Scan:{description:"Applies a function to a set of values, iteratively",arguments:[{name:"initial value",boxed:!0},{name:"data",description:"Input data",boxed:!0},{name:"lambda",description:"Function to apply",boxed:!0}],fp:!0,fn:function(l,e,t){if(!this?.apply)return M();if(t.type!==6)return U();e.type!==9&&(e={type:9,value:[[e]]});let r=[],i=e.value.length,n=e.value[0].length;for(let o=0;o<i;o++)r.push([]);for(let o=0;o<n;o++)for(let a=0;a<i;a++){let s=[l,e.value[a][o]],c=this.apply(t,s);r[a][o]=c,l=c}return{type:9,value:r}}},ByRow:{description:"Apply a function to each row in an array",arguments:[{name:"data",description:"Input data",repeat:!0,boxed:!0},{name:"lambda",description:"Function to apply",boxed:!0}],fp:!0,fn:function(l,e){if(!this?.apply)return M();if(e.type!==6)return U();l.type!==9&&(l={type:9,value:[[l]]});let t=l.value.length,r=l.value[0].length,i=[[]];for(let n=0;n<r;n++){let o=[];for(let a=0;a<t;a++)o.push(l.value[a][n]);i[0].push(this.apply(e,[{type:9,value:[o]}]))}return{type:9,value:i}}},ByCol:{description:"Apply a function to each column in an array",arguments:[{name:"data",description:"Input data",repeat:!0,boxed:!0},{name:"lambda",description:"Function to apply",boxed:!0}],fp:!0,fn:function(l,e){if(!this?.apply)return M();if(e.type!==6)return U();l.type!==9&&(l={type:9,value:[[l]]});let t=l.value.length,r=l.value[0].length,i=[];for(let n=0;n<t;n++){let o=[];for(let a=0;a<r;a++)o.push(l.value[n][a]);i.push([this.apply(e,[{type:9,value:[o]}])])}return{type:9,value:i}}},Map:{description:"Apply a function to a set of values",arguments:[{name:"data",description:"Input data",repeat:!0,boxed:!0},{name:"lambda",description:"Function to apply",boxed:!0}],fp:!0,fn:function(...l){if(l.length<2)return U();let e=l[l.length-1];if(e.type!==6)return U();let t=this?.apply;if(!t)return M();for(let n=0;n<l.length-1;n++){let o=l[n];o.type!==9&&(l[n]={type:9,value:[[o]]})}let r=l[0],i=[];if(r.type===9)for(let n=0;n<r.value.length;n++){let o=r.value[n],a=[];for(let s=0;s<o.length;s++){let c=[o[s]];for(let d=1;d<l.length-1;d++){let u=l[d];u.type===9&&c.push(u.value[n][s])}a.push(t(e,c))}i.push(a)}return{type:9,value:i}}}};var tt=class l extends ze{static type="state-leaf-vertex";state_id=0;type=l.type;color=2;Calculate(){if(this.dirty){for(let e of this.edges_in)if(e.dirty)return;this.state_id++,this.dirty=!1}}AddDependent(){throw new Error("leaf vertex cannot have dependents")}};var pr=class l extends ze{static type="calculation-leaf-vertex";type=l.type;address={row:-1,column:-1};use;updated=!1;color=2;Calculate(e){if(!this.dirty)return;for(let r of this.edges_in)if(r.dirty)return;let t=e.CalculationCallback.call(e,this);this.result=t.value,this.dirty=!1,this.updated=!0}AddDependent(){throw new Error("leaf vertex cannot have dependents")}};var Ea=l=>{if(typeof l=="string")switch(l=l.toUpperCase(),l){case"AVERAGE":case"MEAN":l=101;break;case"COUNT":l=102;break;case"COUNTA":l=103;break;case"MAX":l=104;break;case"MIN":l=105;break;case"PRODUCT":l=106;break;case"STDEV":l=107;break;case"STDEVP":l=108;break;case"SUM":l=109;break;case"VAR":l=110;break;case"VARP":l=111;break;default:l=0;break}return l},Ta={complex_numbers:"off",spill:!1},br=class extends er{constructor(t,r={}){super();this.model=t;if(this.expression_calculator=new or(this.model,this.library,this.parser),this.options={...Ta,...r},this.options.complex_numbers==="on"){for(let o of Object.keys(ai))et[o]=ai[o];_n()}this.UpdateLocale(),this.library.Register(et,zn,Gn,Dn,Ln,Bn,$n,jn,qn,Jn);for(let o of Object.keys(mi))this.library.Alias(o,mi[o]);for(let o of Object.keys(li))this.library.Alias(o,li[o]);let i=(o,a,...s)=>{Array.isArray(a)||(a=[[a]]);let c=[];for(let f=0;f<s.length;f+=2){let m=s[f];Array.isArray(m)||(m=[[m]]);{let p=n(m,s[f+1]);if(p.type!==9)return p;for(let[b,g]of p.value[0].entries())c[b]=!!g.value&&c[b]!==!1}}let d=X(a,!0),u=0,h=0;for(let[f,m]of c.entries())if(m){u++;let p=d[f];typeof p=="number"&&(h+=p)}switch(o){case"count":return{type:3,value:u};case"sum":return{type:3,value:h};case"average":return u===0?ye():{type:3,value:h/u}}},n=(o,a)=>{let s=X(o,!0),c,d,u="=";if(typeof a=="string"){a=a.trim();let f=a.match(/^([=<>]+)/);f&&(u=f[1],a=a.substring(u.length));let m=_e.TryParse(a);if(m?.type===2?a=`"${m.value}"`:a=m?.value?.toString()||"",/[?*]/.test(a)){let p=this.parser.argument_separator;if(u==="="||u==="<>"){if(c=this.parser.Parse(`=WildcardMatch({}${p} ${a}${p} ${u==="<>"})`),d=c.expression,c.error||!d)return fe();d?.type==="call"&&d.args[0]?.type==="array"&&(d.args[0].values=[oi(s,!0)])}}}else a=(a||0).toString();if(!c){if(c=this.parser.Parse("{}"+u+a),d=c.expression,c.error||!d)return fe();if(d.type!=="binary")return console.warn("invalid expression [1]",d),fe();if(d.left.type!=="array")return console.warn("invalid expression [1]",d),fe();d.right.type==="identifier"&&(console.warn("will never happen"),d.right={...d.right,type:"literal",value:d.right.name}),d.left.values=[oi(s,!0)]}return d?this.CalculateExpression(d):M()};this.library.Register({Subtotal:{arguments:[{name:"type"},{name:"range",metadata:!0}],fn:(o,...a)=>{if(o=Ea(o),o>100&&(o-=100),o<1||o>11)return U();let s=oe(a),c=[],d=0,u=0,h;for(let m of s){let p=m.value?.address;if(!p)return $();if(!h||h.id!==p.sheet_id){if(!p.sheet_id)return console.warn("invalid reference in metadata"),$();if(h=this.model.sheets.Find(p.sheet_id),!h)return console.warn("invalid sheet in metadata"),$()}if(!h.GetRowHeight(p.row))continue;let g=m.value?.value;typeof g>"u"||(d++,typeof g=="number"&&(u+=g,c.push(g)))}let f=0;switch(o){case 1:if(c.length===0)return ye();f=u/c.length;break;case 2:f=c.length;break;case 3:f=d;break;case 4:if(c.length===0)return M();f=Math.max.apply(0,c);break;case 5:if(c.length===0)return M();f=Math.min.apply(0,c);break;case 6:if(c.length===0)return M();f=1;for(let m of c)f*=m;break;case 7:if(c.length<2)return ye();f=Math.sqrt(Te(c,!0));break;case 8:if(c.length===0)return ye();f=Math.sqrt(Te(c,!1));break;case 9:f=u;break;case 10:if(c.length<2)return ye();f=Te(c,!0);break;case 11:if(c.length===0)return ye();f=Te(c,!1);break}return{type:3,value:f}}},Cell:{description:"Returns data about a cell",arguments:[{name:"type",description:"Type of data to return",unroll:!0},{name:"reference",description:"Cell reference",metadata:!0,unroll:!0}],fn:(o,a)=>{if(!ue(a))return $();if(o)switch(o.toString().toLowerCase()){case"format":return a.value.format?{type:2,value:a.value.format}:$();case"address":{let s="";return a.value.address.sheet_id&&(s=this.model.sheets.Find(a.value.address.sheet_id)?.name||""),s&&(Ce.test(s)&&(s=`'${s}'`),s+="!"),{type:2,value:"[]"+s+a.value.address.label.replace(/\$/g,"")}}}return{type:7,value:tn.error}}},Address:{arguments:[{name:"row"},{name:"column"},{name:"absolute"},{name:"a1"},{name:"sheet name"}],fn:(o=1,a=1,s=1,c=!0,d)=>{let u={type:"address",id:0,position:0,label:"",row:o-1,column:a-1};switch(s){case 2:u.absolute_row=!0;break;case 3:u.absolute_column=!0;break;case 4:break;default:u.absolute_column=!0,u.absolute_row=!0}return d&&(u.sheet=d),xn(this.parser.Render(u,{r1c1:!c}))}},CountIfs:{arguments:[{name:"range"},{name:"criteria"},{name:"range"},{name:"criteria"}],fn:(...o)=>i("count",o[0],...o)},AverageIf:{arguments:[{name:"range"},{name:"criteria"}],fn:(o,a,s)=>i("average",s||o,o,a)},AverageIfs:{arguments:[{name:"value range"},{name:"criteria range"},{name:"criteria"},{name:"criteria range"},{name:"criteria"}],fn:(o,...a)=>i("average",o,...a)},SumIf:{arguments:[{name:"range"},{name:"criteria"}],fn:(o,a,s)=>i("sum",s||o,o,a)},SumIfs:{arguments:[{name:"value range"},{name:"criteria range"},{name:"criteria"},{name:"criteria range"},{name:"criteria"}],fn:(o,...a)=>i("sum",o,...a)},CountIf:{arguments:[{name:"range"},{name:"criteria"}],fn:(o,a)=>i("count",o,o,a)},Offset:{arguments:[{name:"reference",description:"Base reference",metadata:!0},{name:"rows",description:"number of rows to offset"},{name:"columns",description:"number of columns to offset"},{name:"height"},{name:"width"}],return_type:"reference",volatile:!0,fn:((o,a=0,s=0,c,d)=>{if(!o)return U();if(o.type===9){let h=typeof c=="number"?a+c:void 0,f=typeof d=="number"?s+d:void 0;return{type:9,value:o.value.slice(a,h).map(p=>p.slice(s,f))}}if(!ue(o))return console.info("e2",{reference:o}),$();let u=this.DynamicDependencies(o.value.address,this.expression_calculator.context.address,!0,a,s,d,c);if(!u)return console.info("e1",{check_result:u}),$();if(u.dirty){let h=this.GetVertex(this.expression_calculator.context.address,!0);return h.short_circuit=!0,{type:0,value:void 0}}if(u.area){let h={type:"address",...u.area.start,label:"",position:0,id:0},f={type:"address",...u.area.end,label:"",position:0,id:0},m=u.area.count===1?h:{type:"range",start:h,end:f,label:"",position:0,id:0};return{type:5,value:m}}return M()}).bind(this)},Indirect:{arguments:[{name:"reference",description:"Cell reference (string)"}],return_type:"reference",volatile:!0,fn:(o=>{if(!o||typeof o!="string")return U();let a=this.parser.Parse(o);if(a.error||!a.expression||a.expression.type!=="address"&&a.expression.type!=="range")return $();let s=this.DynamicDependencies(a.expression,this.expression_calculator.context.address);if(!s)return $();if(s.dirty){let c=this.GetVertex(this.expression_calculator.context.address,!0);return c.short_circuit=!0,{type:0,value:void 0}}return{type:5,value:a.expression}}).bind(this)},Match:{arguments:[{name:"value",boxed:!0},{name:"range",boxed:!0},{name:"type"}],fn:(o,a,s=0)=>{if(s)return console.warn("inexact match not supported",{value:o,range:a,type:s}),we();if(a.type===9){if(a.value.length===1){let c=a.value[0];for(let d=0;d<c.length;d++)if(o.type==c[d].type&&o.value===c[d].value)return{type:3,value:d+1}}else for(let c=0;c<a.value.length;c++){let d=a.value[c];if(d.length!==1)return we();if(o.type==d[0].type&&o.value===d[0].value)return{type:3,value:c+1}}return we()}else return o.type===a.type&&o.value===a.value?{type:3,value:1}:we();return U()}},Index:{arguments:[{name:"range",boxed:!0},{name:"row"},{name:"column"}],volatile:!1,fn:(o,a,s)=>{if(o&&o.type!==9&&(o={type:9,value:[[o]]}),a&&s){let c=o.value[s-1];if(c){let d=c[a-1];if(d)return d}}else if(a){let c=[];for(let d of o.value){if(!d[a-1])return U();c.push([d[a-1]])}return{type:9,value:c}}else if(s){let c=o.value[s-1];if(c)return{type:9,value:[c]}}return U()}},Rows:{arguments:[{name:"reference",description:"Array or reference"}],volatile:!1,fn:o=>{if(!o)return U();if(Array.isArray(o)){let a=o[0];return Array.isArray(a)?{type:3,value:a.length}:M()}return{type:3,value:1}}},Columns:{arguments:[{name:"reference",description:"Array or reference"}],volatile:!1,fn:o=>o?Array.isArray(o)?{type:3,value:o.length}:{type:3,value:1}:U()},FormulaText:{description:"Returns a formula as a string",arguments:[{name:"reference",description:"Cell reference",metadata:!0,unroll:!0}],fn:o=>{if(!ue(o))return $();let a=this.model.sheets.Find(o.value?.address?.sheet_id||0);if(a){let s=a.cells.GetCell(o.value.address,!1);return{type:2,value:s?.value?.toString()||""}}return $()}},IsFormula:{description:"Returns true if the reference is a formula",arguments:[{name:"Reference",unroll:!0,metadata:!0}],fn:o=>{let a=o?.value?.address,s=this.model.sheets.Find(a?.sheet_id||0);if(a&&s){let c=s.cells.GetCell(a,!1);return{type:4,value:c?.type===1}}return{type:4,value:!1}}}})}get parser(){return this.model.parser}library=new lr;registered_libraries={};expression_calculator;full_rebuild_required=!1;options;grid_expanded=!1;ExportCalculatedValues(){let t={};for(let r of this.model.sheets.list){let i=r.cells.toJSON({calculated_value:!0}).data;t[r.id]=i.filter(n=>n.calculated!==void 0)}return t}ApplyCalculatedValues(t){for(let r of this.model.sheets.list){let i=t[r.id];if(!i)console.info("mismatch",r.id);else for(let n of i)r.cells.data[n.row][n.column].SetCalculatedValue(n.calculated)}}AttachSpillData(t,r){if(r||(r=(t.start.sheet_id?this.model.sheets.Find(t.start.sheet_id):void 0)?.cells),!r)throw console.info({area:t,cells:r}),new Error("invalid sheet ID in attach spill data");let i=new tt,n=0,o=!1;for(let{cell:a,row:s,column:c}of r.IterateRC(t,!0))n++&&(a.type!==0||a.area||a.merge_area||a.table)&&(o=!0),this.AddLeafVertexEdge({row:s,column:c,sheet_id:t.start.sheet_id},i);return this.spill_data.push({area:t,vertex:i}),{vertex:i,area:t,error:o}}SpillCallback(t,r){let{reference:i,address:n}=t,{value:o}=r,a=[];if(!i)return console.error("invalid reference in spill callback"),a;if(!n||!n.sheet_id)return console.error("invalid address in spill callback"),a;if(o.length===1&&o[0].length===1||!this.options.spill)return i.SetCalculatedValue(o[0][0].value),a;let s=this.model.sheets.Find(n.sheet_id),c=s?.cells;if(c){let d=r.value.length,u=r.value[0].length,h=new v(n).Reshape(u,d),{error:f}=this.AttachSpillData(h,c);if(f)return i.SetCalculationError("SPILL"),a;s.rows<h.end.row+1&&(s.cells.EnsureRow(h.end.row+1),this.grid_expanded=!0),s.columns<h.end.column+1&&(s.cells.EnsureColumn(h.end.column+1),this.grid_expanded=!0);let m=n.sheet_id;for(let{row:p,column:b}of c.IterateRC(h)){if(p===n.row&&b===n.column)continue;let g=this.GetVertex({sheet_id:m,row:p,column:b},!1);g&&(g.dirty||a.push(g))}for(let{cell:p,row:b,column:g}of c.IterateRC(h)){p.spill=h,b-=n.row,g-=n.column;let x=r.value[g][b];switch(x.type){case 5:case 9:case 6:break;default:p.SetCalculatedValue(x.value,x.type);break}}return a}return console.error("invalid cell reference in spill callback"),i.SetCalculationError("SPILL"),[]}SpreadCallback(t,r){if(!t.address||!t.address.sheet_id)throw new Error("spread callback called without sheet id");let i=this.model.sheets.Find(t.address.sheet_id)?.cells;if(!i)throw new Error("spread callback called without cells");if(!t||!t.reference)return;let n=t.reference.area;if(n){let o=n.rows,a=n.columns;if(r.type===9){let s=ar(r.value);for(let c=0;c<o;c++)if(s[c]){let d=0;for(;d<a&&d<s[c].length;d++){let u=s[c][d];switch(u.type===9&&(u=u.value[0][0]),u.type){case 9:case 5:case 6:i.data[c+n.start.row][d+n.start.column].SetCalculatedValue(void 0);break;default:i.data[c+n.start.row][d+n.start.column].SetCalculatedValue(u.value,u.type)}}for(;d<a;d++)i.data[c+n.start.row][d+n.start.column].SetCalculatedValue(void 0,0)}else for(let d=0;d<a;d++)i.data[c+n.start.row][d+n.start.column].SetCalculatedValue(void 0,0)}else{let s={...r};(s.type===5||s.type===6)&&(s={type:0,value:void 0});for(let c=0;c<o;c++)for(let d=0;d<a;d++)i.data[c+n.start.row][d+n.start.column].SetCalculatedValue(s.value,s.type)}}}CalculationCallback(t){if(!t.address)throw new Error("vertex missing address");return t.expression_error?{value:Qt()}:this.expression_calculator.Calculate(t.expression,t.address,t.reference?.area)}DynamicDependencies(t,r,i=!1,n=0,o=0,a=1,s=1){let c=this.ResolveExpressionAddress(t,r);if(!c)return;let d=!1,u;if(t.type==="address"||t.type==="range"){let f=t.type==="range"?t.start:t;f.sheet_id?u=this.model.sheets.Find(f.sheet_id):f.sheet&&(u=this.model.sheets.Find(f.sheet))}if(!u&&r?.sheet_id&&(u=this.model.sheets.Find(r.sheet_id)),!u)throw new Error("missing sheet in dynamic dependencies [b21]");c=u.RealArea(c);let h=c.start.sheet_id;i&&(c=new v({column:c.start.column+o,row:c.start.row+n,sheet_id:c.start.sheet_id},{column:c.start.column+o+a-1,row:c.start.row+n+s-1,sheet_id:c.end.sheet_id}));for(let f=c.start.row;f<=c.end.row;f++)for(let m=c.start.column;m<=c.end.column;m++){let p=this.GetVertex({row:f,column:m,sheet_id:h},!1);p&&p.dirty&&(this.AddEdge({row:f,column:m,sheet_id:h},this.expression_calculator.context.address),d=!0)}return{dirty:d,area:c}}UpdateLocale(){F.decimal_separator===","?this.parser.SetLocaleSettings(","):this.parser.SetLocaleSettings(".")}SupportedFunctions(){let t=this.library.List(),r=Object.keys(t).map(i=>{let n=t[i].canonical_name;return n||(n=i.replace(/_/g,".")),{name:n,description:t[i].description,arguments:(t[i].arguments||[]).map(o=>({name:o.name||""})),type:"function"}});for(let i of this.model.macro_functions.values())r.push({name:i.name,description:i.description,arguments:(i.argument_names||[]).map(n=>({name:n})),type:"function"});return r}RegisterLibrary(t,r){return this.registered_libraries[t]?!1:(this.RegisterFunction(r),this.registered_libraries[t]=!0,!0)}RegisterFunction(t){for(let r of Object.keys(t)){let i=t[r];this.library.Register({[r]:i})}}Calculate(t){if(t&&!t.start.sheet_id)throw new Error("CalculateInternal called with subset w/out sheet ID");this.full_rebuild_required&&(t=void 0,this.UpdateAnnotations(),this.UpdateConditionals(),this.UpdateConnectedElements(),this.full_rebuild_required=!1),this.RebuildGraph(t),this.grid_expanded=!1;try{this.Recalculate()}catch(r){console.error(r),console.info("calculation error trapped")}}Reset(){this.FlushTree(),this.full_rebuild_required=!0}DecoratedFunctionList(){let t={},r=this.library.List();for(let i of Object.keys(r)){let n=r[i];n.xlfn?t[i]="_xlfn":n.extension&&(t[i]="_xll")}return t}Evaluate(t,r,i={},n=!1){let o=i?.preparsed;if(!o){this.parser.Save(),i.argument_separator&&(i.argument_separator===","?this.parser.SetLocaleSettings("."):this.parser.SetLocaleSettings(",")),i.r1c1&&(this.parser.flags.r1c1=i.r1c1);let a=this.parser.Parse(t);if(this.parser.Restore(),o=a.expression,a.error)throw new Error(a.error)}if(o){this.parser.Walk(o,s=>{if(s.type==="address"||s.type==="range"){if(s.type==="address"){if(s.offset_column||s.offset_row)throw new Error("Evaluate does not support offset references")}else if(s.start.offset_column||s.start.offset_row||s.end.offset_column||s.end.offset_row)throw new Error("Evaluate does not support offset references");this.model.ResolveSheetID(s,void 0,r)}return!0});let a=this.CalculateExpression(o,i.address);return n?a:a.type===9?a.value.map(s=>s.map(c=>c.value)):a.value}throw new Error("invalid expression")}CalculateExpression(t,r={row:-1,column:-1},i=!1){return this.expression_calculator.Calculate(t,r,void 0,i).value}RebuildClean(t=!1){this.full_rebuild_required=!1,this.RebuildGraph(),this.UpdateAnnotations(),this.UpdateConditionals(),this.UpdateConnectedElements(),this.InitializeGraph(),t&&this.volatile_list.length&&this.Recalculate()}FlattenCellList(t){let r={},i=[];for(let n of t){let o={column:n.column,row:n.row,sheet_id:n.sheet_id},a=v.CellAddressToLabel(o,!0);r[a]||(r[a]=a,i.push(o))}return i}Unresolve(t,r,i=!0,n=!0){let o="",a=N(t)?new v(t):new v(t.start,t.end);if(n){let d=this.model.named.MatchSelection(a);if(d)return d}if(o=a.spreadsheet_label,!i)return o;let s=a.start.sheet_id||r?.id,c=this.ResolveSheetName(s,!0);return c?c+"!"+o:o}ResolveSheetName(t,r=!1){let i=this.model.sheets.Find(t);if(i)return r&&Ce.test(i.name)?`'${i.name}'`:i.name}RemoveConditional(t){if(t.type==="expression"){let r=t.internal?.vertex;r&&(r.Reset(),this.RemoveLeafVertex(r))}}RemoveConnectedELement(t){let r=t.internal;return r?.vertex?(this.RemoveLeafVertex(r.vertex),!0):!1}UpdateConnectedElements(t,r){if(t||(t=this.model.sheets.list[0]),r){let n=r.internal;n?.vertex&&this.RemoveLeafVertex(n.vertex)}let i=r?[r]:this.model.connected_elements.values();for(let n of i){let o=n.internal;o||(o={vertex:new tt},n.internal=o);let a=o.vertex;this.AddLeafVertex(a),this.UpdateLeafVertex(a,n.formula,t)}}UpdateConditionals(t,r){if(!t){for(let i of this.model.sheets.list)i.conditional_formats?.length&&this.UpdateConditionals(i.conditional_formats,i);return}if(!r)throw new Error("invalid call to update conditionals without context");t&&!Array.isArray(t)&&(t=[t]);for(let i of t){let n="";switch(i.type){case"cell-match":i.between?n=`BETWEEN(${[this.Unresolve(i.area,r,!0,!1),...i.between].join(", ")})`:n=this.Unresolve(i.area,r,!0,!1)+" "+i.expression;break;case"expression":n=i.expression;break;case"duplicate-values":n=`UniqueValues(${this.Unresolve(i.area,r,!0,!1)})`,i.unique||(n=`NOT(${n})`);break;case"data-bar":case"gradient":n=`=Gradient(${[this.Unresolve(i.area,r,!0,!1),i.min??"",i.max??"",...i.type==="data-bar"?["TRUE"]:[]].join(",")})`;break;default:continue}if(!n)continue;if(i.internal||(i.internal={}),!i.internal.vertex){let a=new pr;a.use="conditional",i.internal.vertex=a;let s={argument_separator:","};i.type!=="gradient"&&i.type!=="duplicate-values"&&i.type!=="data-bar"&&(s={...i.options,...s});let c=this.Evaluate(n,r,s,!0);i.internal.vertex.result=c,i.internal.vertex.updated=!0}let o=i.internal.vertex;this.AddLeafVertex(o),this.UpdateLeafVertex(o,n,r,".")}}RemoveAnnotation(t){let r=t.temp;r.vertex&&(r.vertex.Reset(),this.RemoveLeafVertex(r.vertex))}UpdateAnnotations(t,r){if(!t){for(let i of this.model.sheets.list)this.UpdateAnnotations(i.annotations,i);return}if(!r)throw new Error("invalid call to UpdateAnnotations with list but no sheet");typeof t<"u"&&!Array.isArray(t)&&(t=[t]);for(let i of t)if(i.data.formula){let n=i.temp;n.vertex||(n.vertex=new tt),this.AddLeafVertex(n.vertex),this.UpdateLeafVertex(n.vertex,i.data.formula,r)}}ResolveExpressionAddress(t,r){switch(t.type){case"address":if(this.model.ResolveSheetID(t,r))return new v(t);break;case"range":if(this.model.ResolveSheetID(t,r))return new v(t.start,t.end);break;case"identifier":{let i=this.model.GetName(t.name,r?.sheet_id||0);if(i&&i.type==="range")return new v(i.area.start,i.area.end)}break}}NamedRangeToAddressUnit(t,r){let i=t.name.toUpperCase(),n=this.model.GetName(i,r.sheet_id||0);if(n&&n.type==="range")return n.area.count===1?this.ConstructAddressUnit(n.area.start,i,t.id,t.position):{type:"range",start:this.ConstructAddressUnit(n.area.start,i,t.id,t.position),end:this.ConstructAddressUnit(n.area.end,i,t.id,t.position),label:i,id:t.id,position:t.position}}ConstructAddressUnit(t,r,i,n){return{type:"address",row:t.row,column:t.column,sheet_id:t.sheet_id,label:r,id:i,position:n}}RebuildDependencies(t,r,i,n={addresses:{},ranges:{}},o){if(!i){let a=this.model.sheets.Find(r);a&&(i=a.name)}switch(t.type){case"literal":case"missing":case"operator":break;case"identifier":{let a=this.model.GetName(t.name,o.sheet_id||0);if(a?.type==="expression")this.RebuildDependencies(a.expression,r,i,n,o);else{let s=this.NamedRangeToAddressUnit(t,o);s&&(s.type==="address"?n.addresses[s.label]=s:n.ranges[s.label]=s)}}break;case"structured-reference":{let a=this.model.ResolveStructuredReference(t,o);a&&(a.type==="address"?n.addresses[a.sheet_id+"!"+a.label]=a:n.ranges[a.label]=a);let s=this.model.tables.get(t.table.toLowerCase());if(s){let c=o.row;if(c<s.area.start.row||c>s.area.end.row)break;let d=t.column.toLowerCase(),u=-1;if(s.columns){for(let h=0;h<s.columns.length;h++)if(d===s.columns[h]){u=s.area.start.column+h;break}}if(u>=0){let h={label:t.label,type:"address",row:c,column:u,sheet_id:s.area.start.sheet_id,id:t.id,position:t.position};n.addresses[h.sheet_id+"!"+h.label]=h}}}break;case"address":if(!t.sheet_id)if(t.sheet){let a=this.model.sheets.Find(t.sheet);a&&(t.sheet_id=a.id)}else t.sheet_id=r,t.sheet=i;t.sheet_id?n.addresses[t.sheet_id+"!"+t.label]=t:console.warn("invalid address in range [9d]");break;case"range":if(!t.start.sheet_id)if(t.start.sheet){let a=this.model.sheets.Find(t.start.sheet);a&&(t.start.sheet_id=a.id)}else t.start.sheet_id=r,t.start.sheet=i;t.start.sheet_id?n.ranges[t.start.sheet_id+"!"+t.start.label+":"+t.end.label]=t:console.warn("invalid sheet in range",t);break;case"unary":this.RebuildDependencies(t.operand,r,i,n,o);break;case"binary":this.RebuildDependencies(t.left,r,i,n,o),this.RebuildDependencies(t.right,r,i,n,o);break;case"group":t.elements.forEach(a=>this.RebuildDependencies(a,r,i,n,o));break;case"implicit-call":{for(let a of t.args)this.RebuildDependencies(a,r,i,n,o);this.RebuildDependencies(t.call,r,i,n,o)}break;case"call":{let a=t.args.slice(0),s=this.library.Get(t.name);s&&s.arguments&&s.arguments.forEach((c,d)=>{c&&c.address&&(this.RebuildDependencies(a[d],r,i,void 0,o),a[d]={type:"missing",id:-1})}),a.forEach(c=>this.RebuildDependencies(c,r,i,n,o))}break}return n}UpdateLeafVertex(t,r,i,n){t.Reset(),n&&(this.parser.Save(),this.parser.SetLocaleSettings(n));let o=this.parser.Parse(r);if(o.expression){let a=this.RebuildDependencies(o.expression,i.id,i.name,void 0,{row:0,column:0});for(let s of Object.keys(a.ranges)){let c=a.ranges[s],d=new v(c.start,c.end);d.entire_column||d.entire_row||d.count>1?this.AddLeafVertexArrayEdge(d,t):this.AddLeafVertexEdge(d.start,t)}for(let s of Object.keys(a.addresses)){let c=a.addresses[s];this.AddLeafVertexEdge(c,t)}}t.expression=o.expression||{type:"missing",id:-1},t.expression_error=!o.valid,n&&this.parser.Restore()}RebuildGraphCell(t,r){if(t.spill&&this.options.spill&&(t.spill.start.row===r.row&&t.spill.start.column===r.column?this.AttachSpillData(new v(t.spill.start,t.spill.end)):this.AddEdge(t.spill.start,r)),t.area&&t.area.start.column===r.column&&t.area.start.row===r.row){let{start:i,end:n}=t.area,o=i.sheet_id||r.sheet_id;i.sheet_id||(i.sheet_id=o);for(let a=i.column;a<=n.column;a++)for(let s=i.row;s<=n.row;s++)this.ResetInbound({column:a,row:s,sheet_id:o},!0,!1);this.SetDirty(r);for(let a=i.column;a<=n.column;a++)for(let s=i.row;s<=n.row;s++)s===i.row&&a===i.column||this.AddEdge(i,{...i,row:s,column:a})}if(t.type===1){this.ResetInbound(r,!0);let i=this.parser.Parse(t.value);if(i.expression){if(i.expression.type==="call"){let a=this.library.Get(i.expression.name);a&&(a.render||a.click)&&(t.render_function=a.render,t.click_function=a.click)}let o=this.RebuildDependencies(i.expression,r.sheet_id,"",void 0,r);for(let a of Object.keys(o.ranges)){let s=o.ranges[a],c=new v(s.start,s.end);if(c.entire_row||c.entire_column)this.AddArrayEdge(c,r);else for(let d of c)this.AddEdge(d,r)}for(let a of Object.keys(o.addresses)){let s=o.addresses[a];this.AddEdge(s,r)}}let n=this.GetVertex(r,!0);n&&(n.expression=i.expression||{type:"missing",id:-1},n.expression_error=!i.valid)}else t.value!==t.calculated?this.ResetInbound(r,!0,!1):t.type===0&&this.ResetInbound(r,!0,!1,!0)}RebuildGraph(t){if(t){if(!t.start.sheet_id)throw new Error("subset missing sheet id");let r=this.model.sheets.Find(t.start.sheet_id)?.cells;if(r)for(let i=t.start.row;i<=t.end.row;i++){let n=r.data[i];if(n)for(let o=t.start.column;o<=t.end.column;o++){let a=n[o];a&&this.RebuildGraphCell(a,{row:i,column:o,sheet_id:t.start.sheet_id})}}}else for(let r of this.model.sheets.list||[]){let i=r.cells.data.length;for(let n=0;n<i;n++){let o=r.cells.data[n];if(o){let a=o.length;for(let s=0;s<a;s++){let c=o[s];c&&this.RebuildGraphCell(c,{row:n,column:s,sheet_id:r.id})}}}}}CheckVolatile(t){if(!t.expression||t.expression_error)return!1;let r=!1;return this.parser.Walk(t.expression,i=>{if(i.type==="call"){let n=this.library.Get(i.name);n&&n.volatile&&(r=!0)}return!r}),r}};var gr=class{model={};layout_element;visible_=!1;timeout=0;pending_dialog_resoltion=[];options_={type:"initial"};set options(e){if(e.type==="about"&&(e.close_box=!0,e.icon=!0),this.options_.icon!==e.icon&&(this.model.left.style.display=e.icon?"block":"none"),this.options_.close_box!==e.close_box&&(this.model.close.style.display=e.close_box?"block":"none"),this.options_.message!==e.message&&(this.model.message.textContent=e.message||"",this.model.message.style.display=e.message?"block":"none"),this.options_.title!==e.title&&(this.model.title.textContent=e.title||"",this.model.title.style.display=e.title?"block":"none"),this.options_.type!==e.type){let t=this.model.dialog.className.replace(/dialog-type-\S+/g,"").trim();e.type&&(t+=` dialog-type-${e.type}`),this.model.dialog.className=t,e.type==="about"?this.model.about.style.display="block":this.model.about.style.display="none"}this.options_=e}event_handler=e=>{(e.key==="Escape"||e.key==="Esc")&&(e.stopPropagation(),e.preventDefault(),this.visible=!1)};get visible(){return this.visible_}set visible(e){if(e!==this.visible_)if(this.visible_=e,e)this.layout_element?.setAttribute("dialog",""),window.addEventListener("keydown",this.event_handler);else{this.layout_element?.removeAttribute("dialog"),window.removeEventListener("keydown",this.event_handler);let t=this.pending_dialog_resoltion.slice(0);this.pending_dialog_resoltion=[],Promise.resolve().then(()=>{for(let r of t)r()})}}constructor(e){this.layout_element=e.parentElement;let t=this.layout_element?.querySelector(".treb-dialog-mask");if(t){let r=t.querySelectorAll("[data-bind]");for(let i of Array.from(r)){let n=i.dataset.bind;n&&(this.model[n]=i)}}if(this.model.about){let r=["<div>TREB version 32.8.1"];r.push("<small><a target=_blank href='https://treb.app'>http://treb.app</a></small>"),this.model.about.innerHTML=r.join(`
12
- `)}this.model.close?.addEventListener("click",r=>{r.stopPropagation(),r.preventDefault(),this.HideDialog()})}Node(e){return this.model[e]}Update(e,t=!0){t&&(e={...this.options_,...e}),this.options=e}HideDialog(){this.visible=!1}ShowDialog(e){return new Promise(t=>{this.pending_dialog_resoltion.push(t),this.options=e,this.visible=!0,this.timeout&&(window.clearTimeout(this.timeout),this.timeout=0),e.timeout&&(this.timeout=window.setTimeout(()=>this.HideDialog(),e.timeout))})}};var _r=class{constructor(e){this.container=e;let t=O.GetInstance(e.ownerDocument);this.node=t.Div("treb-spinner",e,{html:"<div><div></div><div></div><div></div><div></div></div>"})}node;visible=!1;Show(){this.node.classList.add("visible")}Hide(){this.node.classList.remove("visible")}};var Wn={formula_bar:!0,in_cell_editor:!0,undo:!0,scrollbars:!0,headers:!0,export:!0,tab_bar:"auto",resizable:!0,hyperlinks:"_blank",max_file_size:94208,tint_theme_colors:!0,dnd:!1,add_tab:!1,expand_formula_button:!1,expand:!0,markdown:!1,spinner:!1,complex:"off",spill:!0};var xe=l=>!!l&&typeof l=="object"&&l.key==="metadata"&&!!l.value&&l.value.type==="metadata",pi=l=>!!l&&typeof l=="object"&&l.key==="series"&&typeof l.value=="object",Xn=l=>!!l&&typeof l=="object"&&l.type===9&&Array.isArray(l.value);var G=class{static Scale(e,t,r=6.5,i,n){return Di(e,t,r,i,n)}static Range(e){let t,r;for(let n of e)typeof n>"u"||((typeof t>"u"||t>n)&&(t=n),(typeof r>"u"||r<n)&&(r=n));let i=typeof t>"u"||typeof r>"u"?0:r-t;return{min:t,max:r,range:i}}static ApplyScale(e,t,r){return t*(e-r.min)/(r.max-r.min)}static Flatten(e){let t=[];if(Array.isArray(e))for(let r of e)Array.isArray(r)?t=t.concat(this.Flatten(r)):t.push(r);else typeof e<"u"&&t.push(e);return t}};var Yn=l=>{bi(l,0,l.length)},Ma=(l,e,t)=>{let r=l[t-1],i=e;for(let n=e;n<t-1;n+=1)l[n]<=r&&(Kn(l,n,i),i+=1);return Kn(l,i,t-1),i},Kn=(l,e,t)=>{let r=l[e];l[e]=l[t],l[t]=r},bi=(l,e,t)=>{if(e<t){let r=Ma(l,e,t);bi(l,e,r),bi(l,r+1,t)}};var gi="#,##0.00",rt=l=>{let e=l[0],t=l[0];for(let r of l)r<e&&(e=r),r>t&&(t=r);return{min:e,max:t}},Qn=l=>{let{label:e,x:t,y:r,z:i,index:n,subtype:o,data_labels:a,axis:s}=l,c={x:{data:[]},y:{data:[]}};if(typeof s=="number"&&(c.axis=s),typeof n=="number"&&(c.index=n),o&&(c.subtype=o.toString()),a){let h=G.Flatten(Array.isArray(a)?a:[a]);c.labels=h.map(f=>typeof f>"u"?"":f.toString())}e&&(c.label=e.toString());let d=(h,f=!1)=>{let m;if(xe(h)&&(h={type:9,value:[[h]]}),Xn(h)){m={data:[]};let p=G.Flatten(h.value);if(m.data=p.map(b=>{if(xe(b)){if(typeof b.value.value=="number")return b.value.value}else if(b.type===3)return b.value}),xe(p[0])&&p[0].value?.format&&(m.format=p[0].value.format,f)){let b=L.Get(m.format);m.labels=m.data.map(g=>g===void 0?void 0:b.Format(g))}}return m};c.y=d(r,!0)||{data:[]},c.x=d(t)||{data:[]},c.z=d(i);let u=[c.x,c.y];for(let h of u)if(h.data.length){let f=h.data.filter(m=>m||m===0);h.range=rt(f)}return c},Zn=l=>{let e={x:{data:[]},y:{data:[]}},t=G.Flatten(l.value),r=[];for(let[n,o]of t.entries()){let a=0;if(typeof o.value=="number")a=o.value,r.push(o.value);else if(xe(o))if(he(o.value.value))e.x.data[n]=o.value.value.real,a=o.value.value.imaginary;else if(typeof o.value.value=="number")a=o.value.value;else continue;else continue;e.y.data[n]=a,r.push(a)}let i="";if(xe(t[0])&&(i=t[0].value.format||""),i){e.y.format=i;let n=L.Get(e.y.format||"");e.y.labels=e.y.data.map(o=>o===void 0?void 0:n.Format(o))}if(e.y.range=rt(r),e.x.data.length){let n=e.x.data.filter(o=>typeof o=="number");if(e.x.range=rt(n),i){e.x.format=i;let o=L.Get(e.x.format||"");e.x.labels=e.x.data.map(a=>a===void 0?void 0:o.Format(a))}}return e},Ct=(l,e)=>{if(!l)return[];let t=[];if(l.type===5){if(l.key==="group"){if(Array.isArray(l.value)){for(let[n,o]of l.value.entries())if(o&&typeof o=="object")if(pi(o)){let a=Qn(o.value);typeof a.index>"u"&&(a.index=n+1),t.push(a)}else o.type===9&&t.push(Zn(o))}}else if(pi(l)){let n=Qn(l.value);t.push(n)}}else l.type===9&&t.push(Zn(l));let r,i=0;if(e?.type===9){let n=G.Flatten(e.value),o="0.00###";xe(n[0])&&n[0].value.format&&(o=n[0].value.format);let a=n.map(c=>{if(c.type===3)return c.value;if(xe(c)&&typeof c.value.value=="number")return c.value.value}),s=a.filter(c=>typeof c=="number");r={data:a,format:o,range:rt(s)}}for(let n of t)i=Math.max(i,n.y.data.length),n.x.data.length&&(r||(r=n.x));if(!r){r={data:[],range:{min:0,max:Math.max(0,i-1)}};for(let n=0;n<i;n++)r.data.push(n)}for(let n of t)n.x.data.length||(n.x=r);return t},eo=l=>{let e=Math.abs(l.step)%1;if(e){if(Math.log10(Math.abs(e))<-4)return"Scientific";let r=0;for(let n=0;n<l.count;n++){let o=((l.min+l.step*n)%1).toFixed(6).replace(/0+$/,"");r=Math.max(r,o.length-2)}let i="#,##0.";for(let n=0;n<r;n++)i+="0";return i}else return Math.log10(Math.abs(l.step))>=5?"Scientific":"#,##0"},it=(l,e,t,r,i,n)=>{let o="",a="",s="";for(let R of l)R.axis?R.y.format&&!s&&(s=R.y.format):R.y.format&&!a&&(a=R.y.format),R.x.format&&!o&&(o=R.x.format);let c;l.some(R=>R.label&&R.label.length>0)&&(c=l.map((R,z)=>({label:R.label||`Series ${z+1}`,index:typeof R.index=="number"?R.index:z+1})));let d=l.filter(R=>R.x.range),u=Math.min.apply(0,d.map(R=>R.x.range?.min||0)),h=Math.max.apply(0,d.map(R=>R.x.range?.max||0)),f=d.filter(R=>!R.axis),m=d.filter(R=>R.axis),p=Math.min.apply(0,f.map(R=>R.y.range?.min||0)),b=Math.max.apply(0,f.map(R=>R.y.range?.max||0)),g=-1,x=-1;m.length&&(g=Math.min.apply(0,m.map(R=>R.y.range?.min||0)),x=Math.max.apply(0,m.map(R=>R.y.range?.max||0)));for(let R of l)if(R.z){for(let[z,K]of R.z.data.entries())if(typeof K<"u"){let ie=R.x.data[z],me=Math.max(0,K/2);typeof ie<"u"&&(u=Math.min(u,ie-me),h=Math.max(h,ie+me));let T=R.y.data[z];typeof T<"u"&&(p=Math.min(p,T-me),b=Math.max(b,T+me))}}typeof r<"u"&&(u=Math.min(u,r)),typeof i<"u"&&(u=Math.max(u,i)),typeof e<"u"&&(p=Math.min(p,e)),typeof t<"u"&&(b=Math.max(b,t));let y=G.Scale(u,h,7),w=G.Scale(p,b,7),_=G.Scale(g,x,7);if(g!==x&&w&&_&&w.count!==_.count){let R=Math.max(w.count,_.count),z=w.count<R?w:_;for(let K=z.count;K<R;K+=2)z.max+=z.step,z.count++,z.count<R&&(z.min-=z.step,z.count++)}let C,S,A;if(o){C=[];let R=L.Get(o);for(let z=0;z<=y.count;z++)C.push(R.Format(y.min+z*y.step))}if(!a&&n&&(a=eo(w)),!s&&n&&(s=eo(_)),a){S=[];let R=L.Get(a);for(let z=0;z<=w.count;z++)S.push(R.Format(w.min+z*w.step))}if(s){A=[];let R=L.Get(s);for(let z=0;z<=_.count;z++)A.push(R.Format(_.min+z*_.step))}let E={x:{format:o,scale:y,labels:C},y:{format:a,scale:w,labels:S},legend:c};return g!==x&&(E.y2={format:s,scale:_,labels:A}),E},yr=(l,e,t)=>{for(let r of l){let i={x:L.Get(r.x.format||""),y:L.Get(r.y.format||"")};r.y.labels=[];for(let n=0;n<r.y.data.length;n++){let o=t?t[n]:typeof r.x.data[n]=="number"?i.x.Format(r.x.data[n]):"",a=typeof r.y.data[n]=="number"?i.y.Format(r.y.data[n]):"";r.y.labels[n]=e.replace(/\bx\b/g,o).replace(/\by\b/g,a)}}},Va=l=>{let e=(a,s=0,c=a.length)=>c%2?a[Math.floor(c/2)+s]:(a[c/2+s]+a[c/2-1+s])/2,t=l.length,r=[0,e(l),0];if(t%2){let a=Math.floor(t/2);r[0]=e(l,0,Math.ceil(t/2)),r[2]=e(l,a,l.length-a)}else r[0]=e(l,0,t/2),r[2]=e(l,t/2,l.length-t/2);let i=r[2]-r[0],n=[0,0],o=0;for(let a=0;a<t;a++)o+=l[a];for(let a=0;a<t;a++){let s=l[a];if(s>=r[0]-i*1.5){n[0]=s;break}}for(let a=t-1;a>=0;a--){let s=l[a];if(s<=r[2]+i*1.5){n[1]=s;break}}return{data:l,quartiles:r,whiskers:n,iqr:i,n:t,mean:t?o/t:0,min:l[0],max:l[t-1]}},to=l=>{let e=Ct(l[0]),t=it(e,void 0,void 0,void 0,void 0,!0),r=0,i=!!l[2],n=e.map(u=>{let h=[];for(let m of u.y.data)m!==void 0&&h.push(m);Yn(h);let f=Va(h);return r=Math.max(r,f.n),i&&(f.whiskers[0]=f.min,f.whiskers[1]=f.max),f}),o=l[1]?.toString()||void 0,a=[],s=[],c=L.Get("#,##0");for(let[u,h]of n.entries()){a.push(c.Format(h.n));let f=e[u];s.push(f.label||`Series ${u+1}`)}return{type:"box",series:e,title:o,max_n:r,data:n,x_labels:a,series_names:e.some(u=>!!u.label)?s:void 0,scale:t.y.scale,y_labels:t.y.labels}},ro=l=>{let e=Ct(l[0]),t,r;for(let a of e)typeof a.x.range?.min=="number"&&a.x.range.min>0&&a.x.range.min<50&&(r=0),typeof a.y.range?.min=="number"&&a.y.range.min>0&&a.y.range.min<50&&(t=0);let i=it(e,t,void 0,r),n=l[1]?.toString()||void 0;return{legend:i.legend,legend_style:2,type:"bubble",series:e,title:n,x_scale:i.x.scale,x_labels:i.x.labels,y_scale:i.y.scale,y_labels:i.y.labels}},_i=(l,e="plot")=>{let t=Ct(l[0]),r=it(t),i=l[1]?.toString()||void 0,n=l[2]?.toString()||void 0,o={legend:r.legend,style:e,type:"scatter2",series:t,title:i,x_scale:r.x.scale,x_labels:r.x.labels,y_scale:r.y.scale,y_labels:r.y.labels,y2_scale:r.y2?.scale,y2_labels:r.y2?.labels,lines:e==="line",points:e==="plot"};if(n){o.markers=/marker/i.test(n),o.smooth=/smooth/i.test(n),o.data_labels=/labels/i.test(n);let a=n.match(/labels="(.*?)"/);a&&o.series?yr(o.series,a[1]):(a=n.match(/labels=([^\s\r\n,]+)(?:\W|$)/),a&&o.series&&yr(o.series,a[1])),a=n.match(/class=([\w_-]+)(?:\W|$)/),a&&(o.class_name=a[1])}return o},yi=(l,e)=>{let[t,r,i,n]=l,o=n?.toString()||void 0,a=/stacked/i.test(o||""),s=Ct(t),c=it(s),d;if(r){d=(r.type===9?G.Flatten(r.value):G.Flatten(r)).map(g=>!g||!g.value?"":xe(g)?typeof g.value.value=="number"?L.Get(g.value.format||gi).Format(g.value.value):g.value.value?.toString()||"":typeof g.value=="number"?L.Get(gi).Format(g.value):g.value.toString());let b=s.reduce((g,x)=>Math.max(g,x.y.data.length),0);for(b<d.length&&(d=d.slice(0,b));b>d.length;)d.push("")}let u,h=c.legend;if(a){u=s;let p=new Map;for(let x of s)for(let[y,w]of x.x.data.entries())if(w!==void 0){let _=x.y.data[y]||0;p.set(w,_+(p.get(w)||0))}let b=Array.from(p.keys()).sort((x,y)=>x-y),g=b.map(x=>p.get(x)||0);s=[{x:{data:b,format:u[0]?.x?.format},y:{data:g,format:u[0]?.y?.format}}],s[0].x.range=rt(b),s[0].y.range=rt(g),c=it(s,Math.min(0,...g))}let f=i?.toString()||void 0,m={type:e,legend:h,legend_style:1,series2:s,stacked_series:u,scale:c.y.scale,title:f,y_labels:e==="bar"?d:c.y.labels,x_labels:e==="bar"?c.y.labels:d};if(o){m.stacked=a,m.round=/round/i.test(o),m.data_labels=/labels/i.test(o);let p=o.match(/labels="(.*?)"/);p&&s?yr(s,p[1],d):(p=o.match(/labels=([^\s\r\n,]+)(?:\W|$)/),p&&s&&yr(s,p[1],d)),p=o.match(/class=([\w_-]+)(?:\W|$)/),p&&(m.class_name=p[1])}return m},vi=(l,e)=>{let t=Ct(l[0],l[1]),r=it(t,0,0),i=l[2]?.toString()||void 0,n=l[3]?.toString()||void 0,o={legend:r.legend,type:"scatter2",series:t,title:i,x_scale:r.x.scale,x_labels:r.x.labels,y_scale:r.y.scale,y_labels:r.y.labels,lines:!0,filled:e==="area"};if(n){o.smooth=/smooth/i.test(n);let a=n.match(/class=([\w_-]+)(?:\W|$)/);a&&(o.class_name=a[1])}return o},io=(l,e=!1)=>{let[t,r,i,n,o]=l,a=l[0]?.type===9?l[0].value:l[0],s=a?G.Flatten(a):[],c=s.map(_=>{if(xe(_)&&typeof _.value.value=="number")return _.value.value}),d=l[1]?.type===9?l[1].value:l[1],u=G.Flatten(d||[]).map(_=>xe(_)?typeof _.value.value=="number"&&_.value.format?L.Get(_.value.format).Format(_.value.value):_.value.value?.toString()||"":_.value?.toString()||""),h=!1;c=c.map(_=>_&&_<0?(h||(console.warn("pie/donut chart does not support negative values (omitted)"),h=!0),0):_);let f=0,m=c.map((_,C)=>(typeof _<"u"&&(f+=_),{value:_||0,label:u[C]||"",index:C+1,percent:0}));if(f)for(let _ of m)_.percent=(_.value||0)/f;let p="";for(let _ of s)if(xe(_)){p=_.value.format||"";break}let b=L.Get(p||gi),g=L.Get("percent");typeof l[4]>"u"&&l[1]&&(l[4]="label");let x=l[4]||"";if(x)for(let _ of m){let C=b.Format(_.value||0),S=g.Format(_.percent);_.title=x.replace(/value%/ig,g.Format(_.value||0)).replace(/value/ig,C).replace(/percent/ig,S).replace(/label/ig,_.label||"").trim()}let y=(n||"").toUpperCase();if(y==="ASC"||y==="ASCENDING"||y==="INC")m.sort((_,C)=>(_.value||0)-(C.value||0));else if(y==="DESC"||y==="DESCENDING"||y==="DEC")m.sort((_,C)=>(C.value||0)-(_.value||0));else{let _=(n||"").match(/sort=([\w]+)(?:\W|$)/i);_&&(y=_[1],/^(asc|inc)/i.test(y)?m.sort((C,S)=>(C.value||0)-(S.value||0)):/^(desc|dec)/i.test(y)&&m.sort((C,S)=>(S.value||0)-(C.value||0)))}let w={type:e?"pie":"donut",slices:m,title:i||""};if(n){let _=n.match(/class=([_-\w]+)(?:\W|$)/);_&&(w.class_name=_[1])}return w};var Me=class{constructor(e=0,t=0,r=100,i=100){this.left=e;this.top=t;this.right=r;this.bottom=i}get width(){return this.right-this.left}get height(){return this.bottom-this.top}get center(){return{x:this.left+this.width/2,y:this.top+this.height/2}}};var Ia="http://www.w3.org/2000/svg",V=(l,e={},t)=>{let r=document.createElementNS(Ia,l);for(let i of Object.keys(e))if(e[i]!==void 0){let n=e[i]??"";r.setAttribute(i,Array.isArray(n)?n.join(" "):n.toString())}return t&&(r.textContent=t),r},vr=class{parent;svg_node;text_measurement_node;container_group;group;axis_group;label_group;size={width:0,height:0};bounds=new Me;constructor(){this.container_group=V("g"),this.group=V("g"),this.axis_group=V("g",{class:"axis-group"}),this.label_group=V("g",{class:"label-group"}),this.container_group.appendChild(this.axis_group),this.container_group.appendChild(this.group),this.container_group.appendChild(this.label_group)}Initialize(e){this.parent=e,this.svg_node=V("svg",{class:"treb-chart"}),this.svg_node.style.overflow="hidden",this.svg_node.style.position="relative",this.svg_node.style.width="100%",this.svg_node.style.height="100%",this.svg_node.appendChild(this.container_group),this.parent.appendChild(this.svg_node),this.Resize()}Legend(e){let t=V("g");this.group.appendChild(t);let r=V("text");t.appendChild(r),t.setAttribute("class","legend");let i=[[]],n=10,o=e.area.width,a=0,s=0,c=e.area.width,d=e.style===1?14:26,u=e.labels.map((b,g)=>{r.textContent=b.label;let x=r.getBoundingClientRect(),y={width:x.width,height:x.height},w=y.width+d+n;return s=Math.max(s,y.height),e.layout===1?i[g]=[g]:w>o?i[a].length===0?(i[a].push(g),a++,i[a]=[],o=c):(a++,i[a]=[g],o=c-w):(i[a].push(g),o-=w),y});t.removeChild(r);let h=s,f=e.layout||0;f===0&&i.every(b=>b.length<=1)&&(f=0);for(let b=0;b<i.length;b++){let g=i[b].reduce((w,_)=>w+u[_].width+d,(i[b].length-1)*n),x=0,y=f===0?Math.round((c-g)/2):Math.round(n/2);for(let w=0;w<i[b].length;w++){let _=i[b][w],C=u[_],S=e.labels[_],A=h-1,E=!1;typeof navigator<"u"&&(E=/trident/i.test(navigator?.userAgent||""));let R=typeof S.index=="number"?S.index:_+1;switch(t.appendChild(V("text",{"dominant-baseline":"middle",x:y+d,y:h,dy:E?".3em":void 0},S.label)),e.style){case 1:t.appendChild(V("rect",{class:`series-${R}`,x:y,y:A-4,width:8,height:8}));break;case 2:t.appendChild(V("circle",{class:`series-${R}`,cx:y+d-11,cy:A-4+3}));break;default:t.appendChild(V("rect",{class:`series-${R}`,x:y,y:A-1,width:d-3,height:2}));break}x=Math.max(x,C.height),y+=C.width+d+n}h=Math.round(h+x*1.1)}let m=t.getBoundingClientRect(),p={width:m.width,height:m.height+s};switch(e.position){case 1:t.setAttribute("transform",`translate(${e.area.left}, ${e.area.bottom-p.height})`);break;case 2:t.setAttribute("transform",`translate(${e.area.left}, ${e.area.top})`);break;case 3:t.setAttribute("transform",`translate(${e.area.right-p.width}, ${e.area.top})`);break;case 0:default:t.setAttribute("transform",`translate(${e.area.left}, ${e.area.top})`)}e.position===0?e.area.top+=p.height||0:e.position===3?e.area.right-=(p.width||0)+8:e.position===2?e.area.left+=(p.width||0)+8:e.area.bottom-=p.height||0}Clear(e){this.group.textContent="",this.axis_group.textContent="",this.label_group.textContent="",e="treb-chart"+(e?" "+e:""),this.svg_node.setAttribute("class",e)}Resize(){let e=this.svg_node.getBoundingClientRect();this.svg_node.setAttribute("width",e.width.toString()),this.svg_node.setAttribute("height",e.height.toString()),this.size={width:e.width,height:e.height}}Prerender(){let e=this.svg_node.getBoundingClientRect();this.bounds.top=e.top,this.bounds.left=e.left,this.bounds.right=e.right,this.bounds.bottom=e.bottom}RenderTitle(e,t,r,i){let n=V("text",{class:"chart-title",x:Math.round(t.width/2)},e);n.style.textAnchor="middle",this.group.appendChild(n);let o=n.getBoundingClientRect();switch(i){case"bottom":n.setAttribute("y",Math.round(t.bottom-o.height).toString()),t.bottom-=o.height+r;break;default:n.setAttribute("y",Math.round(t.top+r+o.height).toString()),t.top+=o.height+r;break}}MeasureText(e,t,r=!1){this.text_measurement_node||(this.text_measurement_node=V("text",{x:"-100px",y:"-100px"}),this.svg_node.appendChild(this.text_measurement_node)),typeof t<"u"?(typeof t=="string"&&(t=[t]),this.text_measurement_node.setAttribute("class",t.join(" "))):this.text_measurement_node.setAttribute("class",""),this.text_measurement_node.textContent=e;let i=this.text_measurement_node.getBoundingClientRect(),n={width:i.width,height:i.height,y_offset:i.height-(this.bounds.top-i.top-100)};return r&&(n.width=Math.ceil(n.width),n.height=Math.ceil(n.height),n.y_offset=Math.ceil(n.y_offset)),n}RenderTicks(e,t,r,i,n){let o=[],a=e.width/i;for(let s=0;s<i;s++){let c=Math.round(e.left+a/2+a*s)-.5;o.push(`M${c} ${t} L${c} ${r}`)}this.group.appendChild(V("path",{d:o,class:n}))}RenderXAxisBar(e,t,r,i,n){let o=r.length;if(!o)return;let a=4,s=t?e.width/o:e.width/(o-1),c=t?s/2:0,d=1,u=!0;for(;u;){u=!1;let h=0;for(let f=0;f<o;f+=d){let m=Math.round(e.left+c+s*f),p=m-i[f].width/2;if(h&&p<=h){d++,u=!0;break}h=m+i[f].width/2+a}}for(let h=0;h<o;h+=d){let f=Math.round(e.left+c+s*h);this.RenderText(this.axis_group,r[h],"center",{x:f,y:e.bottom},n)}}RenderXAxisTicks(e,t,r){let i=t?e.width/r:e.width/(r-1),n=t?i/2:0,o=[];for(let a=0;a<r;a++){let s=Math.round(e.left+n+i*a)+.5;o.push(`M${s},${e.bottom+.5} v6`)}this.axis_group.appendChild(V("path",{d:o.join(" "),class:"x-axis-tick axis-tick"}))}RenderXAxis(e,t,r,i,n){let o=r.length;if(!o)return;let a=4,s=t?e.width/o:e.width/(o-1),c=t?s/2:0,d=1,u=!0,h=(r.length-1)%2===0,f=(r.length-1)%3===0;for(;u;){u=!1;let m=0;for(let p=0;p<o;p+=d){let b=Math.round(e.left+c+s*p),g=b-i[p].width/2;if(m&&g<=m){d++,u=!0;break}m=b+i[p].width/2+a}}d===3&&!f&&h&&d++;for(let m=0;m<o;m+=d){let p=Math.round(e.left+c+s*m);this.RenderText(this.axis_group,r[m],"center",{x:p,y:e.bottom},n)}}RenderYAxisBar(e,t,r,i){r=r.slice(0),r.reverse();let n=r.length;if(!n)return;let o=e.height/n,a=1,s=!0;for(;s;){s=!1;let c=0;for(let d=0;d<n;d+=a){let u=r[d],h=Math.round(e.bottom-o*(d+.5)+u.metrics.height/4);if(c&&h>=c){a++,s=!0;break}c=h-u.metrics.height}}for(let c=0;c<n;c+=a){let d=r[c],u=Math.round(e.bottom-o*(c+.5)+d.metrics.height/4);this.RenderText(this.axis_group,d.label,"right",{x:t,y:u},i)}}RenderYAxis(e,t,r,i,n="right"){let o=r.length;if(!o)return;let a=e.height/(o-1),s=1,c=!0;for(;c;){c=!1;let d=0;for(let u=0;u<o;u+=s){let h=r[u],f=Math.round(e.bottom-a*u+h.metrics.height/4);if(d&&f>=d){s++,c=!0;break}d=f-h.metrics.height}}for(let d=0;d<o;d+=s){let u=r[d],h=Math.round(e.bottom-a*d+u.metrics.height/4);this.RenderText(this.axis_group,u.label,n,{x:t,y:h},i)}}LineProperties(e,t){let r=t.x-e.x,i=t.y-e.y;return{length:Math.sqrt(r*r+i*i),angle:Math.atan2(i,r)}}RenderSmoothLine(e,t,r=!1,i,n){let o=V("g"),a=[],s=[],c=t.length,d=c-1,u=e.width/c/2,h=[],f=t.map((b,g)=>{if(!(typeof b>"u"))return{x:Math.round(e.left+e.width/d*g),y:e.bottom-b}}),m=[],p=()=>{if(m.length<2)return;let b="",g=m[0],x=m[m.length-1];m.length===2?b=`${m[0].x},${m[0].y} L${m[1].x},${m[1].y}`:m.length>2&&(b=""+this.CatmullRomChain(m).map(w=>`${w.x},${w.y}`).join(" L")),b&&(a.push("M"+b),r&&(s.push(`M ${g.x},${e.bottom} L ${g.x},${g.y}`),s.push("L"+b),s.push(`L ${x.x},${e.bottom}`)))};for(let b of f)b?m.push(b):(p(),m=[]);if(m.length&&p(),r&&o.appendChild(V("path",{class:"fill",d:s})),o.appendChild(V("path",{class:"line",d:a})),typeof n<"u"&&(typeof n=="string"&&(n=[n]),o.setAttribute("class",n.join(" "))),this.group.appendChild(o),i&&h.length){let b=V("g");for(let g of h){let x=V("circle",{cx:g.x,cy:g.y,r:u});x.addEventListener("mouseenter",()=>{this.parent.setAttribute("title",i[g.i]||"")}),x.addEventListener("mouseleave",()=>{this.parent.setAttribute("title","")}),b.appendChild(x)}b.setAttribute("class","mouse-layer"),this.group.appendChild(b)}}RenderLine(e,t,r=!1,i,n){let o=V("g"),a=[],s=[],c=t.length,d=c-1,u=e.width/c/2,h=[],f=0,m=!0,p;for(;f<c;f++){let b=t[f];if(typeof b>"u"){m=!0,r&&typeof p<"u"&&s.push(`L${p} ${e.bottom}Z`),p=void 0;continue}let g=Math.round(+e.left+e.width/d*f);m?(r&&s.push(`M${g} ${e.bottom} L${g} ${e.bottom-b}`),a.push(`M${g} ${e.bottom-b}`)):(a.push(`L${g} ${e.bottom-b}`),s.push(`L${g} ${e.bottom-b}`)),h.push({x:g,y:e.bottom-b,i:f}),p=g,m=!1}if(r&&typeof p<"u"&&s.push(`L${p} ${e.bottom}Z`),r&&o.appendChild(V("path",{class:"fill",d:s})),o.appendChild(V("path",{class:"line",d:a})),typeof n<"u"&&(typeof n=="string"&&(n=[n]),o.setAttribute("class",n.join(" "))),this.group.appendChild(o),i&&h.length){let b=V("g");for(let g of h){let x=V("circle",{cx:g.x,cy:g.y,r:u});x.addEventListener("mouseenter",()=>{this.parent.setAttribute("title",i[g.i]||"")}),x.addEventListener("mouseleave",()=>{this.parent.setAttribute("title","")}),b.appendChild(x)}b.setAttribute("class","mouse-layer"),this.group.appendChild(b)}}RenderBarGrid(e,t,r){let i=[],n=e.width/t;for(let o=0;o<=t;o++){let a=Math.round(e.left+n*o)-.5;i.push(`M${a} ${e.top} L${a} ${e.bottom}`)}this.group.appendChild(V("path",{d:i,class:r}))}RenderGrid(e,t,r=0,i,n){let o=[],a=[],s=e.height/t;for(let c=0;c<=t;c++){let d=Math.round(e.top+s*c)-.5;n&&n[1]===c?a.push(`M${e.left} ${d} L${e.right} ${d}`):o.push(`M${e.left} ${d} L${e.right} ${d}`)}s=e.width/(r-1);for(let c=0;c<r;c++){let d=Math.round(e.left+s*c)-.5;n&&n[0]===c?a.push(`M${d} ${e.top} L${d} ${e.bottom}`):o.push(`M${d} ${e.top} L${d} ${e.bottom}`)}this.group.appendChild(V("path",{d:o,class:i})),a.length&&(i?Array.isArray(i)?i.push("zero"):i=i+" zero":i="zero",this.group.appendChild(V("path",{d:a,class:i})))}MultiplyPoint(e,t){return{x:e.x*t,y:e.y*t}}AddPoints(e,t){return{x:e.x+t.x,y:e.y+t.y}}CatmullRomSpline(e,t){let r=.5;r=r/2;let i=(u,h,f)=>{let{x:m,y:p}=h,{x:b,y:g}=f;return((b-m)**2+(g-p)**2)**r+u},n=0,o=i(n,e[0],e[1]),a=i(o,e[1],e[2]),s=i(a,e[2],e[3]),c=(a-o)/t,d=[];for(let u=0;u<t;u++){let h=o+c*u,f=this.AddPoints(this.MultiplyPoint(e[0],(o-h)/(o-n)),this.MultiplyPoint(e[1],(h-n)/(o-n))),m=this.AddPoints(this.MultiplyPoint(e[1],(a-h)/(a-o)),this.MultiplyPoint(e[2],(h-o)/(a-o))),p=this.AddPoints(this.MultiplyPoint(e[2],(s-h)/(s-a)),this.MultiplyPoint(e[3],(h-a)/(s-a))),b=this.AddPoints(this.MultiplyPoint(f,(a-h)/(a-n)),this.MultiplyPoint(m,(h-n)/(a-n))),g=this.AddPoints(this.MultiplyPoint(m,(s-h)/(s-o)),this.MultiplyPoint(p,(h-o)/(s-o))),x=this.AddPoints(this.MultiplyPoint(b,(a-h)/(a-o)),this.MultiplyPoint(g,(h-o)/(a-o)));d.push(x)}return d}CatmullRomChain(e,t=30){let r=e.slice(0),i=[],n=r.length;if(n){let o=r[n-1].x-r[n-2].x,a=r[n-1].y-r[n-2].y;r.push({x:r[n-1].x+o,y:r[n-1].y+a}),r.push({x:r[n-1].x+o,y:r[n-1].y+a}),o=r[1].x-r[0].x,a=r[1].y-r[0].y,r.unshift({x:r[0].x-o,y:r[0].y-a});for(let s=0;s<r.length-4;s++){let c=r.slice(s,s+4),d=this.CatmullRomSpline(c,t);i.push(...d)}}return i}RenderDataLabels(e,t,r,i,n,o,a){let s=Math.max(t.length,r.length),c=i.max-i.min||1,d=n.max-n.min||1;for(let u=0;u<s;u++){let h=t[u],f=r[u];if(h!==void 0&&f!==void 0){let m={x:e.left+(h-i.min)/c*e.width,y:e.bottom-(f-n.min)/d*e.height},p=o[u];if(p){this.label_group.appendChild(V("circle",{class:"label-target",cx:m.x,cy:m.y,r:10}));let b=V("g",{class:"data-label",transform:`translate(${m.x+10},${m.y})`});this.label_group.appendChild(b);let g=V("circle",{cx:-10,y:0,r:5,class:`marker-highlight series-${a}`});b.appendChild(g);let x=V("text",{x:4,y:0},p);b.appendChild(x);let y=x.getBoundingClientRect(),w=y.height,_=y.width+8;_+15+m.x>=e.right&&(b.setAttribute("transform",`translate(${m.x-_-15},${m.y})`),g.setAttribute("cx",(_+15).toString()));let C=V("path",{d:`M0,5 h${_} v-${w} h-${_} Z`});b.insertBefore(C,x)}}}}RenderBoxAndWhisker(e,t,r,i,n,o,a){let s=V("g",{class:a});this.group.appendChild(s);let c=e.width/o,d=c*.2,h=Math.min(c-2*d,90);i>0&&(h=h*Math.sqrt(t.n)/Math.sqrt(i));let f=g=>e.top+e.height-(g-n.min)/(n.max-n.min)*e.height,m=e.left+r*c+c/2,p=f(t.quartiles[0]),b=f(t.quartiles[2]);s.appendChild(V("rect",{class:"iqr",x:e.left+r*c+(c-h)/2,y:b,width:h,height:p-b})),s.appendChild(V("line",{class:"median",x1:m-h*.5,x2:m+h*.5,y1:f(t.quartiles[1]),y2:f(t.quartiles[1])})),s.appendChild(V("line",{class:"whisker",x1:m-h*.25,x2:m+h*.25,y1:f(t.whiskers[0]),y2:f(t.whiskers[0])})),s.appendChild(V("line",{class:"whisker-extent",x1:m,x2:m,y1:f(t.whiskers[0])-2,y2:f(t.quartiles[0])+2})),s.appendChild(V("line",{class:"whisker",x1:m-h*.25,x2:m+h*.25,y1:f(t.whiskers[1]),y2:f(t.whiskers[1])})),s.appendChild(V("line",{class:"whisker-extent",x1:m,x2:m,y1:f(t.whiskers[1])+2,y2:f(t.quartiles[2])-2}));for(let g of t.data)(g<t.whiskers[0]||g>t.whiskers[1])&&s.appendChild(V("circle",{class:"outlier",cx:m,cy:f(g),r:3}))}RenderBubbleSeries(e,t,r,i,n){let o=r.max-r.min||1,a=i.max-i.min||1,s=[],c=[],d=V("g",{class:n});if(this.group.appendChild(d),t.z)for(let[u,h]of t.z.data.entries()){let f=t.x.data[u],m=t.y.data[u];if(typeof f<"u"&&typeof m<"u"&&typeof h<"u"&&h>0){let p=h/o*e.width,b=h/a*e.height,g=Math.max(p,b),x={x:e.left+(f-r.min)/o*e.width,y:e.bottom-(m-i.min)/a*e.height,z:g};if(s.push(x),t.labels?.[u]){let y=x.z/2;c.push({x:x.x,y:x.y,text:t.labels?.[u]||"",offset:Math.cos(Math.PI/4)*y})}}}for(let u of s)u&&d.appendChild(V("circle",{cx:u.x,cy:u.y,r:u.z/2,class:"point"}));if(c.length){let u=this.label_group.getBoundingClientRect();for(let h of c)if(h.text){let f=this.label_group.appendChild(V("g",{class:"bubble-label"})),m=f.appendChild(V("rect",{x:h.x,y:h.y,class:"label-background"})),b=f.appendChild(V("text",{x:h.x,y:h.y,offset:h.offset,class:"label-text","text-anchor":"middle","alignment-baseline":"middle",style:`--translate-offset: ${Math.round(h.offset)}px`},h.text)).getBoundingClientRect();m.setAttribute("x",(b.left-u.left-2).toString()),m.setAttribute("y",(b.top-u.top-1).toString()),m.style.height=b.height+2+"px",m.style.width=b.width+4+"px"}}}RenderScatterSeries(e,t,r,i,n,o=!0,a=!1,s=!1,c=!1,d=!1,u){let h=Math.max(t.length,r.length),f=i.max-i.min||1,m=n.max-n.min||1,p=[],b=[],g=[],x=V("g",{class:u});this.group.appendChild(x);for(let y=0;y<h;y++){let w=t[y],_=r[y];typeof w>"u"||typeof _>"u"?p.push(void 0):p.push({x:e.left+(w-i.min)/f*e.width,y:e.bottom-(_-n.min)/m*e.height})}if(o){let y=[],w=d?()=>y.length===2?`${y[0].x},${y[0].y} L${y[1].x},${y[1].y}`:y.length>2?this.CatmullRomChain(y).map(C=>`${C.x},${C.y}`).join(" L"):"":()=>y.map(_=>`${_.x},${_.y}`).join(" L");for(let _ of p)if(_)y.push(_);else{if(y.length>=2){let C=w();b.push("M"+C),g.push(`M${y[0].x},${e.bottom}L`+C+`L${y[y.length-1].x},${e.bottom}Z`)}y=[]}if(y.length>=2){let _=w();b.push("M"+_),g.push(`M${y[0].x},${e.bottom}L`+_+`L${y[y.length-1].x},${e.bottom}Z`)}}if(s&&x.appendChild(V("path",{d:g,class:"fill"})),o&&x.appendChild(V("path",{d:b,class:"line"})),a)for(let y of p)y&&x.appendChild(V("circle",{cx:y.x,cy:y.y,r:1,class:"point"}));if(c)for(let y of p)y&&x.appendChild(V("circle",{cx:y.x,cy:y.y,r:3,class:"marker"}))}RenderPoints(e,t,r,i){let n=[];for(let o=0;o<t.length;o++){let a=t[o]*e.width+e.left,s=e.bottom-r[o]*e.height;n.push(`M${a-1},${s-1} L${a+1},${s+1}`),n.push(`M${a-1},${s+1} L${a+1},${s-1}`)}this.group.appendChild(V("path",{d:n,class:i}))}RenderPoint(e,t,r){this.group.appendChild(V("circle",{cx:e,cy:t,r:1,class:r}))}RenderCalloutLines(e){let t=V("g",{class:"callouts"});this.label_group.appendChild(t);for(let r of e)t.appendChild(V("path",{d:`M${r.x1},${r.y1} L${r.x2},${r.y2}`,class:"callout "+(r.classes||"").trim()}))}RenderRectangle(e,t,r,i,n,o){let a="";if(t)if(t[0]&&t[0]===t[1]&&t[0]>=e.height){let c=t[0],d=t[0]-e.height,u=Math.sqrt(c*c-d*d);a=`M${e.left+e.width/2-u},${e.bottom} a${c},${c} 0 0 1 ${u*2},0 z`}else if(t[1]&&t[1]===t[2]&&t[1]>=e.width){let c=t[1],d=t[1]-e.width,u=Math.sqrt(c*c-d*d);a=`M${e.left},${e.top+e.height/2-u} a${c},${c} 0 0 1 0,${u*2} z`}else a=`M${e.left},${e.top+t[0]} a${t[0]},${t[0]} 0 0 1 ${t[0]},${-t[0]} h${e.width-t[0]-t[1]} a${t[1]},${t[1]} 0 0 1 ${t[1]},${t[1]} v${e.height-t[1]-t[2]} a${t[2]},${t[2]} 0 0 1 ${-t[2]},${t[2]} h${-e.width+t[2]+t[3]} a${t[3]},${t[3]} 0 0 1 ${-t[3]},${-t[3]} v${-e.height+t[3]+t[0]} `;else a=`M${e.left},${e.top} h${e.width} v${e.height} h${-e.width} v${-e.height} `;let s=V("path",{d:a,class:r});if(i&&(s.addEventListener("mouseenter",()=>{this.parent.setAttribute("title",i)}),s.addEventListener("mouseleave",()=>{this.parent.setAttribute("title","")})),this.group.appendChild(s),n){this.label_group.appendChild(V("path",{class:"label-target",d:a}));let c=o||{x:Math.round(e.left+e.width/2),y:Math.round(e.top-10)},d=V("g",{class:"data-label",transform:`translate(${c.x},${c.y})`});this.label_group.appendChild(d);let u=V("text",{x:0,y:0},n);d.appendChild(u);let h=u.getBoundingClientRect(),f=h.height,m=h.width+8;c.y-h.height<4&&(c.y-=c.y-h.height-4,d.setAttribute("transform",`translate(${c.x},${c.y})`)),u.setAttribute("x",Math.floor(-h.width/2).toString());let p=Math.ceil(f*.125),b=V("rect",{rx:3,x:-m/2,y:Math.round(-f+p*2/3),width:m,height:f+p});d.insertBefore(b,u)}}RenderText(e,t,r,i,n){let o=V("text",{x:i.x,y:i.y,class:n},t);switch(r){case"right":o.style.textAnchor="end";break;case"center":o.style.textAnchor="middle";break;default:o.style.textAnchor="start";break}(e||this.group).appendChild(o)}RenderDonut(e,t,r,i,n,o,a){let s=-Math.PI/2,c=0;o&&(r*=.8,i*=.7);let d=(u,h,f)=>[Math.cos(f)*h+u.x,Math.sin(f)*h+u.y];for(let u of e){let h=u.title||"",f=u.percent,m=u.index,p=[],b=0,g=d.bind(0,t,r),x=d.bind(0,t,i);if(f>.5){b=s+f/2*Math.PI*2,c=s+f*Math.PI*2;let _=b-s,C=c-b;p.push(`M${g(s)}`,`A${r},${r},${_},0,1,${g(b)}`,`A${r},${r},${C},0,1,${g(c)}`,`L${x(c)}`,`A${i},${i},${C},0,0,${x(b)}`,`A${i},${i},${_},0,0,${x(s)}`,"Z")}else{c=s+f*Math.PI*2,b=(c-s)/2+s;let _=c-s;p.push(`M${g(s)}`,`A${r},${r},${_},0,1,${g(c)}`,`L${x(c)}`,`A${i},${i},${_},0,0,${x(s)}`,"Z")}let y=V("path",{d:p,class:typeof m>"u"?void 0:`series-${m}`});typeof m<"u"&&y.setAttribute("data-index",m.toString());let w=V("g",{class:a});if(w.appendChild(y),this.group.appendChild(w),f>=.05&&h){let _=r-i;p=[];let C=d(t,i+(r-i)/2+_,b);p.push(`M${d(t,i+(r-i)/2,b)}`),p.push(`L${C}`),w.appendChild(V("path",{d:p,class:"callout"}));let S=[],A=V("text",{class:"callout-label"});w.appendChild(A);let E=b+Math.PI/2,R=h;A.textContent=R;let z=A.getBoundingClientRect(),K={width:z.width,height:z.height},[ie,me]=C;ie+=K.height/2*Math.cos(b),me+=K.height/4+K.height/2*Math.sin(b);let T=!1;E>Math.PI?ie-K.width<=n.left&&(T=!0):ie+K.width>n.right&&(T=!0);let q=/[\s-]/;if(T&&q.test(R)){let Y=-1,J=1;for(let k=0;k<R.length;k++)if(q.test(R[k])){let P=Math.abs(.5-k/R.length);P<J&&(J=P,Y=k)}Y>0&&(S.push(R.substr(0,Y+1).trim()),S.push(R.substr(Y+1).trim()))}if(S.length){let Y=0,J=0,k=S.map(P=>{A.textContent=P,z=A.getBoundingClientRect();let Z={width:z.width,height:z.height};return J=Math.max(J,Z.width),{text:P,metrics:Z}});A.textContent="";for(let P of k){let Z=V("tspan");Z.textContent=P.text;let pe=E>Math.PI?ie-(J-P.metrics.width)/2:ie+(J-P.metrics.width)/2;Z.setAttribute("x",pe.toString()),Z.setAttribute("dy",Y.toString()),A.appendChild(Z),Y=P.metrics.height}}let se=E>Math.PI?"end":"start";A.setAttribute("text-anchor",se),A.setAttribute("x",ie.toString()),A.setAttribute("y",me.toString()),typeof m<"u"&&A.setAttribute("data-index",m.toString())}s=c}}};var wr=class{renderer=new vr;margin={top:.025,left:.05,bottom:.025,right:.075};Resize(e,t){this.renderer.Resize()}Initialize(e){this.renderer.Initialize(e)}Update(e,t){this.renderer.Resize(),this.renderer.Prerender(),this.renderer.Clear(t.class_name);let r=new Me(0,0,this.renderer.size.width,this.renderer.size.height),i={top:Math.round(r.height)*this.margin.top,bottom:Math.round(r.height)*this.margin.bottom,left:Math.round(r.width)*this.margin.left,right:Math.round(r.width)*this.margin.right},n=t.title;if(n&&this.renderer.RenderTitle(n,r,i.top,t.title_layout||"top"),r.top+=i.top,r.left+=i.left,r.bottom-=i.bottom,r.right-=i.right,t.legend&&t.legend.length){let a=0;t.title&&(!t.title_layout||t.title_layout==="top")&&(a=1);let s=t.legend_position||a;this.renderer.Legend({labels:t.legend,position:s,style:t.legend_style,layout:s===0||s===1?0:1,area:r})}if(t.type==="histogram"||t.type==="line"||t.type==="area"||t.type==="column"||t.type==="histogram2"||t.type==="bar"||t.type==="scatter2"||t.type==="bubble"||t.type==="box"){let a=[],s=0;t.x_labels&&t.x_labels.length&&(a=t.x_labels.map(h=>{let f=this.renderer.MeasureText(h,["axis-label","x-axis-label"],!0);return s=Math.max(s,f.height),f}));let c=[],d=0;t.type==="box"&&t.series_names?.length&&(c=t.series_names.map(h=>{let f=this.renderer.MeasureText(h,["axis-label","x-axis-label","series-name"],!0);return d=Math.max(d,f.height),f}));let u=s&&d?4:0;if(t.y_labels&&t.y_labels.length){let h=[],f=0,m=0,p=t.type==="scatter2"||t.type==="bubble"?t.y_scale:t.scale,b=t.type==="bar"?t.y_labels.length:p.count+1;for(let g=0;g<b;g++){let x=this.renderer.MeasureText(t.y_labels[g],["axis-label","y-axis-label"]);h.push({label:t.y_labels[g],metrics:x}),f=Math.max(f,x.width),m=Math.max(m,x.height)}r.bottom=Math.round(r.bottom-m/2),r.top=Math.round(r.top+m/2),a.length&&(r.bottom-=s+i.bottom),c.length&&(r.bottom-=d+i.bottom),u&&(r.bottom-=u),t.type==="bar"?this.renderer.RenderYAxisBar(r,r.left+f,h,["axis-label","y-axis-label"]):this.renderer.RenderYAxis(r,r.left+f,h,["axis-label","y-axis-label"]),r.left+=f+i.left}if(t.type==="scatter2"&&t.y2_labels&&t.y2_labels.length&&t.y2_scale){let h=[],f=0,m=0,b=t.y2_scale.count+1;for(let g=0;g<b;g++){let x=this.renderer.MeasureText(t.y2_labels[g],["axis-label","y-axis-label"]);h.push({label:t.y2_labels[g],metrics:x}),f=Math.max(f,x.width),m=Math.max(m,x.height)}this.renderer.RenderYAxis(r,r.right-f,h,["axis-label","y-axis-label"],"left"),r.right-=f+i.left}if(a.length&&t.x_labels?.length){let h=t.type==="histogram2",f=t.type!=="line"&&t.type!=="area"&&t.type!=="bar"&&t.type!=="scatter2"&&t.type!=="bubble"&&t.type!=="histogram2";h&&this.renderer.RenderXAxisTicks(r,f,t.x_labels.length),t.y_labels&&(r.bottom+=s+i.bottom),this.renderer.RenderXAxis(r,f,t.x_labels,a,["axis-label","x-axis-label"]),r.bottom-=s+i.bottom}u&&(r.bottom+=u),t.type==="box"&&c.length&&t.series_names?.length&&(t.y_labels&&(r.bottom+=s+d+u+i.bottom),this.renderer.RenderXAxis(r,!0,t.series_names,c,["axis-label","x-axis-label","series-name"]),r.bottom-=s+d+i.bottom+i.bottom)}let o=[];switch(t.type){case"scatter":this.renderer.RenderPoints(r,t.x,t.y,"mc mc-correlation series-1");break;case"box":this.renderer.RenderGrid(r,t.scale.count,void 0,"chart-grid",o);for(let[a,s]of t.data.entries())s.iqr>0&&this.renderer.RenderBoxAndWhisker(r,s,a,t.max_n,t.scale,t.data.length,`box-plot series-${a}`);break;case"bubble":t.x_scale.min<=0&&t.x_scale.max>=0&&(o[0]=Math.round(Math.abs(t.x_scale.min/t.x_scale.step))),t.y_scale.min<=0&&t.y_scale.max>=0&&(o[1]=Math.round(Math.abs(t.y_scale.max/t.y_scale.step))),this.renderer.RenderGrid(r,t.y_scale.count,t.x_scale.count+1,"chart-grid",o);for(let[a,s]of t.series.entries()){let c=typeof s.index=="number"?s.index:a+1;this.renderer.RenderBubbleSeries(r,s,t.x_scale,t.y_scale,`bubble-chart series-${c}`)}break;case"scatter2":if(this.renderer.RenderGrid(r,t.y_scale.count,t.x_scale.count+1,"chart-grid"),t.series){for(let a=0;a<t.series.length;a++){let s=t.series[a],c=!!t.lines,d=!!t.points;s.subtype==="plot"?(d=!0,c=!1):s.subtype==="line"&&(d=!1,c=!0);let u=typeof s.index=="number"?s.index:a+1;this.renderer.RenderScatterSeries(r,s.x.data,s.y.data,t.x_scale,s.axis&&t.y2_scale?t.y2_scale:t.y_scale,c,d,!!t.filled,!!t.markers,!!t.smooth,`scatter-plot series-${u}`)}if(t.data_labels)for(let a=0;a<t.series.length;a++){let s=t.series[a];s.y.labels&&this.renderer.RenderDataLabels(r,s.x.data,s.y.data,t.x_scale,t.y_scale,s.y.labels,a+1)}}break;case"pie":case"donut":{let a=Math.min(r.height,r.width)/2*.9,s=t.type==="pie"?0:a*.8;this.renderer.RenderDonut(t.slices,r.center,a,s,r,!0,"donut")}break;case"line":case"area":{let a=t.scale;if(t.series){let s=t.x_scale?t.x_scale.max:Math.max.apply(0,t.series.map(u=>u.length)),c=t.smooth?this.renderer.RenderSmoothLine:this.renderer.RenderLine;this.renderer.RenderGrid(r,t.scale.count,t.x_scale?t.x_scale.count+1:s,"chart-grid");let d=0;for(let u of t.series){let h=u.map(m=>{if(!(typeof m>"u"))return G.ApplyScale(m,r.height,a)});if(h.length<s)for(let m=h.length;m<s;m++)h.push(void 0);let f=[t.type==="area"?"chart-area":"chart-line",`series-${d+1}`];c.call(this.renderer,r,h,t.type==="area",t.titles,f),d++}}}break;case"bar":{let a;if(this.renderer.RenderBarGrid(r,t.scale.count,"chart-grid"),t.series2){let s=0,c=t.series2.length;for(let p of t.series2)s=Math.max(s,p.y.data.length);let d=r.height/s,u=.7;typeof t.space=="number"&&(u=Math.max(0,Math.min(1,1-t.space)));let h=d*(1-u)/2,f=(d-h*2)/c,m=0;if(t.scale.min<0&&(m=G.ApplyScale(0,r.width,t.scale)),t.round){let p=Math.floor(f/2);a=[0,p,p,0]}for(let p=0;p<c;p++){let b=t.series2[p],g=typeof b.index=="number"?b.index:p+1;for(let x=0;x<b.y.data.length;x++){let y=b.y.data[x];if(typeof y=="number"){let w=Math.round(r.top+x*d+h)+p*f,_=0,C=0;m?y>0?(C=G.ApplyScale(y+t.scale.min,r.width,t.scale),_=r.left+m):(C=G.ApplyScale(t.scale.min-y,r.width,t.scale),_=r.left+m-C):(C=G.ApplyScale(y,r.width,t.scale),_=r.left),C&&this.renderer.RenderRectangle(new Me(_,w,_+C,w+f),a,["chart-column",`series-${g}`],void 0||void 0)}}}}}break;case"column":case"histogram2":if(this.renderer.RenderGrid(r,t.scale.count,0,"chart-grid"),t.series2){let a=0,s=t.series2.length;for(let p of t.series2)a=Math.max(a,p.y.data.length);let c=r.width/a,d=.7;typeof t.space=="number"&&(d=Math.max(0,Math.min(1,1-t.space)));let u=c*(1-d)/2,h=(c-u*2)/s,f=0;if(t.scale.min<0&&(f=G.ApplyScale(0,r.height,t.scale)),t.callouts&&t.x_scale){let p=t.x_scale,b=t.callouts.map((g,x)=>{let y=Math.round(r.left+G.ApplyScale(g.value,r.width,p))+.5;return{x1:y,y1:r.bottom-r.height,x2:y,y2:r.bottom,classes:`callout-${x+1}`}});this.renderer.RenderCalloutLines(b)}let m;if(t.round){let p=Math.floor(h/2);m=[p,p,0,0]}if(t.stacked_series)for(let p=0;p<t.stacked_series[0].y.data.length;p++){let b=r.left+p*c+u,g=0;for(let x=0;x<t.stacked_series.length;x++){let y=t.stacked_series[x],w=typeof y.index=="number"?y.index:x+1,_=0,C=y.y.data[p]||0;x===0&&(g=Math.min(t.scale.min||0,C)),_=G.ApplyScale(C,r.height,t.scale);let S=r.bottom-_-G.ApplyScale(g,r.height,t.scale);this.renderer.RenderRectangle(new Me(b,S,b+h,S+_),m,["chart-column",`series-${w}`],void 0||void 0,void 0,void 0),g+=C}}else for(let p=0;p<s;p++){let b=t.series2[p],g=typeof b.index=="number"?b.index:p+1;for(let x=0;x<b.y.data.length;x++){let y=b.y.data[x];if(typeof y=="number"){let w=r.left+x*c+u+p*h,_=0,C=0;f?y>0?(_=G.ApplyScale(y+t.scale.min,r.height,t.scale),C=r.bottom-_-f):(_=G.ApplyScale(t.scale.min-y,r.height,t.scale),C=r.bottom-f):(_=G.ApplyScale(y,r.height,t.scale),C=r.bottom-_);let S=void 0;if(_){let A=t.data_labels&&b.y.labels?b.y.labels[x]:"",E={x:Math.round(w+h/2),y:Math.round(C-10)};this.renderer.RenderRectangle(new Me(w,C,w+h,C+_),m,["chart-column",`series-${g}`],S||void 0,A,E)}}}}}break;case"histogram":{this.renderer.RenderGrid(r,t.scale.count,0,"chart-grid");let a=r.width/t.count,s=t.column_width,c=a*(1-s)/2;for(let d=0;d<t.count;d++){let u=Math.round(r.left+d*a+c),h=a-c*2,f=G.ApplyScale(t.bins[d],r.height,t.scale),m=r.bottom-f,p=t.titles?t.titles[d]:void 0;this.renderer.RenderRectangle(new Me(u,m,u+h,m+f),void 0,"chart-column series-1",p||void 0)}}break}}};var qe=class{constructor(e=new wr){this.renderer=e}static functions_registered=!1;chart_data={type:"null"};node;Initialize(e){this.node=e,this.renderer.Initialize(e)}Exec(e,t){let r=t?.value||[];switch(e.toLowerCase()){case"column.chart":this.chart_data=yi(r,"column");break;case"bar.chart":this.chart_data=yi(r,"bar");break;case"line.chart":this.chart_data=vi(r,"line");break;case"area.chart":this.chart_data=vi(r,"area");break;case"donut.chart":case"pie.chart":this.chart_data=io(r,e.toLowerCase()==="pie.chart");break;case"scatter.plot":this.chart_data=_i(r,"plot");break;case"scatter.line":this.chart_data=_i(r,"line");break;case"bubble.chart":this.chart_data=ro(r);break;case"box.plot":this.chart_data=to(r);break;default:this.Clear();break}}Clear(){this.chart_data={type:"null"}}Resize(){this.node&&this.renderer.Resize(this.node,this.chart_data)}Update(){this.node&&this.renderer.Update(this.node,this.chart_data)}};var Ue=(...l)=>({type:5,value:l,key:"arguments"}),wi={Group:{arguments:[{name:"Array...",metadata:!0}],fn:(...l)=>({type:5,value:l,key:"group"}),category:["grouping"]},Series:{arguments:[{name:"Label"},{name:"X",metadata:!0},{name:"Y",metadata:!0},{name:"Z",metadata:!0},{name:"Index"},{name:"Subtype"},{name:"Labels",description:"Labels for bubble charts only (atm)"},{name:"Axis",description:"Series axis (scatter plot only)"}],fn:(...l)=>({type:5,value:{label:l[0],x:l[1],y:l[2],z:l[3],index:l[4],subtype:l[5],data_labels:l[6],axis:l[7]},key:"series"}),category:["chart functions"]},"Bar.Chart":{arguments:[{name:"Data",metadata:!0},{name:"Categories",metadata:!0},{name:"ChartTitle"}],fn:Ue,category:["chart functions"]},"Line.Chart":{arguments:[{name:"y",metadata:!0},{name:"x",metadata:!0},{name:"ChartTitle"}],fn:Ue,category:["chart functions"]},"Area.Chart":{arguments:[{name:"y",metadata:!0},{name:"x",metadata:!0},{name:"ChartTitle"}],fn:Ue,category:["chart functions"]},"Pie.Chart":{arguments:[{name:"Values",metadata:!0},{name:"Labels"},{name:"Title"},{name:"Sort"},{name:"Label"}],fn:Ue,category:["chart functions"]},"Donut.Chart":{arguments:[{name:"Values",metadata:!0},{name:"Labels",metadata:!0},{name:"Title"},{name:"Sort"},{name:"Label"}],fn:Ue,category:["chart functions"]},"Scatter.Line":{arguments:[{name:"Data",metadata:!0},{name:"ChartTitle"}],fn:Ue,category:["chart functions"]},"Scatter.Plot":{arguments:[{name:"Data",metadata:!0},{name:"ChartTitle"}],fn:Ue,category:["chart functions"]},"Column.Chart":{arguments:[{name:"Data",metadata:!0},{name:"Categories",metadata:!0},{name:"Chart Title"}],fn:Ue,category:["chart functions"]},"Bubble.Chart":{arguments:[{name:"Data",metadata:!0},{name:"Chart Title"}],fn:Ue,category:["chart functions"]},"Box.Plot":{arguments:[{name:"Data",metadata:!0},{name:"Chart Title"},{name:"Min/Max Style"}],fn:Ue,category:["chart functions"]}};var xr=class l{static treb_base_path="";static failed_dynamic_modules=[];static one_time_warnings={};static clipboard;DOM=O.GetInstance();loaded=!1;document_styles={number_formats:[],colors:[],theme_colors:[]};selection_state={};options;get Localization(){return F}events=new ge;calculation=0;file_version=0;last_save_version=0;initial_load_source=void 0;calculator;grid;model;dialog;spinner;file_chooser;file_chooser_operation=0;get parser(){return this.model.parser}view_node;key_listener;views=[];focus_target=this;parent_view;export_worker;undo_pointer=0;undo_stack=[];last_selection;get active_sheet(){let e=this.grid.active_sheet.name;return Ce.test(e)?`'${e}'`:e}get modified(){return this.undo_stack.length!==1}get document_name(){return this.grid.model.document_name}set document_name(e){this.grid.model.document_name=e,this.DocumentChange()}get user_data(){return this.grid.model.user_data}set user_data(e){this.grid.model.user_data=e,this.DocumentChange()}get scale(){return this.grid.scale}set scale(e){this.grid.scale=e}get headless(){return this.grid.headless}set headless(e){this.grid.headless!==e&&(this.grid.headless=e,e||(this.grid.Update(!0),this.RebuildAllAnnotations()))}get state(){return this.file_version}get can_revert(){return!this.options.inline_document&&!this.options.document?!1:this.initial_load_source==="local-storage"?!0:this.dirty}get dirty(){return this.file_version!==this.last_save_version}set dirty(e){e?this.file_version++:this.last_save_version=this.file_version}get sheet_names(){return this.model.sheets.list.map(e=>e.name)}constructor(e){e.storage_key&&!e.local_storage&&(e.local_storage=e.storage_key),this.options={...Wn,...e,local_storage:this.ResolveStorageKey(e.local_storage,"document")},typeof this.options.imaginary_value=="string"&&(de.imaginary_character=this.options.imaginary_value),this.options.network_document&&(console.warn("the option `network_document` is deprecated. please use `document` instead."),this.options.document||(this.options.document=this.options.network_document)),this.options.document&&this.options.inline_document&&console.warn("both document and inline-document are provided");let t=this.options.document,r,i;this.options.local_storage&&!this.options.toll_initial_load&&!e.model&&(r=localStorage.getItem(this.options.local_storage)||void 0,r&&(i="local-storage")),!r&&!this.options.toll_initial_load&&!e.model&&e.inline_document&&(r=e.inline_document,i="inline-document"),this.options.local_storage&&!e.model&&window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.options.local_storage&&this.dirty&&this.SaveLocalStorage(this.options.local_storage)});let n;typeof this.options.container=="string"?n=document.querySelector(this.options.container):this.options.container&&(n=this.options.container);let o={in_cell_editor:!0,repaint_on_cell_change:!1,scrollbars:this.options.scrollbars,markdown:!!this.options.markdown,formula_bar:this.options.formula_bar,expand_formula_button:this.options.expand_formula_button,tab_bar:this.options.tab_bar,add_tab:this.options.add_tab,expand:this.options.expand,support_font_stacks:!!this.options.font_stack};if(this.options.scale&&(o.initial_scale=this.options.scale),this.options.stats&&(o.stats=this.options.stats,o.tab_bar=!0),this.options.scale_control&&(o.scale_control=!0,o.tab_bar=!0,this.options.persist_scale&&(o.persist_scale_key=this.ResolveStorageKey(this.options.persist_scale,"scale"),o.persist_scale_key))){let a=localStorage.getItem(o.persist_scale_key);if(a)try{let s=JSON.parse(a);o.initial_scale=s.scale||1}catch{console.warn("parsing persisted scale failed")}}if(e.model?(this.model=e.model.model,this.calculator=e.model.calculator,this.DOM=e.model.DOM):(this.model=new _t,this.model.sheets.Add(re.Blank(this.model.theme_style_properties)),this.calculator=this.CreateCalculator(this.model,this.options)),n&&(this.DOM=O.GetInstance(n.ownerDocument)),this.grid=new gt(o,this.model,void 0,!!n,this.DOM),this.options.headless&&(this.grid.headless=!0),this.LoadLanguage(e.language),n){this.DOM=O.GetInstance(n.ownerDocument),this.parent_view||(j.is_windows?n.parentElement?.classList.add("treb-ua-windows"):j.is_mac&&n.parentElement?.classList.add("treb-ua-osx"),j.is_iphone&&n.parentElement?.classList.add("treb-ua-iphone"));let a=n.querySelector(".treb-view-template");this.view_node=a.content.firstElementChild?.cloneNode(!0),n.prepend(this.view_node),this.view_node.addEventListener("focusin",()=>{this.focus_target!==this&&(this.Publish({type:"focus-view"}),this.focus_target=this)}),this.key_listener=c=>this.HandleKeyDown(c),n.addEventListener("keydown",this.key_listener);let s=!!(r||this.options.document);this.grid.Initialize(this.view_node,s),this.options.dnd&&(this.view_node.addEventListener("dragenter",c=>this.HandleDrag(c)),this.view_node.addEventListener("dragover",c=>this.HandleDrag(c)),this.view_node.addEventListener("drop",c=>this.HandleDrop(c))),this.grid.grid_events.Subscribe(c=>{switch(c.type){case"error":this.dialog?.ShowDialog({type:"error",...this.TranslateGridError(c.code),timeout:3e3,close_box:!0});break;case"selection":this.UpdateSelection(c.selection),this.UpdateSelectionStyle(c.selection);break;case"sheet-change":this.OnSheetChange(c),this.UpdateSelectionStyle();break;case"scale":this.RebuildAllAnnotations(),this.Publish({type:"view-change"});break;case"cell-event":this.HandleCellEvent(c);break;case"composite":{let d=this.last_selection;this.calculation===0&&this.Recalculate(c),this.DocumentChange(d),this.UpdateDocumentStyles(),this.UpdateSelectionStyle()}break;case"data":{let d=this.last_selection;this.calculation===0&&this.Recalculate(c),this.DocumentChange(d)}break;case"style":this.DocumentChange(),this.UpdateDocumentStyles(),this.UpdateSelectionStyle();break;case"annotation":if(c.annotation){let d=c.annotation.view[this.grid.view_index]||{},u=!1;if(c.event==="select")u=!0;else switch(this.DocumentChange(),c.event){case"create":this.InflateAnnotation(c.annotation),this.calculator.UpdateAnnotations(c.annotation,this.grid.active_sheet),this.grid.AnnotationUpdated(c.annotation),u=c.annotation===this.grid.selected_annotation;break;case"delete":this.calculator.RemoveAnnotation(c.annotation);break;case"update":d.update_callback?(d.update_callback(),this.grid.AnnotationUpdated(c.annotation)):console.info("annotation update event without update callback"),this.calculator.UpdateAnnotations(c.annotation,this.grid.active_sheet),u=c.annotation===this.grid.selected_annotation;break;case"resize":d.resize_callback&&(d.resize_callback(),this.grid.AnnotationUpdated(c.annotation));break}if(u){this.UpdateSelectionStyleAnnotation(c.annotation),this.Publish({type:"annotation-selection"});break}}else console.info("annotation event without annotation");break;case"structure":{let d=this.last_selection;c.conditional_format&&(this.calculator.UpdateConditionals(),this.ApplyConditionalFormats(this.grid.active_sheet,!1)),c.rebuild_required?(this.calculator.Reset(),this.calculation===0&&this.Recalculate(c),this.DocumentChange(d)):this.DocumentChange(d)}this.UpdateSelectionStyle();break}}),this.options.prompt_save&&window.addEventListener("beforeunload",c=>{this.last_save_version!==this.file_version&&(c.preventDefault(),c.returnValue="")})}else l.one_time_warnings.headless||(l.one_time_warnings.headless=!0,console.info("not initializing layout; don't call UI functions"));if(e.preload&&e.preload.call(0,this),r?(typeof r=="string"&&(r=JSON.parse(r)),r?this.LoadDocument(r,{recalculate:!!this.options.recalculate,source:i}):this.UpdateDocumentStyles()):t||(this.calculator.RebuildClean(!0),this.UpdateDocumentStyles()),this.FlushUndo(),this.grid.ShowHeaders(this.options.headers),this.options.scroll&&!this.options.document){let a=this.options.scroll;requestAnimationFrame(()=>{this.ScrollTo(a)})}this.UpdateAC(),this.options.global_name&&(self[this.options.global_name]=this),n&&this.options.spinner&&(this.spinner=new _r(n)),t&&!e.model&&!r&&this.LoadNetworkDocument(t,this.options),n&&(this.dialog=new gr(n))}UpdateAC(){let e=this.calculator.SupportedFunctions();if(this.model.language_model?.functions){let t={};for(let r of this.model.language_model.functions||[])t[r.base.toUpperCase()]=r;e=e.map(r=>{let i=t[r.name.toUpperCase()];if(i){let n=JSON.parse(JSON.stringify({...r,name:i.name}));if(i.description&&(n.description=i.description),i.arguments&&n.arguments)for(let[o,a]of i.arguments.entries())n.arguments[o]&&(n.arguments[o].name=a);return n}return r})}this.grid.SetAutocompleteFunctions(e)}CreateCalculator(e,t){return new br(e,{complex_numbers:t.complex,spill:t.spill})}TranslateGridError(e){switch(e){case 0:return{message:"No error"};case 2:return{message:"You can't change part of an array"};case 5:return{message:"Invalid area for paste"};case 4:return{message:"Invalid area for table"};case 3:return{message:"Invalid value (data validation)"};default:return{message:`Unknown error (${e})`}}}CreateView(){let e=new l({...this.options,global_name:void 0,model:this});return e.parent_view=this,e}Unsplit(){let e=this.views.pop();if(e){let t=e.view;t.grid.grid_events.CancelAll(),t.events.CancelAll(),t.view_node?.parentElement&&(t.key_listener&&t.view_node.parentElement.removeEventListener("keydown",t.key_listener),t.view_node.parentElement.removeChild(t.view_node)),this.view_node?.focus(),this.Resize()}}ExternalEditor(e){this.grid.ExternalEditor(e)}Split(){let e=this.CreateView();e.grid.EnsureActiveSheet(!0),e.view_node?.addEventListener("focusin",()=>{this.focus_target!==e&&(this.Publish({type:"focus-view"}),this.focus_target=e)}),e.grid.grid_events.Subscribe(r=>{r.type==="structure"&&(this.grid.EnsureActiveSheet(),this.grid.UpdateLayout(),this.grid.UpdateTabBar(),r.update_annotations&&(this.grid.RefreshAnnotations(),this.InflateAnnotations()))}),e.Subscribe(r=>{switch(r.type){case"selection":break;default:e.UpdateAnnotations(),this.grid.Update(!0),this.grid.UpdateAnnotations()}}),this.grid.grid_events.Subscribe(r=>{r.type==="structure"&&(e.grid.EnsureActiveSheet(),e.grid.UpdateLayout(),e.grid.UpdateTabBar(),r.update_annotations&&(e.grid.RefreshAnnotations(),e.InflateAnnotations()))});let t=this.Subscribe(r=>{switch(r.type){case"selection":break;case"load":case"reset":e.grid.EnsureActiveSheet(!0),e.UpdateAnnotations(),e.grid.UpdateAnnotations(),e.grid.Update(!0);break;default:e.UpdateAnnotations(),e.grid.Update(!0),e.grid.UpdateAnnotations()}});this.views.push({view:e,subscription:t})}ListConditionalFormats(e){return(typeof e>"u"?this.grid.active_sheet:this.model.sheets.Find(e))?.conditional_formats||[]}ConditionalFormatDuplicateValues(e,t){return this.AddConditionalFormat({type:"duplicate-values",area:this.RangeOrSelection(e,"invalid range (no selection)"),...t})}ConditionalFormatGradient(e,t){let r=this.RangeOrSelection(e,"invalid range (no selection)"),i=typeof t=="object"?{type:"gradient",area:r,...t}:{type:"gradient",area:r,...en[t]};return this.AddConditionalFormat(i),i}ConditionalFormatDataBars(e,t){let i={type:"data-bar",area:this.RangeOrSelection(e,"invalid range (no selection)"),fill:{theme:4,tint:.5},...t};return this.AddConditionalFormat(i),i}ConditionalFormatCellMatch(e,t){let r={type:"cell-match",area:this.RangeOrSelection(e,"invalid range (no selection)"),...t};return this.AddConditionalFormat(r),r}ConditionalFormatExpression(e,t){let r={type:"expression",area:this.RangeOrSelection(e,"invalid range (no selection)"),...t};return this.AddConditionalFormat(r),r}AddConditionalFormat(e){return this.grid.AddConditionalFormat(e),e}RemoveConditionalFormat(e){this.grid.RemoveConditionalFormat({format:e})}RemoveConditionalFormats(e){let t=this.RangeOrSelection(e);t&&this.grid.RemoveConditionalFormat({area:t})}HandleToolbarMessage(e){if(this.focus_target!==this){this.focus_target.HandleToolbarMessage(e);return}let t={};if(this.grid.AnnotationSelected()){switch(e.command){case"adjust-font-scale":{let i=Number(e.delta||0),n=this.grid.GetAnnotationStyle()?.font_size;(!n||n.unit!=="em")&&(n={unit:"em",value:1}),n&&(n.value+=i,t.font_size=n,this.grid.ApplyAnnotationStyle(t))}break;case"font-scale":{let i=Number(e.scale||1);i&&!isNaN(i)&&(t.font_size={unit:"em",value:i},this.grid.ApplyAnnotationStyle(t))}break;case"font-stack":e.font_stack&&(t.font_face="stack:"+e.font_stack),this.grid.ApplyAnnotationStyle(t);break}this.Focus();return}let r=i=>{let n=this.grid.GetSelection();if(n&&!n.empty){let o=n.area.spreadsheet_label;i==="Scatter.Plot"||i==="Scatter.Line"||i==="Box.Plot"?this.InsertAnnotation(`=${i}(Series(,,${o}),"${o}")`,void 0,void 0,","):this.InsertAnnotation(`=${i}(${o},,"${o}")`,void 0,void 0,",")}};if(/^border-/.test(e.command))if(e.command==="border-color")try{t.border_top_fill=t.border_bottom_fill=t.border_left_fill=t.border_right_fill=e.color||{}}catch(i){console.error(i)}else{let i=1,n=e.command.substring(7);e.command==="border-double-bottom"&&(n="bottom",i=2),this.grid.ApplyBorders2(void 0,n,e.color||{},i)}else switch(e.command){case"about":this.About();break;case"number-format":t.number_format=e.format||"General";break;case"font-stack":e.font_stack&&(t.font_face="stack:"+e.font_stack);break;case"adjust-font-scale":{let i=this.selection_state.style?.font_size,n=this.grid.GetSelection(),o=this.grid.active_sheet.RealArea(n.area),a=Number(e.delta||0);if((!i||i.unit!=="em")&&(i={unit:"em",value:1}),i&&a&&!isNaN(a)){i.value+=a,this.grid.ApplyStyle(void 0,{font_size:i},!0);let s=[];for(let c=o.start.row;c<=o.end.row;c++)s.push(c);this.selection_state?.merge||this.grid.SetRowHeight(s,void 0,!1)}}break;case"font-scale":{let i=this.grid.GetSelection(),n=this.grid.active_sheet.RealArea(i.area),o=Number(e.scale||1);if(o&&!isNaN(o)){this.grid.ApplyStyle(void 0,{font_size:{unit:"em",value:o}},!0);let a=[];for(let s=n.start.row;s<=n.end.row;s++)a.push(s);this.selection_state?.merge||this.grid.SetRowHeight(a,void 0,!1)}}break;case"update-comment":this.SetNote(void 0,e.comment||"");break;case"clear-comment":this.SetNote(void 0,"");break;case"text-color":case"fill-color":try{let i=e.color||{};e.command==="text-color"?t.text=i:e.command==="fill-color"&&(t.fill=i)}catch(i){console.error(i)}break;case"insert-table":this.InsertTable();break;case"remove-table":this.RemoveTable();break;case"insert-row":this.InsertRows();break;case"insert-column":this.InsertColumns();break;case"delete-row":this.DeleteRows();break;case"delete-column":this.DeleteColumns();break;case"insert-sheet":this.grid.InsertSheet();break;case"delete-sheet":this.grid.DeleteSheet();break;case"freeze-panes":{let i=this.grid.GetFreeze();i.rows||i.columns?this.Freeze(0,0):this.FreezeSelection()}break;case"insert-image":this.InsertImage();break;case"insert-donut-chart":r("Donut.Chart");break;case"insert-column-chart":r("Column.Chart");break;case"insert-bar-chart":r("Bar.Chart");break;case"insert-line-chart":r("Line.Chart");break;case"insert-scatter-plot":r("Scatter.Plot");break;case"insert-box-plot":r("Box.Plot");break;case"increase-precision":case"decrease-precision":if(this.selection_state?.style){let i=L.Get(this.selection_state.style.number_format||"General");if(i.date_format)break;let n=new de(i.pattern);if(i.magic_decimal){let o=0,a=this.GetRange();Array.isArray(a)||(a=[[a]]);e:for(let s=0;s<a.length;s++)for(let c=0;c<a[s].length;c++){let d=a[s][c];if(typeof d<"u"&&he(d)){let u=L.Get(this.selection_state.style.number_format||"General",!0),h=u.BaseFormat(d.real),f=u.BaseFormat(d.imaginary);h.parts&&typeof h.parts[1]=="string"&&(o=h.parts[1].length),f.parts&&typeof f.parts[1]=="string"&&(o=Math.max(o,f.parts[1].length));break e}else if(typeof d=="number"){let u=i.BaseFormat(d);u.parts&&typeof u.parts[1]=="string"&&(o=u.parts[1].length);break e}}e.command==="increase-precision"?n.SetDecimal(o+1):n.SetDecimal(Math.max(0,o-1))}else e.command==="increase-precision"?n.IncreaseDecimal():n.DecreaseDecimal();t.number_format=n.toString()}break;case"merge-cells":this.grid.MergeCells();break;case"unmerge-cells":this.grid.UnmergeCells();break;case"lock-cells":t={locked:this.selection_state?.style?!this.selection_state.style.locked:!0};break;case"wrap-text":t={wrap:this.selection_state?.style?!this.selection_state?.style.wrap:!0};break;case"justify-left":t={horizontal_align:"left"};break;case"justify-center":t={horizontal_align:"center"};break;case"justify-right":t={horizontal_align:"right"};break;case"align-top":t={vertical_align:"top"};break;case"align-middle":t={vertical_align:"middle"};break;case"align-bottom":t={vertical_align:"bottom"};break;case"reset":this.Reset();break;case"import-file":this.LoadLocalFile();break;case"save-json":this.SaveToDesktop();break;case"save-csv":this.SaveToDesktop("csv");break;case"export-xlsx":this.Export();break;case"revert":this.Revert();break;case"recalculate":this.Recalculate();break;case"toggle-toolbar":case"show-toolbar":case"hide-toolbar":this.ShowToolbar(e.command==="toggle-toolbar"?void 0:e.command==="show-toolbar");break;case"toggle-sidebar":case"show-sidebar":case"hide-sidebar":this.ShowSidebar(e.command==="toggle-sidebar"?void 0:e.command==="show-sidebar");break;case"revert-indicator":this.dialog?.ShowDialog({title:`This is a modified version of the document.
9
+ `)+"<ul>";let i=this.completion_list.offsetHeight,n=!1;this.options.autocomplete_prefer_top?n=r.top>=200:this.DOM.doc?.documentElement&&Math.max(this.DOM.doc.documentElement.clientHeight,this.DOM.view?.innerHeight||0)-r.bottom<200&&(n=!0),n?this.completion_list.style.top=r.top-i-5+"px":this.completion_list.style.top=r.bottom+5+"px",this.completion_list.style.left=r.left+"px";let o=this.completion_list.querySelectorAll("a");this.active_element=o[this.selected_index],o[this.selected_index].classList.add("selected"),this.last_completion=o[this.selected_index].textContent||void 0,this.completion_list.scrollTop=this.active_element.offsetTop,this.completion_list_visible=!0}else this.completion_list.style.top="-1000px"}};var pt=(k=>(k[k.Null=0]="Null",k[k.InsertRows=1]="InsertRows",k[k.InsertColumns=2]="InsertColumns",k[k.ResizeRows=3]="ResizeRows",k[k.ResizeColumns=4]="ResizeColumns",k[k.Select=5]="Select",k[k.SetRange=6]="SetRange",k[k.UpdateStyle=7]="UpdateStyle",k[k.UpdateBorders=8]="UpdateBorders",k[k.Indent=9]="Indent",k[k.MergeCells=10]="MergeCells",k[k.UnmergeCells=11]="UnmergeCells",k[k.Clear=12]="Clear",k[k.UpdateTheme=13]="UpdateTheme",k[k.SetNote=14]="SetNote",k[k.SetLink=15]="SetLink",k[k.Freeze=16]="Freeze",k[k.SetName=17]="SetName",k[k.ShowHeaders=18]="ShowHeaders",k[k.AddSheet=19]="AddSheet",k[k.DuplicateSheet=20]="DuplicateSheet",k[k.DeleteSheet=21]="DeleteSheet",k[k.ActivateSheet=22]="ActivateSheet",k[k.RenameSheet=23]="RenameSheet",k[k.ReorderSheet=24]="ReorderSheet",k[k.ShowSheet=25]="ShowSheet",k[k.DataValidation=26]="DataValidation",k[k.Reset=27]="Reset",k[k.SortTable=28]="SortTable",k[k.InsertTable=29]="InsertTable",k[k.RemoveTable=30]="RemoveTable",k[k.AddConditionalFormat=31]="AddConditionalFormat",k[k.RemoveConditionalFormat=32]="RemoveConditionalFormat",k[k.TabColor=33]="TabColor",k[k.CreateAnnotation=34]="CreateAnnotation",k[k.RemoveAnnotation=35]="RemoveAnnotation",k))(pt||{});var $t=class{function_names=[];argument_separator=F.argument_separator.charCodeAt(0);function_map=new Map;RemoveFunctions(e){Array.isArray(e)||(e=[e]);for(let t of e)this.function_map.delete(t.name.toLowerCase());this.UpdateNameList()}AddFunctions(e){Array.isArray(e)||(e=[e]);for(let t of e)this.function_map.set(t.name.toLowerCase(),t);this.UpdateNameList()}SetFunctions(e){this.function_map.clear();for(let t of e)this.function_map.set(t.name.toLowerCase(),t);this.UpdateNameList()}NormalizeIdentifier(e){return this.function_map.get(e.toLowerCase())?.name}Get(e){return this.function_map.get(e.toLowerCase())}Exec(e){if(e.text[0]!=="=")return{};let t,r={};if(e.cursor===e.text.length&&(t=e.text.match(/(?:^|[^a-zA-Z\u00C0-\u024F_\d])([a-zA-Z\u00C0-\u024F_][\w\d\u00C0-\u024F_.]*)\s*$/),t)){let n=t[1],o=new RegExp("^"+n.replace(".","\\."),"i");r={completions:this.function_names.filter(s=>o.test(s)).map(s=>this.function_map.get(s.toLowerCase())).filter(s=>!!s),token:n,position:e.cursor-n.length}}let i=this.ParseTooltip(e.text.substr(0,e.cursor));if(i.function){let n=this.function_map.get(i.function.toLowerCase());n&&(r.tooltip='<span class="notranslate">'+n.name+"</span>",r.arguments="("+(n.arguments||[]).map((o,a)=>{let s=o.name||"argument";return a===i.argument?`<span class="active-argument">${s}</span>`:s}).join(F.argument_separator+" ")+")",r.description=n.description?`<span class="function-description">${n.description}</span>`:"",r.function_position=i.position||0)}return r}ParseTooltip(e){let t=[],r=0,i="",n=!1,o=0;for(let s of e){let c=s.charCodeAt(0);if(n)c===34&&(n=!1);else switch(c){case 40:t.push({buffer:i.trim(),argument:r,position:o-i.length}),i="",r=0;break;case this.argument_separator:r++;break;case 41:r=t.pop()?.argument||0;break;case 34:i="",n=!0;break;default:c>=97&&c<=122||c>=65&&c<=90||c>=48&&c<=57||c>=192&&c<=591||c===95||c===46?i+=s:i=""}o++}let a=t.pop();return{function:a?.buffer||void 0,position:a?.position||0,argument:r}}UpdateNameList(){this.function_names=[...this.function_map.keys()].sort((e,t)=>e.toLowerCase().localeCompare(t.toLowerCase()))}};var Xi={scrollbars:!0,in_cell_editor:!0,formula_bar:!0,add_tab:!1,tab_bar:"auto",expand_formula_button:!1,expand:!0,comment_markdown:!0,repaint_on_cell_change:!0,grid_over_background:!1};var ra=l=>{console.error("invalid case")},bt=class{grid_events=new _e;command_log=new _e;model;view;get active_sheet(){return this.view.active_sheet}set active_sheet(e){this.view.active_sheet=e}get view_index(){return this.view.view_index}batch=0;batch_paint=!1;batch_events=[];autocomplete_matcher=new $t;flags={};options;parser;constructor(e={},t){this.model=t,this.view={active_sheet:this.model.sheets.list[0],view_index:this.model.view_count++},this.parser=t.parser,this.options={...Xi,...e}}RemoveConditionalFormat(e){this.ExecCommand({key:32,...e})}AddConditionalFormat(e){this.ExecCommand({key:31,format:e})}RemoveTable(e){this.ExecCommand({key:30,table:e})}InsertTable(e,t=!0,r=void 0,i){e.start.sheet_id||(e.start.sheet_id=this.active_sheet.id);let n=this.FindSheet(e);for(let o=e.start.row;o<=e.end.row;o++)for(let a=e.start.column;a<=e.end.column;a++){let s=n.cells.GetCell({row:o,column:a},!1);if(s&&(s.area||s.merge_area||s.table)){this.Error(4);return}}this.ExecCommand({key:29,area:JSON.parse(JSON.stringify(e)),totals:t,sortable:r,theme:i})}ActivateSheet(e,t){let r=typeof e=="number"?e:void 0,i=typeof e=="string"?e:void 0;this.ExecCommand({key:22,index:r,name:i,user:t})}ActivateSheetID(e){this.ExecCommand({key:22,id:e})}DuplicateSheet(e,t,r){let i={key:20,new_name:t,insert_before:r};typeof e>"u"?i.id=this.active_sheet.id:i.index=e,this.ExecCommand(i)}AddSheet(e){this.ExecCommand({key:19,name:e,show:!0})}DeleteSheet(e){if(typeof e>"u"&&!this.model.sheets.list.some((t,r)=>t===this.active_sheet?(e=r,!0):!1))throw new Error("invalid index");this.ExecCommand({key:21,index:e})}InsertSheet(e,t){if(typeof e>"u"&&!this.model.sheets.list.some((r,i)=>r===this.active_sheet?(e=i+1,!0):!1))throw new Error("invalid index");this.ExecCommand({key:19,insert_index:e,name:t,show:!0})}DeleteSheetID(e){this.ExecCommand({key:21,id:e})}Reset(){this.ExecCommand({key:27})}SetLink(e,t){this.ExecCommand({key:15,area:e,reference:t})}ShowAll(){let e=[];for(let t=0;t<this.model.sheets.length;t++)e.push({key:25,index:t,show:!0});this.ExecCommand(e)}ShowSheet(e=0,t=!0){let r={key:25,show:t};typeof e=="string"?r.name=e:r.index=e,this.ExecCommand(r)}SortTable(e,t={}){this.ExecCommand({key:28,table:JSON.parse(JSON.stringify(e)),...Yi,...t})}GetFreeze(){return{...this.active_sheet.freeze}}InsertRows(e=0,t=1){this.ExecCommand({key:1,before_row:e,count:t})}GetTableReference(e){return this.model.sheets.Find(e.sheet_id||this.active_sheet.id)?.CellData(e).table||void 0}FromCSV(e){this.parser.Save(),this.parser.SetLocaleSettings(".");let r=Di(e).map(n=>n.map(o=>{if(o){let a=this.parser.Parse(o);if(a.expression?.type==="complex")return a.expression}return ye.TryParse(o).value}));this.parser.Restore();let i={row:Math.max(0,r.length-1),column:r.reduce((n,o)=>Math.max(n,Math.max(0,o.length-1)),0)};this.ExecCommand([{key:27},{key:6,area:{start:{row:0,column:0},end:i},value:r}])}InsertColumns(e=0,t=1){this.ExecCommand({key:2,before_column:e,count:t})}ReorderSheet(e,t){this.ExecCommand({key:24,index:e,move_before:t})}RenameSheet(e,t){this.ExecCommand({key:23,new_name:t,id:e.id})}Freeze(e=0,t=0,r=!0){this.ExecCommand({key:16,rows:e,columns:t,highlight_transition:r})}SetRowHeight(e,t,r=!0){this.ExecCommand({key:3,row:e,height:t,shrink:r})}SetColumnWidth(e,t){this.ExecCommand({key:4,column:e,width:t})}FilterTable(e,t,r){let i=[];if(!e.area.start.sheet_id)throw new Error("invalid table area");let n=this.model.sheets.Find(e.area.start.sheet_id);if(!n)throw new Error("invalid table sheet");let o=[],a=[],s=e.totals_row?e.area.end.row-1:e.area.end.row;t+=e.area.start.column;for(let c=e.area.start.row+1;c<=s;c++){let d=n.CellData({row:c,column:t}),u=r(d),h=n.GetRowHeight(c);u&&!h?o.push(c):!u&&h&&a.push(c)}o&&i.push({key:3,sheet_id:n.id,row:o,height:n.default_row_height}),a&&i.push({key:3,sheet_id:n.id,row:a,height:0}),i.length&&this.ExecCommand(i)}UpdateSheets(e,t=!1,r){re.Reset();let i=e.map(n=>re.FromJSON(n,this.model.theme_style_properties));if(i.length===0&&i.push(re.Blank(this.model.theme_style_properties)),this.model.sheets.Assign(i),this.ResetMetadata(),this.active_sheet=i[0],r){let n=this.model.sheets.Find(r);n&&(this.active_sheet=n)}}SetAutocompleteFunctions(e){let t=[];for(let i of this.model.named.list)t.push({name:i.name,named:!0,type:"token"});let r=e.slice(0).concat(t);this.autocomplete_matcher.SetFunctions(r)}ResetMetadata(){this.model.document_name=void 0,this.model.user_data=void 0}ResizeColumnsInternal(e){let t=e.sheet_id?this.FindSheet(e.sheet_id):this.active_sheet,r=e.column;if(typeof r>"u"){r=[];for(let i=0;i<t.columns;i++)r.push(i)}if(typeof r=="number"&&(r=[r]),e.width)for(let i of r)t.SetColumnWidth(i,e.width);else console.error("auto size not supported")}RemoveAnnotationInternal(e){for(let t=0;t<e.sheet.annotations.length;t++)if(e.annotation===e.sheet.annotations[t]){e.sheet.annotations.splice(t,1),this.grid_events.Publish({type:"annotation",annotation:e.annotation,event:"delete"});return}}CreateAnnotationInternal(e){}ResizeRowsInternal(e){let t=e.sheet_id?this.FindSheet(e.sheet_id):this.active_sheet,r=e.row;if(typeof r>"u"){r=[];for(let i=0;i<t.rows;i++)r.push(i)}if(typeof r=="number"&&(r=[r]),e.height)for(let i of r)t.SetRowHeight(i,e.height);else console.error("auto size not supported")}ResetInternal(){re.Reset(),this.UpdateSheets([],!0),this.model.named.Reset(),this.model.macro_functions.clear(),this.model.tables.clear()}ValidatePasteAreas(e){for(let t of e){let r=this.active_sheet;if(t.start.sheet_id&&t.start.sheet_id!==r.id&&(r=this.model.sheets.Find(t.start.sheet_id)),!r)return!1;for(let i of r.cells.Iterate(t)){if(i.style?.locked)return console.info("invalid: locked cells"),!1;if(i.merge_area&&(!t.Contains(i.merge_area.start)||!t.Contains(i.merge_area.end)))return console.info("invalid: merge area"),!1;if(i.area&&(!t.Contains(i.area.start)||!t.Contains(i.area.end)))return console.info("invalid: array"),!1}}return!0}SetValidationInternal(e){let t=this.FindSheet(e.area);if(!t)throw new Error("invalid sheet in set validation");let r={start:e.area.start,end:e.area.end};e.range?t.AddValidation({type:"range",error:!!e.error,area:e.range,target:[r]}):e.list?t.AddValidation({type:"list",error:!!e.error,list:JSON.parse(JSON.stringify(e.list)),target:[r]}):t.RemoveValidations(r)}GetValidationRange(e){let t,r=this.FindSheet(e);if(r){t=[],e=r.RealArea(new v(e.start,e.end),!0);for(let i=e.start.row;i<=e.end.row;i++)for(let n=e.start.column;n<=e.end.column;n++){let o=r.CellData({row:i,column:n});o&&o.formatted&&(typeof o.formatted=="string"?t.push(o.formatted):t.push(ue.FormatPartsAsText(o.formatted)))}}return t}DeleteSheetInternal(e){let t=!1,r=-1,i="",n=!1,o=e.name?e.name.toLowerCase():"",a=this.model.sheets.list.filter((s,c)=>c===e.index||s.id===e.id||s.name.toLowerCase()===o?(t=s===this.active_sheet,this.model.named.RemoveRangesForSheet(s.id),i=s.name,r=c,!1):!0);if(i&&this.RenameSheetReferences(a,i,"#REF")>0&&(n=!0),!a.length)a.push(re.Blank(this.model.theme_style_properties)),r=0;else if(a.every(s=>!s.visible))a.unshift(re.Blank(this.model.theme_style_properties)),r=0;else for(r>=a.length&&(r=0);!a[r].visible;)r++;return this.model.sheets.Assign(a),t&&this.ActivateSheetInternal({key:22,index:r}),n}RenameSheetInternal(e,t){if(!t||Vi.test(t))throw new Error("invalid sheet name");let r=t.toLowerCase();for(let n of this.model.sheets.list)if(n!==e&&n.name.toLowerCase()===r)throw new Error("sheet name already exists");let i=e.name;e.name=t,this.model.sheets.Assign(this.model.sheets.list),this.RenameSheetReferences(this.model.sheets.list,i,t)}SortTableInternal(e){if(!e.table.area.start.sheet_id)throw new Error("table has invalid area");let t=this.model.sheets.Find(e.table.area.start.sheet_id);if(!t)throw new Error("invalid sheet in table area");let r=[],i=[],n=e.table.area.end.row;e.table.totals_row&&n--;let o=0,a=0;for(let h=e.table.area.start.row+1;h<=n;h++){if(t.GetRowHeight(h))i.push(h);else continue;let f={row:h,number:0,text:"",type:0,data:[]};for(let p=e.table.area.start.column;p<=e.table.area.end.column;p++){let b=t.CellData({row:h,column:p});if(p===e.column+e.table.area.start.column){let g=b.calculated_type||b.type;g===2?o++:g===3&&a++;let x=b.calculated_type?b.calculated:b.value;f.text=x?.toString()||"",f.number=Number(x)||0,f.type=b.calculated_type||b.type}f.data.push({address:{row:h,column:p},data:b.value,type:b.type,style:b.style})}r.push(f)}let s=e.type;s==="auto"&&(a>o?s="numeric":s="text");let c=e.asc?1:-1;switch(s){case"numeric":r.sort((h,m)=>h.type===0?m.type===0?0:1:m.type===0?-1:(h.number-m.number)*c);break;case"text":default:r.sort((h,m)=>h.type===0?m.type===0?0:1:m.type===0?-1:h.text.localeCompare(m.text)*c);break}let d={row:e.table.area.start.row+1,column:e.table.area.start.column};for(let h=0;h<i.length;h++){d.row=i[h];let m=r[h];d.column=e.table.area.start.column;for(let f of m.data){if(f.type===1){let p=f.data,b={columns:0,rows:d.row-m.row},g=this.parser.Parse(p);g.expression&&(p="="+this.parser.Render(g.expression,{offset:b,missing:""})),t.SetCellValue(d,p)}else t.SetCellValue(d,f.data);t.UpdateCellStyle(d,f.style||{},!1),d.column++}}let u=this.model.tables.get(e.table.name.toLowerCase());u&&(u.sort={type:e.type,asc:!!e.asc,column:e.column});{let h=e.table.area.start.row;for(let m=e.table.area.start.column;m<=e.table.area.end.column;m++)t.cells.data[h][m]?.FlushStyle();if(e.table.totals_row){h=e.table.area.end.row;for(let m=e.table.area.start.column;m<=e.table.area.end.column;m++)t.cells.data[h][m]?.FlushStyle()}}return new v(e.table.area.start,e.table.area.end)}UpdateTableColumns(e){if(!e.area.start.sheet_id)throw new Error("invalid area in table");let t=this.model.sheets.Find(e.area.start.sheet_id);if(!t)throw new Error("invalid sheet in table");let r=e.columns?.slice(0)||void 0,i=[],n=e.area.start.row,o=e.area.end.column-e.area.start.column+1,a=e.area.start.column;for(let s=0;s<o;s++,a++){let c=t.CellData({row:n,column:a}),d="";c.type!==2?(typeof c.formatted<"u"?d=c.formatted.toString():typeof c.calculated<"u"?d=c.calculated.toString():typeof c.value<"u"&&(d=c.value.toString()),c.Set(d,2)):d=c.value||"",d||(d=`Column${s+1}`);let u=d,h=!1,m=1;for(;!h;){h=!0;e:for(let f of i)if(f.toLowerCase()===u.toLowerCase()){h=!1,u=`${d}${++m}`;break e}}c.Set(u,2),i.push(u.toLowerCase())}if(r&&r.length===i.length){let s=new Map;for(let c=0;c<r.length;c++){let d=r[c].toLowerCase();d!==i[c]&&s.set(d,i[c])}if(s.size){let c=e.name.toLowerCase();for(let d of this.model.sheets.list)for(let u of d.cells.Iterate())if(u.ValueIsFormula()){let h=!1,m=this.parser.Parse(u.value);m.expression&&(this.parser.Walk(m.expression,f=>{if(f.type==="structured-reference"&&(f.table.toLowerCase()===c||!f.table&&u.table===e))for(let[p,b]of s.entries())f.column.toLowerCase()===p&&(f.column=b,h=!0);return!0}),h&&(console.info("updating value"),u.value="="+this.parser.Render(m.expression,{missing:""})))}}}return e.columns=i,{start:{...e.area.start},end:{row:e.area.start.row,column:e.area.end.column}}}SetRangeInternal(e,t={}){let r=N(e.area)?new v(e.area):new v(e.area.start,e.area.end),i=this.FindSheet(r);if(r.start.sheet_id||(r.start.sheet_id=i.id),!r.entire_row&&!r.entire_column&&(r.end.row>=i.rows||r.end.column>=i.columns)&&(i.cells.EnsureCell(r.end),i===this.active_sheet&&(t.layout=!0)),N(e.area)){let n=i.CellData(e.area);if(n.area&&(n.area.rows>1||n.area.columns>1)){this.Error(2);return}let o=Array.isArray(e.value)?Array.isArray(e.value[0])?e.value[0][0]:e.value[0]:e.value;return e.r1c1&&(o=this.TranslateR1C1(e.area,o)),e.array?i.SetArrayValue(r,o):i.SetCellValue(e.area,o),r}else{if(e.array){let n=Array.isArray(e.value)?Array.isArray(e.value[0])?e.value[0][0]:e.value[0]:e.value;e.r1c1&&(n=this.TranslateR1C1(r.start,n)),i.SetArrayValue(r,n)}else{if(e.r1c1){if(Array.isArray(e.value))for(let n=0;n<e.value.length&&n<r.rows;n++){e.value[n]||(e.value[n]=[]);let o=e.value[n];for(let a=0;a<o.length&&a<r.columns;a++){let s={...r.start,row:r.start.row+n,column:r.start.column+a};o[a]=this.TranslateR1C1(s,o[a])}}else if(typeof e.value=="string"&&e.value[0]==="="){let n=[];for(let o=0;o<r.rows;o++){let a=[];for(let s=0;s<r.columns;s++){let c={...r.start,row:r.start.row+o,column:r.start.column+s};a.push(this.TranslateR1C1(c,e.value))}n.push(a)}e.value=n}}i.SetAreaValues2(r,e.value)}return r}}ActivateSheetInternal(e){let t=this.ResolveSheet(e)||this.model.sheets.list[0];if(this.active_sheet===t&&!e.force)return;if(!t.visible)throw new Error("cannot activate hidden sheet");let r=this.active_sheet;this.active_sheet=t,this.grid_events.Publish({type:"sheet-change",deactivate:r,activate:this.active_sheet})}ShowSheetInternal(e){let t=this.ResolveSheet(e);if(t&&t.visible!==e.show){if(!e.show){let r=0;for(let i of this.model.sheets.list)(!t.visible||i===t)&&r++;if(r>=this.model.sheets.length)throw new Error("can't hide all sheets")}if(t.visible=e.show,t===this.active_sheet){let r=this.model.sheets.list;for(let i=0;i<r.length;i++)if(r[i]===this.active_sheet){for(let n=i+1;n<r.length;n++)if(r[n].visible){this.ActivateSheetInternal({key:22,index:n});return}for(let n=0;n<r.length;n++)if(r[n].visible){this.ActivateSheetInternal({key:22,index:n});return}throw new Error("no visible sheet")}}}}NormalizeCommands(e){Array.isArray(e)||(e=[e]);let t=this.active_sheet.id;for(let r of e)switch(r.key){case 0:case 33:case 18:case 25:case 19:case 20:case 21:case 22:case 23:case 24:case 27:case 34:case 35:break;case 28:case 30:r.table.area.start.sheet_id||(r.table.area.start.sheet_id=t);break;case 31:r.format.area.start.sheet_id||(r.format.area.start.sheet_id=t);break;case 3:case 4:case 2:case 1:case 16:r.sheet_id||(r.sheet_id=t);break;case 12:case 14:case 15:case 9:case 8:case 10:case 11:case 26:case 6:case 7:case 17:case 5:case 29:case 32:r.area&&(N(r.area)?r.area.sheet_id||(r.area.sheet_id=t):r.area.start.sheet_id||(r.area.start.sheet_id=t));break;default:ra(r)}return e}TabColor(e,t){this.ExecCommand({key:33,sheet:e,color:t})}AddSheetInternal(e=re.default_sheet_name,t=-1){if(!this.options.add_tab){console.warn("add tab option not set or false");return}for(;this.model.sheets.list.some(i=>i.name===e);){let i=e.match(/^(.*?)(\d+)$/);i?e=i[1]+(Number(i[2])+1):e=e+"2"}let r=re.Blank(this.model.theme_style_properties,e);return t>=0?this.model.sheets.Splice(t,0,r):this.model.sheets.Add(r),r.id}ResolveSheet(e){if(typeof e.index<"u")return this.model.sheets.list[e.index];if(typeof e.name<"u")return this.model.sheets.Find(e.name);if(e.id)return this.model.sheets.Find(e.id)}FindSheet(e){if(e===void 0)return this.active_sheet;let t=typeof e=="number"?e:N(e)?e.sheet_id:e.start.sheet_id;if(!t||t===this.active_sheet.id)return this.active_sheet;let r=this.model.sheets.Find(t);return r||this.active_sheet}PatchFormulasInternal(e,t,r,i,n,o,a){let s=this.parser.Parse(e||""),c=!1;if(s.expression&&(this.parser.Walk(s.expression,d=>{if(d.type==="range"||d.type==="address"){let u=[];d.type==="range"?(d.start.sheet&&d.start.sheet.toLowerCase()===o||!d.start.sheet&&a)&&u.push(d.start,d.end):d.type==="address"&&(d.sheet&&d.sheet.toLowerCase()===o||!d.sheet&&a)&&u.push(d);for(let h of u)r&&h.row>=t&&(r<0&&h.row+r<t?h.column=h.row=-1:h.row+=r,c=!0),n&&h.column>=i&&(n<0&&h.column+n<i?h.column=h.row=-1:h.column+=n,c=!0);return!1}return!0}),c))return"="+this.parser.Render(s.expression,{missing:""})}PatchExpressionSheetName(e,t,r){let i=!1,n=this.parser.Parse(e||"");if(n.expression&&(this.parser.Walk(n.expression,o=>(o.type==="address"&&o.sheet&&o.sheet.toLowerCase()===t&&(o.sheet=r,i=!0),!0)),i))return"="+this.parser.Render(n.expression,{missing:""})}RenameSheetReferences(e,t,r){let i=0;t=t.toLowerCase();for(let n of e){for(let o of n.cells.Iterate())if(o.ValueIsFormula()){let a=this.PatchExpressionSheetName(o.value||"",t,r);a&&(o.value=a,i++)}if(n.conditional_formats?.length)for(let o of n.conditional_formats)switch(o.type){case"cell-match":case"expression":{let a=this.PatchExpressionSheetName(o.expression,t,r);a&&(o.expression=a,i++)}break}for(let o of n.annotations)if(o.data.formula){let a=this.PatchExpressionSheetName(o.data.formula,t,r);a&&(o.data.formula=a,i++)}}for(let n of this.model.connected_elements.values())if(n.formula){let o=this.PatchExpressionSheetName(n.formula,t,r);o&&(n.formula=o,i++)}return i}ApplyBordersInternal(e){let t=e.borders,r=e.borders==="none"?0:e.width,i=new v(e.area.start,e.area.end),n=this.FindSheet(i);i.start.sheet_id=n.id;let o={border_top:r},a={border_bottom:r},s={border_left:r},c={border_right:r},d={border_top:0,border_top_fill:{}},u={border_bottom:0,border_bottom_fill:{}},h={border_left:0,border_left_fill:{}},m={border_right:0,border_right_fill:{}};return e.color?(o.border_top_fill={...e.color},a.border_bottom_fill={...e.color},s.border_left_fill={...e.color},c.border_right_fill={...e.color}):(o.border_top_fill={},a.border_bottom_fill={},s.border_left_fill={},c.border_right_fill={}),(t==="none"||t==="all")&&n.UpdateAreaStyle(i,{...o,...a,...s,...c},!0),(t==="top"||t==="outside")&&(i.entire_column||n.UpdateAreaStyle(i.top,{...o},!0)),(t==="none"||t==="all"||t==="outside"||t==="top")&&(i.entire_column||i.start.row&&n.UpdateAreaStyle(new v({row:i.start.row-1,column:i.start.column},{row:i.start.row-1,column:i.end.column}),{...u},!0)),(t==="bottom"||t==="outside")&&(i.entire_column||n.UpdateAreaStyle(i.bottom,{...a},!0)),(t==="none"||t==="all"||t==="outside"||t==="bottom")&&(i.entire_column||n.UpdateAreaStyle(new v({row:i.end.row+1,column:i.start.column},{row:i.end.row+1,column:i.end.column}),{...d},!0)),(t==="left"||t==="outside")&&(i.entire_row||n.UpdateAreaStyle(i.left,{...s},!0)),(t==="none"||t==="all"||t==="outside"||t==="left")&&(i.entire_row||i.start.column&&n.UpdateAreaStyle(new v({row:i.start.row,column:i.start.column-1},{row:i.end.row,column:i.start.column-1}),{...m},!0)),(t==="right"||t==="outside")&&(i.entire_row||n.UpdateAreaStyle(i.right,{...c},!0)),(t==="none"||t==="all"||t==="outside"||t==="right")&&(i.entire_row||n.UpdateAreaStyle(new v({row:i.start.row,column:i.end.column+1},{row:i.end.row,column:i.end.column+1}),{...h},!0)),v.Bleed(i)}TranslateR1C1(e,t){let r=!1,i=this.parser.flags.r1c1;if(this.parser.flags.r1c1=!0,typeof t=="string"&&t[0]==="="){let n=this.parser.Parse(t);n.expression&&(this.parser.Walk(n.expression,o=>(o.type==="address"&&o.r1c1&&(r=!0,o.offset_column?(o.absolute_column=!1,o.column=o.column+e.column):o.absolute_column=!0,o.offset_row?(o.absolute_row=!1,o.row=o.row+e.row):o.absolute_row=!0),!0)),r&&(t="="+this.parser.Render(n.expression,{missing:""})))}return this.parser.flags.r1c1=i,t}ClearAreaInternal(e){let t;if(e.start.sheet_id?t=this.model.sheets.Find(e.start.sheet_id):t=this.active_sheet,!t){console.warn("can't resolve sheet in ClearAreaInternal");return}e=t.RealArea(e);for(let i of t.cells.Iterate(e))if(i.area&&!e.ContainsArea(i.area)){this.Error(2);return}let r=this.model.tables.keys();for(let i of r){let n=this.model.tables.get(i);if(n&&n.area.start.sheet_id===t.id){let o=new v(n.area.start,n.area.end);if(e.ContainsArea(o)){for(let a=o.start.row;a<=o.end.row;a++)for(let s=o.start.column;s<=n.area.end.column;s++){let c=t.cells.GetCell({row:a,column:s},!1);c&&(c.table=void 0)}this.model.tables.delete(i)}}}t.ClearArea(e)}Error(e){this.grid_events.Publish({type:"error",code:e})}DuplicateSheetInternal(e){if(!this.options.add_tab){console.warn("add tab option not set or false");return}let t=this.ResolveSheet(e),r=this.model.sheets.list.reduce((s,c)=>Math.max(s,c.id),0)+1,i=-1;for(let s=0;s<this.model.sheets.length;s++)this.model.sheets.list[s]===t&&(i=s+1);if(!t||i<0)throw new Error("source sheet not found");if(typeof e.insert_before=="number")i=e.insert_before;else if(typeof e.insert_before=="string"){let s=e.insert_before.toLowerCase();for(let c=0;c<this.model.sheets.length;c++)if(this.model.sheets.list[c].name.toLowerCase()===s){i=c;break}}let n={rendered_values:!0},o=re.FromJSON(t.toJSON(n),this.model.theme_style_properties),a=e.new_name||t.name;for(;this.model.sheets.list.some(s=>s.name===a);){let s=a.match(/^(.*?)(\d+)$/);s?a=s[1]+(Number(s[2])+1):a=a+"2"}return o.name=a,o.id=r,this.model.sheets.Splice(i,0,o),o.id}SelectInternal(e){}FreezeInternal(e){let t=this.FindSheet(e.sheet_id||this.active_sheet.id);t.freeze.rows=e.rows,t.freeze.columns=e.columns}PatchExpression(e,t){let r=0,i=this.parser.Parse(e);if(i.expression&&(this.parser.Walk(i.expression,n=>{if(n.type==="range"){if(!n.start.sheet||n.start.sheet.toLowerCase()===t.sheet.name.toLowerCase()){let o=v.PatchArea(n,t);o?(n.start.row=o.start.row,n.start.column=o.start.column,n.end.row=o.end.row,n.end.column=o.end.column):n.start.row=n.end.row=n.start.column=n.end.column=-1}return r++,!1}else if(n.type==="address"){let o=v.PatchArea({start:n,end:n},t);return o?(n.row=o.start.row,n.column=o.start.column):n.row=n.column=-1,r++,!1}return!0}),r))return this.parser.Render(i.expression,{missing:""})}PatchConditionalsAndValidations(e){if(e.sheet.data_validation.length){let t=new Set;for(let r of e.sheet.data_validation){let i=[];for(let n of r.target){let o=v.PatchArea(n,e);o&&i.push(o)}if(i.length>0){if(r.target=i,r.type==="range"&&r.area.start.sheet_id===e.sheet.id){let n=v.PatchArea(r.area,e);n?r.area=n:t.add(r)}}else t.add(r)}t.size&&(e.sheet.data_validation=e.sheet.data_validation.filter(r=>!t.has(r)))}if(e.sheet.conditional_formats?.length){let t=new Set;for(let r of e.sheet.conditional_formats){let i=v.PatchArea(r.area,e);if(i)r.area=JSON.parse(JSON.stringify(i));else{t.add(r);continue}switch(r.type){case"expression":case"cell-match":{let n=this.PatchExpression(r.expression,e);n&&(r.expression=n)}break}}t.size&&(e.sheet.conditional_formats=e.sheet.conditional_formats.filter(r=>!t.has(r)))}}InsertRowsInternal(e){let t=this.FindSheet(e.sheet_id);if(e.count===1/0?e.count=1:e.count===-1/0&&(e.count=-t.rows),!t.InsertRows(e.before_row,e.count))return this.Error(2),{error:!0};this.PatchConditionalsAndValidations({sheet:t,before_column:0,column_count:0,before_row:e.before_row,row_count:e.count});for(let s of this.model.connected_elements.values())if(s.formula){let c=this.PatchFormulasInternal(s.formula,e.before_row,e.count,0,0,t.name.toLowerCase(),!1);c&&(s.formula=c)}let r=Array.from(this.model.tables.values());for(let s of r)if(s.area.start.sheet_id===e.sheet_id)if(e.count>0){if(e.before_row<=s.area.start.row)s.area.start.row+=e.count,s.area.end.row+=e.count;else if(e.before_row<=s.area.end.row){s.area.end.row+=e.count;for(let c=s.area.start.row;c<=s.area.end.row;c++)for(let d=s.area.start.column;d<=s.area.end.column;d++){let u=t.CellData({row:c,column:d});u.table=s}}}else if(e.before_row<=s.area.start.row)if(e.before_row-e.count<=s.area.start.row)s.area.start.row+=e.count,s.area.end.row+=e.count;else if(e.before_row-e.count>=s.area.end.row)this.model.tables.delete(s.name.toLowerCase());else{this.model.tables.delete(s.name.toLowerCase());for(let c=e.before_row;c<=s.area.end.row;c++)for(let d=s.area.start.column;d<=s.area.end.column;d++){let u=t.CellData({row:c,column:d});u.table===s&&(u.table=void 0)}}else e.before_row<=s.area.end.row&&(e.before_row-e.count>s.area.end.row&&(s.totals_row=!1),s.area.end.row=Math.max(0,s.area.end.row+e.count,e.before_row-1));this.model.named.PatchNamedRanges(t.id,0,0,e.before_row,e.count);let i=t.name.toLowerCase();for(let s of this.model.sheets.list){let c=s===t;for(let d of s.cells.Iterate())if(d.ValueIsFormula()){let u=this.PatchFormulasInternal(d.value||"",e.before_row,e.count,0,0,i,c);u&&(d.value=u)}for(let d of s.annotations)if(d.data.formula){let u=this.PatchFormulasInternal(d.data.formula||"",e.before_row,e.count,0,0,i,c);u&&(d.data.formula=u)}}let n=[],o=[],a=[];if(e.count>0){let s=e.before_row;for(let c of t.annotations)if(c.data.layout){let[d,u,h]=[c.data.layout.tl.address.row,c.data.layout.br.address.row,c.data.layout.br.offset.y];if(s<=d)c.data.layout.tl.address.row+=e.count,c.data.layout.br.address.row+=e.count;else if(s<u||s===u&&h>0)c.data.layout.br.address.row+=e.count,o.push(c);else continue;n.push(c)}}else if(e.count<0){let s=e.before_row,c=e.before_row-e.count-1;for(let d of t.annotations)if(d.data.layout){let[u,h,m]=[d.data.layout.tl.address.row,d.data.layout.br.address.row,d.data.layout.br.offset.y];if(s<=u)if(c<u)d.data.layout.tl.address.row+=e.count,d.data.layout.br.address.row+=e.count;else if(c<h-1||c===h-1&&m>0)d.data.layout.tl.address.row=s,d.data.layout.tl.offset.y=0,d.data.layout.br.address.row+=e.count,o.push(d);else{a.push(d);continue}else if(s<h||s===h&&m>0)c<h-1||c===h-1&&m>0?(d.data.layout.br.address.row+=e.count,o.push(d)):(d.data.layout.br.address.row=s,d.data.layout.br.offset.y=0,o.push(d));else continue;n.push(d)}}for(let s of a)t.annotations=t.annotations.filter(c=>c!==s);return{update_annotations_list:n,resize_annotations_list:o,delete_annotations_list:a}}InsertColumnsInternal(e){let t=this.FindSheet(e.sheet_id);if(e.count===1/0?e.count=1:e.count===-1/0&&(e.count=-t.columns),!t.InsertColumns(e.before_column,e.count))return this.Error(2),{error:!0};this.PatchConditionalsAndValidations({sheet:t,before_column:e.before_column,column_count:e.count,before_row:0,row_count:0});for(let s of this.model.connected_elements.values())if(s.formula){let c=this.PatchFormulasInternal(s.formula,0,0,e.before_column,e.count,t.name.toLowerCase(),!1);c&&(s.formula=c)}let r=Array.from(this.model.tables.values());for(let s of r)if(s.area.start.sheet_id===e.sheet_id)if(e.count>0){if(e.before_column<=s.area.start.column)s.area.start.column+=e.count,s.area.end.column+=e.count;else if(e.before_column<=s.area.end.column){s.area.end.column+=e.count;for(let c=s.area.start.row;c<=s.area.end.row;c++)for(let d=s.area.start.column;d<=s.area.end.column;d++){let u=t.CellData({row:c,column:d});u.table=s}this.UpdateTableColumns(s)}}else e.before_column<=s.area.start.column?e.before_column-e.count<=s.area.start.column?(s.area.start.column+=e.count,s.area.end.column+=e.count):e.before_column-e.count>=s.area.end.column?this.model.tables.delete(s.name.toLowerCase()):(s.area.start.column=e.before_column,s.area.end.column+=e.count,this.UpdateTableColumns(s)):e.before_column<=s.area.end.column&&(s.area.end.column=Math.max(0,s.area.end.column+e.count,e.before_column-1),this.UpdateTableColumns(s));this.model.named.PatchNamedRanges(t.id,e.before_column,e.count,0,0);let i=t.name.toLowerCase();for(let s of this.model.sheets.list){let c=s===t;for(let d of s.cells.Iterate())if(d.ValueIsFormula()){let u=this.PatchFormulasInternal(d.value||"",0,0,e.before_column,e.count,i,c);u&&(d.value=u)}for(let d of s.annotations)if(d.data.formula){let u=this.PatchFormulasInternal(d.data.formula,0,0,e.before_column,e.count,i,c);u&&(d.data.formula=u)}}let n=[],o=[],a=[];if(e.count>0){let s=e.before_column;for(let c of t.annotations)if(c.data.layout){let[d,u,h]=[c.data.layout.tl.address.column,c.data.layout.br.address.column,c.data.layout.br.offset.x];if(s<=d)c.data.layout.tl.address.column+=e.count,c.data.layout.br.address.column+=e.count;else if(s<u||s===u&&h>0)c.data.layout.br.address.column+=e.count,o.push(c);else continue;n.push(c)}}else if(e.count<0){let s=e.before_column,c=e.before_column-e.count-1;for(let d of t.annotations)if(d.data.layout){let[u,h,m]=[d.data.layout.tl.address.column,d.data.layout.br.address.column,d.data.layout.br.offset.x];if(s<=u)if(c<u)d.data.layout.tl.address.column+=e.count,d.data.layout.br.address.column+=e.count;else if(c<h-1||c===h-1&&m>0)d.data.layout.tl.address.column=s,d.data.layout.tl.offset.x=0,d.data.layout.br.address.column+=e.count,o.push(d);else{a.push(d);continue}else if(s<h||s===h&&m>0)c<h-1||c===h-1&&m>0?(d.data.layout.br.address.column+=e.count,o.push(d)):(d.data.layout.br.address.column=s,d.data.layout.br.offset.x=0,o.push(d));else continue;n.push(d)}}for(let s of a)t.annotations=t.annotations.filter(c=>c!==s);return{update_annotations_list:n,resize_annotations_list:o,delete_annotations_list:a}}ExecCommand(e,t=!0){let r={pending:[]},i=[];e=this.NormalizeCommands(e),t&&this.command_log.Publish({command:e,timestamp:new Date().getTime()});for(let a of e)switch(a.key){case 27:this.ResetInternal();break;case 12:if(a.area){let s=new v(a.area.start,a.area.end);this.ClearAreaInternal(s),r.data_area=v.Join(s,r.data_area),r.formula=!0}break;case 5:this.SelectInternal(a);break;case 16:this.FreezeInternal(a),r.structure_event=!0;break;case 31:{let s=this.FindSheet(a.format.area);s.conditional_formats.push(a.format),s.Invalidate(new v(a.format.area.start,a.format.area.end)),s===this.active_sheet&&(r.render_area=v.Join(a.format.area,r.render_area)),r.structure_event=!0,r.conditional_formatting_event=!0}break;case 32:{let s,c=0;if(a.format){let d=JSON.stringify(a.format);s=this.FindSheet(a.format.area),s.conditional_formats=s.conditional_formats.filter(u=>JSON.stringify(u)===d?(c++,r.render_area=v.Join(u.area,r.render_area),!1):!0)}else if(a.area){let d=new v(a.area.start,a.area.end);s=this.FindSheet(a.area),s.conditional_formats=s.conditional_formats.filter(u=>{let h=new v(u.area.start,u.area.end);return h.Intersects(d)?(c++,r.render_area=v.Join(h,r.render_area),!1):!0})}s&&c&&(s.FlushConditionalFormats(),r.structure_event=!0,r.conditional_formatting_event=!0)}break;case 29:{let s=this.FindSheet(a.area),c=new v(a.area.start,a.area.end),d=!0;e:for(let u=c.start.row;u<=c.end.row;u++)for(let h=c.start.column;h<=c.end.column;h++){let m=s.cells.GetCell({row:u,column:h},!1);if(m&&(m.area||m.merge_area||m.table)){d=!1;break e}}if(d){let u=this.model.tables.size+1,h="";for(;h=`Table${u++}`,!!this.model.tables.has(h.toLowerCase()););let m={area:a.area,name:h,sortable:a.sortable,theme:a.theme};a.totals&&(m.totals_row=!0),this.model.tables.set(h.toLowerCase(),m);for(let f=c.start.row;f<=c.end.row;f++)for(let p=c.start.column;p<=c.end.column;p++){let b=s.cells.GetCell({row:f,column:p},!0);b.table=m}this.UpdateTableColumns(m),s.Invalidate(new v(m.area.start,m.area.end)),s===this.active_sheet?(r.style_area=v.Join(c,r.style_area),r.render_area=v.Join(c,r.render_area)):r.style_event=!0}}break;case 30:{let s=this.FindSheet(a.table.area),c=new v(a.table.area.start,a.table.area.end);for(let u=c.start.row;u<=c.end.row;u++)for(let h=c.start.column;h<=c.end.column;h++){let m=s.cells.GetCell({row:u,column:h},!1);m&&(m.table=void 0)}this.model.tables.delete(a.table.name.toLowerCase());let d=s.RealArea(c.Clone().Shift(-1,-1).Resize(c.rows+2,c.columns+2));s.Invalidate(d),s===this.active_sheet?(r.style_area=v.Join(c,r.style_area),r.render_area=v.Join(c,r.render_area)):r.style_event=!0}break;case 10:{let s=this.FindSheet(a.area);s.MergeCells(new v(a.area.start,a.area.end)),r.structure_event=!0,r.structure_rebuild_required=!0,s===this.active_sheet?(r.data_area=v.Join(a.area,r.data_area),r.render_area=v.Join(a.area,r.render_area)):(r.data_event=!0,r.pending||(r.pending=[]),r.pending.push(s.id))}break;case 11:{let s=this.FindSheet(a.area),c={},d=new v(a.area.start,a.area.end);for(let h of s.cells.Iterate(d,!1))if(h.merge_area){let m=v.CellAddressToLabel(h.merge_area.start)+":"+v.CellAddressToLabel(h.merge_area.end);c[m]=h.merge_area}let u=Object.keys(c);for(let h=0;h<u.length;h++)s.UnmergeCells(c[u[h]]);s===this.active_sheet?(r.render_area=v.Join(a.area,r.render_area),r.data_area=v.Join(a.area,r.data_area)):(r.data_event=!0,r.pending||(r.pending=[]),r.pending.push(s.id)),r.structure_event=!0,r.structure_rebuild_required=!0}break;case 9:{let s,c=this.FindSheet(a.area);if(N(a.area)){s=new v(a.area);let d=c.GetCellStyle(a.area,!0);c.UpdateCellStyle(a.area,{indent:Math.max(0,(d.indent||0)+a.delta)},!0)}else{s=new v(a.area.start,a.area.end);for(let d of s){let u=c.GetCellStyle(d,!0);c.UpdateCellStyle(d,{indent:Math.max(0,(u.indent||0)+a.delta)},!0)}}c===this.active_sheet?(r.style_area=v.Join(s,r.style_area),r.render_area=v.Join(s,r.render_area)):r.style_event=!0}break;case 7:{let s,c=this.FindSheet(a.area);N(a.area)?(s=new v(a.area),c.UpdateCellStyle(a.area,a.style,!!a.delta)):(s=new v(a.area.start,a.area.end),c.UpdateAreaStyle(s,a.style,!!a.delta)),c===this.active_sheet?(r.style_area=v.Join(s,r.style_area),(!a.delta||a.style.fill||a.style.border_top||a.style.border_left||a.style.border_right||a.style.border_bottom)&&(s=v.Bleed(s),this.active_sheet.Invalidate(s)),r.render_area=v.Join(s,r.render_area)):r.style_event=!0}break;case 26:this.SetValidationInternal(a),(!a.area.start.sheet_id||a.area.start.sheet_id===this.active_sheet.id)&&(r.render_area=v.Join(new v(a.area.start,a.area.end),r.render_area));break;case 17:{let s={type:"token",named:!0,name:a.name,scope:a.scope};a.area||a.expression?(a.area?this.model.named.SetNamedRange(a.name,new v(a.area.start,a.area.end),a.scope):a.expression&&this.model.named.SetNamedExpression(a.name,a.expression,a.scope),this.autocomplete_matcher.AddFunctions(s)):(this.model.named.ClearName(a.name,a.scope),this.autocomplete_matcher.RemoveFunctions(s)),r.structure_event=!0,r.structure_rebuild_required=!0}break;case 8:{let s=this.ApplyBordersInternal(a);s.start.sheet_id===this.active_sheet.id?(r.render_area=v.Join(s,r.render_area),r.style_area=v.Join(s,r.style_area)):r.style_event=!0}break;case 25:this.ShowSheetInternal(a),r.sheets=!0,r.structure_event=!0;break;case 33:a.sheet.tab_color=a.color,r.sheets=!0,r.structure_event=!0;break;case 24:{let s=[],c=this.model.sheets.list[a.index];for(let d=0;d<this.model.sheets.length;d++)d!==a.index&&(d===a.move_before&&s.push(c),s.push(this.model.sheets.list[d]));a.move_before>=this.model.sheets.length&&s.push(c),this.model.sheets.Assign(s),r.sheets=!0,r.structure_event=!0}break;case 23:{let s=this.ResolveSheet(a);s&&(this.RenameSheetInternal(s,a.new_name),r.sheets=!0,r.structure_event=!0)}break;case 35:this.RemoveAnnotationInternal(a),r.structure_event=!0,r.structure_rebuild_required=!0,r.annotation_event=!0;break;case 34:this.CreateAnnotationInternal(a),r.structure_event=!0,r.structure_rebuild_required=!0,r.annotation_event=!0;break;case 3:{let s=this.ResizeRowsInternal(a);if(s)if(s.start.sheet_id===this.active_sheet.id){let c=this.active_sheet.RealArea(new v(s.start,s.end));r.render_area=v.Join(c,r.render_area),r.data_area=v.Join(c,r.data_area),r.data_event=!0}else r.data_event=!0,r.pending||(r.pending=[]),s.start.sheet_id&&r.pending.push(s.start.sheet_id);r.structure_event=!0}break;case 4:this.ResizeColumnsInternal(a),r.structure_event=!0;break;case 18:this.active_sheet.SetHeaderSize(a.show?void 0:1,a.show?void 0:1),this.flags.layout=!0,this.flags.repaint=!0;break;case 1:this.InsertRowsInternal(a),r.structure_event=!0,r.structure_rebuild_required=!0;break;case 2:this.InsertColumnsInternal(a),r.structure_event=!0,r.structure_rebuild_required=!0;break;case 15:case 14:{let s=this.FindSheet(a.area),c=s.cells.GetCell(a.area,!0);if(c){let d;c.merge_area?(d=new v(c.merge_area.start),c=s.cells.GetCell(c.merge_area.start,!0)):d=new v(a.area),a.key===14?c.SetNote(a.note):(c.hyperlink=a.reference||void 0,c.render_clean=[]),s===this.active_sheet?(r.style_area=v.Join(d,r.style_area),r.render_area=v.Join(d,r.render_area)):r.style_event=!0}}break;case 28:{let s=this.SortTableInternal(a);s&&s.start.sheet_id===this.active_sheet.id?(r.data_area=v.Join(s,r.data_area),this.options.repaint_on_cell_change&&(r.render_area=v.Join(s,r.render_area))):r.data_event=!0}break;case 6:{let s=this.SetRangeInternal(a,r);if(s){let d=this.model.sheets.Find(s.start.sheet_id||this.active_sheet.id)?.TablesFromArea(s,!0)||[];for(let u of d)this.UpdateTableColumns(u)}s&&s.start.sheet_id===this.active_sheet.id?(r.data_area=v.Join(s,r.data_area),this.options.repaint_on_cell_change&&(r.render_area=v.Join(s,r.render_area))):r.data_event=!0}break;case 21:this.DeleteSheetInternal(a),r.sheets=!0,r.structure_event=!0,r.structure_rebuild_required=!0;break;case 20:this.DuplicateSheetInternal(a),r.sheets=!0,r.structure_event=!0,r.structure_rebuild_required=!0;break;case 19:{let s=this.AddSheetInternal(a.name,a.insert_index);typeof s=="number"&&a.show&&this.ActivateSheetInternal({key:22,id:s}),r.structure_event=!0,r.sheets=!0,r.structure=!0}break;case 22:this.ActivateSheetInternal(a);break;default:console.warn(`unhandled command: ${pt[a.key]} (${a.key})`)}let n,o;return r.data_area?(r.data_area.start.sheet_id||r.data_area.SetSheetID(this.active_sheet.id),n={type:"data",area:r.data_area}):r.data_event&&(n={type:"data"}),r.style_area?(r.style_area.start.sheet_id||r.style_area.SetSheetID(this.active_sheet.id),o={type:"style",area:r.style_area}):r.style_event&&(o={type:"style"}),n&&o?i.push({type:"composite",data_area:n.area,style_area:o.area}):(n&&i.push(n),o&&i.push(o)),r.structure_event&&i.push({type:"structure",rebuild_required:r.structure_rebuild_required,conditional_format:r.conditional_formatting_event,update_annotations:r.annotation_event}),this.batch>0?this.batch_events.push(...i):this.grid_events.Publish(i),r}};var jt=class extends Fe{get active(){return this.nodes.length>0}Reset(){this.AttachNodes()}AttachNodes(e=[],t=!0){this.assume_formula=t;let r=[];r=e.map(i=>{for(let n of this.nodes)if(n.node===i)return n;return{node:i}});for(let i of this.nodes)if(i.listeners){for(let[n,o]of i.listeners.entries())i.node.removeEventListener(n,o);i.listeners.clear()}this.nodes=r;for(let i of this.nodes){if(i.formatted_text===i.node.textContent){let n=i.node.innerHTML.length;i.check!==n&&(i.formatted_text=void 0)}i.node.ownerDocument.activeElement===i.node&&(this.active_editor=i),this.UpdateText(i,{toll_events:!0}),this.RegisterListener(i,"focusin",()=>{this.active_editor=i}),this.RegisterListener(i,"focusout",()=>{this.active_editor=void 0}),this.RegisterListener(i,"input",n=>{n.isTrusted&&(this.UpdateText(i),this.UpdateColors())})}this.UpdateColors(!0)}};var gt=class extends bt{hide_selection=!1;headless=!1;edit_state={};get scale(){return this.layout.scale}set scale(e){this.layout.scale=e,this.UpdateLayout(),this.UpdateAnnotationLayout(),this.layout.UpdateAnnotation(this.active_sheet.annotations,this.theme),this.layout.ApplyTheme(this.theme),this.overlay_editor?.UpdateScale(e),this.tab_bar?.UpdateScale(e),this.grid_events.Publish({type:"scale",scale:e});for(let t of this.model.sheets.list)for(let r of t.annotations)r.dirty=!0}theme;selected_annotation;hover_data={};editing_state=0;editing_cell={row:-1,column:-1,sheet_id:0};editing_selection;editing_annotation;pending_reset_selection=!1;view_node;container;layout;tile_update_pending=!1;scroll_offset_pending;pending_layout_update=new Set;decimal_separator_code=46;overlay_editor;autocomplete;formula_bar;RESIZE_PIXEL_BUFFER=5;external_editor_config;external_editor;cell_resize={row:-1,column:-1};render_tiles=new v({row:0,column:0});primary_selection={target:{row:0,column:0},area:new v({row:0,column:0}),empty:!0};spill_selection={target:{row:0,column:0},area:new v({row:0,column:0}),empty:!0};active_selection={target:{row:0,column:0},area:new v({row:0,column:0}),empty:!0};nub_select_flag=!1;additional_selections=[];double_click_data={};layout_token=0;render_token=0;tile_renderer;selection_renderer;tab_bar;DOM=O.GetInstance();constructor(e={},t,r=qt,i=!0,n){if(super(e,t),this.decimal_separator_code=F.decimal_separator.charCodeAt(0),this.theme=JSON.parse(JSON.stringify(r)),!i){this.headless=!0,this.layout=new Pt(this.model,this.view);return}this.DOM=n,this.layout=new Ot(this.model,this.view,n),e.initial_scale&&(typeof e.initial_scale=="string"&&(e.initial_scale=Number(e.initial_scale)),this.layout.scale=e.initial_scale),this.tile_renderer=new Gt(this.theme,this.layout,this.model,this.view,this.options),this.selection_renderer=new It(this.theme,this.layout,this.model,this.view,this.primary_selection,this.additional_selections)}CopyArea(e,t="copy"){let r=(e.start.sheet_id?this.model.sheets.Find(e.start.sheet_id):this.active_sheet)||this.active_sheet,i=r.GetCellStyle(e,!1),n=t!=="cut",o=[];for(let{cell:a,row:s,column:c}of r.cells.IterateRC(e)){let d=a.value;n&&d&&a.type===1&&(d=this.FormatR1C1(d,{row:s,column:c})[0][0]);let u=s-e.start.row,h=c-e.start.column;o[u]||(o[u]=[]);let m;a.area&&(m={start:{row:a.area.start.row-e.start.row,column:a.area.start.column-e.start.column},end:{row:a.area.end.row-e.start.row,column:a.area.end.column-e.start.column}}),o[u][h]={value:d,calculated:a.calculated,style:i[u][h],area:m}}return t==="cut"&&this.SetRange(e,void 0,{recycle:!0}),o}PasteArea(e,t,r={}){if(!t)throw new Error("no clipboad data");let i=t.length,n=t[0]?.length||0;e.Resize(Math.max(1,Math.floor(e.rows/i))*i,Math.max(1,Math.floor(e.columns/n))*n);let o=(e.start.sheet_id?this.model.sheets.Find(e.start.sheet_id):this.active_sheet)||this.active_sheet,a=[];if(r.values)for(let[d,u]of t.entries()){a[d]=[];for(let h of u)a[d].push(typeof h.calculated>"u"?h.value:h.calculated)}let s=t,c=this.Batch(()=>{if(r.values)this.SetRange(e,a,{r1c1:!0,recycle:!0});else{this.SetRange(e,void 0,{recycle:!0});for(let d of e){let u=(d.row-e.start.row)%i,h=(d.column-e.start.column)%n,m=s[u][h];if(m.area){if(m.area.start.row===u&&m.area.start.column===h){let f=new v(m.area.start,m.area.end);f.Shift(e.start.row,e.start.column),this.SetRange(f,m.value,{r1c1:!0,array:!0})}}else m.value&&this.SetRange(new v(d),m.value,{r1c1:!0})}}if(r.formatting==="number-formats")for(let d of e){let u=(d.row-e.start.row)%i,h=(d.column-e.start.column)%n,m=(s[u][h].style||{}).number_format;o.UpdateCellStyle(d,{number_format:m},!0)}else if(r.formatting!=="target")for(let d of e){let u=(d.row-e.start.row)%i,h=(d.column-e.start.column)%n;o.UpdateCellStyle(d,s[u][h].style||{},!1)}},!0);this.grid_events.Publish(c)}Reselect(){this.primary_selection.empty||this.Select(this.primary_selection,this.primary_selection.area,this.primary_selection.target)}SetNote(e,t){if(!e){if(this.primary_selection.empty)return;e=this.primary_selection.target}this.ExecCommand({key:14,area:e,note:t})}FindAnnotation(e){for(let t of this.active_sheet.annotations)if((t.view[this.view_index]||{}).node===e)return t}CreateAnnotation(e={},t=this.active_sheet,r=!0,i=!1,n,o){this.ExecCommand({key:34,properties:e,add_to_sheet:r,offset:i,target:n,focus:o,sheet:t})}CreateAnnotationInternal(e){let t=new Ne(e.properties);if(e.offset)if(!t.data.layout&&t.scaled_rect&&(t.data.layout=this.layout.RectToAnnotationLayout(t.scaled_rect)),!t.data.layout)console.warn("can't offset annotation without layout");else{let r=this.layout.AnnotationLayoutToRect(t.data.layout).Shift(20,20),i=!0;for(;i;){i=!1;for(let n of e.sheet.annotations)if(n!==t&&n.scaled_rect&&n.scaled_rect.top===r.top&&n.scaled_rect.left===r.left){r=r.Shift(20,20),i=!0;break}}t.data.layout=this.layout.RectToAnnotationLayout(r)}if(e.target&&(B.IsRectangle(e.target)?(t.data.layout=void 0,t.rect=B.Create(e.target)):e.target.start&&(t.rect=void 0,t.data.layout=this.layout.AddressToAnnotationLayout(e.target.start,e.target.end||e.target.start))),e.add_to_sheet&&(e.sheet.annotations.some(r=>r===t)||e.sheet.annotations.push(t),this.AddAnnotation(t)),e.focus){let r=t.view[this.view_index];if(r&&r.node){let i=r.node;setTimeout(()=>{i.focus()},1)}}}UpdateAnnotationLayout(){}AddAnnotation(e,t=!1,r=!0){let i=e.view[this.view_index];if(i||(i={},e.view[this.view_index]=i),!i.node){let n=this.DOM.Div("annotation",void 0,{data:{scale:this.layout.scale.toString()},style:{fontSize:`${10*this.layout.scale}pt`},attrs:{tabindex:"-1"},events:{mousedown:s=>{s.button===0&&this.layout.AnnotationMouseDown(e,n,s,o,a).then(c=>{c?this.grid_events.Publish(c):this.selected_annotation!==e&&this.grid_events.Publish({type:"annotation",annotation:e,event:"select"}),e.data.layout&&this.EnsureAddress(e.data.layout.br.address,1)})},focusin:()=>{for(let s of this.layout.GetFrozenAnnotations(e))s.classList.add("clone-focus");this.selected_annotation=e,this.primary_selection.empty=!0,this.primary_selection.target={row:-1,column:-1,sheet_id:this.active_sheet.id},this.HideGridSelection()},focusout:s=>{for(let c of this.layout.GetFrozenAnnotations(e))c.classList.remove("clone-focus");this.formula_bar&&this.formula_bar.IsElement(s.relatedTarget)?(this.primary_selection.empty=!0,this.RenderSelections(),this.editing_annotation=e,this.layout.ShowSelections(!0)):this.formula_bar?.IsExpandButton(s.relatedTarget)||this.layout.FocusInLayout(s.relatedTarget||void 0)&&(this.selected_annotation===e&&(this.selected_annotation=void 0),this.ShowGridSelection())}}});i.node=n,i.content_node=this.DOM.Div("annotation-content",n);let o=this.DOM.Div("annotation-move-target",n),a=this.DOM.Div("annotation-resize-target",n);n.addEventListener("keydown",s=>{let c=e.scaled_rect;if(!c){console.info("missing scaled rect!");return}let d=[n,...this.layout.GetFrozenAnnotations(e)];if(s.ctrlKey||j.is_mac&&s.metaKey){let h=e.data.style?{...e.data.style}:{},m=!0;switch(s.key){case"b":this.ApplyAnnotationStyle({bold:!h.bold});break;case"i":this.ApplyAnnotationStyle({italic:!h.italic});break;case"u":this.ApplyAnnotationStyle({underline:!h.underline});break;default:m=!1}if(m){s.stopPropagation(),s.preventDefault();return}}let u={x:c.left,y:c.top};switch(s.key){case"ArrowUp":case"Up":s.ctrlKey?(this.layout.AnnotationLayoutOrder(e,1)&&this.grid_events.Publish({type:"annotation",event:"move",annotation:e}),n.focus()):u.y--;break;case"ArrowLeft":case"Left":if(s.ctrlKey)return;u.x--;break;case"ArrowRight":case"Right":if(s.ctrlKey)return;u.x++;break;case"ArrowDown":case"Down":s.ctrlKey?(this.layout.AnnotationLayoutOrder(e,-1)&&this.grid_events.Publish({type:"annotation",event:"move",annotation:e}),n.focus()):u.y++;break;case"Escape":case"Esc":this.Focus();break;case"Backspace":s.metaKey&&j.is_mac&&(this.Focus(),this.RemoveAnnotation(e));break;case"Delete":case"Del":this.Focus(),this.RemoveAnnotation(e);break;default:return}if(s.stopPropagation(),s.preventDefault(),u.x=Math.max(u.x,0),u.y=Math.max(u.y,0),c.left!==u.x||c.top!==u.y){c.left=Math.round(u.x),c.top=Math.round(u.y);for(let h of d)h.style.top=c.top+"px",h.style.left=c.left+"px";e.data.extent=void 0,this.grid_events.Publish({type:"annotation",event:"move",annotation:e}),e.data.layout=this.layout.RectToAnnotationLayout(c)}})}r&&(this.layout.AddAnnotation(e,this.theme),e.data.layout&&this.EnsureAddress(e.data.layout.br.address,1,t)),t||this.grid_events.Publish({type:"annotation",annotation:e,event:"create"})}AnnotationUpdated(e){this.layout.CloneFrozenAnnotation(e)}RemoveAnnotation(e,t=this.active_sheet){this.ExecCommand({key:35,annotation:e,sheet:t})}RemoveAnnotationInternal(e){super.RemoveAnnotationInternal(e),this.layout.RemoveAnnotation(e.annotation)}RemoveAnnotationNodes(){this.headless||this.layout.RemoveAnnotationNodes()}ShowHeaders(e=!0){this.ExecCommand({key:18,show:e})}FromImportData(e,t=!1){this.RemoveAnnotationNodes();let r=e.sheets,i=r.map(()=>re.Blank(this.model.theme_style_properties).toJSON()),n;if(typeof e.active_tab=="number")n=i[e.active_tab]?.id;else for(let a=0;a<e.sheets.length;a++)if(!e.sheets[a].hidden){n=i[a].id;break}this.UpdateSheets(i,!0,n);let o={};this.model.macro_functions.clear(),this.ClearSelection(this.primary_selection),this.model.tables.clear();for(let a=0;a<r.length;a++){let s=this.model.sheets.list[a];s.ImportData(r[a]),o[s.name]=s.id;for(let c of r[a].cells)c.table&&(c.table.area.start.sheet_id=s.id,this.model.tables.set(c.table.name.toLowerCase(),c.table));for(let c of this.model.tables.values())this.UpdateTableColumns(c)}this.model.sheets.UpdateIndexes(),this.model.named.Reset(),e.named&&this.model.UnserializeNames(e.named,this.active_sheet,!0);for(let a of this.active_sheet.annotations)this.AddAnnotation(a,!0);this.ActivateSheetTasks(),this.QueueLayoutUpdate(),this.StyleDefaultFromTheme(),t&&this.Repaint(!1,!1),this.tab_bar&&this.tab_bar.Update(!1)}NextSheet(e=1,t=!1){if(this.model.sheets.length===1)return;let r=this.model.sheets.list.map((i,n)=>({sheet:i,index:n})).filter(i=>i.sheet.visible);if(r.length!==1){for(let i=0;i<r.length;i++)if(r[i].sheet===this.active_sheet){let n=(i+e)%r.length;for(;n<0;)n+=r.length;this.ActivateSheet(r[n].index,t);return}}}UpdateSheets(e,t=!1,r){if(super.UpdateSheets(e,t,r),this.RemoveAnnotationNodes(),this.ClearSelection(this.primary_selection),e[0]&&e[0].primary_selection){let i=e[0].primary_selection;i.empty||this.Select(this.primary_selection,new v(i.area.start,i.area.end),i.target)}else if(!this.active_sheet.selection.empty){let i=this.active_sheet.selection;this.Select(this.primary_selection,new v(i.area.start,i.area.end),i.target)}this.layout.ClearLayoutCaches();for(let i of this.model.sheets.list)for(let n of i.annotations)this.AddAnnotation(n,!0,i===this.active_sheet);this.ActivateSheetTasks(),this.QueueLayoutUpdate(JSON.parse(JSON.stringify(this.active_sheet.scroll_offset))),this.StyleDefaultFromTheme(),t&&this.Repaint(!1,!1),this.tab_bar&&this.tab_bar.Update(!1)}UpdateLayout(){this.layout.UpdateTiles(),this.layout.UpdateContentsSize(),this.render_tiles=this.layout.VisibleTiles(),this.Repaint(!0)}UpdateTabBar(){this.tab_bar&&this.tab_bar.Update(!0)}UpdateTheme(e=!1,t){if(!e)for(let i of Object.keys(this.theme))delete this.theme[i];let r=JSON.parse(JSON.stringify(qt));this.view_node&&(r={...Qi(this.view_node,this.options.support_font_stacks)}),r={...this.theme,...r,...t},Object.assign(this.theme,r),this.StyleDefaultFromTheme(),this.active_sheet.UpdateDefaultRowHeight(this.theme),this.active_sheet.FlushCellStyles(),this.layout.ApplyTheme(this.theme),this.tab_bar&&this.tab_bar.UpdateTheme(),e||(this.UpdateLayout(),this.overlay_editor?.UpdateScale(this.layout.scale),this.Repaint(!0,!0,!0))}SetScale(e){e=Math.round(e*1e3)/1e3,e=Math.min(2,Math.max(e,.5)),this.options.persist_scale_key&&localStorage.setItem(this.options.persist_scale_key,JSON.stringify({scale:e})),this.scale=e}Initialize(e,t=!1){if(!this.tile_renderer||!this.selection_renderer)return;this.view_node=e,this.UpdateTheme(!0);let i=e.querySelector(".treb-spreadsheet-body").querySelector("div");this.options.formula_bar&&(this.autocomplete||(this.autocomplete=new ft({theme:this.theme,container:i})),this.InitFormulaBar(e,this.autocomplete)),this.options.tab_bar&&(this.tab_bar=new Nt(this.layout,this.model,this.view,this.options,this.theme,e),this.tab_bar.Subscribe(n=>{switch(n.type){case"cancel":break;case"scale":{let o=this.layout.scale;if(o=Math.round(n.value*1e3)/1e3,o=Math.min(2,Math.max(o,.5)),this.options.persist_scale_key&&localStorage.setItem(this.options.persist_scale_key,JSON.stringify({scale:o})),this.scale=o,n.keep_focus)return}break;case"reorder-sheet":this.ReorderSheet(n.index,n.move_before);break;case"delete-sheet":this.DeleteSheet();break;case"add-sheet":this.AddSheet();break;case"rename-sheet":this.RenameSheet(n.sheet,n.name);break;case"activate-sheet":this.ActivateSheetID(n.sheet.id);break}this.SelectingArgument()||this.Focus()})),this.container=i,this.container.classList.add("treb-grid"),j.is_mac&&j.is_safari&&this.container.classList.add("safari"),this.container.setAttribute("tabindex","-1"),this.layout.Initialize(i,{scroll:()=>this.OnScroll(),dropdown:n=>this.OnDropdownSelect(n),sort:(n,o,a)=>{let s=this.model.tables.get(n.toLowerCase());s&&this.SortTable(s,{column:o,asc:a})},focus:()=>this.Focus()},this.options.scrollbars),this.selection_renderer.Initialize(),this.layout.UpdateTiles(),this.autocomplete||(this.autocomplete=new ft({theme:this.theme,container:i})),this.InitOverlayEditor(this.autocomplete),this.AttachListeners(),this.render_tiles=this.layout.VisibleTiles(),t||(this.tab_bar?.Update(!1),this.Repaint(!0))}MergeCells(e){!e&&this.primary_selection.empty||(this.layout.HideDropdownCaret(),this.ExecCommand({key:10,area:e||this.primary_selection.area}))}UnmergeCells(e){!e&&this.primary_selection.empty||(this.layout.HideDropdownCaret(),this.ExecCommand({key:11,area:e||this.primary_selection.area}))}GetAnnotationStyle(){if(this.selected_annotation)return this.selected_annotation.data?.style?JSON.parse(JSON.stringify(this.selected_annotation.data.style)):{}}ApplyAnnotationStyle(e={},t=!0){if(this.selected_annotation){let r=this.selected_annotation;r.data.style=JSON.parse(JSON.stringify(t?I.Composite([r.data.style||{},e]):e));let i=r.view[this.view_index]?.node;this.layout.UpdateAnnotation(r,this.theme),i&&i.focus(),this.grid_events.Publish({type:"annotation",event:"update",annotation:r}),this.DelayedRender()}}AnnotationSelected(){return!!this.selected_annotation}Focus(e="",t=!1){if(this.selected_annotation)if(t)this.editing_annotation===this.selected_annotation?this.pending_reset_selection=!0:(this.selected_annotation=void 0,this.ShowGridSelection());else{this.selected_annotation.view[this.view_index].node?.focus();return}j.is_mobile?this.container?.focus():this.overlay_editor?.Focus(e)}SetValidation(e,t,r){if(!e){if(this.primary_selection.empty)throw new Error("invalid target in set validation");e=this.primary_selection.area}let i=new v(e.start,e.end),n={key:26,area:{start:i.start,end:i.end},error:r};t&&(Array.isArray(t)?n.list=t:typeof t=="object"&&t.start&&t.end&&N(t.start)&&N(t.end)&&(n.range=t)),this.ExecCommand(n),!this.primary_selection.empty&&(!e.start.sheet_id||e.start.sheet_id===this.active_sheet.id)&&i.Contains(this.primary_selection.target)&&requestAnimationFrame(()=>this.Select(this.primary_selection,this.primary_selection.area,this.primary_selection.target))}SetName(e,t,r,i,n=!1){let o=this.model.named.ValidateNamed(e);if(!o)throw new Error("invalid name");if(e=o,this.autocomplete_matcher){let s=this.autocomplete_matcher.Get(e);if(s&&(!s.named||!n)&&(t||r))throw new Error("name already defined")}let a={key:17,name:e,scope:i};if(t)N(t)&&(t=new v(t)),t.start.sheet_id||(t=new v({...t.start,sheet_id:this.active_sheet.id},t.end)),a.area=new v(t.start,t.end);else if(r){let s=this.parser.Parse(r);if(s.valid&&s.expression)this.parser.Walk(s.expression,c=>{if(c.type==="address"||c.type==="range"){if(c.type==="range"&&(c=c.start),!c.sheet_id&&c.sheet){let d=this.model.sheets.Find(c.sheet);d&&(c.sheet_id=d.id)}return c.sheet_id||(c.sheet_id=this.active_sheet.id),!1}return!0}),a.expression=s.expression;else throw console.info({expression:r,parse_result:s}),new Error("invalid expression")}this.ExecCommand(a)}SelectAll(){this.Select(this.primary_selection,new v({row:1/0,column:1/0}),void 0,!0),this.RenderSelections()}ExternalEditor(e){if(this.external_editor_config=e,e){let t=(e.dependencies||[]).filter(r=>!!r).map(r=>N(r)?new v(r):new v(r.start,r.end));if(e.nodes?.length){if(!this.external_editor){let r=new jt(this.model,this.view);this.external_editor=r,r.Subscribe(()=>this.HighlightDependencies(r.dependencies))}this.external_editor.AttachNodes(e.nodes,e.assume_formula??!0)}else this.external_editor&&this.external_editor.Reset();e.dependencies&&this.HighlightDependencies(t)}else this.external_editor&&this.external_editor.Reset(),this.ClearAdditionalSelections(),this.RenderSelections(!0)}SelectRange(e){this.Select(this.primary_selection,e),this.RenderSelections()}GetRangeStyle(e,t=!1){let r=0;if(N(e)?r=e.sheet_id||this.active_sheet.id:r=e.start.sheet_id||this.active_sheet.id,r)return this.model.sheets.Find(r)?.GetCellStyle(e,t)||void 0}FormatR1C1(e,t){ut(t)&&(t=t.start),Array.isArray(e)||(e=[[e]]);let r={type:"address",label:"",row:t.row,column:t.column,sheet:t.sheet_id?this.model.sheets.Name(t.sheet_id):this.active_sheet.name,position:0,id:0};for(let i=0;i<e.length;i++){let n=e[i];for(let o=0;o<n.length;o++){let a=n[o];if(typeof a=="string"&&a[0]==="="){let s=this.parser.Parse(a);s.expression&&(n[o]="="+this.parser.Render(s.expression,{missing:"",r1c1:!0,r1c1_base:{...r,row:t.row+i,column:t.column+o}}))}}}return e}GetRange(e,t){if(N(e)){let i=this.model.sheets.Find(e.sheet_id||this.active_sheet.id);if(i){if(t==="A1"||t==="R1C1"){let n=i.cells.RawValue(e);return t==="R1C1"?this.FormatR1C1(n,e):n}return t==="formatted"?i.GetFormattedRange(e):i.cells.GetRange(e)}return}let r=this.model.sheets.Find(e.start.sheet_id||this.active_sheet.id);if(r){if(t==="A1"||t==="R1C1"){let i=r.cells.RawValue(e.start,e.end);return t==="R1C1"?this.FormatR1C1(i,e):i}return t==="formatted"?r.GetFormattedRange(e.start,e.end):r.cells.GetRange(e.start,e.end)}}SetRange(e,t,r={}){let{recycle:i,transpose:n,array:o,r1c1:a}=r;if(r.argument_separator){let s={argument_separator:this.parser.argument_separator,decimal_mark:this.parser.decimal_mark};this.parser.Save();let c=!1;if(r.argument_separator===","&&this.parser.argument_separator!==","&&(this.parser.SetLocaleSettings("."),c=!0),r.argument_separator===";"&&this.parser.argument_separator!==";"&&(this.parser.SetLocaleSettings(","),c=!0),c){this.parser.flags.r1c1=a;let d=u=>{if(typeof u=="string"&&u[0]==="="){let h=this.parser.Parse(u);h.expression&&(u="="+this.parser.Render(h.expression,{missing:"",convert_decimal:s.decimal_mark,convert_argument_separator:s.argument_separator,pass_through_addresses:!0}))}return u};Array.isArray(t)?t=t.map(u=>Array.isArray(u)?u.map(h=>d(h)):d(u)):t=d(t)}this.parser.Restore()}if(t=this.model.UntranslateData(t,{r1c1:a}),!Array.isArray(t))i||o?this.ExecCommand({key:6,area:e,value:t,array:o,r1c1:a}):this.ExecCommand({key:6,area:e.start,value:t,array:o,r1c1:a});else{if(Mt(t)){if(i){if(e.rows>t.length){let c=Math.floor(e.rows/t.length);if(c>1){let d=[...t];for(let u=0;u<c;u++){let h=JSON.parse(JSON.stringify(d));t.push(...h)}}}let s=0;for(let c of t)s=Math.max(s,c.length);if(e.columns>s){let c=Math.floor(e.columns/s);if(c>1)for(let d of t){for(;d.length<s;)d.push(void 0);let u=[...d];for(let h=0;h<c;h++){let m=JSON.parse(JSON.stringify(u));d.push(...m)}}}}}else if(i){let s=e.entire_column?this.active_sheet.rows:e.rows,c=e.entire_row?this.active_sheet.columns:e.columns,d=s*c;if(d>t.length){let h=t.slice(0),m=Math.ceil(d/h.length);for(let f=1;f<m;f++)h=h.concat(t.slice(0));t=h}let u=[];for(let h=0,m=0;h<c;h++,m+=s)u[h]=t.slice(m,m+s);t=u}else t=[t];n&&(t=this.Transpose(t)),this.ExecCommand({key:6,area:e,value:t,array:o,r1c1:a})}!this.primary_selection.empty&&e.Contains(this.primary_selection.target)&&this.UpdateFormulaBarFormula()}ApplyStyle(e,t={},r=!0){if(!e){if(this.primary_selection.empty)return;e=this.primary_selection.area}re.UpdateStyle(t),this.ExecCommand({key:7,area:e,style:t,delta:r}),this.UpdateFormulaBarFormula()}GetSelection(){return this.primary_selection}Update(e=!1,t){this.DelayedRender(e,t)}UpdateAnnotations(){this.active_sheet.annotations.length&&this.layout.UpdateAnnotation(this.active_sheet.annotations,this.theme)}Indent(e,t=0){if(!e){if(this.primary_selection.empty)return;e=this.active_sheet.RealArea(this.primary_selection.area)}this.ExecCommand({key:9,area:e,delta:t})}ApplyBorders2(e,t="none",r,i=1){if(!e){if(this.primary_selection.empty)return;e=this.primary_selection.area}t==="none"&&(i=0),this.ExecCommand({key:8,color:r,area:e,borders:t,width:i})}Batch(e,t=!0){if(this.batch===0?this.batch_paint=t:this.batch_paint=this.batch_paint||t,this.batch++,e(),this.batch--,this.batch===0){let r=this.batch_events.slice(0);return this.batch_events=[],this.batch_paint&&this.DelayedRender(!1),r}return[]}ScrollTo(e,t=!0,r=!0,i=!1){this.layout.ScrollTo(e,t,r,i)}ScrollIntoView(e,t=!1){this.options.scrollbars&&this.layout.ScrollIntoView(e,t)}GetScrollOffset(){return this.layout.GetScrollOffset()}ScrollOffset(e){if(e)this.layout.scroll_offset=e;else return this.layout.scroll_offset}RenameSheetInternal(e,t){super.RenameSheetInternal(e,t),this.tab_bar?.Update(!1)}StyleDefaultFromTheme(){this.model.theme_style_properties.font_face=this.theme.grid_cell?.font_face||"",this.model.theme_style_properties.font_size=this.theme.grid_cell?.font_size||{unit:"pt",value:10}}AutoSizeRow(e,t,r=!0){if(!this.tile_renderer)return;let i=e.GetRowHeight(t),n=0,o=6;for(let a=0;a<e.cells.columns;a++){let s=e.CellData({row:t,column:a}),{height:c}=this.tile_renderer.MeasureText(s,e.GetColumnWidth(a),1);n=Math.max(n,c+o)}r||(n=Math.max(i,n)),n>o+2&&e.SetRowHeight(t,n)}AutoSizeColumn(e,t,r=!0){if(!this.tile_renderer)return;let i=e.GetColumnWidth(t),n=0,o=14;for(let a=0;a<e.cells.rows;a++){let s=e.CellData({row:a,column:t}),{width:c}=this.tile_renderer.MeasureText(s,i,1);n=Math.max(n,c+o)}r||(n=Math.max(i,n)),n>o+2&&e.SetColumnWidth(t,n)}EnsureActiveSheet(e=!1){for(let t of this.model.sheets.list)if(t===this.active_sheet){e&&this.ActivateSheetInternal({key:22,id:t.id,force:!0});return}this.ActivateSheetInternal({key:22,index:0})}RefreshAnnotations(){this.RemoveAnnotationNodes();for(let e of this.active_sheet.annotations)this.AddAnnotation(e,!0,!0)}ActivateSheetInternal(e){let t=this.SelectingArgument(),r=this.ResolveSheet(e)||this.model.sheets.list[0];if(this.active_sheet===r&&!e.force)return;if(!r.visible)throw new Error("cannot activate hidden sheet");this.HideHoverInfo(),this.active_sheet.selection=JSON.parse(JSON.stringify(this.primary_selection)),this.active_sheet.scroll_offset=this.layout.scroll_offset;let i=this.active_sheet;this.RemoveAnnotationNodes(),this.active_sheet=r,t?this.RenderSelections():(this.ClearSelection(this.primary_selection),r.selection&&!r.selection.empty&&this.Select(this.primary_selection,new v(r.selection.area.start,r.selection.area.end),r.selection.target));let n=this.active_sheet.annotations;for(let o of n)this.AddAnnotation(o,!0);this.ActivateSheetTasks(),this.QueueLayoutUpdate(),this.pending_layout_update.has(this.active_sheet.id)?(this.Repaint(!0,!0),this.pending_layout_update.delete(this.active_sheet.id)):this.Repaint(!1,!1),this.grid_events.Publish({type:"sheet-change",deactivate:i,activate:this.active_sheet}),this.tab_bar&&this.tab_bar.Update(!!e.user),this.layout.scroll_offset=this.active_sheet.scroll_offset,this.formula_bar?.selecting&&requestAnimationFrame(()=>this.formula_bar?.FocusEditor())}ActivateSheetTasks(){if(this.active_sheet.Activate(this.DOM),this.active_sheet.image&&!this.active_sheet.image.complete){let e=this.active_sheet.image,t=0,r=()=>{e.complete?this.UpdateLayout():t++<5&&setTimeout(()=>r(),10)};r()}}HighlightFreezeArea(){for(let e of[this.layout.corner_selection,this.layout.row_header_selection,this.layout.column_header_selection])e.classList.add("highlight-area"),setTimeout(()=>{e.classList.remove("highlight-area")},400)}QueueLayoutUpdate(e){this.tile_update_pending=!0,e&&(this.scroll_offset_pending=e)}HandleAddressLabelEvent(e){if(e){let t=(o="")=>{let a=o.toLowerCase();for(let s of this.model.sheets.list)if(s.name.toLowerCase()===a)return s.id;return this.active_sheet.id},r=o=>{for(let a of this.model.sheets.list)if(a.id===o)return a;return this.active_sheet},i,n=this.parser.Parse(e);if(n.expression)switch(n.expression.type){case"address":n.expression.sheet_id=t(n.expression.sheet),i=new v(n.expression);break;case"range":n.expression.start.sheet_id=t(n.expression.start.sheet),i=new v(n.expression.start,n.expression.end);break;case"identifier":{let o=this.model.GetName(n.expression.name,this.active_sheet.id);o?.type==="range"&&(i=o.area),i||this.primary_selection.empty||this.SetName(n.expression.name.toUpperCase(),this.primary_selection.area)}break;default:break}if(i){let o=r(i.start.sheet_id);if(o.columns>=i.end.column&&o.rows>=i.end.row){this.ExecCommand({key:5,area:i});return}else console.warn("address out of range")}}this.UpdateAddressLabel(),this.Focus()}InitFormulaBar(e,t){this.formula_bar=new Bt(e,this.model,this.view,this.options,t),this.formula_bar.autocomplete_matcher=this.autocomplete_matcher,this.formula_bar.Subscribe(r=>{switch(r.type){case"address-label-event":this.HandleAddressLabelEvent(r.text);break;case"stop-editing":this.pending_reset_selection&&this.ShowGridSelection(),this.pending_reset_selection=!1,this.editing_state=0;break;case"start-editing":this.editing_state=2,this.editing_cell={...this.primary_selection.target},this.editing_selection={...this.primary_selection};break;case"toll":this.editing_state=0,this.ClearAdditionalSelections(),this.ClearSelection(this.active_selection),this.DelayedRender();break;case"discard":if(this.editing_state=0,this.editing_annotation){this.ClearAdditionalSelections(),this.ClearSelection(this.active_selection);let i=this.editing_annotation.view[this.view_index]?.node;i&&i.focus(),this.editing_annotation=void 0,this.UpdateFormulaBarFormula(),this.DelayedRender();return}this.container&&this.Focus(),this.ClearAdditionalSelections(),this.ClearSelection(this.active_selection),this.UpdateFormulaBarFormula(),this.DelayedRender();break;case"commit":if(this.active_sheet.id!==this.editing_cell.sheet_id&&this.editing_cell.sheet_id&&this.ActivateSheetID(this.editing_cell.sheet_id),this.editing_state=0,this.editing_annotation){let i=this.editing_annotation;if(this.ClearAdditionalSelections(),this.ClearSelection(this.active_selection),i.data.formula=r.value?this.FixFormula(r.value):"",!this.pending_reset_selection){let n=this.editing_annotation.view[this.view_index]?.node;n&&n.focus()}this.grid_events.Publish({type:"annotation",event:"update",annotation:i}),this.editing_annotation=void 0,this.DelayedRender();return}this.container&&this.Focus(),r.event?this.SetInferredType(this.primary_selection,r.value,r.array):this.editing_selection&&this.SetInferredType(this.editing_selection,r.value,r.array),this.ClearAdditionalSelections(),this.ClearSelection(this.active_selection),this.options.repaint_on_cell_change&&this.DelayedRender(!1,this.primary_selection.area),r.event&&this.OverlayKeyDown(r.event);break;case"update":r.dependencies&&this.HighlightDependencies(r.dependencies);break}})}InitOverlayEditor(e){this.container&&(this.overlay_editor=new Ht(this.container,this.theme,this.model,this.view,e),this.overlay_editor.UpdateScale(this.layout.scale),this.overlay_editor.autocomplete_matcher=this.autocomplete_matcher,this.overlay_editor.Subscribe(t=>{switch(t.type){case"stop-editing":this.editing_state=0;break;case"start-editing":this.editing_state=1,this.editing_cell={...this.primary_selection.target};break;case"update":t.dependencies&&this.HighlightDependencies(t.dependencies);break;case"end-selection":case"reset-selection":this.ClearSelection(this.active_selection),this.overlay_editor?.target_address?.sheet_id&&this.active_sheet.id!==this.overlay_editor.target_address.sheet_id&&this.ActivateSheetID(this.overlay_editor.target_address.sheet_id),this.DelayedRender();break}}))}DelayedRender(e=!1,t,r=!1){!this.tile_update_pending&&t?this.layout.DirtyArea(t):!this.tile_update_pending&&e&&this.layout.DirtyAll(),this.render_token||(this.render_token=1,Promise.resolve().then(()=>{this.render_token=0,this.Repaint(e,r)}))}Repaint(e=!1,t=!1,r=!1){if(this.headless||!this.tile_renderer)return;if(this.tile_update_pending&&(this.tile_update_pending=!1,this.layout.UpdateTiles(),this.scroll_offset_pending&&(this.layout.scroll_offset=this.scroll_offset_pending,this.scroll_offset_pending=void 0),this.render_tiles=this.layout.VisibleTiles(),this.layout.UpdateAnnotation(this.active_sheet.annotations,this.theme)),this.layout_token=0,this.tile_renderer.OverflowDirty(t),e)for(let s of this.layout.grid_tiles)for(let c of s)c.dirty=!0;let i=this.render_tiles.start,n=this.render_tiles.end,o=[];for(let s=i.row;s<=n.row;s++)o.push(s);let a=[];for(let s=i.column;s<=n.column;s++)a.push(s);i.row>0&&this.active_sheet.freeze.rows&&o.push(0),i.column>0&&this.active_sheet.freeze.columns&&a.push(0);for(let s of a)for(let c of o){let d=this.layout.grid_tiles[s][c];(e||d.dirty||d.needs_full_repaint)&&(this.tile_renderer.Render(d),d.dirty=d.needs_full_repaint=!1)}this.tile_renderer.RenderHeaders(this.render_tiles,r),this.tile_renderer.RenderCorner(),this.RenderSelections()}MouseMove_RowHeader(e){let t=this.layout.CoordinateToRowHeader(e.offsetY),r=this.layout.OffsetCellAddressToRectangle({row:t.row,column:0});this.hover_data.address&&(this.hover_data.address.row!==-1||this.hover_data.address.column!==-1)&&this.HoverCell({row:-1,column:-1});let i=-1;e.offsetY-r.top<=this.RESIZE_PIXEL_BUFFER&&t.row>0?i=t.row-1:r.bottom-e.offsetY<=this.RESIZE_PIXEL_BUFFER&&(i=t.row),i>=0?this.layout.ResizeCursor("row"):this.cell_resize.row&&(this.cell_resize.row=-1,this.layout.ResizeCursor()),this.cell_resize.row=i}MouseMove_ColumnHeader(e){let t=this.layout.CoordinateToColumnHeader(e.offsetX),r=this.layout.OffsetCellAddressToRectangle({row:0,column:t.column});this.hover_data.address&&(this.hover_data.address.row!==-1||this.hover_data.address.column!==-1)&&this.HoverCell({row:-1,column:-1});let i=-1;e.offsetX-r.left<=this.RESIZE_PIXEL_BUFFER&&t.column>0?i=t.column-1:r.right-e.offsetX<=this.RESIZE_PIXEL_BUFFER&&(i=t.column),i>=0?this.layout.ResizeCursor("column"):this.cell_resize.column&&(this.cell_resize.column=-1,this.layout.ResizeCursor()),this.cell_resize.column=i}MouseDown_RowHeader(e){if(e.button!==0)return;e.stopPropagation(),e.preventDefault();let t=this.layout.CoordinateToRowHeader(e.offsetY),r=this.layout.row_header_cover.getBoundingClientRect(),i={x:r.left,y:r.top};if(this.cell_resize.row>=0){let n=this.cell_resize.row,o=i.y+e.offsetY;if(this.layout.HideDropdownCaret(),this.IsDoubleClick({row:n,column:-1})){let m=[n];if(!this.primary_selection.empty&&this.primary_selection.area.rows>1&&this.primary_selection.area.start.column===1/0&&this.primary_selection.area.ContainsRow(n)){let f=this.active_sheet.RealArea(this.primary_selection.area);m=[];for(let p=f.start.row;p<=f.end.row;p++)m.push(p)}this.ExecCommand({key:3,row:m});return}let a=this.layout.RowHeight(n),s=a,c=this.layout.OffsetCellAddressToRectangle({row:n,column:0}),d=i.y+c.bottom;this.layout.ShowTooltip({left:!0,text:`${s}px`,x:Math.round(r.right+10),y:d});let u=[],h=[];for(let m of this.active_sheet.annotations){let f=c.bottom-1;if(!m.scaled_rect||m.scaled_rect.bottom<f)continue;let p=[...this.layout.GetFrozenAnnotations(m)],b=m.view[this.view_index]?.node;b&&p.push(b),f<=m.scaled_rect.top&&m.data.move_with_cells?u.push({annotation:m,y:m.scaled_rect.top,nodes:p}):f>m.scaled_rect.top&&m.data.resize_with_cells&&h.push({annotation:m,height:m.scaled_rect.height,nodes:p})}ke(this.layout.mask,"row-resize",m=>{let f=Math.max(-a,Math.round(m.offsetY-o));if(f+a!==s){s=f+a,this.layout.SetRowHeight(n,s),this.layout.UpdateTooltip({text:`${s}px`,y:d+f});for(let{annotation:p,y:b}of u)p.scaled_rect&&(p.scaled_rect.top=b+f);for(let{annotation:p,height:b}of h)p.scaled_rect&&(p.scaled_rect.height=b+f);requestAnimationFrame(()=>{for(let{annotation:p,nodes:b}of h)if(p.scaled_rect)for(let g of b)p.scaled_rect.ApplyStyle(g);for(let{annotation:p,nodes:b}of u)if(p.scaled_rect)for(let g of b)p.scaled_rect.ApplyStyle(g);this.layout.UpdateTileHeights(!0,n),this.Repaint(!1,!0),this.layout.UpdateAnnotation(this.active_sheet.annotations,this.theme)})}},()=>{this.layout.HideTooltip(),requestAnimationFrame(()=>{let m=[n];if(!this.primary_selection.empty&&this.primary_selection.area.rows>1&&this.primary_selection.area.start.column===1/0&&this.primary_selection.area.ContainsRow(n)){let f=this.active_sheet.RealArea(this.primary_selection.area);m=[];for(let p=f.start.row;p<=f.end.row;p++)m.push(p)}this.layout.SetRowHeight(n,a),this.ExecCommand({key:3,row:m,height:s/this.scale});for(let{annotation:f}of u)f.scaled_rect&&(f.data.layout=this.layout.RectToAnnotationLayout(f.scaled_rect));for(let{annotation:f}of h){f.scaled_rect&&(f.data.layout=this.layout.RectToAnnotationLayout(f.scaled_rect));let p=f.view[this.view_index];p&&p.resize_callback&&p.resize_callback.call(void 0)}})})}else{let n=this.SelectingArgument()?this.active_selection:this.primary_selection;if(this.SelectingArgument()||this.Focus(void 0,!0),e.shiftKey&&!n.empty){let o=n.target;this.Select(n,new v(n.target,t,!0),void 0,!0),t=o}else this.Select(n,new v(t),{column:0,row:t.row});this.RenderSelections(),ke(this.layout.mask,[],o=>{let a=this.layout.CoordinateToRowHeader(o.offsetY-i.y),s=new v(a,t,!0);(n.empty||!s.Equals(n.area))&&(this.Select(n,s,void 0,!0),this.RenderSelections())},()=>{})}}MouseDown_ColumnHeader(e){if(e.button!==0)return;e.stopPropagation(),e.preventDefault();let t=this.layout.CoordinateToColumnHeader(e.offsetX),r=this.layout.column_header_cover.getBoundingClientRect(),i={x:r.left,y:r.top};if(this.cell_resize.column>=0){let n=this.cell_resize.column,o=i.x+e.offsetX;if(this.layout.HideDropdownCaret(),this.IsDoubleClick({row:-1,column:n})){let m=[n];if(!this.primary_selection.empty&&this.primary_selection.area.columns>1&&this.primary_selection.area.start.row===1/0&&this.primary_selection.area.ContainsColumn(n)){let f=this.active_sheet.RealArea(this.primary_selection.area);m=[];for(let p=f.start.column;p<=f.end.column;p++)m.push(p)}this.ExecCommand({key:4,column:m});return}let a=this.layout.ColumnWidth(n),s=a,c=this.layout.OffsetCellAddressToRectangle({row:0,column:n}),d=i.x+c.right;this.layout.ShowTooltip({up:!0,text:`${s}px`,x:d,y:Math.round(r.bottom+10)});let u=[],h=[];for(let m of this.active_sheet.annotations){let f=c.right-1;if(!m.scaled_rect||m.scaled_rect.right<f)continue;let p=[...this.layout.GetFrozenAnnotations(m)],b=m.view[this.view_index]?.node;b&&p.push(b),f<=m.scaled_rect.left&&m.data.move_with_cells?u.push({annotation:m,x:m.scaled_rect.left,nodes:p}):f>m.scaled_rect.left&&m.data.resize_with_cells&&h.push({annotation:m,width:m.scaled_rect.width,nodes:p})}ke(this.layout.mask,"column-resize",m=>{let f=Math.max(-a,Math.round(m.offsetX-o));if(f+a!==s){s=f+a,this.layout.UpdateTooltip({text:`${s}px`,x:d+f}),this.layout.SetColumnWidth(n,s);for(let{annotation:p,x:b}of u)p.scaled_rect&&(p.scaled_rect.left=b+f);for(let{annotation:p,width:b}of h)p.scaled_rect&&(p.scaled_rect.width=b+f);requestAnimationFrame(()=>{for(let{annotation:p,nodes:b}of h)if(p.scaled_rect)for(let g of b)p.scaled_rect.ApplyStyle(g);for(let{annotation:p,nodes:b}of u)if(p.scaled_rect)for(let g of b)p.scaled_rect.ApplyStyle(g);this.layout.UpdateTileWidths(!0,n),this.Repaint(!1,!0)})}},()=>{this.layout.HideTooltip(),requestAnimationFrame(()=>{let m=[n];if(!this.primary_selection.empty&&this.primary_selection.area.columns>1&&this.primary_selection.area.start.row===1/0&&this.primary_selection.area.ContainsColumn(n)){let f=this.active_sheet.RealArea(this.primary_selection.area);for(let p=f.start.column;p<=f.end.column;p++)m.push(p)}this.ExecCommand({key:4,column:m,width:s});for(let{annotation:f}of u)f.scaled_rect&&(f.data.layout=this.layout.RectToAnnotationLayout(f.scaled_rect));for(let{annotation:f}of h){f.scaled_rect&&(f.data.layout=this.layout.RectToAnnotationLayout(f.scaled_rect));let p=f.view[this.view_index];p&&p.resize_callback&&p.resize_callback.call(void 0)}})})}else{let n=this.SelectingArgument()?this.active_selection:this.primary_selection;if(this.SelectingArgument()||this.Focus(void 0,!0),e.shiftKey&&!n.empty){let o=n.target;this.Select(n,new v(n.target,t,!0),void 0,!0),t=o}else this.Select(n,new v(t),{row:0,column:t.column});this.RenderSelections(),ke(this.layout.mask,[],o=>{let a=this.layout.CoordinateToColumnHeader(o.offsetX-i.x),s=new v(a,t,!0);(n.empty||!s.Equals(n.area))&&(this.Select(n,s,void 0,!0),this.RenderSelections())})}}HoverCell(e,t){let r=this.active_sheet.cells.GetCell(e,!1);if(r?.table&&r.table.area.start.row===e.row&&r.table.sortable!==!1?(this.hover_data.table_header=!0,this.layout.ShowTableSortButton(r.table,e.column-r.table.area.start.column,e)):(this.hover_data.table_header&&this.layout.HideTableSortButton(),this.hover_data.table_header=!1),r?.merge_area){let i=r.merge_area;e=i.start,r=this.active_sheet.cells.GetCell(e,!1),e={row:i.start.row,column:i.end.column}}if(r?.note){let i=Ie.instance.Parse(r.note),n=this.options.comment_markdown?Ie.instance.HTML(i,{br:!1}):void 0;this.layout.ShowNote(r.note,e,t,n),this.hover_data.note=!0}else this.hover_data.note&&(this.layout.HideNote(),this.hover_data.note=!1);r?.hyperlink?(this.layout.ShowTitle("Link: "+r.hyperlink,e),this.hover_data.link=!0,this.hover_data.cell=r):this.hover_data.link&&(this.layout.HideTitle(),this.hover_data.cell=void 0),this.hover_data.address={...e}}HideHoverInfo(){this.layout.HideTitle(),this.layout.HideTooltip(),this.hover_data.note=this.hover_data.link=!1,this.hover_data.cell=void 0,this.hover_data.pointer&&this.layout.grid_cover.classList.remove("link-pointer"),this.hover_data.pointer=!1}MouseMove_Grid(e){if(e.stopPropagation(),e.preventDefault(),!this.selection_renderer)return;(this.cell_resize.row>=0||this.cell_resize.column>=0)&&this.layout.ResizeCursor();let t={x:e.offsetX,y:e.offsetY},r;if(this.overlay_editor?.editing||(r=this.layout.PointToAddress_Grid(t),(!this.hover_data.address||this.hover_data.address.row!==r.row||this.hover_data.address.column!==r.column)&&this.HoverCell(r,e)),this.hover_data.link&&r&&(this.hover_data.point=t,this.hover_data.handler||(this.hover_data.handler=requestAnimationFrame(()=>{let n=this.hover_data.address&&this.hover_data.point&&this.hover_data.cell&&this.PointInTextPart(this.hover_data.address,this.hover_data.point,this.hover_data.cell);n!==!!this.hover_data.pointer&&(this.hover_data.pointer=n,n?this.layout.grid_cover.classList.add("link-pointer"):this.layout.grid_cover.classList.remove("link-pointer")),this.hover_data.handler=void 0}))),this.primary_selection.empty||!this.selection_renderer.nub_rectangle){this.nub_select_flag&&(this.layout.grid_cover.classList.remove("nub-select"),this.nub_select_flag=!1);return}let i=this.selection_renderer.nub_rectangle.Contains(e.offsetX,e.offsetY);i!==this.nub_select_flag&&(i?this.layout.grid_cover.classList.add("nub-select"):this.layout.grid_cover.classList.remove("nub-select"),this.nub_select_flag=i)}ClearDoubleClick(){this.double_click_data.address=void 0}IsDoubleClick(e,t=300){if(this.double_click_data.address&&this.double_click_data.address.row===e.row&&this.double_click_data.address.column===e.column)return clearTimeout(this.double_click_data.timeout),this.double_click_data.address=void 0,this.double_click_data.timeout=void 0,!0;this.double_click_data.timeout&&clearTimeout(this.double_click_data.timeout),this.double_click_data.address={...e},this.double_click_data.timeout=window.setTimeout(()=>{this.double_click_data.address=void 0,this.double_click_data.timeout=void 0},t)}PointInTextPart(e,t,r){let i=this.layout.CellAddressToRectangle(e);r.merge_area&&(i=i.Combine(this.layout.CellAddressToRectangle(r.merge_area.end)));let n=t.x-i.left,o=t.y-i.top,a=r.renderer_data?.text_data?.strings||[];for(let s of a)for(let c of s)if(typeof c.left=="number"&&typeof c.top=="number"&&typeof c.width=="number"&&typeof c.height=="number"&&n>=c.left&&o>=c.top&&n<=c.left+c.width&&o<=c.top+c.height)return!0;return!1}MouseDown_Grid(e){if(e.button!==0)return;e.stopPropagation(),e.preventDefault();let t=this.SelectingArgument();if(!t&&this.additional_selections.length&&this.ClearAdditionalSelections(),(!t||!this.formula_bar?.selecting&&!this.external_editor?.selecting)&&this.Focus(void 0,!0),this.overlay_editor?.editing&&!this.overlay_editor?.selecting){if(this.overlay_editor?.selection){let u=this.overlay_editor?.edit_node.textContent||void 0;this.SetInferredType(this.overlay_editor.selection,u,!1)}this.DismissEditor()}let r={x:e.offsetX,y:e.offsetY},i=this.layout.PointToAddress_Grid(r),n=t?this.active_selection:this.primary_selection;if(!t&&this.IsDoubleClick(i)){j.is_mobile&&this.overlay_editor?.edit_node?.focus(),this.OverlayEditCell({target:i,area:new v(i)},!1);return}let o=this.layout.grid_cover.getBoundingClientRect(),a={x:o.left,y:o.top},s=[],c;if(e.shiftKey&&!n.empty){let u=n.target;this.Select(n,new v(i,n.target,!0),void 0,!0),i=u}else if(this.nub_select_flag)i=n.area.TopLeft(),s.push("nub-select"),c=this.active_sheet.RealArea(n.area);else{let u=i,h=this.active_sheet.CellData(u);if(h.merge_area&&(u=h.merge_area.start,h=this.active_sheet.CellData(h.merge_area.start)),h.hyperlink&&this.PointInTextPart(u,r,h)){let m=h.hyperlink;Promise.resolve().then(()=>{this.grid_events.Publish({type:"cell-event",data:{type:"hyperlink",reference:m}})}),this.ClearDoubleClick();return}if(h.click_function){let m=this.layout.CellAddressToRectangle(u);h.merge_area&&(m=m.Combine(this.layout.CellAddressToRectangle(h.merge_area.end)));let f=h.click_function.call(this,{cell:h,x:r.x-m.left,y:r.y-m.top,width:m.width,height:m.height,scale:this.layout.scale});if(f.value&&this.ExecCommand({key:6,value:f.value,area:u}),f.block_selection){this.ClearDoubleClick(),!this.primary_selection.empty&&this.primary_selection.target.row===u.row&&this.primary_selection.target.column===u.column&&this.UpdateFormulaBarFormula();return}}this.Select(n,new v(i),i)}this.RenderSelections(),t&&this.UpdateSelectedArgument(n);let d=this.layout.CellAddressToRectangle({row:0,column:0}).Combine(this.layout.CellAddressToRectangle({row:this.active_sheet.rows-1,column:this.active_sheet.columns-1})).Expand(-1,-1);ke(this.layout.mask,s,u=>{let h={x:u.offsetX-a.x,y:u.offsetY-a.y},m=d.Clamp(h.x,h.y),f=this.layout.PointToAddress_Grid(m),p=this.layout.scroll_reference_node,b=!1;this.container&&this.options.scrollbars&&(h.x<p.scrollLeft?(p.scrollLeft-=25,b=!0):h.x>p.scrollLeft+this.container.clientWidth&&(p.scrollLeft+=25,b=!0),h.y<p.scrollTop?(p.scrollTop-=25,b=!0):h.y>p.scrollTop+this.container.clientHeight&&(p.scrollTop+=25,b=!0),b&&(o=this.layout.grid_cover.getBoundingClientRect(),a.x=o.left+document.body.scrollLeft,a.y=o.top+document.body.scrollTop));let g=new v(f,i,!0);if(c&&(g=c.Clone(),g.ConsumeAddress(f),g.rows!==c.rows&&g.columns!==c.columns)){let x={rows:f.row>c.end.row?f.row-c.end.row:c.start.row-f.row,columns:f.column>c.end.column?f.column-c.end.column:c.start.column-f.column};x.rows>=x.columns?g=new v({row:g.start.row,column:c.start.column},{row:g.end.row,column:c.end.column}):g=new v({row:c.start.row,column:g.start.column},{row:c.end.row,column:g.end.column})}(n.empty||!g.Equals(n.area))&&(this.Select(n,g,void 0,!0),this.RenderSelections(),t?this.UpdateSelectedArgument(n):this.UpdateAddressLabelArea(n))},()=>{this.UpdateAddressLabel(),t?this.overlay_editor?.editing||(this.external_editor_config?(this.external_editor?.active&&this.external_editor.FocusEditor(),this.external_editor_config.update):this.formula_bar&&this.formula_bar.FocusEditor()):c&&this.RecycleNubArea(n.area,c)})}Transpose(e){let t=[],r=e.length,i=e[0].length;for(let n=0;n<i;n++){t[n]=[];for(let o=0;o<r;o++)t[n][o]=e[o][n]}return t}RecycleNubArea(e,t){if(e.Equals(t))return;let r=[];for(let u=0;u<t.rows;u++){r[u]=[];for(let h=0;h<t.columns;h++){let m={row:t.start.row+u,column:t.start.column+h};r[u][h]=this.active_sheet.CellData(m)}}if(r[0][0].area&&r[0][0].area.Equals(t)){this.ExecCommand({key:6,value:r[0][0].value,array:!0,area:e});return}if(r[0][0].table&&t.Equals(new v(r[0][0].table.area.start,r[0][0].table.area.end))){let u=r[0][0].table,h=u.sortable,m=u.totals_row,f=u.theme;this.ExecCommand([{key:30,table:u},{key:29,area:e,sortable:h,totals:m,theme:f}]);return}let i=[],n=[],o=t.columns,a=e.rows,s=!1,c=!1;e.columns===t.columns?s=e.start.row<t.start.row:(o=t.rows,a=e.columns,s=e.start.column<t.start.column,r=this.Transpose(r),c=!0);for(let u=0;u<a;u++)i[u]=[],n[u]=[];for(let u=0;u<o;u++){let h=0;if(r.length>1){h=1;let m=[],f=[];for(let p=0;p<r.length;p++){let b=r[p][u];b.ValueIsNumber()&&(f.push(p),m.push(b.value))}if(m.length>1){let p=m.slice(1).map((b,g)=>b-m[g]);p.every(b=>b===p[0])&&(h=p[0])}m.length&&(h+=m[m.length-1]-m[0])}for(let m=0;m<r.length;m++){let f,p=r[m][u];if(p.ValueIsFormula()){let _=this.parser.Parse(p.value);_.expression&&_.full_reference_list?.length&&(f=_.expression)}let b=0,g=m,x=r.length,y=0,w=h;s&&(g=a-r.length+m,x=-r.length,w=-h);for(let _=g;_>=0&&_<a;_+=x,b+=x,y+=w){let C={offset:c?{rows:0,columns:b}:{rows:b,columns:0}};if(f)i[_][u]="="+this.parser.Render(f,C);else{let S=r[m][u];S.ValueIsNumber()?i[_][u]=S.value+y:i[_][u]=S.value}n[_][u]=r[m][u].style||{}}}}let d=[{key:6,value:c?this.Transpose(i):i,array:!1,area:e}];c&&(n=this.Transpose(n));for(let u=0;u<n.length;u++)for(let h=0;h<n[u].length;h++)d.push({key:7,area:{row:u+e.start.row,column:h+e.start.column},style:n[u][h],delta:!1});this.ExecCommand(d)}UpdateSelectedArgument(e){let t=this.active_sheet.CellData(e.area.start),r=new v(t.merge_area?t.merge_area.start:e.target),i=this.model.named.MatchSelection(e.area,r);if(!i&&(i=e.area.spreadsheet_label,t.merge_area&&t.merge_area.Equals(e.area)&&(i=v.CellAddressToLabel(t.merge_area.start)),this.external_editor_config||this.active_sheet.id!==this.editing_cell.sheet_id)){let n=this.active_sheet.name;Se.test(n)?i=`'${n}'!${i}`:i=`${n}!${i}`}if(this.overlay_editor?.editing&&this.overlay_editor.selecting)this.overlay_editor.InsertReference(i);else if(this.formula_bar&&this.formula_bar.selecting)this.formula_bar.InsertReference(i);else if(this.external_editor_config&&(this.external_editor?.active&&(this.external_editor.FocusEditor(),this.external_editor.InsertReference(i)),this.external_editor_config.update)){let n=this.external_editor_config.update.call(0,i);n&&Array.isArray(n)&&this.HighlightDependencies(n.filter(o=>!!o).map(o=>N(o)?new v(o):new v(o.start,o.end)))}}SelectingArgument(){return this.overlay_editor?.editing&&this.overlay_editor?.selecting||this.formula_bar&&this.formula_bar.selecting||!!this.external_editor_config}ReleaseOverlayEditor(){this.editing_state=0,this.DismissEditor(),this.DelayedRender()}RestoreOverlayEditor(){this.overlay_editor?.FocusEditor()}OverlayKeyDown(e){let t=!1;if(this.overlay_editor&&this.overlay_editor.editing)switch(t=!0,this.overlay_editor.HandleKeyDown(e)){case"handled":return;case"discard":this.editing_state=0,this.DismissEditor(),this.DelayedRender();return;case"commit":if(this.active_sheet.id!==this.editing_cell.sheet_id&&this.editing_cell.sheet_id&&this.ActivateSheetID(this.editing_cell.sheet_id),this.editing_state=0,this.overlay_editor?.selection){let c=this.overlay_editor?.edit_node.textContent||void 0,d=e.key==="Enter"&&(e.ctrlKey||j.is_mac&&e.metaKey)&&e.shiftKey;this.SetInferredType(this.overlay_editor.selection,c,d,void 0,this.overlay_editor.edit_style)}this.DismissEditor(),this.options.repaint_on_cell_change&&this.DelayedRender(!1,this.overlay_editor?.selection.area||void 0);break}let r=this.SelectingArgument();if(this.formula_bar&&this.formula_bar.focused&&!r||this.selected_annotation&&!r)return;let i=r?this.active_selection:this.primary_selection,n={rows:0,columns:0},o=!1,a=!1;if(e.ctrlKey||j.is_mac&&e.metaKey){switch(e.key){case"ArrowDown":case"Down":n.rows++;break;case"ArrowUp":case"Up":n.rows--;break;case"ArrowLeft":case"Left":n.columns--;break;case"ArrowRight":case"Right":n.columns++;break;case"Backspace":e.metaKey&&j.is_mac&&(i.empty||this.DeleteSelection(i));break;case"Delete":case"Del":{e.stopPropagation(),e.preventDefault();for(let s=0;s<this.model.sheets.length;s++)if(this.model.sheets.list[s]===this.active_sheet){this.DeleteSheet(s);break}return}break;case"/":e.stopPropagation(),e.preventDefault(),this.SelectArrayOrTable();break;default:if(e.shiftKey)return}if(n.columns||n.rows)if(e.stopPropagation(),e.preventDefault(),!i.empty&&(n.columns||n.rows)){if(this.BlockSelection(i,!!e.shiftKey,n.columns,n.rows)){e.shiftKey&&!r&&this.UpdateAddressLabelArea(i);return}}else return;else{let s={},c=this.primary_selection.empty?{}:this.active_sheet.CellData(this.primary_selection.target).style||{};switch(e.key.toLowerCase()){case"b":s.bold=!c.bold;break;case"i":s.italic=!c.italic;break;case"u":s.underline=!c.underline;break;case"a":this.SelectAll();break;case"0":if(!e.altKey)return;this.ClearSelection(this.primary_selection),this.RenderSelections();break;default:e.key;return}Object.keys(s).length&&this.ApplyStyle(void 0,s)}}else{if(/^F\d+$/.test(e.key))return;switch(e.key){case"Tab":e.shiftKey?n.columns--:n.columns++,o=!0;break;case"Enter":e.shiftKey?n.rows--:n.rows++,o=!0;break;case"ArrowDown":case"Down":n.rows++,a=e.shiftKey;break;case"ArrowUp":case"Up":n.rows--,a=e.shiftKey;break;case"ArrowLeft":case"Left":n.columns--,a=e.shiftKey;break;case"ArrowRight":case"Right":n.columns++,a=e.shiftKey;break;case"Delete":case"Del":i.empty||this.DeleteSelection(i);break;case"PageUp":case"PageDown":if(e.shiftKey){this.NextSheet(e.key==="PageUp"?-1:1,!0);break}return;case"Control":case"Shift":case"Alt":return;default:i.empty||e.key!=="Escape"&&this.OverlayEditCell(i,!0,e);return}}e.stopPropagation(),e.preventDefault(),(n.rows||n.columns)&&(this.AdvanceSelection(n,i,o,a,!t),e.shiftKey&&!r&&this.UpdateAddressLabelArea(i))}SelectArrayOrTable(){if(this.primary_selection.empty)return;let e=this.active_sheet.CellData(this.primary_selection.target);if(!(!e||!e.area&&!e.table&&!e.spill)){if(e.area&&this.Select(this.primary_selection,e.area,e.area.start),e.spill&&this.Select(this.primary_selection,e.spill,e.spill.start),e.table){let t=new v(e.table.area.start,e.table.area.end);this.Select(this.primary_selection,t,t.start)}this.RenderSelections()}}RenderSelections(e=!0){let t=this.hide_selection?!1:!this.editing_state||this.editing_cell.sheet_id===this.active_sheet.id,r=this.primary_selection.empty?void 0:this.active_sheet.CellData(this.primary_selection.target);this.layout.ShowSpillBorder(r?.spill),this.selection_renderer?.RenderSelections(t,e)}BlockSelection(e,t,r,i,n=!0){if(e.empty)return!1;let o={...e.target};i>0?o.row=Math.max(o.row,e.area.end.row):i<0&&(o.row=Math.min(o.row,e.area.start.row)),r>0?o.column=Math.max(o.column,e.area.end.column):r<0&&(o.column=Math.min(o.column,e.area.start.column));let a=this.active_sheet.cells,s=a.GetCell(e.target,!1);if(!s||s.type===0&&!s.area&&!s.spill)return!1;let c={...o};for(;;){let d={row:c.row+i,column:c.column+r};if(d.column<0||d.row<0||d.column>=this.active_sheet.columns||d.row>=this.active_sheet.rows)break;let u=!1;if(i)for(let h=e.area.start.column;!u&&h<=e.area.end.column;h++)s=a.GetCell({row:d.row,column:h},!1),u=u||!!s&&(s.type!==0||!!s.area||!!s.spill),!u&&s&&s.merge_area&&(s=a.GetCell(s.merge_area.start,!1),u=u||!!s&&(s.type!==0||!!s.area||!!s.spill));else for(let h=e.area.start.row;!u&&h<=e.area.end.row;h++)s=a.GetCell({row:h,column:d.column},!1),u=u||!!s&&(s.type!==0||!!s.area||!!s.spill),!u&&s&&s.merge_area&&(s=a.GetCell(s.merge_area.start,!1),u=u||!!s&&(s.type!==0||!!s.area||!!s.spill));if(!u)break;c=d}if(t){i?(o.row=e.target.row,o.column=e.area.start.column,c.column=e.area.end.column):(o.column=e.target.column,o.row=e.area.start.row,c.row=e.area.end.row);let d=new v(o,c,!0);this.Select(e,d,e.target,!0)}else this.Select(e,new v(c));return this.ScrollIntoView(c),this.SelectingArgument()&&this.UpdateSelectedArgument(e),n&&this.DelayedRender(),!0}DeleteSelection(e){if(e.empty)return;let t=this.active_sheet.RealArea(e.area);this.ExecCommand({key:12,area:t})}SetInferredType(e,t,r=!1,i=!0,n){let o=e.target||e.area.start,a=this.active_sheet.CellData(o);if(a.area){if(!r&&a.area.count>1||!e.area||!e.area.Equals(a.area)){this.Error(2);return}}else if(r){for(let m of this.active_sheet.cells.Iterate(e.area,!1))if(m.area){this.Error(2);return}}let s=this.active_sheet.GetValidation(o)[0];if(s&&s.error){let m;if(s.type==="list"?m=s.list:s.type==="range"&&(m=this.GetValidationRange(s.area)),m&&m.length){let f=!1;if(t){let p=t.toUpperCase();for(let b of m)if(b&&b.toString().toUpperCase()===p){t=b.toString(),f=!0;break}}if(!f){this.Error(3);return}}}a.merge_area&&(o=a.merge_area.start);let c=[];n&&c.push({key:7,style:n,delta:!0,area:r?e.area:e.target});let d=typeof t=="string"&&t.trim()[0]==="=";if(d&&(t=this.FixFormula(t||""),!this.active_sheet.HasCellStyle(o))){let m=this.parser.Parse(t);if(m){if(m.expression?.type==="call"&&(!a.style||!a.style.number_format||L.Equals(a.style.number_format,"General"))){let f=m.expression.name.toLowerCase(),p;switch(f){case"today":p="Short Date";break;case"now":p="Timestamp";break}p&&c.push({key:7,area:r?e.area:o,style:{number_format:p},delta:!0})}if(m.expression){let f,p=(x,y=this.active_sheet)=>{if(y.HasCellStyle({...x})){let w=y.CellData({...x});if(w.style&&w.style.number_format&&(!f||/%/.test(f))&&(f=L.Translate(w.style.number_format),!/%/.test(f)))return!0}return!1},b=!1,g=this.active_sheet;if(this.parser.Walk(m.expression,x=>{if(b)return!1;switch(x.type){case"address":this.model.ResolveSheetID(x),g=this.model.sheets.Find(x.sheet_id||0),b=b||p(x,g);break;case"range":this.model.ResolveSheetID(x),g=this.model.sheets.Find(x.start.sheet_id||0);for(let y of new v(x.start,x.end))if(b=b||p(y,g),b)break;break}return!b}),f){let x={number_format:L.SymbolicName(f)||f};c.push({key:7,area:r?e.area:o,style:x,delta:!0})}}}}let u=this.parser.Parse(t||"").expression;u?.type==="group"&&u.elements.length===1&&u.elements[0].type==="complex"&&(u=u.elements[0]);let h;if(u?.type==="complex"?h={type:8,value:{real:u.real,imaginary:u.imaginary}}:u?.type==="literal"&&typeof u.value=="boolean"?h={type:4,value:u.value}:h=ye.TryParse(t),!d&&h.type===3){let m="",f=h.hints||{};(!a.style||!a.style.number_format||L.Equals(a.style.number_format,"General"))&&(f.Date?m="Short Date":f.Exponential?m="Exponential":f.Percent?m="Percent":f.Currency?m="Currency":(f.Grouping||f.Parens)&&(m="Accounting")),m&&c.push({key:7,area:r?e.area:o,style:{number_format:m},delta:!0})}if(c.push({key:6,area:r?e.area:o,array:r,value:d?this.model.UntranslateFunction(t||""):h.value}),i)this.ExecCommand(c);else return c}FixFormula(e){if(e.trim()[0]!=="=")return e;e=e.replace(/^\s+/,"");let t=!1,r=!1,i=0,n=!1,o=e.length;for(let a=0;a<o;a++){let s=e[a];if(!n)switch(s){case'"':t?e[a+1]==='"'?a++:t=!1:r||(t=!0);break;case"'":r?r=!1:t||(r=!0);break;case"\\":n=!0;break;case"(":!t&&!r&&i++;break;case")":!t&&!r&&i--;break}}for(t?e+='"':r&&(e+="'");i>0;)e+=")",i--;return e=this.NormalizeFormula(e),e}NormalizeFormula(e){let t=this.parser.Parse(e);return t.error&&console.warn(t.error),t&&t.expression&&(this.parser.Walk(t.expression,r=>{switch(r.type){case"call":r.name=this.autocomplete_matcher.NormalizeIdentifier(r.name)||r.name;break;case"identifier":this.model.GetName(r.name,this.active_sheet.id)?.type==="range"&&(r.name=r.name.toUpperCase());break}return!0}),e="="+this.parser.Render(t.expression,{missing:""})),e}DismissEditor(){this.overlay_editor?.active_cell&&(this.overlay_editor.active_cell.editing=!1,this.overlay_editor.active_cell.render_clean=[],this.DelayedRender(void 0,this.overlay_editor.selection.area)),this.editing_state=0,this.Focus(),this.overlay_editor?.CloseEditor(),this.ClearAdditionalSelections(),this.ClearSelection(this.active_selection)}NormalizeCellValue(e){let t=e.value;if(e.ValueIsNumber()&&e.style&&e.style.number_format)if(L.Get(e.style.number_format).date_format){let i=Re(e.value),n=i.getUTCHours()||i.getUTCMinutes()||i.getUTCSeconds()?"Timestamp":"Short Date";t=L.Get(n).Format(t)}else if(/(?:%|percent)/i.test(e.style.number_format)){let i=0,n=e.value.toString().match(/\.(.*?)$/);n&&n[1]&&(i=Math.max(0,n[1].length-2)),t=(e.value*100).toFixed(i)+"%",F.decimal_separator===","&&(t=t.replace(/\./,","))}else t&&F.decimal_separator===","&&(t=e.value.toString().replace(/\./,","));else{if(e.ValueIsBoolean())return e.value?this.model.language_model?.boolean_true||"TRUE":this.model.language_model?.boolean_false||"FALSE";e.ValueIsNumber()?t&&F.decimal_separator===","&&(t=e.value.toString().replace(/\./,",")):e.ValueIsComplex()?(e.value.imaginary?e.value.real?t=`${e.value.real.toString()}${e.value.imaginary<0?" - ":" + "}${e.value.imaginary===1||e.value.imaginary===-1?"":Math.abs(e.value.imaginary).toString()}i`:e.value.imaginary===1?t="i":e.value.imaginary===-1?t="-i":t=e.value.imaginary.toString()+"i":t=e.value.real.toString(),F.decimal_separator===","&&(t=t.replace(/\./,","))):e.ValueIsFormula()&&(t=this.model.TranslateFunction(e.value))}return t}IsNumeric(e){return e>=48&&e<=57||e===this.decimal_separator_code||e===45||e===43}OverlayEditCell(e,t=!0,r){if(!this.options.in_cell_editor)return;let i=e.target||e.area.start,n=this.active_sheet.CellData(i),o;if(this.HideHoverInfo(),n.merge_area?(o=this.layout.OffsetCellAddressToRectangle(n.merge_area.start).Combine(this.layout.OffsetCellAddressToRectangle(n.merge_area.end)),i=n.merge_area.start,n=this.active_sheet.CellData(i)):o=this.layout.OffsetCellAddressToRectangle(i),n.style?.locked){console.info("cell is locked for editing");return}o=o.Shift(this.layout.header_size.width,this.layout.header_size.height);let a=n.value,s;typeof a>"u"&&!n.style?.font_face&&(s=this.edit_state),t?(n.type===3||n.rendered_type===3)&&n.style&&n.style.number_format&&/(?:%|percent)/i.test(n.style.number_format)&&(!r||this.IsNumeric(r.key.charCodeAt(0)))?a="%":a=void 0:a=this.NormalizeCellValue(n),this.overlay_editor?.Edit(e,o.Expand(-1,-1),n,a,r,s),n.editing=!0,n.render_clean=[],this.DelayedRender(!1,e.area)}BoundAddressArea(e,t){e.column>t.end.column?(e.row=this.StepVisibleRows(e.row,1),e.row>t.end.row&&(e.row=t.start.row),e.column=t.start.column):e.column<t.start.column?(e.row=this.StepVisibleRows(e.row,-1),e.row<t.start.row&&(e.row=t.end.row),e.column=t.end.column):e.row>t.end.row?(e.column=this.StepVisibleColumns(e.column,1),e.column>t.end.column&&(e.column=t.start.column),e.row=t.start.row):e.row<t.start.row&&(e.column=this.StepVisibleColumns(e.column,-1),e.column<t.start.column&&(e.column=t.end.column),e.row=t.end.row)}StepVisibleRows(e,t){if(t>0)for(let r=0;r<t;r++)this.layout.RowHeight(++e)||r--;else if(t<0)for(let r=0;r>t;r--)--e>=0&&!this.layout.RowHeight(e)&&r++;return e}StepVisibleColumns(e,t){if(t>0)for(let r=0;r<t;r++)this.layout.ColumnWidth(++e)||r--;else if(t<0)for(let r=0;r>t;r--)--e>=0&&!this.layout.ColumnWidth(e)&&r++;return e}EnsureAddress(e,t=8,r=!1){let i=!1;if(this.options.expand){if(e.row!==1/0&&e.row>=this.active_sheet.rows){let n=this.active_sheet.rows;for(;e.row>=n;)n+=t;this.active_sheet.cells.EnsureRow(n),i=!0}if(e.column!==1/0&&e.column>=this.active_sheet.columns){let n=this.active_sheet.columns;for(;e.column>=n;)n+=t;this.active_sheet.cells.EnsureColumn(n),i=!0}i&&!r&&(this.layout.UpdateTiles(),this.layout.UpdateContentsSize(),this.Repaint(!0,!0))}return i}AdvanceSelection(e,t,r=!1,i=!1,n=!0){let o=this.SelectingArgument();if(t.empty)if(o){let a={row:Math.max(0,this.StepVisibleRows(this.primary_selection.target.row,e.rows)),column:Math.max(0,this.StepVisibleColumns(this.primary_selection.target.column,e.columns))};this.Select(t,new v(a))}else this.Select(t,new v({row:0,column:0}));else{let a=this.active_sheet.CellData(t.target);if(a.merge_area&&r&&(r=!a.merge_area.Equals(t.area)),r&&t.area.count>1){let s=this.active_sheet.RealArea(t.area),c=t.target;for(;;){c.row=this.StepVisibleRows(c.row,e.rows),c.column=this.StepVisibleColumns(c.column,e.columns),this.BoundAddressArea(c,s);let d=this.active_sheet.CellData(c);if(!d.merge_area||d.merge_area.start.row===c.row&&d.merge_area.start.column===c.column)break}this.Select(t,s,c)}else if(i&&t&&t.target){let s=t.area,c=t.target,d=s.start,u=s.end,h={row:1/0,column:1/0};if(e.columns&&(s.columns===1?e.columns>0?(u.column=this.StepVisibleColumns(u.column,1),h.column=u.column):(d.column=this.StepVisibleColumns(d.column,-1),h.column=d.column):s.end.column>c.column?(u.column=this.StepVisibleColumns(u.column,e.columns),h.column=u.column):s.start.column<c.column&&(d.column=this.StepVisibleColumns(d.column,e.columns),h.column=d.column),u.column=Math.max(0,u.column),d.column=Math.max(0,d.column)),e.rows&&(s.rows===1?e.rows>0?(u.row=this.StepVisibleRows(u.row,1),h.row=u.row):(d.row=this.StepVisibleRows(d.row,-1),h.row=d.row):s.end.row>c.row?(u.row=this.StepVisibleRows(u.row,e.rows),h.row=u.row):s.start.row<c.row&&(d.row=this.StepVisibleRows(d.row,e.rows),h.row=d.row),u.row=Math.max(0,u.row),d.row=Math.max(0,d.row)),this.options.expand){for(let m of[d,u,h])m.row!==1/0&&(m.row=Math.max(0,m.row)),m.column!==1/0&&(m.column=Math.max(0,m.column));this.EnsureAddress(u)&&(n=!0),this.ScrollIntoView(h),this.Select(t,new v(d,u),void 0,!0)}else{for(let m of[d,u,h])m.row!==1/0&&(m.row=Math.max(0,Math.min(m.row,this.active_sheet.rows-1))),m.column!==1/0&&(m.column=Math.max(0,Math.min(m.column,this.active_sheet.columns-1)));this.ScrollIntoView(h),this.Select(t,new v(d,u),void 0,!0)}}else{let s=t.target;a.merge_area?(e.columns<0?s.column=this.StepVisibleColumns(a.merge_area.start.column,-1):e.columns>0&&(s.column=this.StepVisibleColumns(a.merge_area.end.column,1)),e.rows<0?s.row=this.StepVisibleRows(a.merge_area.start.row,-1):e.rows>0&&(s.row=this.StepVisibleRows(a.merge_area.end.row,1))):(s.row=this.StepVisibleRows(s.row,e.rows),s.column=this.StepVisibleColumns(s.column,e.columns)),this.EnsureAddress(s)&&(n=!0),this.Select(t,new v({row:Math.min(Math.max(0,s.row),this.active_sheet.rows-1),column:Math.min(Math.max(0,s.column),this.active_sheet.columns-1)})),this.RenderSelections(),this.ScrollIntoView(t.target)}}this.SelectingArgument()&&this.UpdateSelectedArgument(t),n&&this.DelayedRender()}HighlightDependencies(e,t=!0){let r=0;e:for(let i of e)if((i.start.row===1/0||i.start.row<this.active_sheet.rows)&&(i.start.column===1/0||i.start.column<this.active_sheet.columns)){if(i.start.spill&&i.end.row===i.start.row&&i.end.column===i.start.column){let a=this.model.sheets.Find(i.start.sheet_id||-1)?.CellData(i.start);a?.spill&&a.spill.start.row===i.start.row&&a.spill.start.column===i.start.column&&i.ConsumeArea(a.spill)}i=this.active_sheet.RealArea(i);let n=i.spreadsheet_label;if(this.additional_selections[r]&&this.additional_selections[r].area.spreadsheet_label===n)r++;else{for(let o=0;o<r;o++)if(this.additional_selections[o].area.spreadsheet_label===n&&this.additional_selections[o].area.start.sheet_id===i.start.sheet_id)continue e;this.additional_selections[r++]={target:i.start,area:i}}}this.additional_selections.splice(r),t&&this.RenderSelections(!1)}ClearAdditionalSelections(){this.additional_selections.splice(0,this.additional_selections.length)}ClearSelection(e){this.Select(e)}HideGridSelection(){this.UpdateAddressLabel(void 0,"");let e=this.selected_annotation&&this.selected_annotation.data.formula?this.selected_annotation.data.formula:"";this.UpdateFormulaBarFormula(e),this.layout.ShowSelections(!1)}ShowGridSelection(){this.UpdateAddressLabel(),this.UpdateFormulaBarFormula(),this.layout.ShowSelections(!0)}Select(e,t,r,i=!1){if(e.empty||i&&(r=e.target),t){let n=this.active_sheet.RealArea(t);r||(r=n.start);e:for(;;){for(let s of this.active_sheet.cells.Iterate(n,!1))if(s.merge_area&&!n.ContainsArea(s.merge_area)){t.ConsumeArea(s.merge_area),n=this.active_sheet.RealArea(t);continue e}break}e.area=new v({...t.start,sheet_id:this.active_sheet.id},t.end),r&&(e.target={...r,sheet_id:this.active_sheet.id}),e.empty=!1;let o=this.active_sheet.CellData(e.target),a="";o.formatted&&(typeof o.formatted=="string"?a=o.formatted:a=o.formatted.map(s=>s.flag===1||s.flag===6?"":s.text).join("")),this.overlay_editor?.UpdateCaption(a)}else e.empty=!0;e===this.primary_selection&&(j.is_edge&&this.Focus(),this.grid_events.Publish({type:"selection",selection:this.primary_selection}),this.UpdateAddressLabel(),this.UpdateFormulaBarFormula(),this.formula_bar&&(this.formula_bar.target_address={...this.primary_selection.target}),this.options.stats&&this.UpdateStats())}UpdateFormulaBarFormula(e){if(this.layout.HideDropdownCaret(),e){this.formula_bar&&(this.formula_bar.shadow=!1,this.formula_bar.formula=e);return}if(this.primary_selection.empty)this.formula_bar&&(this.formula_bar.shadow=!1,this.formula_bar.formula="");else{let t=this.active_sheet.CellData(this.primary_selection.target),r=t.merge_area||t.area||t.spill,i=!1;r&&(r.start.column!==this.primary_selection.target.column||r.start.row!==this.primary_selection.target.row)&&(t=this.active_sheet.CellData(r.start),t.spill&&(i=!0)),this.formula_bar&&(this.formula_bar.editable=!t.style?.locked);let n=this.NormalizeCellValue(t),o=this.active_sheet.GetValidation(this.primary_selection.target)[0];if(o&&!t.style?.locked){let a;o.type==="list"?a=o.list:o.type==="range"&&(a=this.GetValidationRange(o.area)),a&&a.length&&this.layout.ShowDropdownCaret(t.merge_area||new v(this.primary_selection.target),a,t.value)}this.formula_bar&&(this.formula_bar.shadow=i,t.area?this.formula_bar.formula="{"+(n||"")+"}":this.formula_bar.formula=(n??"").toString())}}RenderStats(e){if(!Array.isArray(e))return[];let t=0,r=0,i={real:0,imaginary:0};for(let o of e)for(let a of o)typeof a=="number"?(i.real+=a,r++):me(a)&&(i.real+=a.real,i.imaginary+=a.imaginary,r++),typeof a<"u"&&t++;let n=o=>{let a=Math.floor(Math.log10(o));return a<-6||a>10?L.Get("Exponential"):a<=-1?L.Get("General"):L.Get("Number")};if(t>1)if(r>0){let o=L.Get("General");if(i.imaginary){let a={real:i.real/r,imaginary:i.imaginary/r};return[{label:"Count",value:t.toString()},{label:"Sum",value:ue.FormatPartsAsText(o.FormatComplex(i))},{label:"Average",value:ue.FormatPartsAsText(o.FormatComplex(a))}]}else return[{label:"Count",value:t.toString()},{label:"Sum",value:n(i.real).Format(i.real)},{label:"Average",value:n(i.real/r).Format(i.real/r)}]}else return[{label:"Count",value:t.toString()}];return[]}UpdateStats(){if(this.tab_bar){let e=[];typeof this.options.stats=="function"?this.primary_selection.empty||(e=this.options.stats.call(void 0,this.GetRange(this.primary_selection.area))):!this.primary_selection.empty&&this.primary_selection.area.count>1&&(e=this.RenderStats(this.GetRange(this.primary_selection.area))),this.tab_bar.stats_data=e}}UpdateAddressLabelArea(e){!e.empty&&!e.area.entire_sheet&&(e.area.entire_column?this.UpdateAddressLabel(void 0,e.area.columns+"C"):e.area.entire_row?this.UpdateAddressLabel(void 0,e.area.rows+"R"):e.area.count>1?this.UpdateAddressLabel(void 0,e.area.rows+"R x "+e.area.columns+"C"):this.UpdateAddressLabel(e))}UpdateAddressLabel(e=this.primary_selection,t){if(this.formula_bar)if(typeof t<"u")this.formula_bar.label=t;else if(e.empty)this.formula_bar.label="";else{let r=this.active_sheet.CellData(this.primary_selection.target),i=new v(r.merge_area?r.merge_area.start:e.target);this.formula_bar.label=this.model.named.MatchSelection(e.area,i)||v.CellAddressToLabel(i.start)}}OnDropdownSelect(e){if(typeof e<"u"){let i=ye.TryParse(e.toString());i.type===3&&(e=i.value)}let t=this.active_sheet.CellData(this.primary_selection.target),r=t.merge_area?t.merge_area.start:this.primary_selection.target;this.ExecCommand({key:6,area:r,value:e}),this.UpdateFormulaBarFormula()}OnScroll(){let e=this.layout.VisibleTiles();e.Equals(this.render_tiles)||(this.render_tiles=e,this.layout_token||(this.layout_token=requestAnimationFrame(()=>this.Repaint())))}AttachListeners(){if(!this.container)throw new Error("invalid container");this.container.addEventListener("copy",this.HandleCopy.bind(this)),this.container.addEventListener("cut",this.HandleCut.bind(this)),this.container.addEventListener("paste",this.HandlePaste.bind(this)),this.layout.grid_cover.addEventListener("mousedown",e=>this.MouseDown_Grid(e)),this.layout.column_header_cover.addEventListener("mousedown",e=>this.MouseDown_ColumnHeader(e)),this.layout.row_header_cover.addEventListener("mousedown",e=>this.MouseDown_RowHeader(e)),this.layout.column_header_cover.addEventListener("mousemove",e=>this.MouseMove_ColumnHeader(e)),this.layout.row_header_cover.addEventListener("mousemove",e=>this.MouseMove_RowHeader(e)),this.layout.grid_cover.addEventListener("mousemove",e=>this.MouseMove_Grid(e)),this.overlay_editor?.edit_node.addEventListener("keydown",e=>this.OverlayKeyDown(e)),this.layout.corner.addEventListener("dblclick",()=>{this.SelectAll()}),window.addEventListener("resize",()=>{this.layout.UpdateDPR()&&(this.QueueLayoutUpdate(),this.Repaint(!0,!0,!0))})}HandleCopy(e){if(e.stopPropagation(),e.preventDefault(),this.primary_selection.empty){if(e.clipboardData&&e.clipboardData.clearData(),this.selected_annotation&&e.clipboardData){let t=JSON.stringify({data:this.selected_annotation,source:this.active_sheet.id});e.clipboardData.setData("text/x-treb-annotation",t);let r=this.selected_annotation.view[this.view_index];if(r&&r.node){let i=r.node.firstChild?.firstChild;if(i){let n=Fi(i).outerHTML;e.clipboardData.setData("text/uri-list","data:image/svg+xml;base64,"+btoa(n)),e.clipboardData.setData("text/html",n),e.clipboardData.setData("text/plain",n)}}}}else{let t=this.active_sheet.RealArea(this.primary_selection.area),r=[],i=[];if(this.primary_selection.area.entire_column)for(let d=t.start.column;d<=t.end.column;d++){let u=this.active_sheet.GetColumnWidth(d);u!==this.active_sheet.default_column_width&&(r[d-t.start.column]=u)}if(this.primary_selection.area.entire_row)for(let d=t.start.row;d<=t.end.row;d++){let u=this.active_sheet.GetRowHeight(d);u!==this.active_sheet.default_row_height&&(i[d-t.start.row]=u)}let n=t.columns,o=t.rows,a=[],s=[];for(let d=0;d<o;d++){let u=[];for(let h=0;h<n;h++){let m={row:t.start.row+d,column:t.start.column+h},f=this.active_sheet.CellData(m),p="";f.calculated!==void 0?f.calculated_type===8?p=Xe(f.calculated):p=f.calculated.toString():f.type===8?p=Xe(f.value):p=f.value?.toString()||"",u.push(p);let b={address:m,data:f.value,type:f.type,style:this.active_sheet.GetCopyStyle(m)};f.area&&f.area.start.row===m.row&&f.area.start.column===m.column&&(b.array={rows:f.area.rows,columns:f.area.columns}),s.push(JSON.parse(JSON.stringify(b)))}a.push(u)}let c=a.map(d=>d.join(" ")).join(`
10
+ `);e.clipboardData&&(e.clipboardData.clearData(),e.clipboardData.setData("text/plain",c),e.clipboardData.setData("text/x-treb",JSON.stringify({source:t,data:s,column_width:r,row_height:i})))}}HandleCut(e){if(e.stopPropagation(),e.preventDefault(),this.HandleCopy(e),this.primary_selection.empty)this.selected_annotation&&this.RemoveAnnotation(this.selected_annotation);else{let t=this.active_sheet.RealArea(this.primary_selection.area);this.ExecCommand({key:12,area:t})}}RecyclePasteAreas(e,t){let r=[];if(e.count===1)for(let i=t.start.row;i<=t.end.row;i++)for(let n=t.start.column;n<=t.end.column;n++)r.push(new v({row:i,column:n}));else if(e.columns===t.columns&&t.rows>=e.rows&&t.rows%e.rows===0)for(let i=t.start.row;i<=t.end.row;i+=e.rows)r.push(new v({row:i,column:t.start.column},{row:i+e.rows-1,column:t.end.column}));else if(e.rows===t.rows&&t.columns>=e.columns&&t.columns%e.columns===0)for(let i=t.start.column;i<=t.end.column;i+=e.columns)r.push(new v({column:i,row:t.start.row},{column:i+e.columns-1,row:t.end.row}));else r.push(t.Clone().Resize(e.rows,e.columns));return r}HandlePaste(e){if(this.overlay_editor?.editing||(e.stopPropagation(),e.preventDefault(),!e.clipboardData))return;let t=e.clipboardData.getData("text/x-treb-annotation");if(t){try{let o=JSON.parse(t);if(o.source&&o.source!==this.active_sheet.id&&o.data&&o.data.formula){let a="",s=this.model.sheets.Find(o.source);if(s&&(a=s.name),a){let c=this.parser.Parse(o.data.formula);c.expression&&(this.parser.Walk(c.expression,d=>d.type==="range"?(!d.start.sheet_id&&!d.start.sheet&&(d.start.sheet=a),!1):(d.type==="address"&&!d.sheet_id&&!d.sheet&&(d.sheet=a),!0)),o.data.formula="="+this.parser.Render(c.expression,{missing:""}))}}this.CreateAnnotation(o.data,void 0,!0,!0,void 0,!0)}catch(o){console.error(o)}return}if(this.primary_selection.empty)return;let r=this.active_sheet.RealArea(this.primary_selection.area),i=[],n=e.clipboardData.getData("text/x-treb");if(n)try{let o=JSON.parse(n),a=new v(o.source.start,o.source.end),s=this.RecyclePasteAreas(a,r);if(s.length===1&&r.Resize(s[0].rows,s[0].columns),!this.ValidatePasteAreas(s)){this.Error(5);return}let c=[];for(let d of s){this.active_sheet.cells.EnsureCell(d.end),i.push({key:12,area:d});let u={rows:d.start.row-a.start.row,columns:d.start.column-a.start.column};if(o.data.forEach(h=>{let m=h.data,f={row:h.address.row-a.start.row+d.start.row,column:h.address.column-a.start.column+d.start.column};if(h.type===1){let p=this.parser.Parse(m);p.expression&&(m="="+this.parser.Render(p.expression,{offset:u,missing:""}))}if(h.array){let p={start:{...f},end:{row:f.row+h.array.rows-1,column:f.column+h.array.columns-1}},b={key:6,value:m,array:!0,area:p};c.push(new v(p.start,p.end)),i.push(b)}else{let p=!1;for(let b of c)if(b.Contains(f)){p=!0;break}p||i.push({key:6,value:m,area:f})}i.push({key:7,style:h.style||{},area:f})}),o.column_width?.length){for(let[h,m]of o.column_width.entries())if(typeof m=="number"){let f=h+d.start.column;i.push({key:4,column:f,width:m})}}if(o.row_height?.length){for(let[h,m]of o.row_height.entries())if(typeof m=="number"){let f=h+d.start.row;i.push({key:3,row:f,height:m})}}}}catch(o){console.error("invalid treb data on clipboard"),console.info(o);return}else{let o=e.clipboardData.getData("text/plain");if(!o)return!0;let s=o.trim().split(`
11
+ `).map(d=>d.split(" ").map(u=>u.trim())),c=this.RecyclePasteAreas(new v({row:0,column:0},{row:s.length-1,column:s[0].length-1}),r);if(c.length===1&&(r.Resize(s.length,s[0].length),r.Resize(c[0].rows,c[0].columns)),!this.ValidatePasteAreas(c)){this.Error(5);return}for(let d of c)for(let u=0;u<s.length;u++)for(let h=0;h<s[0].length;h++){let m=new v({row:u+d.start.row,column:h+d.start.column});if(this.active_sheet.cells.EnsureCell(m.end),s[u][h]){let f=this.SetInferredType({area:m,target:m.start,empty:!1},s[u][h],!1,!1);if(f)for(let p of f)i.push(p)}else{let f=this.active_sheet.cells.GetCell(m.start,!1);f&&f.type!==0&&i.push({key:12,area:m.Clone()})}}}this.ExecCommand(i),this.Select(this.primary_selection,r)}AllSelections(e=!1){let t=[this.primary_selection,this.active_selection].concat(this.additional_selections);return e?t:t.filter(r=>!r.empty)}InsertRowsInternal(e){let t=super.InsertRowsInternal(e);if(t.error)return t;let r=this.FindSheet(e.sheet_id);if(r===this.active_sheet){if(e.count<0)for(let i of this.AllSelections())i.empty=!0;else for(let i of this.AllSelections())i.target.row>=e.before_row&&(i.target.row+=e.count),i.area.entire_column||(i.area.start.row>=e.before_row?i.area.Shift(e.count,0):i.area.end.row>=e.before_row&&i.area.ConsumeAddress({row:i.area.end.row+e.count,column:i.area.end.column}));for(let i of t.delete_annotations_list||[])this.layout.RemoveAnnotation(i);if(this.QueueLayoutUpdate(),this.Repaint(),t.update_annotations_list?.length){this.layout.UpdateAnnotation(t.update_annotations_list,this.theme);for(let i of t.resize_annotations_list||[]){let n=i.view[this.view_index];n?.resize_callback&&n.resize_callback.call(void 0)}}}else this.pending_layout_update.add(r.id);return t}InsertColumnsInternal(e){let t=super.InsertColumnsInternal(e);if(t.error)return t;let r=this.FindSheet(e.sheet_id);if(r===this.active_sheet){if(e.count<0)for(let i of this.AllSelections())i.empty=!0;else for(let i of this.AllSelections())i.target.column>=e.before_column&&(i.target.column+=e.count),i.area.entire_row||(i.area.start.column>=e.before_column?i.area.Shift(0,e.count):i.area.end.column>=e.before_column&&i.area.ConsumeAddress({row:i.area.end.row,column:i.area.end.column+e.count}));for(let i of t.delete_annotations_list||[])this.layout.RemoveAnnotation(i);if(this.tile_renderer?.FlushOverflows(),this.QueueLayoutUpdate(),this.DelayedRender(!0,void 0,!0),t.update_annotations_list?.length){this.layout.UpdateAnnotation(t.update_annotations_list,this.theme);for(let i of t.resize_annotations_list||[]){let n=i.view[this.view_index];n?.resize_callback&&n.resize_callback.call(void 0)}}}else this.pending_layout_update.add(r.id);return t}ResetInternal(){super.ResetInternal(),this.RemoveAnnotationNodes(),this.ClearSelection(this.primary_selection),this.ScrollIntoView({row:0,column:0}),this.QueueLayoutUpdate(),this.layout.HideNote()}ResizeColumnsInternal(e){if(this.headless)return super.ResizeColumnsInternal(e);let t=e.sheet_id?this.FindSheet(e.sheet_id):this.active_sheet,r=e.column;if(typeof r>"u"){r=[];for(let o=0;o<t.columns;o++)r.push(o)}typeof r=="number"&&(r=[r]);let i=typeof e.width!="number",n=Math.round((e.width||0)/this.scale);if(i)for(let o of r)this.AutoSizeColumn(t,o,!0);else for(let o of r)t.SetColumnWidth(o,n);t===this.active_sheet?(this.layout.UpdateTotalSize(),this.layout.container&&this.layout.container.offsetWidth&&this.layout.container.offsetWidth>this.layout.total_width?this.UpdateLayout():(this.layout.UpdateTileWidths(!0),this.render_tiles=this.layout.VisibleTiles(),this.Repaint(!1,!0)),this.layout.UpdateAnnotation(this.active_sheet.annotations,this.theme),this.RenderSelections()):this.pending_layout_update.add(t.id)}ResizeRowsInternal(e){let t,r=e.sheet_id?this.FindSheet(e.sheet_id):this.active_sheet,i=e.row;if(typeof i>"u"){i=[];for(let s=0;s<r.rows;s++)i.push(s)}typeof i=="number"&&(i=[i]);let n=typeof e.shrink=="boolean"?e.shrink:!0,o=typeof e.height!="number",a=Math.round(e.height||0/this.scale);if(o)for(let s of i)r.GetRowHeight(s)||(t?t.ConsumeAddress({row:s,column:1}):t=new v({row:s,column:1/0,sheet_id:r.id})),this.AutoSizeRow(r,s,n);else for(let s of i){let c=r.GetRowHeight(s);(!c&&a||c&&!a)&&(t?t.ConsumeAddress({row:s,column:1}):t=new v({row:s,column:1/0,sheet_id:r.id})),r.SetRowHeight(s,a)}return r===this.active_sheet?(this.layout.UpdateTotalSize(),this.layout.container&&this.layout.container.offsetHeight&&this.layout.container.offsetHeight>this.layout.total_height?this.UpdateLayout():(this.layout.UpdateTileHeights(!0),this.render_tiles=this.layout.VisibleTiles(),this.Repaint(!1,!0)),this.layout.UpdateAnnotation(this.active_sheet.annotations,this.theme),this.RenderSelections()):this.pending_layout_update.add(r.id),t?{start:t.start,end:t.end}:void 0}SelectInternal(e){e.area?(e.area.start.sheet_id&&e.area.start.sheet_id!==this.active_sheet.id&&this.ActivateSheetInternal({key:22,id:e.area.start.sheet_id}),this.Select(this.primary_selection,new v(e.area.start,e.area.end)),this.RenderSelections()):this.ClearSelection(this.primary_selection)}FreezeInternal(e){let t=this.FindSheet(e.sheet_id||this.active_sheet.id),r=(typeof e.highlight_transition=="boolean"?e.highlight_transition:!0)&&t===this.active_sheet;if(e.rows===t.freeze.rows&&e.columns===t.freeze.columns){r&&this.HighlightFreezeArea();return}t.freeze.rows=e.rows,t.freeze.columns=e.columns,t===this.active_sheet?(this.QueueLayoutUpdate(),this.Repaint(),r&&this.HighlightFreezeArea(),e.rows||e.columns?this.layout.CloneFrozenAnnotations():this.layout.ClearFrozenAnnotations()):this.pending_layout_update.add(t.id)}ExecCommand(e,t=!0){let r=super.ExecCommand(e,t);this.batch||r.render_area&&this.DelayedRender(!1,r.render_area),r.repaint&&this.Repaint();for(let i of r.pending||[])this.pending_layout_update.add(i);return r.layout&&this.QueueLayoutUpdate(),r.sheets&&this.tab_bar&&this.tab_bar.Update(),r.formula&&this.UpdateFormulaBarFormula(),r}};var en=["default","old-style","transitional","handwritten","monospace","industrial","ui"],Jt={default:"Sans-serif","old-style":"Old style",transitional:"Serif",handwritten:"Handwritten",monospace:"Monospace",industrial:"Industrial sans",ui:"System UI"},Zi=new Map,Kr=(l,e)=>{let t=e.fontFamily,r="",i=t.split(/,/);for(let u of i){u=u.replace(/'"/g,"").trim();let h=u.toLowerCase();if(j.is_firefox&&/sitka text/i.test(h))continue;let m=Zi.get(h);if(typeof m>"u"&&(m=se.FontLoaded(u),Zi.set(h,m)),m){r=u;break}}r||console.warn("no font found for font stack",l);let n=r.toLowerCase().replace(/['"]/g,"").replace(/\W+/g,"-"),o=e.getPropertyValue("--treb-font-stack-default-size"),a=e.getPropertyValue(`--treb-font-stack-${n}-size`),s=e.getPropertyValue(`--treb-font-stack-${n}-variant`),c=I.ParseFontSize(a||o||"10pt").font_size||{unit:"pt",value:10};return{family:t,font:r,variants:s,size:c}};var qt={grid_color:"#ccc",note_marker_color:"#d2c500",mode:"light",offset_cache:{},offset_light:"#fff",offset_dark:"#000",font_stacks:{},grid_cell_font_size:{value:10,unit:"pt"}},ia=(l,e)=>{let t=Hr(e),r=e.tint||0;l.mode==="dark"&&(r=-r),l.tint_cache||(l.tint_cache=[]),l.tint_cache[t]||(l.tint_cache[t]={});let i=l.tint_cache[t][r];if(!i){let n=(l.theme_colors_rgb?l.theme_colors_rgb[t]:[0,0,0])||[0,0,0],o;r>0?o=W.Lighten(n[0],n[1],n[2],r*100,!0):o=W.Darken(n[0],n[1],n[2],-r*100,!0),i=`rgb(${o.r},${o.g},${o.b})`,l.tint_cache[t][r]=i}return i},D=(l,e,t)=>{if(e&&e.offset){if(e.offset.offset)return console.warn("invalid offset color"),"";let r="";if(ee(e.offset)){let n=se.MeasureColor(e.offset.text);r=`rgb(${n[0]}, ${n[1]}, ${n[2]})`}else r=D(l,e.offset,void 0);if(l.offset_cache&&l.offset_cache[r])return l.offset_cache[r];let i=l.offset_light;if(r){let n=r.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(n){let o=[Number(n[1]),Number(n[2]),Number(n[3])],a=Array.from(se.MeasureColor(l.offset_dark)),s=Array.from(se.MeasureColor(l.offset_light)),c=W.GetTextColor(o,a,s);i=`rgb(${c[0]}, ${c[1]}, ${c[2]})`}else console.warn("can't offset against color",r,"(1)");l.offset_cache||(l.offset_cache={}),l.offset_cache[r]=i}else console.warn("can't resolve offset color",e.offset,"(2)");return i}return ee(e)?e.text==="none"?"":e.text:Ke(e)?e.tint?ia(l,e):l.theme_colors?l.theme_colors[Hr(e)]:"":(t||t===0)&&l.theme_colors?l.theme_colors[t]:""},na=l=>{let e=10,t="pt",r=l.match(/^([\d.]+)(\D.*)$/);return r&&(e=Number(r[1]),t=r[2]),{value:e,unit:t}},tn=(l,e=!1)=>{let t={fill:{text:l.backgroundColor},text:{text:l.color},font_size:{unit:"em",value:1}};return e&&(t.font_face=l.fontFamily),/italic/i.test(l.font)&&(t.italic=!0),l.fontWeight==="700"&&(t.bold=!0),t},oa=(l,e)=>{let t=l.grid_cell?.text,r=l.grid_cell?.fill;e.fillStyle=ee(t)?t.text:"",e.fillRect(0,0,3,3);let i=W.RGBToHSL(...Array.from(e.getImageData(1,1,1,1).data));e.fillStyle=ee(r)?r.text:"",e.fillRect(0,0,3,3);let n=W.RGBToHSL(...Array.from(e.getImageData(1,1,1,1).data));return i.l>n.l?"dark":"light"},Wt=(l,e=.7)=>{let t={border_top:1,border_top_fill:{theme:l},border_bottom:1,border_bottom_fill:{theme:l}};return{header:{text:{offset:{theme:l}},fill:{theme:l},bold:!0,...t},odd:{fill:{theme:l,tint:e},...t},even:{...t},total:{...t,border_top:2}}},Qi=(l,e=!1)=>{let t=JSON.parse(JSON.stringify(qt)),r=O.GetInstance(l.ownerDocument),i=(h,m)=>r.Div(m,h),n=(h,m)=>r.view?.getComputedStyle(i(h,m)),o=i(l,""),a=n.bind(0,o),s=a("grid-cells");if(t.grid_cell=tn(s,!1),t.grid_color=s.stroke||"",t.grid_cell_font_size=na(s.fontSize||""),e)for(let h of en)s=a(`treb-font-stack-${h}`),t.font_stacks[h]=Kr(h,s);else s=a("treb-font-stack-default"),t.font_stacks.default=Kr("default",s);s=a("grid-headers"),t.headers=tn(s,!0),t.headers_grid_color=s.stroke,(!t.headers_grid_color||t.headers_grid_color==="none")&&(t.headers_grid_color=t.grid_color),s=a("treb-offset-dark"),s.color&&(t.offset_dark=s.color),s=a("treb-offset-light"),s.color&&(t.offset_light=s.color),s=a("note-marker"),t.note_marker_color=s.backgroundColor,o.style.color="rgba(1,2,3,.4)",s=a("");let c=s.color;t.theme_colors=[ee(t.grid_cell.fill)?t.grid_cell.fill.text:"rgb(255, 255, 255)",ee(t.grid_cell.text)?t.grid_cell.text.text:"rgb(51, 51, 51)"];for(let h=1;h<32&&(s=a(`theme-color-${h}`),!(!s.color||s.color===c));h++)t.theme_colors.push(s.color);let d=r.Create("canvas");d.width=3,d.height=3;let u=d.getContext("2d",{willReadFrequently:!0});return u&&(t.mode=oa(t,u)),u&&(t.theme_colors_rgb=t.theme_colors.map(h=>{u.fillStyle=h,u.fillRect(0,0,3,3);let m=u.getImageData(1,1,1,1);return Array.from(m.data)})),t.table=Wt(4),o.parentElement?.removeChild(o),t};var Yi={column:0,type:"auto",asc:!0};var Xt=class{constructor(e,t,r="RGB"){this.color_space=r;this.mapped=e.map(i=>{if(i.value<0||i.value>1)throw new Error("invalid stop value");let n=se.MeasureColor(D(t,i.color)),o=[];if(r==="HSL"){let a=W.RGBToHSL(n[0],n[1],n[2]);o=[a.h,a.s,a.l]}else o=[...n];return{...i,resolved:o}}),this.mapped.sort((i,n)=>i.value-n.value),this.mapped[0].value>0&&this.mapped.unshift({...this.mapped[0],value:0}),this.mapped[this.mapped.length-1].value<1&&this.mapped.push({...this.mapped[this.mapped.length-1],value:1})}mapped;RenderColor(e){return this.color_space==="RGB"?{text:`rgb(${e})`}:{text:`hsl(${e[0]},${e[1]*100}%,${e[2]*100}%)`}}Interpolate(e){e=Math.min(1,Math.max(0,e));for(let[t,r]of this.mapped.entries()){if(e===r.value)return this.RenderColor(r.resolved);if(e<r.value){let i=this.mapped[t-1],n=r,o=n.value-i.value,a=e-i.value,s=[0,1,2].map(c=>i.resolved[c]+(n.resolved[c]-i.resolved[c])/o*a);return this.RenderColor(s)}}return{text:""}}};var Kt={};fo(Kt,{Iterate:()=>aa});function*aa(l){if(l.start.row===1/0||l.end.row===1/0)throw new Error("don't iterate infinite area");let e=l.start.sheet_id;for(let t=l.start.row;t<=l.end.row;t++)for(let r=l.start.column;r<=l.end.column;r++)yield{row:t,column:r,sheet_id:e}}var Yt=class{constructor(e){this.parser=e}named=new Map;get list(){return this.named.values()}SetNamedExpression(e,t,r){return this.SetName({type:"expression",name:e,expression:t,scope:r})}SetNamedRange(e,t,r){return this.SetName({type:"range",name:e,area:new v(t.start,t.end),scope:r})}SetName(e){let t=e.name;return this.ValidateNamed(t)?(this.named.set(this.ScopedName(t,e.scope),e),!0):(console.warn("invalid name",{name:t}),!1)}ScopedName(e,t){return typeof t=="number"?t+":"+e.toLowerCase():e.toLowerCase()}ClearName(e,t){typeof t=="number"?this.named.delete(this.ScopedName(e,t)):this.named.delete(e.toLowerCase())}RemoveRangesForSheet(e){let t=[];for(let[r,i]of this.named)(i.type==="range"&&i.area.start.sheet_id===e||i.scope===e)&&t.push(r);for(let r of t)this.named.delete(r)}Reset(){this.named.clear()}Get_(e,t,r=!1){return r?this.named.get(this.ScopedName(e,t)):this.named.get(this.ScopedName(e,t))??this.named.get(e.toLowerCase())}ValidateNamed(e){return e=e.trim().toUpperCase(),!e.length||/[^A-Z\d_.?]/.test(e)||/^[^A-Z_]/.test(e)||e==="R"||e==="C"||/^[A-Z]{1,3}[1-9]\d*$/.test(e)||/^R[[\]\d]+C/.test(e)?!1:e}MatchSelection(e,t){if(!e.start.sheet_id)throw new Error("match selection without sheet id");let r;for(let i of this.named.values())if(i.type==="range"&&i.area.start.sheet_id===e.start.sheet_id&&(e.Equals(i.area)&&(r=i.name),t?.Equals(i.area)))return i.name;return r}PatchNamedRanges(e,t,r,i,n){let o=[...this.list];for(let a of o){if(a.type==="expression")continue;let s=a.name,c=a.area;if(c.start.sheet_id!==e){console.info("skipping name",s);continue}if(r&&t<=c.end.column){if(r>0)t<=c.start.column?c.Shift(0,r):t>c.start.column&&t<=c.end.column?c.ConsumeAddress({row:c.end.row,column:c.end.column+r}):console.warn("PNR X case 1",t,r,JSON.stringify(c));else if(r<0)if(t-r<=c.start.column)c.Shift(0,r);else if(t<=c.start.column&&t-r>c.end.column)this.ClearName(s);else if(t<=c.start.column){let d=t-r-1;this.SetName({type:"range",area:new v({row:c.start.row,column:d+1+r,sheet_id:e},{row:c.end.row,column:c.end.column+r}),name:s})}else t<=c.end.column?t-r-1>=c.end.column?this.SetName({type:"range",area:new v({row:c.start.row,column:c.start.column,sheet_id:e},{row:c.end.row,column:t-1}),name:s}):this.SetName({type:"range",name:s,area:new v({row:c.start.row,column:c.start.column,sheet_id:e},{row:c.end.row,column:c.start.column+c.columns+r-1})}):console.warn("PNR X case 2",t,r,JSON.stringify(c))}if(n&&i<=c.end.row){if(n>0)i<=c.start.row?c.Shift(n,0):i>c.start.row&&i<=c.end.row?c.ConsumeAddress({row:c.end.row+n,column:c.end.column}):console.warn("PNR X case 3",i,n,JSON.stringify(c));else if(n<0)if(i-n<=c.start.row)c.Shift(n,0);else if(i<=c.start.row&&i-n>c.end.row)this.ClearName(s);else if(i<=c.start.row){let d=i-n-1;this.SetNamedRange(s,new v({column:c.start.column,row:d+1+n,sheet_id:e},{column:c.end.column,row:c.end.row+n}))}else i<=c.end.row?i-n-1>=c.end.row?this.SetNamedRange(s,new v({column:c.start.column,row:c.start.row,sheet_id:e},{column:c.end.column,row:i-1})):this.SetNamedRange(s,new v({column:c.start.column,row:c.start.row,sheet_id:e},{column:c.end.column,row:c.start.row+c.rows+n-1})):console.warn("PNR X case 4",i,n,JSON.stringify(c))}}}};var _t=class{parser=new We;language_model;document_name;user_data;sheets=new At;named=new Yt(this.parser);macro_functions=new Map;view_count=0;theme_style_properties=JSON.parse(JSON.stringify(I.DefaultProperties));tables=new Map;GetName(e,t){let r=e.split(/!/);if(r.length===1)return this.named.Get_(e,t);let i=r[0];/^'.*?'$/.test(i)&&(i=i.substring(1,i.length-1));let n=this.sheets.ID(i);return this.named.Get_(r[1],n||0,!1)}UnserializeNames(e,t,r=!1){this.parser.Save(),r&&this.parser.SetLocaleSettings(".",",");for(let i of e){if(!i.expression)continue;let n=this.parser.Parse(i.expression);if(n.expression){let o=typeof i.scope=="string"?this.sheets.ID(i.scope):void 0;if(n.expression.type==="address"||n.expression.type==="range"){let[a,s]=n.expression.type==="range"?[n.expression.start,n.expression.end]:[n.expression,n.expression];if(a.sheet)if(/^\[\d+\]/.test(a.sheet))console.warn("named range refers to an external file");else{let c=new v({...a,sheet_id:this.sheets.ID(a.sheet)},s);c.start.sheet_id?this.named.SetNamedRange(i.name,c,o):console.warn("missing sheet ID?",a)}else console.warn("missing sheet name?",a)}else this.parser.Walk(n.expression,a=>a.type==="address"||a.type==="range"?(a.type==="range"&&(a=a.start),a.sheet_id||a.sheet&&(a.sheet_id=this.sheets.ID(a.sheet)),a.sheet_id||(a.sheet_id=t?.id),!1):!0),this.named.SetNamedExpression(i.name,n.expression,o)}}this.parser.Restore()}SerializeNames(e){let t=[];for(let r of this.named.list){let i={name:r.name,expression:"",type:r.type};if(r.scope&&(i.scope=this.sheets.Name(r.scope)),r.type==="expression")this.parser.Walk(r.expression,n=>{if(n.type==="address"||n.type==="range"){let o=n.type==="range"?n.start:n;return o.absolute_column=o.absolute_row=!0,o.sheet||(o.sheet_id&&(o.sheet=this.sheets.Name(o.sheet_id)),o.sheet||(o.sheet=e?.name)),n.type==="range"&&(n.end.absolute_column=n.end.absolute_row=!0),!1}return!0}),i.expression=this.parser.Render(r.expression,{missing:""});else{let n={start:{...r.area.start,absolute_column:!0,absolute_row:!0},end:{...r.area.end,absolute_column:!0,absolute_row:!0}};i.expression=this.AddressToLabel(n)}t.push(i)}return t}ResolveStructuredReference(e,t){let r;if(e.table?r=this.tables.get(e.table.toLowerCase()):t.sheet_id&&(r=this.sheets.Find(t.sheet_id)?.CellData(t)?.table),!r)return;let i=e.column.toLowerCase(),n=-1;if(r.columns){for(let o=0;o<r.columns.length;o++)if(i===r.columns[o]){n=r.area.start.column+o;break}}if(!(n<0))if(e.scope==="row"){let o=t.row;return o<r.area.start.row||o>r.area.end.row?void 0:{label:e.label,type:"address",row:o,column:n,sheet_id:r.area.start.sheet_id,id:e.id,position:e.position}}else{let o=r.area.start.row,a=r.area.end.row;return e.scope==="column"&&(o++,r.totals_row&&a--),{label:e.label,type:"range",position:e.position,id:e.id,start:{type:"address",row:o,column:n,sheet_id:r.area.start.sheet_id,label:e.label,position:e.position,id:0},end:{type:"address",row:a,column:n,label:e.label,position:e.position,id:0}}}}AddressToLabel(e){let t=N(e)?e:e.start,r=N(e)?[v.CellAddressToLabel(e)]:[v.CellAddressToLabel(e.start),v.CellAddressToLabel(e.end)],i=this.sheets.Find(t.sheet_id||0),n=i?.name?Se.test(i.name)?`'${i.name}'`:i.name:"";return n+(n?"!":"")+(r[0]===r[1]?r[0]:r.join(":"))}ResolveSheetID(e,t,r){let i=e.type==="address"?e:e.start;if(i.sheet_id)return!0;if(i.sheet){let n=this.sheets.Find(i.sheet);if(n)return i.sheet_id=n.id,!0}else{if(t?.sheet_id)return i.sheet_id=t.sheet_id,!0;if(r?.id)return i.sheet_id=r.id,!0}return!1}ResolveArea(e,t,r){let i=this.ResolveAddress(e,t,r);return N(i)?new v(i):new v(i.start,i.end)}ResolveAddress(e,t,r){if(typeof e=="string"){r?.r1c1&&(this.parser.Save(),this.parser.flags.r1c1=!0);let i=this.parser.Parse(e);if(r?.r1c1&&this.parser.Restore(),i.expression&&i.expression.type==="address")return this.ResolveSheetID(i.expression,void 0,t),{row:i.expression.row,column:i.expression.column,sheet_id:i.expression.sheet_id};if(i.expression&&i.expression.type==="range")return this.ResolveSheetID(i.expression,void 0,t),{start:{row:i.expression.start.row,column:i.expression.start.column,sheet_id:i.expression.start.sheet_id},end:{row:i.expression.end.row,column:i.expression.end.column}};if(i.expression&&i.expression.type==="identifier"){let n=this.GetName(i.expression.name,t.id);if(n?.type==="range")return n.area}return{row:0,column:0}}return e}AddConnectedElement(e){let t=this.connected_element_id++;return this.connected_elements.set(t,e),t}RemoveConnectedElement(e){let t=this.connected_elements.get(e);return this.connected_elements.delete(e),t}connected_element_id=100;connected_elements=new Map;language_map;reverse_language_map;SetLanguageMap(e){if(!e)this.language_map=this.reverse_language_map=void 0;else{let t=Object.keys(e);this.language_map={};for(let r of t)this.language_map[r.toUpperCase()]=e[r];this.reverse_language_map={};for(let r of t){let i=e[r];this.reverse_language_map[i.toUpperCase()]=r}}}TranslateFunction(e,t){return this.language_map?this.TranslateInternal(e,this.language_map,this.language_model?.boolean_true,this.language_model?.boolean_false,t):e}UntranslateFunction(e,t){return this.reverse_language_map?this.TranslateInternal(e,this.reverse_language_map,"TRUE","FALSE",t):e}UntranslateData(e,t){return Array.isArray(e)?Mt(e)?e.map(r=>r.map(i=>i&&typeof i=="string"&&i[0]==="="?this.UntranslateFunction(i,t):i)):e.map(r=>r&&typeof r=="string"&&r[0]==="="?this.UntranslateFunction(r,t):r):(e&&typeof e=="string"&&e[0]==="="&&(e=this.UntranslateFunction(e,t)),e)}TranslateInternal(e,t,r,i,n){this.parser.Save(),this.parser.flags.r1c1=n?.r1c1;let o=this.parser.Parse(e);if(o.expression){let a=!1;if(this.parser.Walk(o.expression,s=>{if(s.type==="call"){let c=t[s.name.toUpperCase()];c&&(a=!0,s.name=c)}else s.type==="literal"&&typeof s.value=="boolean"&&(a=!0);return!0}),a)return"="+this.parser.Render(o.expression,{missing:"",boolean_true:r,boolean_false:i,r1c1:n?.r1c1})}return this.parser.Restore(),e}SetLanguage(e){if(this.language_model=e,!e)this.SetLanguageMap(),this.parser.flags.boolean_true="TRUE",this.parser.flags.boolean_false="FALSE";else{let t={};if(e.functions)for(let r of e.functions||[])t[r.base.toUpperCase()]=r.name;this.SetLanguageMap(t),e.boolean_false||(e.boolean_false=t.FALSE),e.boolean_true||(e.boolean_true=t.TRUE),this.parser.flags.boolean_true=e.boolean_true||"TRUE",this.parser.flags.boolean_false=e.boolean_false||"FALSE"}for(let t of this.sheets.list)t.FlushCellStyles()}};var rn=()=>({target:{row:0,column:0},area:new v({row:0,column:0}),empty:!0});var sa=100,nn={move_with_cells:!0,resize_with_cells:!0,movable:!0,resizable:!0,removable:!0,selectable:!0},Ne=class{data={...nn};get key(){return this.key_}rect;scaled_rect;temp={};view=[];dirty;key_=sa++;constructor(e={}){this.data={...nn,...JSON.parse(JSON.stringify(e))},e.rect&&(this.rect=B.Create(e.rect))}toJSON(){return{...this.data,rect:this.rect}}};var la=100,on=60,re=class l{static base_id=100;static default_sheet_name="Sheet1";default_style_properties;annotations=[];freeze={rows:0,columns:0};visible=!0;default_column_width=100;default_row_height=25;cells=new Tt;selection=rn();scroll_offset={x:0,y:0};name=l.default_sheet_name;tab_color;background_image;_image=void 0;flush_conditional_formats=!1;get image(){return this._image}conditional_formats=[];data_validation=[];outline;id_;row_height_map=new Map;column_width_=[];row_headers=[];column_headers=[];row_header_width=100;column_header_height=25;style_map=[];style_json_map=[];sheet_style={};row_styles={};column_styles={};row_pattern=[];cell_style=[];conditional_format_cache=[];conditional_format_checklist=[];get header_offset(){return{x:this.row_header_width,y:this.column_header_height}}get rows(){return this.cells.rows}get columns(){return this.cells.columns}get id(){return this.id_}set id(e){this.id_=e,this.id>=l.base_id&&(l.base_id=this.id+1)}constructor(e){this.default_style_properties=e,this.default_column_width=la,this.row_header_width=on,this.id_=l.base_id++}static Reset(){this.base_id=100}static Blank(e,t,r=30,i=20,n){let o=new l(e);return n&&o.UpdateDefaultRowHeight(n),t&&(o.name=t),r=Math.max(r,1),i=Math.max(i,1),o.cells.EnsureCell({row:r-1,column:i-1}),o}static UpdateStyle(e){if(typeof e.horizontal_align=="number"){let t=["","left","center","right"];e.horizontal_align=t[e.horizontal_align]||void 0}if(typeof e.vertical_align=="number"){let t=["","top","bottom","middle"];e.vertical_align=t[e.vertical_align]||void 0}}static FromJSON(e,t,r){let i=typeof e=="string"?JSON.parse(e):e,n=(c,d)=>{Object.keys(d).forEach(u=>{let h=Number(u)||0;c[h]=d[u]})};r||(r=new l(t)),i.default_column_width&&(r.default_column_width=i.default_column_width),i.default_row_height&&(r.default_row_height=i.default_row_height),i.conditional_formats&&(r.conditional_formats=i.conditional_formats),r.data_validation=(i.data_validations||[]).map(c=>({...c,target:(c.target||[]).map(d=>new v(d.start,d.end))})),i.id&&(r.id=i.id),i.name&&(r.name=i.name),i.tab_color&&(r.tab_color=i.tab_color),i.background_image&&(r.background_image=i.background_image);let o=c=>{let d=c;this.UpdateStyle(d),(d.font_size_value||d.font_size_unit)&&(d.font_size={unit:d.font_size_unit||"pt",value:d.font_size_value||10},d.font_size_unit=void 0,d.font_size_value=void 0),d.font_bold&&(d.bold=!0,d.font_bold=void 0),d.font_italic&&(d.italic=!0,d.font_italic=void 0),d.font_underline&&(d.underline=!0,d.font_underline=void 0),d.font_strike&&(d.strike=!0,d.font_strike=void 0),d.text_color&&(d.text_color!=="none"&&(d.text={text:d.text_color}),d.text_color=void 0),d.background&&(d.background!=="none"&&(d.fill={text:d.background}),d.background=void 0),d.border_top_color&&(d.border_top_color!=="none"&&(d.border_top_fill={text:d.border_top_color}),d.border_top_color=void 0),d.border_left_color&&(d.border_left_color!=="none"&&(d.border_left_fill={text:d.border_left_color}),d.border_left_color=void 0),d.border_bottom_color&&(d.border_bottom_color!=="none"&&(d.border_bottom_fill={text:d.border_bottom_color}),d.border_bottom_color=void 0),d.border_right_color&&(d.border_right_color!=="none"&&(d.border_right_fill={text:d.border_right_color}),d.border_right_color=void 0)},a=i.styles||i.cell_style_refs||[];for(let c of a)o(c);if(r.cell_style=[],a&&(i.cell_styles||[]).forEach(c=>{typeof c.ref=="number"&&(c.style=JSON.parse(JSON.stringify(a[c.ref])))}),r.cells.FromJSON(i.data),i.rows&&r.cells.EnsureRow(i.rows-1),i.columns&&r.cells.EnsureColumn(i.columns-1),i.data)if(ht(i.data))for(let c of i.data)c.style_ref&&(r.cell_style[c.column]||(r.cell_style[c.column]=[]),r.cell_style[c.column][c.row]=JSON.parse(JSON.stringify(a[c.style_ref])));else if(Or(i.data))for(let c of i.data){let d=c.row;for(let u of c.cells){let h=u.column;u.style_ref&&(r.cell_style[h]||(r.cell_style[h]=[]),r.cell_style[h][d]=JSON.parse(JSON.stringify(a[u.style_ref])))}}else for(let c of i.data){let d=c.column;for(let u of c.cells){let h=u.row;u.style_ref&&(r.cell_style[d]||(r.cell_style[d]=[]),r.cell_style[d][h]=JSON.parse(JSON.stringify(a[u.style_ref])))}}r.freeze.rows=0,r.freeze.columns=0,i.freeze&&(r.freeze.rows=i.freeze.rows||0,r.freeze.columns=i.freeze.columns||0),r.scroll_offset=i.scroll?{...i.scroll}:{x:0,y:0};for(let c of i.cell_styles||[])if(c.style&&(r.cell_style[c.column]||(r.cell_style[c.column]=[]),r.cell_style[c.column][c.row]=c.style,c.rows))for(let d=1;d<c.rows;d++)r.cell_style[c.column][c.row+d]=JSON.parse(JSON.stringify(c.style));r.sheet_style=i.sheet_style||{},r.column_styles={},r.row_styles={};let s=(c,d)=>{for(let u of Object.keys(c)){let h=Number(u),m=c[h];if(typeof m=="number"){let f=a[m];f&&(d[h]=JSON.parse(JSON.stringify(f)),o(d[h]))}else m&&(d[h]=m,o(d[h]))}};s(i.row_style,r.row_styles),s(i.column_style,r.column_styles),r.row_pattern=i.row_pattern||[],o(r.sheet_style||{});for(let c of r.row_pattern)o(c);if(r.row_height_map=new Map,i.row_height)for(let[c,d]of Object.entries(i.row_height))r.row_height_map.set(Number(c),d);if(r.row_height_map.size>0){let c=Math.max(...r.row_height_map.keys());r.cells.EnsureRow(c)}return r.column_width_=[],n(r.column_width_,i.column_width||{}),r.column_width_.length&&r.cells.EnsureColumn(r.column_width_.length-1),r.annotations=(i.annotations||[]).map(c=>new Ne(c)),i.selection&&(r.selection=JSON.parse(JSON.stringify(i.selection))),r.visible=!0,typeof i.visible<"u"&&(r.visible=!!i.visible),r}AddValidation(e){this.data_validation.push({...e,target:(e.target||[]).map(t=>new v(t.start,t.end))})}RemoveValidations(e){let t=new v(e.start,e.end);this.data_validation=this.data_validation.filter(r=>(r.target=r.target.filter(i=>!t.Equals2(i)),r.target.length>0))}GetValidation(e){let t=[];for(let r of this.data_validation)for(let i of r.target)if(i.Contains(e)){t.push(r);break}return t}Activate(e){if(this.background_image){let t=Ut(this.background_image);t&&(this._image=e.Create("img"),this._image.src=t)}}MergeCells(e){e=e.Clone();let t=[...this.cells.Iterate(e,!0)];for(let[r,i]of t.entries())i.merge_area=e,i.render_clean=[],r&&i.Reset()}UnmergeCells(e){for(let t of this.cells.Iterate(e,!1))if(!t.merge_area||!e.Equals(t.merge_area)){console.warn("area mismatch");return}for(let t of this.cells.Iterate(e,!1))t.merge_area=void 0,t.render_clean=[]}UpdateDefaultRowHeight(e,t=1){if(typeof window<"u"){let r=I.Composite([this.default_style_properties,this.sheet_style]),i=I.CompositeFont(e.grid_cell_font_size,r,t,e),o=Ge(i.font,i.variants).height*1.25;this.default_row_height<o&&(this.default_row_height=o)}}SetRowHeaders(e){this.row_headers=e.map(t=>t===void 0?"":t.toString()),this.row_headers&&this.cells.EnsureRow(this.row_headers.length-1)}SetColumnHeaders(e){this.column_headers=e.map(t=>t===void 0?"":t.toString()),e&&this.cells.EnsureColumn(e.length-1)}RowHeader(e){return this.row_headers?this.row_headers.length>e?this.row_headers[e]:"":e+1}ColumnHeader(e){let t="";if(this.column_headers)return this.column_headers.length>e?this.column_headers[e]:"";for(;;){let r=e%26;if(t=String.fromCharCode(65+r)+t,e=Math.floor(e/26),e)e--;else break}return t}GetRowHeight(e){let t=this.row_height_map.get(e);return typeof t>"u"?this.default_row_height:t}SetRowHeight(e,t){return this.row_height_map.set(e,t),this.cells.EnsureRow(e),t}GetColumnWidth(e){let t=this.column_width_[e];return typeof t>"u"?this.default_column_width:t}SetColumnWidth(e,t){return this.column_width_[e]=t,this.cells.EnsureColumn(e),t}Delta(e,t){let r={},i=[...Object.keys(e),...Object.keys(t)];for(let n of i){let o=e[n],a=t[n];typeof o=="object"&&typeof a=="object"?JSON.stringify(o)!==JSON.stringify(a)&&(r[n]=a):o!==a&&(r[n]=a)}return r}UpdateCellStyle(e,t,r=!0){let{row:i,column:n}=e;this.cell_style[n]||(this.cell_style[n]=[]);let o=this.CompositeStyleForCell(e,!1,!1,void 0,!1),a=I.Composite([this.default_style_properties,o,I.Merge(this.cell_style[n][i]||{},t,r)]),s=this.Delta(o,a);this.cell_style[n][i]=s,this.BleedFlush({start:e,end:e})}Invalidate(e){for(let t of this.cells.Iterate(this.RealArea(e),!1))t.render_clean=[]}UpdateAreaStyle(e,t={},r=!0){if(e)if(e.entire_sheet)this.UpdateSheetStyle(t,r);else if(e.entire_column)for(let i=e.start.column;i<=e.end.column;i++)this.UpdateColumnStyle(i,t,r);else if(e.entire_row)for(let i=e.start.row;i<=e.end.row;i++)this.UpdateRowStyle(i,t,r);else for(let i of e)this.UpdateCellStyle(i,t,r)}HasCellStyle(e){return!!(this.cell_style[e.column]&&this.cell_style[e.column][e.row]||this.row_styles[e.row]||this.column_styles[e.column]||this.row_pattern.length)}NextVisibleColumn(e){for(++e;this.column_width_[e]===0;e++);return e}PreviousVisibleColumn(e){for(--e;e>=0&&this.column_width_[e]===0;e--);return e}NextVisibleRow(e){for(++e;this.GetRowHeight(e)===0;e++);return e}PreviousVisibleRow(e){for(--e;e>=0&&this.GetRowHeight(e)===0;e--);return e}TableRow(e,t){let r={alternate:!1,header:t===e.area.start.row,last:!1,totals:e.totals_row&&t===e.area.end.row};if(r.header||r.totals)return r;if(!(e.totals_row&&this.GetRowHeight(e.area.end.row)>0)){let a=e.area.end.row;for(;a>=e.area.start.row;a--)if(this.GetRowHeight(a)){r.last=a===t;break}}let n=e.area.start.row+1,o=t-n;for(let[a,s]of this.row_height_map.entries())if(!(a<n)){if(a>e.area.end.row)break;s||o--}return r.alternate=o%2===1,r}SurroundingStyle(e,t){let r=[{},{},{},{},{},{},{},{},{},{}],i=e.column+1,n=e.column-1,o=e.row+1,a=e.row-1;for(;this.column_width_[i]===0;i++);for(;this.GetRowHeight(o)===0;o++);for(;n>=0&&this.column_width_[n]===0;n--);for(;a>=0&&this.GetRowHeight(a)===0;a--);return n>=0&&a>=0&&(r[7]=this.CellStyleData({row:a,column:n},t)||{}),n>=0&&(r[4]=this.CellStyleData({row:e.row,column:n},t)||{},r[1]=this.CellStyleData({row:o,column:n},t)||{}),a>=0&&(r[8]=this.CellStyleData({row:a,column:e.column},t)||{},r[9]=this.CellStyleData({row:a,column:i},t)||{}),r[6]=this.CellStyleData({row:e.row,column:i},t)||{},r[2]=this.CellStyleData({row:o,column:e.column},t)||{},r[3]=this.CellStyleData({row:o,column:i},t)||{},r}CellStyleData(e,t){let r=this.cells.GetCell(e);if(r){if(!r.style){let i=this.GetStyleIndex(this.CompositeStyleForCell(e));r.style=this.style_map[i]}if(r.table){let i=r.table.theme||t;if(i){let n=JSON.parse(JSON.stringify(r.style)),o=this.TableRow(r.table,e.row);return o.header?i.header&&(n=I.Composite([n,i.header])):o.totals?i.total&&(n=I.Composite([n,i.total])):o.alternate?i.odd&&(n=I.Composite([n,i.odd])):i.even&&(n=I.Composite([n,i.even])),n}}return r.style}}GetCopyStyle(e){return this.CompositeStyleForCell(e,!0,!1,void 0,!1)}CellData(e){let t=this.cells.EnsureCell(e);if(t.rendered_type)return t;let r,i;if(t.calculated_type?(i=t.calculated,r=t.calculated_type):(i=t.value,r=t.type),!t.style){let n=this.GetStyleIndex(this.CompositeStyleForCell(e));t.style=this.style_map[n]}if(!r||i===null||typeof i>"u")t.formatted="",t.rendered_type=2;else if(r===3)isNaN(i)?t.formatted=typeof t.style.nan>"u"?"NaN":t.style.nan:t.formatted=this.FormatNumber(i,t.style.number_format),t.rendered_type=3;else if(r===7)t.formatted="#"+(i||"ERR?"),t.rendered_type=7;else if(r===4)t.formatted=i.toString().toUpperCase(),t.rendered_type=4;else if(r===1&&t.calculated===void 0)t.formatted="",t.rendered_type=2;else if(r===8){let n=i;if(isNaN(n.real)||isNaN(n.imaginary))t.formatted=typeof t.style.nan>"u"?"NaN":t.style.nan;else{let o=L.Get(t.style.number_format||"",!0);t.formatted=o.FormatComplex(n)}t.rendered_type=8}else if(r===10){if(isNaN(i.value))t.formatted=typeof t.style.nan>"u"?"NaN":t.style.nan,t.formatted+=" "+i.unit;else{let n=L.Get(t.style.number_format||"",!0);t.formatted=n.FormatDimensionedQuantity(i)}t.rendered_type=10}else r===6?(t.formatted="\u{1D453}()",t.rendered_type=2):(t.formatted=this.FormatNumber(i,t.style.number_format),t.rendered_type=2);return t}FormatNumber(e,t=""){let r=L.Get(t).FormatParts(e);return r.length?r.length===1&&!r[0].flag?r[0].text||"":r:""}SetHeaderSize(e=on,t=this.default_row_height){this.row_header_width=e,this.column_header_height=t}GetStyle(e){return this.style_map[e]}InsertRows(e=0,t=1){if(e)for(let c=0;c<this.cells.columns;c++){let d=this.cells.GetCell({row:e-1,column:c},!1);if(d&&d.area){let u=this.cells.GetCell({row:e,column:c},!1);if(u&&u.area&&u.area.Equals(d.area))return!1}}t<0?this.cells.DeleteRows(e,-t):this.cells.InsertRows(e,t);let r={},i={};for(let c=e;c<this.cells.rows;c++)for(let d=0;d<this.cells.columns;d++){let u=this.cells.GetCell({row:c,column:d},!1);u&&(u.area&&!i[u.area.spreadsheet_label]&&(i[u.area.spreadsheet_label]=u.area),u.merge_area&&!r[u.merge_area.spreadsheet_label]&&(r[u.merge_area.spreadsheet_label]=u.merge_area))}for(let c of Object.keys(i)){let d=i[c],u=new v({row:d.start.row+t,column:d.start.column},{row:d.end.row+t,column:d.end.column});for(let h of u){let m=this.cells.GetCell(h,!0);m.area=u}}for(let c of Object.keys(r)){let d=r[c],u={row:d.start.row,column:d.start.column};d.start.row>=e&&(u.row+=t);let h=new v(u,{row:d.end.row+t,column:d.end.column});for(let m of h){let f=this.cells.GetCell(m,!0);f.merge_area=h}}let n=Object.keys(this.row_styles),o={};n.forEach(c=>{let d=Number(c);d<e?o[d]=this.row_styles[d]:t<0&&d<e-t||(o[d+t]=this.row_styles[d])}),this.row_styles=o;let a=[];if(t<0)a=[e,-t];else{a=[e,0];for(let c=0;c<t;c++)a.push(void 0)}this.cell_style.forEach(c=>{c&&c.length>=e&&c.splice.apply(c,a)});let s=new Map;if(t>0)for(let[c,d]of this.row_height_map)c>=e?s.set(c+t,d):s.set(c,d);else if(t<0)for(let[c,d]of this.row_height_map)c>=e?c>=e-t&&s.set(c+t,d):s.set(c,d);return this.row_height_map=s,this.FlushCellStyles(),!0}InsertColumns(e=0,t=1){if(e)for(let s=0;s<this.cells.rows;s++){let c=this.cells.GetCell({row:s,column:e-1},!1);if(c&&c.area){let d=this.cells.GetCell({row:s,column:e},!1);if(d&&d.area&&d.area.Equals(c.area))return!1}}t<0?this.cells.DeleteColumns(e,-t):this.cells.InsertColumns(e,t);let r={},i={};for(let s=e;s<this.cells.columns;s++)for(let c=0;c<this.cells.rows;c++){let d=this.cells.GetCell({row:c,column:s},!1);d&&(d.area&&!i[d.area.spreadsheet_label]&&(i[d.area.spreadsheet_label]=d.area),d.merge_area&&!r[d.merge_area.spreadsheet_label]&&(r[d.merge_area.spreadsheet_label]=d.merge_area))}for(let s of Object.keys(i)){let c=i[s],d=new v({row:c.start.row,column:c.start.column+t},{row:c.end.row,column:c.end.column+t});for(let u of d){let h=this.cells.GetCell(u,!0);h.area=d}}for(let s of Object.keys(r)){let c=r[s],d={row:c.start.row,column:c.start.column};c.start.column>=e&&(d.column+=t);let u=new v(d,{row:c.end.row,column:c.end.column+t});for(let h of u){let m=this.cells.GetCell(h,!0);m.merge_area=u}}let n=Object.keys(this.column_styles),o={};n.forEach(s=>{let c=Number(s);c<e?o[c]=this.column_styles[c]:t<0&&c<e-t||(o[c+t]=this.column_styles[c])}),this.column_styles=o;let a=[];if(t<0)a=[e,-t];else{a=[e,0];for(let s=0;s<t;s++)a.push(void 0)}return this.cell_style.splice.apply(this.cell_style,a),this.column_width_.splice.apply(this.column_width_,a),this.FlushCellStyles(),!0}ClearArea(e){for(let t of this.cells.Iterate(this.RealArea(e),!1))t.Reset()}SetAreaValues2(e,t){e=this.RealArea(e),this.cells.SetArea(e,t)}SetArrayValue(e,t){e=this.RealArea(e);for(let i of this.cells.Iterate(e,!0))i.SetArray(e);this.cells.GetCell(e.start,!0).SetArrayHead(e,t)}SetCellValue(e,t){this.cells.GetCell(e,!0).Set(t)}TablesFromArea(e,t=!1){if(N(e)){let i=this.cells.GetCell(e,!1);return i?.table&&(!t||e.row===i.table.area.start.row)?[i.table]:[]}let r=new Set;for(let i=e.start.row;i<=e.end.row;i++)for(let n=e.start.column;n<=e.end.column;n++){let o=this.cells.GetCell({row:i,column:n},!1);o?.table&&!r.has(o.table)&&(!t||i===o.table.area.start.row)&&r.add(o.table)}return Array.from(r.values())}RealArea(e,t=!1){let r=e.start,i=e.end;return e.entire_row&&(r.column=0,r.absolute_column=!1,i.column=this.cells.columns-1,i.absolute_column=!1),e.entire_column&&(r.row=0,r.absolute_row=!1,i.row=this.cells.rows-1,i.absolute_row=!1),t&&(i.row>=this.rows&&(i.row=this.rows-1,i.absolute_row=!1),i.column>=this.columns&&(i.column=this.columns-1,i.absolute_column=!1)),new v(r,i)}GetCellStyle(e,t=!1){if(N(e))return this.CompositeStyleForCell(e,!0,!1,t);if(e.start.row===e.end.row&&e.start.column===e.end.column)return[[this.CompositeStyleForCell(e.start,!0,!1,t)]];let r=[];for(let i=e.start.row;i<=e.end.row;i++){let n=[];for(let o=e.start.column;o<=e.end.column;o++)n.push(this.CompositeStyleForCell({row:i,column:o},!0,!1,t));r.push(n)}return r}FormattedCellValue(e){let t=this.CellData(e);if(t)return typeof t.formatted=="string"?t.formatted:t.formatted?t.formatted.map(r=>{switch(r.flag){case 1:return" ";case 2:return" ";default:return r.text}}).join(""):t.value}GetFormattedRange(e,t=e){if(e.row===t.row&&e.column===t.column)return this.FormattedCellValue(e);let r=[];for(let i=e.row;i<=t.row;i++){let n=[];for(let o=e.column;o<=t.column;o++)n.push(this.FormattedCellValue({row:i,column:o}));r.push(n)}return r}NumberFormatsAndColors(e,t){let r=i=>{i.number_format&&(t[i.number_format]=1),ee(i.text)&&(e[i.text.text]=1),ee(i.fill)&&(e[i.fill.text]=1),ee(i.border_top_fill)&&(e[i.border_top_fill.text]=1),ee(i.border_left_fill)&&(e[i.border_left_fill.text]=1),ee(i.border_right_fill)&&(e[i.border_right_fill.text]=1),ee(i.border_bottom_fill)&&(e[i.border_bottom_fill.text]=1)};r(this.sheet_style);for(let i in this.row_styles)r(this.row_styles[i]);for(let i in this.column_styles)r(this.column_styles[i]);for(let i of this.row_pattern)r(i);for(let i of this.cell_style)if(i)for(let n of i)n&&r(n)}CompressCellStyles(e){let t=[];for(let r=0;r<e.length;r++){let i=e[r];if(i)for(let n=0;n<i.length;n++){let o=i[n];if(o){let a=n+1;for(;a<i.length&&i[a]===o;a++);a>n+1?t.push({row:n,column:r,ref:o,rows:a-n}):t.push({row:n,column:r,ref:o}),n=a-1}}}return t}toJSON(e={}){let t=(S,A)=>{let E={};for(let R=0;R<S.length;R++)typeof S[R]<"u"&&S[R]!==A&&(E[R]=S[R]);if(Object.keys(E).length)return E},r=[{}],i={},n=[],o=JSON.stringify({});for(let S=0;S<this.cell_style.length;S++){let A=this.cell_style[S];if(A){n[S]=[];for(let E=0;E<A.length;E++)if(A[E]){let R=I.Serialize(A[E]);if(R!==o){let z=i[R];typeof z!="number"&&(i[R]=z=r.length,r.push(A[E])),n[S][E]=z}}}}let a=S=>{let A=I.Serialize(S);if(A===o)return 0;let E=i[A];return typeof E!="number"&&(i[A]=E=r.length,r.push(S)),E};r=JSON.parse(JSON.stringify(r));let s=JSON.parse(JSON.stringify(this.sheet_style)),c=JSON.parse(JSON.stringify(this.row_pattern)),d={},u={};for(let S of Object.keys(this.column_styles)){let A=Number(S),E=this.column_styles[A];if(E){let R=a(E);R&&(d[A]=R)}}if(this.row_pattern&&this.row_pattern.length&&e.apply_row_pattern){let S=this.rows+1;for(let A of Object.keys(this.row_styles)){let E=Number(A);!isNaN(E)&&E>=S&&(S=E+1)}for(let A=0;A<S;A++){let E=this.row_pattern[A%this.row_pattern.length],R=this.row_styles[A]||{},z=I.Composite([E,R]),K=a(z);K&&(u[A]=K)}}else for(let S of Object.keys(this.row_styles)){let A=Number(S),E=this.row_styles[A];if(E){let R=a(E);R&&(u[A]=R)}}let h=(S={},A={})=>{let E={...A,...S};if(ee(E))return E.text=se.MeasureColorARGB(E.text),E;if(Ke(E))return E};if(e.export_colors){let S=[];for(let A of[r,[s],c])if(Array.isArray(A))for(let E of A)S.push(E);else for(let E of Object.keys(A))S.push(A[E]);for(let A of S){let E=h(A.border_top_fill,I.DefaultProperties.border_top_fill);E!==void 0&&(A.border_top_fill=E),E=h(A.border_left_fill,I.DefaultProperties.border_left_fill),E!==void 0&&(A.border_left_fill=E),E=h(A.border_right_fill,I.DefaultProperties.border_right_fill),E!==void 0&&(A.border_right_fill=E),E=h(A.border_bottom_fill,I.DefaultProperties.border_bottom_fill),E!==void 0&&(A.border_bottom_fill=E),ee(A.fill)&&(A.fill.text=se.MeasureColorARGB(A.fill.text)),ee(A.text)&&(A.text.text=se.MeasureColorARGB(A.text.text))}}let m={calculated_value:!!e.rendered_values,preserve_type:!!e.preserve_type,expand_arrays:!!e.expand_arrays,decorated_cells:!!e.decorated_cells,nested:!0,cell_style_refs:n,tables:!!e.tables},f=this.cells.toJSON(m),p=f.data,{rows:b,columns:g}=f;e.shrink?(b+=2,g+=1):(b=this.rows,g=this.columns);for(let S of this.annotations)S.data.extent||this.CalculateAnnotationExtent(S),S.data.extent&&(b=Math.max(b,S.data.extent.row+1),g=Math.max(g,S.data.extent.column+1));let x=this.CompressCellStyles(n),y=this.conditional_formats.length?JSON.parse(JSON.stringify(this.conditional_formats.map(S=>({...S,internal:void 0})))):void 0,w=this.data_validation.length?JSON.parse(JSON.stringify(this.data_validation)):void 0,_={};for(let[S,A]of this.row_height_map.entries())_[S]=A;let C={id:this.id,name:this.name,tab_color:this.tab_color,data:p,sheet_style:s,rows:b,columns:g,cell_styles:x,styles:r,row_style:u,column_style:d,conditional_formats:y,data_validations:w,row_pattern:c.length?c:void 0,default_row_height:this.default_row_height,default_column_width:this.default_column_width,row_height:_,column_width:t(this.column_width_,this.default_column_width),selection:JSON.parse(JSON.stringify(this.selection)),annotations:JSON.parse(JSON.stringify(this.annotations))};return this.visible||(C.visible=this.visible),(this.scroll_offset.x||this.scroll_offset.y)&&(C.scroll=this.scroll_offset),this.background_image&&(C.background_image=this.background_image),(this.freeze.rows||this.freeze.columns)&&(C.freeze=this.freeze),C}FlushCellStyles(){this.style_map=[],this.style_json_map=[],this.cells.FlushCellStyles()}ImportData(e){let t=e.styles;e.outline&&(this.outline=e.outline);let r=e.sheet_style;r&&this.UpdateAreaStyle(new v({row:1/0,column:1/0},{row:1/0,column:1/0}),t[r]);let i=e.column_styles;if(i)for(let o=0;o<i.length;o++)i[o]&&this.UpdateAreaStyle(new v({row:1/0,column:o},{row:1/0,column:o}),t[i[o]]);if(e.row_styles)for(let[o,a]of e.row_styles.entries())a&&this.UpdateAreaStyle(new v({row:o,column:1/0}),t[a]);this.cells.FromJSON(e.cells),e.name&&(this.name=e.name||"");for(let o of this.cells.Iterate())o.spill&&(o.spill.start.sheet_id||o.spill.SetSheetID(this.id));e.tab_color&&(this.tab_color=e.tab_color);let n=this.cell_style;for(let o of e.cells)o.style_ref&&(n[o.column]||(n[o.column]=[]),n[o.column][o.row]=t[o.style_ref]);for(let o=0;o<e.column_widths.length;o++)typeof e.column_widths[o]<"u"&&this.SetColumnWidth(o,e.column_widths[o]);for(let o=0;o<e.row_heights.length;o++)typeof e.row_heights[o]<"u"&&this.SetRowHeight(o,e.row_heights[o]);for(let o of e.annotations||[])this.annotations.push(new Ne(o));for(let o of e.conditional_formats||[])this.conditional_formats.push(o);for(let o of e.data_validations||[])this.AddValidation(o);e.hidden&&(this.visible=!1)}CalculateAnnotationExtent(e){if(e.data.layout){e.data.extent={...e.data.layout.br.address};return}let t=1e3;e.data.extent={row:0,column:0};let r=e.rect?.right;if(r&&this.default_column_width){for(let n=0;r>=0&&n<t;n++)if(r-=this.GetColumnWidth(n),r<0){e.data.extent.column=n;break}}let i=e.rect?.bottom;if(i&&this.default_row_height){for(let n=0;i>=0&&n<t;n++)if(i-=this.GetRowHeight(n),i<0){e.data.extent.row=n;break}}}UpdateSheetStyle(e,t=!0){this.sheet_style=I.Merge(this.sheet_style,e,t);let r=Object.keys(e);for(let i of this.cell_style)if(i)for(let n of i)n&&r.forEach(o=>delete n[o]);for(let i of Object.keys(this.row_styles))r.forEach(n=>delete this.row_styles[i][n]);for(let i of Object.keys(this.column_styles))r.forEach(n=>delete this.column_styles[i][n]);this.FlushCellStyles()}UpdateRowStyle(e,t,r=!0){this.row_styles[e]=I.Merge(this.row_styles[e]||{},t,r);let i=Object.keys(t);for(let n of this.cell_style)n&&n[e]&&i.forEach(o=>delete n[e][o]);for(let n=0;n<this.cells.columns;n++)if(this.column_styles[n]){let o=this.column_styles[n],a=this.cell_style[n]?this.cell_style[n][e]||{}:{};for(let s of i)typeof o[s]<"u"&&(a[s]=t[s]);Object.keys(a).length&&(this.cell_style[n]||(this.cell_style[n]=[]),this.cell_style[n][e]=JSON.parse(JSON.stringify(a)))}for(let n of this.cells.Iterate(this.RealArea(v.FromRow(e))))n.FlushStyle()}UpdateColumnStyle(e,t,r=!0){this.column_styles[e]=I.Merge(this.column_styles[e]||{},t,r);let i=Object.keys(t);if(this.cell_style[e])for(let n of this.cell_style[e])n&&i.forEach(o=>delete n[o]);for(let n of this.cells.Iterate(this.RealArea(v.FromColumn(e))))n.FlushStyle()}BleedFlush(e){let t=[Math.max(0,e.start.row-1),e.end.row+1],r=[Math.max(0,e.start.column-1),e.end.column+1];for(let i=t[0];i<=t[1];i++)for(let n=r[0];n<=r[1];n++)this.cells.GetCell({row:i,column:n},!1)?.FlushStyle()}FlushConditionalFormats(){this.flush_conditional_formats=!0}ApplyConditionalFormats(){let e=this.flush_conditional_formats;for(let i of this.conditional_formats)if(i.internal?.vertex?.updated){e=!0;break}if(!e)return;this.flush_conditional_formats=!1;let t=[],r=[...this.conditional_format_checklist];this.conditional_format_checklist=[];for(let i of this.conditional_formats){i.internal?.vertex?.updated&&(i.internal.vertex.updated=!1);let n=JSON.parse(JSON.stringify(i.area));(n.start.row===null||n.end.row===null)&&(n.start.row=0,n.end.row=this.cells.rows-1),(n.start.column===null||n.end.column===null)&&(n.start.column=0,n.end.column=this.cells.columns-1);let o=i.internal?.vertex?.result;if(i.type==="gradient"){if(o&&i.internal?.gradient){let a=i.property??"fill";if(o.type===9)for(let s=n.start.row;s<=n.end.row;s++)for(let c=n.start.column;c<=n.end.column;c++){let d=o.value[c-n.start.column][s-n.start.row];if(d.type===3){t[s]||(t[s]=[]),t[s][c]||(t[s][c]=[]);let u=i.internal.gradient.Interpolate(d.value);t[s][c].push({[a]:u})}}else if(o.type===3){let s=i.internal.gradient.Interpolate(o.value);for(let c=n.start.row;c<=n.end.row;c++){t[c]||(t[c]=[]);for(let d=n.start.column;d<=n.end.column;d++)t[c][d]||(t[c][d]=[]),t[c][d].push({[a]:s})}}r.push(n),this.conditional_format_checklist.push(n)}}else if(i.type==="data-bar"){if(o){if(o.type===9)for(let a=n.start.row;a<=n.end.row;a++)for(let s=n.start.column;s<=n.end.column;s++){let c=o.value[s-n.start.column][a-n.start.row];if(c.type===9){let[d,u]=c.value[0];d.type===3&&u.type===3&&(t[a]||(t[a]=[]),t[a][s]||(t[a][s]=[]),t[a][s].push({databar:{value:d.value,zero:u.value,fill:i.fill,negative:i.negative,hide_values:i.hide_values}}))}}r.push(n),this.conditional_format_checklist.push(n)}}else if(o){if(o.type===9)for(let a=n.start.row;a<=n.end.row;a++)for(let s=n.start.column;s<=n.end.column;s++){let c=o.value[s-n.start.column][a-n.start.row];c&&(c.type===4||c.type===3)&&c.value&&(t[a]||(t[a]=[]),t[a][s]||(t[a][s]=[]),t[a][s].push(i.style))}else if((o.type===4||o.type===3)&&o.value)for(let a=n.start.row;a<=n.end.row;a++){t[a]||(t[a]=[]);for(let s=n.start.column;s<=n.end.column;s++)t[a][s]||(t[a][s]=[]),t[a][s].push(i.style)}r.push(n),this.conditional_format_checklist.push(n)}}for(let i of r)this.BleedFlush(i);this.conditional_format_cache=t}ConditionalFormatForCell(e){return this.conditional_format_cache[e.row]?this.conditional_format_cache[e.row][e.column]||[]:[]}CompositeStyleForCell(e,t=!0,r=!0,i=!0,n=!0){let{row:o,column:a}=e,s=[];return i&&s.push(this.default_style_properties),s.push(this.sheet_style),r&&this.row_pattern.length&&s.push(this.row_pattern[o%this.row_pattern.length]),this.row_styles[o]&&s.push(this.row_styles[o]),this.column_styles[a]&&s.push(this.column_styles[a]),t&&this.cell_style[a]&&this.cell_style[a][o]&&s.push(this.cell_style[a][o]),n&&s.push(...this.ConditionalFormatForCell(e)),I.Composite(s)}GetStyleIndex(e){let t=JSON.stringify(e);for(let i=0;i<this.style_json_map.length;i++)if(t===this.style_json_map[i])return i;let r=this.style_map.length;return this.style_map.push(JSON.parse(t)),this.style_json_map.push(t),r}};var an={"red-green":{color_space:"RGB",stops:[{value:0,color:{theme:5,tint:.5}},{value:1,color:{theme:9,tint:.5}}]},"red-yellow-green":{color_space:"RGB",stops:[{value:0,color:{theme:5,tint:.5}},{value:.5,color:{theme:7,tint:.5}},{value:1,color:{theme:9,tint:.5}}]},"green-red":{color_space:"RGB",stops:[{value:0,color:{theme:9,tint:.5}},{value:1,color:{theme:5,tint:.5}}]},"green-yellow-red":{color_space:"RGB",stops:[{value:0,color:{theme:9,tint:.5}},{value:.5,color:{theme:7,tint:.5}},{value:1,color:{theme:5,tint:.5}}]}};var Qt=class l{static type="vertex";type=l.type;color=0;edges_in=new Set;edges_out=new Set;get has_inbound_edges(){return this.edges_in.size>0}get has_outbound_edges(){return this.edges_out.size>0}Reset(){for(let e of this.edges_out)e.RemoveDependency(this);for(let e of this.edges_in)e.RemoveDependent(this);this.edges_out.clear(),this.edges_in.clear()}ClearDependencies(){for(let e of this.edges_in)e.RemoveDependent(this);this.edges_in.clear()}AddDependent(e){e!==this&&(this.edges_out.has(e)||this.edges_out.add(e))}RemoveDependent(e){this.edges_out.delete(e)}AddDependency(e){e!==this&&(this.edges_in.has(e)||this.edges_in.add(e))}RemoveDependency(e){this.edges_in.delete(e)}LinkTo(e){this.AddDependent(e),e.AddDependency(this)}DependsOn(e){this.AddDependency(e),e.AddDependent(this)}LoopCheck(){let e=[this];for(;e.length;){let t=e[e.length-1],r=!0;if(t.color!==2){t.color=1;for(let i of t.edges_out){if(i.color===1)return this.color=0,!0;i.color===0&&i.edges_out.size&&(e.push(i),r=!1)}}r&&(t.color=2,e.pop())}return this.color=2,!1}};var Ze=class extends Qt{dirty=!1};var sn={error:"NOTIMPL"},xe=()=>({type:7,value:"N/A"}),fe=()=>({type:7,value:"EXPR"});var ve=()=>({type:7,value:"DIV/0"}),M=()=>({type:7,value:"ARG"}),U=()=>({type:7,value:"VALUE"}),$=()=>({type:7,value:"REF"}),Yr=()=>({type:7,value:"NAME"}),ln=()=>({type:7,value:"SPILL"}),Zt=()=>({type:7,value:"UNK"});var ze=class l extends Ze{static type="spreadsheet-vertex";reference;error=0;address;result={type:0};expression={type:"missing",id:-1};expression_error=!1;short_circuit=!1;type=l.type;get array_head(){return this.address?!!this.reference&&!!this.reference.area&&this.reference.area.start.column===this.address.column&&this.reference.area.start.row===this.address.row:!1}TakeReferenceValue(){this.reference&&(this.result=Q(this.reference.GetValue()))}Calculate(e){if(this.dirty){if(this.color===0&&this.LoopCheck()&&(this.dirty=!1,this.edges_in.size)){this.reference&&(this.array_head||this.reference.type===1)&&this.reference.SetCalculationError("LOOP");for(let t of this.edges_out)t.Calculate(e);return}for(let t of this.edges_in)if(t.dirty)return;if(this.reference){if(this.reference.type===1){this.short_circuit=!1;let t=e.CalculationCallback.call(e,this);if(this.result=t.value,this.short_circuit)return;t.volatile&&e.volatile_list.push(this)}else this.result=this.reference.GetValue4();if(this.array_head)e.SpreadCallback.call(e,this,this.result);else if(this.reference.type===1)if(this.result.type===9){let t=e.SpillCallback.call(e,this,this.result);if(t)for(let r of t)for(let i of r.edges_out)i.dirty=!0,i.Calculate(e)}else this.reference.SetCalculatedValue(this.result.value,this.result.type)}else console.info("skip dirty constant? [or dangling...]");this.dirty=!1;for(let t of this.edges_out)t.dirty&&e.calculation_list.push(t)}}};var Be=class l extends Ze{static type="array-vertex";static list=[];type=l.type;area;static GetVertex(e){for(let t of this.list)if(t.area.start.sheet_id===e.start.sheet_id&&t.area.Equals(e))return[t,!1];return[new l(e),!0]}static Clear(){this.list=[]}static GetContainingArrays(e){let t=[];for(let r of this.list)r.area.start.sheet_id===e.sheet_id&&r.area.Contains(e)&&t.push(r);return t}static CreateImplicitEdges(e,t){for(let r of this.list)r.area.start.sheet_id===t.sheet_id&&r.area.Contains(t)&&r.DependsOn(e)}constructor(e){super(),this.area=e.Clone(),l.list.push(this)}RemoveDependent(e){super.RemoveDependent(e),this.edges_out.size||(this.Reset(),l.list=l.list.filter(t=>t!==this))}Calculate(e){if(this.dirty){if(this.color===0&&this.LoopCheck()&&(this.dirty=!1,this.edges_in.size)){for(let t of this.edges_out)t.Calculate(e);return}for(let t of this.edges_in)if(t.dirty)return;this.dirty=!1;for(let t of this.edges_out)t.Calculate(e)}}};var tr=class{vertices=[[]];volatile_list=[];calculation_list=[];spill_data=[];loop_hint;leaf_vertices=new Set;dirty_list=[];loop_check_required=!1;IsSpreadsheetVertex(e){return e.type===ze.type}FlushTree(){this.dirty_list=[],this.volatile_list=[],this.vertices=[[]],this.leaf_vertices.clear(),Be.Clear()}ResolveArrayHead(e){if(!e.sheet_id)throw new Error("resolve array head with no sheet id");let t=this.model.sheets.Find(e.sheet_id)?.cells;if(!t)throw new Error("no cells? sheet id "+e.sheet_id);let r=t.data[e.row];if(r){let i=r[e.column];if(i&&i.area){let n={row:i.area.start.row,column:i.area.start.column,sheet_id:e.sheet_id};return console.info("array head",e,n),n}}return e}*IterateVertices(e,t=!1){for(let r of Kt.Iterate(e)){let i=this.GetVertex(r,t);i&&(yield i)}}GetVertex(e,t){if(!e.sheet_id)throw console.info(JSON.stringify({address:e,create:t})),console.trace(),new Error("getvertex with no sheet id");let r=this.model.sheets.Find(e.sheet_id)?.cells;if(!r)throw new Error("no cells? sheet id "+e.sheet_id);if(!this.vertices[e.sheet_id]){if(!t)return;this.vertices[e.sheet_id]=[]}if(this.vertices[e.sheet_id][e.column]){let n=this.vertices[e.sheet_id][e.column][e.row];if(n)return n;if(!t)return}else{if(!t)return;this.vertices[e.sheet_id][e.column]=[]}let i=new ze;return i.address={row:e.row,column:e.column,absolute_row:e.absolute_row,absolute_column:e.absolute_column,sheet_id:e.sheet_id},i.reference=r.EnsureCell(e),this.vertices[e.sheet_id][e.column][e.row]=i,Be.CreateImplicitEdges(i,e),i}RemoveVertex(e){if(!e.sheet_id)throw new Error("removevertex with no sheet id");let t=this.GetVertex(e,!1);t&&(t.Reset(),this.vertices[e.sheet_id][e.column][e.row]=void 0)}ResetVertex(e){let t=this.GetVertex(e,!1);t&&t.Reset()}RIBcount=0;ResetInbound(e,t=!1,r=!0,i=!1){this.RIBcount++;let n=this.GetVertex(e,r);if(!n){if(t){let a=Be.GetContainingArrays(e);for(let s of a)this.SetVertexDirty(s)}return}let o=[];if(i&&(o=Array.from(n.edges_in)),n.ClearDependencies(),t&&this.SetVertexDirty(n),i){n.has_outbound_edges||this.RemoveVertex(e);for(let a of o)if(!a.has_inbound_edges&&!a.has_outbound_edges){let s=a;s.address&&this.RemoveVertex(s.address)}}}ResetLoopState(){for(let e of this.vertices)if(e){for(let t of e)if(t)for(let r of t)r&&(r.color=r.edges_out.size?0:2)}for(let e of this.leaf_vertices)e.color=2}LoopCheck(e=!1){if(!this.loop_check_required&&!e)return!1;let t=[];for(let i of this.vertices)if(i){for(let n of i)if(n)for(let o of n)o&&(o.color=o.edges_out.size?0:2,t.push(o))}let r=[];for(let i of t)if(i.color===0){for(i.color=1,r.push(i);r.length;){let n=r[r.length-1],o=!0;if(n.color!==2)for(let a of n.edges_out){if(a.color===1)return this.loop_hint=this.RenderAddress(i.address),console.info("loop detected @",this.loop_hint),!0;a.color===0&&(r.push(a),o=!1)}o&&(r.pop(),n.color=2)}i.color=2}return this.loop_check_required=!1,this.loop_hint=void 0,!1}RenderAddress(e){if(!e)return"undefined";let t="";if(e.sheet_id){let i=this.model.sheets.Find(e.sheet_id);i&&(t=i.name+"!")}let r=new v(e);return t+r.spreadsheet_label}CompositeAddArrayEdge(e,t){if(!e.start.sheet_id)throw new Error("AddArrayEdge called without sheet ID");let[r,i]=Be.GetVertex(e);if(t.DependsOn(r),this.loop_check_required=!0,!i)return;let n=this.vertices[e.start.sheet_id];if(n){if(e.entire_row){for(let o=0;o<n.length;o++)if(n[o])for(let a=e.start.row;a<=e.end.row;a++){let s=n[o][a];s&&r.DependsOn(s)}}else if(e.entire_column){for(let o=e.start.column;o<=e.end.column;o++)if(n[o])for(let a of n[o])a?.address&&r.DependsOn(a)}else for(let o=e.start.row;o<=e.end.row;o++)for(let a=e.start.column;a<=e.end.column;a++)if(n[a]){let s=n[a][o];s&&r.DependsOn(s)}}}AddLeafVertexArrayEdge(e,t){this.CompositeAddArrayEdge(e,t)}AddArrayEdge(e,t){if(!e.start.sheet_id)throw new Error("AddArrayEdge called without sheet ID");let r=this.GetVertex(t,!0);this.CompositeAddArrayEdge(e,r)}AddEdge(e,t){let r=this.GetVertex(e,!0);this.GetVertex(t,!0).DependsOn(r),r.reference&&r.reference.area&&!r.array_head&&this.AddEdge({...e,row:r.reference.area.start.row,column:r.reference.area.start.column},t),this.loop_check_required=!0}RemoveEdge(e,t){let r=this.GetVertex(e,!1),i=this.GetVertex(t,!1);!r||!i||(r.RemoveDependent(i),i.RemoveDependency(r))}SetAreaDirty(e){if(e.start.column===1/0||e.end.column===1/0||e.start.row===1/0||e.end.row===1/0)throw new Error("don't iterate over infinite area");let t=e.start.sheet_id;if(!t)throw new Error("invalid area, missing sheet id");for(let r=e.start.column;r<=e.end.column;r++)for(let i=e.start.row;i<=e.end.row;i++){let n={row:i,column:r,sheet_id:t};this.GetVertex(n,!1)&&this.SetDirty(n)}}SetVertexDirty(e){if(!e.dirty){this.dirty_list.push(e),e.dirty=!0;for(let t of e.edges_out)this.SetVertexDirty(t)}}SetDirty(e){let t=this.GetVertex(e,!0);this.SetVertexDirty(t)}AddLeafVertex(e){this.leaf_vertices.add(e)}RemoveLeafVertex(e){this.leaf_vertices.delete(e)}AddLeafVertexEdge(e,t){let r=this.GetVertex(e,!0);return t.DependsOn(r),0}RemoveLeafVertexEdge(e,t){let r=this.GetVertex(e,!1);r&&(r.RemoveDependent(t),t.RemoveDependency(r))}InitializeGraph(){for(let e of this.dirty_list)this.IsSpreadsheetVertex(e)&&(e.TakeReferenceValue(),this.CheckVolatile(e)&&this.volatile_list.push(e)),e.dirty=!1;this.dirty_list=[]}Recalculate(){for(let e of this.volatile_list)this.SetVertexDirty(e);this.spill_data=this.spill_data.filter(({area:e,vertex:t})=>{if(t.dirty){t.Reset();let r=e.start.sheet_id?this.model.sheets.Find(e.start.sheet_id)?.cells:void 0;if(r)for(let{cell:i,row:n,column:o}of r.IterateRC(new v(e.start,e.end)))i.spill&&(i.spill=void 0,typeof i.value>"u"&&i.Reset()),this.SetDirty({row:n,column:o,sheet_id:e.start.sheet_id});return!1}return!0}),this.calculation_list=this.dirty_list.slice(0),this.volatile_list=[],this.dirty_list=[],this.loop_check_required&&(this.ResetLoopState(),this.loop_check_required=!1);for(let e=0;e<this.calculation_list.length;e++)this.calculation_list[e].Calculate(this);this.calculation_list=[]}};var ca=l=>{let e={m:l,n:l,array:[]};for(let t=0;t<l;t++){let r=[];for(let i=0;i<l;i++)r.push({real:0,imaginary:0});e.array.push(r)}return e};var da=l=>{let{r:e,theta:t}=l,r=e*Math.cos(t),i=e*Math.sin(t);return{real:r,imaginary:i}},rr=l=>{let e=Math.sqrt(l.real*l.real+l.imaginary*l.imaginary),t=Math.atan2(l.imaginary,l.real);return{r:e,theta:t}},dn=l=>{let e={real:Math.sinh(l.real)*Math.cos(l.imaginary),imaginary:Math.cosh(l.real)*Math.sin(l.imaginary)},t={real:Math.cosh(l.real)*Math.cos(l.imaginary),imaginary:Math.sinh(l.real)*Math.sin(l.imaginary)};return Pe(e,t)},un=l=>Pe({real:Math.tan(l.real),imaginary:Math.tanh(l.imaginary)},{real:1,imaginary:-(Math.tan(l.real)*Math.tanh(l.imaginary))}),hn=l=>({real:Math.cosh(l.real)*Math.cos(l.imaginary),imaginary:Math.sinh(l.real)*Math.sin(l.imaginary)}),mn=l=>({real:Math.cos(l.real)*Math.cosh(l.imaginary),imaginary:Math.sin(l.real)*Math.sinh(l.imaginary)}),fn=l=>({real:Math.sinh(l.real)*Math.cos(l.imaginary),imaginary:Math.cosh(l.real)*Math.sin(l.imaginary)}),ir=l=>({real:Math.sin(l.real)*Math.cosh(l.imaginary),imaginary:Math.cos(l.real)*Math.sinh(l.imaginary)}),Zr=l=>{if(l.imaginary===0)return{real:Math.asin(l.real),imaginary:0};let e=Math.hypot(l.real+1,l.imaginary)/2,t=Math.hypot(l.real-1,l.imaginary)/2,r=e+t,i=e-t,n={real:Math.asin(i),imaginary:Math.log(r+Math.sqrt(r*r-1))};return(l.imaginary<0||l.imaginary===0&&l.real>1)&&(n.imaginary=-n.imaginary),n},pn=l=>{if(l.imaginary===0)return{real:Math.acos(l.real),imaginary:0};let e=Zr(l);return{real:Math.PI/2-e.real,imaginary:e.imaginary}},bn=l=>{let{real:e,imaginary:t}=l;if(e===0){if(t>1)return{real:Math.PI/2,imaginary:.5*Math.log((t-1)/(t+1))};if(t<-1)return{real:-Math.PI/2,imaginary:.5*Math.log((1-t)/(-1-t))}}let r=e*e,i=t*t,n=.5*Math.atan2(2*e,1-r-i),o=.25*Math.log((r+(t+1)*(t+1))/(r+(t-1)*(t-1)));return{real:n,imaginary:o}},gn=(l,e)=>{if(e.real===0&&e.imaginary===0&&l.real===0&&l.imaginary===0)return!1;let t=e.real*e.real+e.imaginary*e.imaginary,r={real:(l.real*e.real+l.imaginary*e.imaginary)/t,imaginary:(l.imaginary*e.real-l.real*e.imaginary)/t},i=r.real*r.real,n=r.imaginary*r.imaginary,o={real:.5*Math.atan2(2*r.real,1-i-n),imaginary:.25*Math.log((i+(r.imaginary+1)*(r.imaginary+1))/(i+(r.imaginary-1)*(r.imaginary-1)))};return e.real<0&&(o.real+=l.real>=0||l.imaginary>=0?Math.PI:-Math.PI),o},_n=(...l)=>{let e=l.shift();if(!e)return{real:0,imaginary:0};for(let t of l)e=ne(e,t);return e},ne=(l,e)=>({real:l.real*e.real-l.imaginary*e.imaginary,imaginary:l.real*e.imaginary+l.imaginary*e.real}),ua=(l,e)=>{let t=[];for(let r=0;r<l.m;r++){let i=[];for(let n=0;n<l.n;n++)i.push(l.array[r][n]+e.array[r][n]);t.push(i)}return{m:l.m,n:l.n,array:t}},Qr=(l,e)=>{let t=[];for(let r=0;r<l.m;r++){let i=[];for(let n=0;n<e.n;n++){let o=0;for(let a=0;a<l.n;a++)o+=l.array[r][a]*e.array[a][n];i.push(o)}t.push(i)}return{array:t,m:l.m,n:e.n}},yn=(l,e)=>{let t=[];for(let r=0;r<l.m;r++){let i=[];for(let n=0;n<e.n;n++){let o={real:0,imaginary:0};for(let a=0;a<l.n;a++)o.real+=l.array[r][a].real*e.array[a][n].real-l.array[r][a].imaginary*e.array[a][n].imaginary,o.imaginary+=l.array[r][a].real*e.array[a][n].imaginary+l.array[r][a].imaginary*e.array[a][n].real;i.push(o)}t.push(i)}return t},nr=l=>{let e={real:0,imaginary:0},t=l.n;if(t==2){let i=ne(l.array[0][0],l.array[1][1]),n=ne(l.array[1][0],l.array[0][1]);return{real:i.real-n.real,imaginary:i.imaginary-n.imaginary}}let r=ca(l.n);for(let i=0;i<t;i++){let n=0;for(let s=1;s<t;s++){let c=0;for(let d=0;d<t;d++)d!=i&&(r.array[n][c]={...l.array[s][d]},c++);n++}r.m=r.n=t-1;let o=Math.pow(-1,i),a=ne({real:l.array[0][i].real*o,imaginary:l.array[0][i].imaginary*o},nr(r));e.real+=a.real,e.imaginary+=a.imaginary}return e};var ha=l=>{let e={real_values:!1,imaginary_values:!1,square:l.m===l.n,unit_diagonal:!0},t={m:l.m,n:l.n,array:[]},r={m:l.m,n:l.n,array:[]};for(let i=0;i<l.m;i++){let n=l.array[i],o=[],a=[];for(let s=0;s<l.n;s++)n[s].real&&(e.real_values=!0),n[s].imaginary&&(e.imaginary_values=!0),s===i&&e.unit_diagonal&&(n[s].real!==1||n[s].imaginary!==0)&&(e.unit_diagonal=!1),o.push(n[s].real),a.push(n[s].imaginary);t.array.push(o),r.array.push(a)}return{real:t,imaginary:r,flags:e}},ma=l=>{let e=l.array.map(t=>t.slice(0));return{m:l.m,n:l.n,array:e}},cn=l=>{if(l.m!==l.n)return;let e=ma(l),t=e.array,r=0,i=0,n=0,o=0,a=l.m;for(i=1;i<a;i++)t[0][i]/=t[0][0];for(i=1;i<a;i++){for(n=i;n<a;n++){for(r=0,o=0;o<i;o++)r+=t[n][o]*t[o][i];t[n][i]-=r}if(i!=a-1)for(n=i+1;n<a;n++){for(r=0,o=0;o<i;o++)r+=t[i][o]*t[o][n];t[i][n]=(t[i][n]-r)/t[i][i]}}for(i=0;i<a;i++)for(n=i;n<a;n++){let s=1;if(i!=n)for(s=0,o=i;o<n;o++)s-=t[n][o]*t[o][i];t[n][i]=s/t[n][n]}for(i=0;i<a;i++)for(n=i;n<a;n++)if(i!=n){for(r=0,o=i;o<n;o++)r+=t[o][n]*(i==o?1:t[i][o]);t[i][n]=-r}for(i=0;i<a;i++)for(n=0;n<a;n++){for(r=0,o=i>n?i:n;o<a;o++)r+=(n==o?1:t[n][o])*t[o][i];t[n][i]=r}return e},vn=l=>{let e=[];if(l.m!==l.n)return;let{real:t,imaginary:r,flags:i}=ha(l),n=cn(t);if(!n)return;if(!i.imaginary_values){for(let u=0;u<l.m;u++){let h=[];for(let m=0;m<l.n;m++)h.push({real:n.array[u][m],imaginary:0});e.push(h)}return e}let o=Qr(n,r),a=Qr(r,o),s=ua(t,a),c=cn(s);if(!c)return;let d=Qr(o,c);for(let u=0;u<l.m;u++){let h=[];for(let m=0;m<l.n;m++)h.push({real:c.array[u][m],imaginary:-d.array[u][m]});e.push(h)}return e},Pe=(l,e)=>{let t={real:e.real,imaginary:-e.imaginary},r=ne(l,t),i=ne(e,t);return{real:r.real/i.real,imaginary:r.imaginary/i.real}},yt=l=>{let e=l.real||0,t=l.imaginary||0;return ne({real:Math.exp(e),imaginary:0},{real:Math.cos(t),imaginary:Math.sin(t)})},ei=l=>{let e=rr(l);return{real:Math.log(e.r),imaginary:e.theta}},we=(l,e)=>{if(e.imaginary)return yt(ne(e,ei(l)));{let t=rr(l);return da({r:Math.pow(t.r,e.real),theta:t.theta*e.real})}};var wn=(l,e=0)=>l&&l.type===8?l:{type:8,value:{real:e,imaginary:0}},$e=l=>l.imaginary?{type:8,value:l}:{type:3,value:l.real},je=(l,e)=>{if(l.type===7)return[0,0,l];if(e.type===7)return[0,0,e];let t=[0,0];switch(l.type){case 3:t[0]=l.value;break;case 4:t[0]=l.value?1:0;break;case 0:break;case 8:t[3]=l;break;default:return[0,0,U()]}switch(e.type){case 3:t[1]=e.value;break;case 4:t[1]=e.value?1:0;break;case 0:break;case 8:t[4]=e;break;default:return[0,0,U()]}return(t[3]||t[4])&&(t[3]=wn(t[3],t[0]),t[4]=wn(t[4],t[1])),t},fa=(l,e)=>{let[t,r,i,n,o]=je(l,e);return i||(n&&o?$e({real:n.value.real+o.value.real,imaginary:n.value.imaginary+o.value.imaginary}):{value:t+r,type:3})},ii=(l,e)=>{let[t,r,i,n,o]=je(l,e);return i||(n&&o?$e({real:n.value.real-o.value.real,imaginary:n.value.imaginary-o.value.imaginary}):{value:t-r,type:3})},pa=(l,e)=>{let[t,r,i,n,o]=je(l,e);if(i)return i;if(n&&o)return $e(we(n.value,o.value));let a=Math.pow(t,r);return isNaN(a)?U():{type:3,value:a}},ba=(l,e)=>{let[t,r,i,n,o]=je(l,e);if(i)return i;if(n&&o)return $e(we(n.value,o.value));if(t<0&&r!==0&&Math.abs(r)<1)return $e(we({real:t,imaginary:0},{real:r,imaginary:0}));let a=Math.pow(t,r);return isNaN(a)?U():{type:3,value:a}},ti=pa,ga=(l,e)=>{let[t,r,i,n,o]=je(l,e);return i||(n&&o?$e(ne(n.value,o.value)):{value:t*r,type:3})},_a=(l,e)=>{let[t,r,i,n,o]=je(l,e);return i||(n&&o?o.value.real===0&&o.value.imaginary===0?ve():$e(Pe(n.value,o.value)):r===0?ve():{value:t/r,type:3})},ya=(l,e)=>{let[t,r,i]=je(l,e);return i||(r===0?ve():{value:t%r,type:3})},ri=(l,e)=>l.type===7?l:e.type===7?e:l.type===0&&(e.value===""||e.value===0||e.type===8&&e.value.real===0&&e.value.imaginary===0)||e.type===0&&(l.value===""||l.value===0||l.type===8&&l.value.real===0&&l.value.imaginary===0)?{type:4,value:!0}:l.type===8?e.type===8?{type:4,value:l.value.imaginary===e.value.imaginary&&l.value.real===e.value.real}:{type:4,value:!l.value.imaginary&&l.value.real===e.value}:e.type===8?{type:4,value:!e.value.imaginary&&l.value===e.value.real}:l.type===2&&e.type===2?{type:4,value:l.value.toLowerCase()===e.value.toLowerCase()}:{type:4,value:l.value==e.value},xn=(l,e)=>{let t=ri(l,e);return t.type===7?t:{type:4,value:!t.value}},va=(l,e)=>l.type===7?l:e.type===7?e:l.type===8||e.type===8?U():{type:4,value:(l.value||0)>(e.value||0)},ni=(l,e)=>!(l.type===8||l.type===9||l.type===10||l.type===5||e.type===8||e.type===9||e.type===10||e.type===5),wa=(l,e)=>l.type===7?l:e.type===7?e:ni(l,e)?{type:4,value:(l.value||0)>=(e.value||0)}:U(),xa=(l,e)=>l.type===7?l:e.type===7?e:ni(l,e)?{type:4,value:(l.value||0)<(e.value||0)}:U(),Ca=(l,e)=>l.type===7?l:e.type===7?e:ni(l,e)?{type:4,value:(l.value||0)<=(e.value||0)}:U(),Cn=()=>{ti=ba},Sn=l=>{switch(l){case"+":return fa;case"-":return ii;case"*":return ga;case"/":return _a;case"^":return ti;case"**":return ti;case"%":return ya;case"=":return ri;case"==":return ri;case"!=":return xn;case"<>":return xn;case">":return va;case">=":return wa;case"<":return xa;case"<=":return Ca}};var oi=l=>!Array.isArray(l)&&l.type===5&&!!l.value.type,he=l=>l.type===5&&l.key==="metadata",ar=class{constructor(e,t,r){this.data_model=e;this.library=t;this.parser=r}context={address:{row:-1,column:-1},volatile:!1,bindings:[]};Calculate(e,t,r,i=!1){return i||(this.context.address=t,this.context.volatile=!1,this.context.area=r),{value:this.CalculateExpression(e),volatile:this.context.volatile}}CellFunction2(e){if(!e.sheet_id)if(e.sheet)e.sheet_id=this.data_model.sheets.ID(e.sheet)||0;else return()=>$();let t=this.data_model.sheets.Find(e.sheet_id)?.cells;if(!t)return console.warn("missing cells reference @ "+e.sheet_id),()=>$();let r=t.GetCell(e);return r?e.spill&&r.spill&&r.spill.start.row===e.row&&r.spill.start.column===e.column?()=>r.spill?t.GetRange4(r.spill.start,r.spill.end,!0)||$():ln():()=>r.GetValue4():()=>({type:3,value:0})}CellFunction4(e,t){return e.sheet_id?this.data_model.sheets.Find(e.sheet_id)?.cells?.GetRange4(e,t,!0)||$():$()}GetMetadata(e,t){let r,i;switch(e.type){case"address":if(e.spill){let n;if(e.sheet_id&&(n=this.data_model.sheets.Find(e.sheet_id)),!n)return console.error("missing sheet [da6]"),$();let o=n.CellData(e);o.spill&&(i=o.spill)}else r=e;break;case"range":i=e;break;case"structured-reference":{let n=this.data_model.ResolveStructuredReference(e,this.context.address);n&&(n.type==="address"?r=n:n.type==="range"&&(i=n))}break;case"identifier":{let n=this.data_model.GetName(e.name,this.context.address.sheet_id||0);n?.type==="range"&&(n.area.count===1?r=n.area.start:i=n.area)}break;case"call":{let n=this.CalculateExpression(e,!0);if(oi(n))if(n.value.type==="address")r=n.value;else if(n.value.type==="range")i=n.value;else return n;else return n}break;default:return this.CalculateExpression(e)}if(r){let n;if(r.sheet_id&&(n=this.data_model.sheets.Find(r.sheet_id)),!n)return console.error("missing sheet [ac8]"),$();let o=n.CellData(r),a=o.calculated_type?o.calculated:o.value,s={type:"metadata",address:{...r,position:0,id:0,type:"address",label:new v(r).spreadsheet_label},value:a,format:o.style?o.style.number_format:void 0,...t(o,r)};return{type:5,value:s,key:"metadata"}}else if(i){if(i.start.row===1/0||i.start.column===1/0)return $();let n;if(i.start.sheet_id&&(n=this.data_model.sheets.Find(i.start.sheet_id)),!n)throw new Error("missing sheet [ac9]");let o=[];for(let a=i.start.column;a<=i.end.column;a++){let s=[];for(let c=i.start.row;c<=i.end.row;c++){let d=n.CellData({row:c,column:a});r={...i.start,row:c,column:a};let u=d.calculated_type?d.calculated:d.value,h={type:"metadata",address:r,value:u,format:d.style?d.style.number_format:void 0,...t(d,r)};s.push({type:5,value:h,key:"metadata"})}o.push(s)}return{type:9,value:o}}return this.CalculateExpression(e)}RewriteMacro(e,t){let r;switch(e.type){case"identifier":if(r=t[e.name.toUpperCase()],r)return JSON.parse(JSON.stringify(r));break;case"binary":e.left=this.RewriteMacro(e.left,t),e.right=this.RewriteMacro(e.right,t);break;case"unary":e.operand=this.RewriteMacro(e.operand,t);break;case"group":e.elements=e.elements.map(i=>this.RewriteMacro(i,t));break;case"call":e.args=e.args.map(i=>this.RewriteMacro(i,t));break}return e}CallMacro(e,t){if(!t.expression)return()=>fe();let r=JSON.stringify(t.expression),i={},n=t.argument_names?.map(o=>o.toUpperCase())||[];return o=>{let a=JSON.parse(r);for(let s=0;s<n.length;s++)i[n[s]]=o.args[s]||{type:"missing",id:0};return this.CalculateExpression(this.RewriteMacro(a,i))}}ImplicitCallTail(e,t){let r=e.value;if(!r.func||!r.bindings)return fe();let i={};for(let o=0;o<r.bindings.length;o++){let a=r.bindings[o];if(a?.type==="identifier")i[a.name.toUpperCase()]=t[o]||{type:"missing"};else return fe()}let n=JSON.parse(JSON.stringify(r.func));return this.parser.Walk2(n,o=>{if(o.type==="identifier"){let a=o.name.toUpperCase(),s=i[a];if(s)return JSON.parse(JSON.stringify(s))}return!0}),this.CalculateExpression(n)}Apply(e,t){let r=t.map(i=>{switch(i.type){case 3:case 4:case 2:return{type:"literal",value:i.value,id:0,position:0};case 7:return{type:"literal",value:"#"+i.value,id:0,position:0};case 9:{let n=[];for(let o=0;o<i.value.length;o++){let a=i.value[o],s=[];for(let c=0;c<a.length;c++){let d=a[c];switch(d.type){case 4:case 3:case 2:s.push(d.value||void 0);break;default:console.warn("unhandled array value",d),s.push(void 0)}}n.push(s)}return{type:"array",values:n,id:0,position:0}}case 0:return{type:"missing",id:0};default:console.warn("unhandled parameter value",i)}return{type:"missing",id:0}});return this.ImplicitCallTail(e,r)}ImplicitCall(){return e=>{e.type==="call"&&(e={type:"implicit-call",args:e.args,call:{type:"identifier",name:e.name,position:e.position,id:0},position:e.position,id:0});let t=this.CalculateExpression(e.call);return t.type===6?this.ImplicitCallTail(t,e.args):fe()}}NormalizeBindings(e){let t={};for(let[r,i]of Object.entries(e))t[r.toUpperCase()]=i;return t}CallExpression(e,t=!1){let r=this.library.Get(e.name);if(!r){let i=e.name.toUpperCase();return this.LookupBinding(i)?this.ImplicitCall():this.data_model.GetName(i,this.context.address.sheet_id||0)?this.ImplicitCall():()=>Yr()}return i=>{this.context.volatile=this.context.volatile||!!r.volatile;let n=e.name.toLowerCase()==="if",o=-1,a,s=i.args,c=r.arguments||[],d;r.create_binding_context&&(d=r.create_binding_context.call(0,{args:i.args,descriptors:c}),d?(s=d.args,d.argument_descriptors&&(c=d.argument_descriptors),this.context.bindings.unshift(this.NormalizeBindings(d.context))):a=M());let u=s.map((f,p)=>{if(a)return;let b=c[Math.min(p,c.length-1)]||{};if(b.passthrough)return f;if(p===o)return b.boxed?{type:0}:void 0;if(typeof f>"u")return n&&p===0&&(o=1),b.boxed?{type:0}:void 0;if(b.address)return b.boxed?{type:2,value:this.parser.Render(f).replace(/\$/g,"")}:this.parser.Render(f).replace(/\$/g,"");if(b.metadata)return this.GetMetadata(f,()=>({}));{let g=this.CalculateExpression(f);if(g.type===7){if(b.allow_error)return g;a=g;return}if(n&&p===0&&g.type!==9){let x=!1;if(g.type===2){let y=g.value.toLowerCase().trim();x=y!=="false"&&y!=="f"}else x=!!g.value;o=x?2:1}return b.boxed?g:g.type===9?g.value.map(x=>x.map(y=>y.value)):g.value}});if(d&&this.context.bindings.shift(),a)return a;let h={address:{...this.context.address},area:this.context.area?{start:{...this.context.area.start},end:{...this.context.area.end}}:void 0,apply:r.fp?this.Apply.bind(this):void 0},m=r.fn.apply(h,u);if(r.return_type==="reference"){if(t)return m;if(oi(m)){if(m.value.type==="address")return this.CellFunction2(m.value)();if(m.value.type==="range")return this.CellFunction4(m.value.start,m.value.end)}return m}return m}}ResolveStructuredReference(e){let t=this.data_model.ResolveStructuredReference(e,this.context.address);if(t){if(t.type==="address")return this.CellFunction2(t);if(t.type==="range")return()=>this.CellFunction4(t.start,t.end)}return()=>$()}ResolveDimensionedQuantity(){return e=>{let t=this.CalculateExpression(e.expression);return{type:10,value:{value:t.value,unit:e.unit.name}}}}UnaryExpression(e,t=!1){switch(e.operator){case"+":return r=>this.CalculateExpression(r.operand);case"-":{let r=ii,i={type:3,value:0};return n=>{let o=this.CalculateExpression(n.operand);return o.type===9?{type:9,value:o.value.map(a=>a.map(s=>r(i,s)))}:r(i,o)}}case"@":return r=>{let i;switch(r.operand.type){case"address":if(r.operand.spill){let o=this.CellFunction2(r.operand)();if(o.type===9){let a=this.context.address.row??-1,s=this.context.address.column??-1;if(a>=r.operand.row&&a<r.operand.row+o.value[0]?.length&&o.value.length===1){if(!t)return o.value[0][a-r.operand.row];i={...r.operand,row:a,spill:!1}}else if(s>=r.operand.column&&s<r.operand.column+o.value.length&&o.value[0]?.length===1){if(!t)return o.value[s-r.operand.column][0];i={...r.operand,column:s,spill:!1}}else return U()}}break;case"range":{let o=this.context.address.row??-1,a=this.context.address.column??-1;if(o>=r.operand.start.row&&o<=r.operand.end.row&&r.operand.start.column===r.operand.end.column)i={...r.operand.start,row:o,spill:!1};else if(a>=r.operand.start.column&&a<=r.operand.end.column&&r.operand.start.row===r.operand.end.row)i={...r.operand.start,column:a,spill:!1};else return U()}}if(i)return t?{type:5,value:i}:this.CellFunction2(i)();let n=this.CalculateExpression(r.operand);return n.type===9?n.value[0][0]:n};default:return()=>(console.warn("unexpected unary operator:",e.operator),fe())}}RecycleArray(e,t,r){if(e[0].length<r){let i=e[0].length;for(let n of e)for(let o=i;o<r;o++)n[o]=n[o%i]}if(e.length<t){let i=e.length;for(let n=i;n<t;n++)e[n]=e[n%i].slice(0)}return e}ElementwiseBinaryExpression(e,t,r){let i=Math.max(t.value.length,r.value.length),n=Math.max(t.value[0].length,r.value[0].length),o=this.RecycleArray(t.value,i,n),a=this.RecycleArray(r.value,i,n),s=[];for(let c=0;c<i;c++){let d=[];for(let u=0;u<n;u++)d[u]=e(o[c][u]||{type:0},a[c][u]||{type:0});s.push(d)}return{type:9,value:s}}AsReference(e){switch(e.type){case"address":return e;case"range":if(e.start.row===e.end.row&&e.start.column===e.end.column)return e.start;break;default:{let t=this.CalculateExpression(e,!0);if(oi(t)){if(t.value.type==="address")return t.value;if(t.value.type==="range"&&t.value.start.row===t.value.end.row&&t.value.start.column===t.value.end.column)return t.value.start}}break}}BinaryExpression(e){let t=e.operator==="&"?(r,i)=>{if(r.type===7)return r;if(i.type===7)return i;let n=[r,i].map(o=>o.type===0?"":o.type===4?o.value?this.data_model.language_model?.boolean_true||"TRUE":this.data_model.language_model?.boolean_false||"FALSE":o.value);return{type:2,value:`${n[0]}${n[1]}`}}:Sn(e.operator);return t?r=>{let i=this.CalculateExpression(r.left),n=this.CalculateExpression(r.right);return i.type===9?n.type===9?this.ElementwiseBinaryExpression(t,i,n):this.ElementwiseBinaryExpression(t,i,{type:9,value:[[n]]}):n.type===9?this.ElementwiseBinaryExpression(t,{type:9,value:[[i]]},n):t(i,n)}:e.operator===":"?r=>{let i=this.AsReference(r.left),n=this.AsReference(r.right);return i&&n?this.CellFunction4(i,n):fe()}:()=>(console.info(`(unexpected binary operator: ${e.operator})`),fe())}Identifier(e){let t=e.name;if(t[0]==="#")return()=>$();let r=t.toUpperCase();switch(r){case"FALSE":return()=>({value:!1,type:4});case"TRUE":return()=>({value:!0,type:4});case"UNDEFINED":return()=>({value:void 0,type:0})}return()=>{let i=this.LookupBinding(r);if(i)return this.CalculateExpression(i);let n=this.data_model.GetName(r,this.context.address.sheet_id||0);switch(n?.type){case"range":return n.area.count===1?this.CellFunction4(n.area.start,n.area.start):this.CellFunction4(n.area.start,n.area.end);case"expression":return this.CalculateExpression(n.expression)}return Yr()}}LookupBinding(e){e=e.toUpperCase();for(let t of this.context.bindings){let r=t[e];if(r)return r}}GroupExpression(e){return!e.elements||e.elements.length!==1?(console.warn("Can't handle group !== 1"),()=>fe()):t=>this.CalculateExpression(t.elements[0])}CalculateExpression(e,t=!1){if(e.fn)return e.fn(e);switch(e.type){case"implicit-call":return(e.fn=this.ImplicitCall())(e);case"call":{let r=this.data_model.macro_functions.get(e.name.toUpperCase());return r?(e.fn=this.CallMacro(e,r))(e):(e.fn=this.CallExpression(e,t))(e)}case"address":return(e.fn=this.CellFunction2(e))();case"range":return(e.fn=r=>this.CellFunction4(r.start,r.end))(e);case"binary":return(e.fn=this.BinaryExpression(e))(e);case"unary":return(e.fn=this.UnaryExpression(e,t))(e);case"identifier":return(e.fn=this.Identifier(e))();case"missing":return(e.fn=()=>({value:void 0,type:0}))();case"dimensioned":return(e.fn=this.ResolveDimensionedQuantity())(e);case"literal":{let r={value:e.value,type:ge(e.value)};return(e.fn=()=>r)()}case"group":return(e.fn=this.GroupExpression(e))(e);case"complex":{let r={value:{real:e.real,imaginary:e.imaginary},type:8};return(e.fn=()=>r)()}case"structured-reference":return(e.fn=this.ResolveStructuredReference(e))();case"array":return(e.fn=()=>({type:9,value:e.values.map(r=>(Array.isArray(r)?r:[r]).map(i=>({type:ge(i),value:i})))}))();default:return console.warn("Unhandled parse expr:",e),Zt()}}};var Au=1e3*60*60*24;var sr=l=>{let e=[],t=l.length,r=l[0].length;for(let i=0;i<r;i++){e[i]=[];for(let n=0;n<t;n++)e[i][n]=l[n][i]}return e},ai=l=>{if(!l)return[];if(typeof l[0]>"u")return[];let e=[],t=l.length,r=l[0].length;for(let i=0;i<r;i++){e[i]=[];for(let n=0;n<t;n++)e[i][n]=l[n][i]}return e};var oe=l=>{let e=[];for(let t of l)if(t?.type===9)for(let r of t.value)e=e.concat(oe(r));else e.push(t);return e},X=(l,e=!1)=>Array.isArray(l)?l.reduce((t,r)=>typeof r>"u"&&!e?t:Array.isArray(r)?t.concat(X(r,e)):r instanceof Float32Array||r instanceof Float64Array?t.concat(Array.from(r)):t.concat([r]),[]):[l],te=l=>X(l).filter(e=>typeof e=="number"),si=(l,e=!1)=>e?l.map(t=>{switch(typeof t){case"number":case"undefined":case"string":case"boolean":return t}}):l.filter(t=>{switch(typeof t){case"number":case"undefined":case"string":case"boolean":return!0}return!1}),Sa=l=>!!l&&typeof l=="object"&&l.type===9,kn=(l,e)=>(...t)=>{let r=[],i=[];for(let[n,o]of t.entries())if(o&&l[n]){let a=Array.isArray(o)?o:Sa(o)?o.value:void 0;a&&(r[n]=a,i.length||(i=a))}return r.length?{type:9,value:i.map((n,o)=>n.map((a,s)=>{let c=t.map((d,u)=>r[u]?r[u][o][s]??{type:0}:d);return e(...c)}))}:e(...t)},vt=l=>{let e=[],t=l.length,r="[\\^$.|?*+()";for(let i=0;i<t;i++){let n=l[i];switch(n){case"*":e.push(".","*");break;case"?":e.push(".");break;case"~":n=l[++i]||"";default:for(let o=0;o<r.length;o++)if(n===r[o]){e.push("\\");break}e.push(n);break}}return e.join("")},Rn=l=>({type:2,value:l});var cr=class{functions={};Register(...e){for(let t of e)for(let r of Object.keys(t)){if(/[^a-zA-Z0-9._]/.test(r))throw new Error("invalid function name (invalid character)");if(r.length>255)throw new Error("invalid function name (too long, > 255)");if(/^[^a-zA-Z]/.test(r))throw new Error("invalid function name (start with an ascii letter)");let i=r.toLowerCase();if(this.functions[i])throw new Error(`function name (${i}) is already in use`);let n=t[r];if(n.canonical_name=r,!n.unrolled){let o=n.arguments?.map(a=>!!a.unroll);o?.some(a=>!!a)&&(n.fn=kn(o,n.fn),n.unrolled=!0)}this.functions[i]=n}}Get(e){let t=e.toLowerCase();return this.functions[t]}List(e=!0){let t={};for(let r of Object.keys(this.functions))e&&this.functions[r].visibility==="internal"||(t[r]=this.functions[r]);return t}Alias(e,t){let r=this.Get(t);if(!r)throw new Error(`referenced function ${t} does not exist`);this.Register({[e]:{...r}})}};var wt=class{static default_color="#888";static UnpackValues(e){if(Array.isArray(e)){let t=e[0];return Array.isArray(t)||t instanceof Float64Array||t instanceof Float32Array?e.reduce((r,i)=>r.concat(this.UnpackValues(i)),[]):e.map(r=>isNaN(r)?void 0:r)}else{if(e instanceof Float32Array||e instanceof Float64Array)return Array.prototype.slice.call(e);if(e&&typeof e=="object"){let r=Object.keys(e).length;if(typeof e[0]<"u"&&typeof e[(r-1).toString()]<"u"){let i=[];for(let n=0;n<r;n++)i[n]=e[n.toString()];return i}}}return[]}static SparklineCommon(e,t){let r=[],i=ee(t.text)?t.text.text:this.default_color,n=[i,i];return Array.isArray(e.calculated)&&(r=this.UnpackValues(e.calculated[0]),typeof e.calculated[1]=="string"&&(n[0]=e.calculated[1]),typeof e.calculated[2]=="string"&&(n[1]=e.calculated[2])),{values:r,colors:n}}static RenderLine(e,t,r,i,n){let{values:o,colors:a}=this.SparklineCommon(i,n),s=.05,c=.1,d=1;Array.isArray(i.calculated)&&typeof i.calculated[2]=="number"&&(d=i.calculated[2]);let u=0,h=0,m=-1;for(let f=0;f<o.length;f++){let p=o[f];typeof p=="number"&&(m>=0?(u=Math.min(u,p),h=Math.max(h,p)):(m=f,u=h=p))}if(u===h&&(u&&(u-=1),h+=1),u!==h){let f=e*(1-2*s)/(o.length-1),p=h-u,b=t*(1-2*c),g=t*c;r.strokeStyle=a[0],r.lineWidth=d,r.lineCap="round",r.lineJoin="round",r.beginPath();let x=0;for(let y=m;y<o.length;y++){let w=o[y];if(typeof w=="number"){let _=e*s+f*y,C=t-(w-u)*b/p-g;x===0?(r.moveTo(_,C),x=1):r.lineTo(_,C)}else x=0}r.stroke()}}static RenderColumn(e,t,r,i,n){let{values:o,colors:a}=this.SparklineCommon(i,n),s=3,c=2.5,d=0,u=0,h=!1;for(let m of o)typeof m=="number"&&(h?(d=Math.min(d,m),u=Math.max(u,m)):(h=!0,d=u=m));if(d===u&&(d&&(d-=1),u+=1),o.length){let m=(e-2*s-2)/(o.length-0),f=t-2*c,p=c;if(d!==u)if(d<0&&u>0){let b=u-d,g=p+u/b*f;for(let x=0;x<o.length;x++){let y=o[x];if(typeof y=="number"){let w=s+x*m,_=Math.abs(y)/b*f;if(y>=0){r.fillStyle=a[0];let C=g-_;r.fillRect(w+2,C,m-2,_)}else{r.fillStyle=a[1];let C=g;r.fillRect(w+2,C,m-2,_)}}}}else if(u>0){r.fillStyle=a[0];let b=u-d;for(let g=0;g<o.length;g++){let x=o[g];if(typeof x=="number"){let y=s+g*m,w=Math.max(1,(x-d)/b*f),_=t-p-w;r.fillRect(y+2,_,m-2,w)}}}else{r.fillStyle=a[1];let b=u-d;for(let g=0;g<o.length;g++){let x=o[g];if(typeof x=="number"){let y=s+g*m,w=Math.max(1,Math.abs(u-x)/b*f),_=p;r.fillRect(y+2,_,m-2,w)}}}}}};var En=l=>{let{x:e,y:t,width:r,height:i,cell:n}=l,o={},a=3,s=Math.round(16*(l.scale||1));if(n&&r&&i&&e&&t){let c={x:a,y:i-a-s};if(n.style){switch(n.style.vertical_align){case"top":c.y=a;break;case"middle":c.y=Math.round((i-s)/2);break}switch(n.style.horizontal_align){case"right":c.x=Math.round(r-a-s);break;case"center":c.x=Math.round((r-s)/2);break}}e>=c.x&&e<=c.x+s&&t>=c.y&&t<=c.y+s&&(o.value=`=Checkbox(${n.calculated?"FALSE":"TRUE"})`,o.block_selection=!0)}return o},Tn=l=>{let{context:e,width:t,height:r,cell:i}=l,n=l.scale||1;e.lineJoin="round",e.lineCap="round";let o=3*n,a=16*n,s=o,c=r-o-a;if(i.style){switch(i.style.vertical_align){case"top":c=o;break;case"middle":c=(r-a)/2;break}switch(i.style.horizontal_align){case"right":s=t-o-a;break;case"center":s=(t-a)/2;break}}s=Math.floor(s)+.5,c=Math.floor(c)+.5;let d=Math.floor(s+a)+.5,u=Math.floor(c+a)+.5;if(i&&i.calculated){e.lineWidth=.5,e.fillStyle=e.strokeStyle,e.beginPath(),e.moveTo(s,c),e.lineTo(s+16*n,c),e.lineTo(s+16*n,c+16*n),e.lineTo(s,c+16*n),e.closePath(),e.moveTo(s+15*n,c+4*n);for(let h of[[13.59,2.58],[6,10.17],[2.41,6.59],[1,8],[6,13]])e.lineTo(s+h[0]*n,c+h[1]*n);e.closePath(),e.fill()}else e.lineWidth=1,e.lineJoin="round",e.beginPath(),e.moveTo(s,c),e.lineTo(d,c),e.lineTo(d,u),e.lineTo(s,u),e.closePath(),e.stroke();return{handled:!0}};var Oe=l=>{switch(l.type){case 8:return l.value;case 3:return{real:l.value,imaginary:0};case 4:return{real:l.value?1:0,imaginary:0};case 0:return{real:0,imaginary:0}}return!1};var Mn=(l,e,t)=>{let r=new Date;return r.setMilliseconds(0),r.setSeconds(0),r.setMinutes(0),r.setHours(0),l<0||l>1e4||(l<1899&&(l+=1900),r.setFullYear(l),e<1||e>12)||(r.setMonth(e-1),t<1||t>31)?!1:(r.setDate(t),Ae(r.getTime()))};var Un=(l,e)=>{let t=new Date(Re(l)),r=t.getUTCMonth()+e,i=t.getUTCFullYear();for(t.setUTCHours(12),t.setUTCMinutes(0),t.setUTCSeconds(0),t.setUTCMilliseconds(0);r<0;)r+=12,i--;for(;r>11;)r-=12,i++;if(t.setUTCMonth(r),t.setUTCFullYear(i),t.getUTCMonth()!==r){let o=t.getUTCDate();t=new Date(t.getTime()-o*86400*1e3)}return t},Vn=[{name:"Lookup value"},{name:"Table"},{name:"Result index"},{name:"Inexact",default:!0}],Dn=(l,e,t,r=!0,i=!1)=>{if(i&&(e=ai(e)),t=Math.max(0,t-1),r){let n=e[t][0];if(typeof l=="number"){let o=Number(e[0][0]);if(isNaN(o)||o>l)return xe();for(let a=1;a<e[0].length&&(o=Number(e[0][a]),!(isNaN(o)||o>l));a++)n=e[t][a]}else{l=(l||"").toString().toLowerCase();let o=(e[0][0]||"").toString().toLowerCase();if(o.localeCompare(l)>0)return xe();for(let a=1;a<e[0].length&&(o=(e[0][a]||"").toString().toLowerCase(),!(o.localeCompare(l)>0));a++)n=e[t][a]}return Q(n)}else{for(let n=0;n<e[0].length;n++)if(e[0][n]==l)return Q(e[t][n]);return xe()}},dr=(l,e=!1)=>{if(!l)return e;switch(l.type){case 3:return l.value;case 0:return e}return!1},Le=(l,e,t)=>({description:t,arguments:[{name:"number",boxed:!0,unroll:!0}],fn:r=>r.type===3?{type:3,value:l(r.value)}:r.type===8?{type:8,value:e(r.value)}:M()}),li={Sqrt:{description:"Returns the square root of the argument",arguments:[{boxed:!0,unroll:!0}],fn:l=>{if(l.type===8){let e=we(l.value,{real:.5,imaginary:0});return de(e)}else{if(l.type===0||!l.value)return{type:3,value:0};if(l.type===3&&l.value<0){let e=we({real:l.value,imaginary:0},{real:.5,imaginary:0});return{type:8,value:e}}else if(l.type===3){let e=Math.sqrt(l.value);return isNaN(e)?U():{type:3,value:e}}else return U()}}},Power:{description:"Returns base raised to the given power",arguments:[{name:"base",boxed:!0,unroll:!0},{name:"exponent",boxed:!0,unroll:!0}],fn:(l,e)=>{if(l.type===3&&e.type===3&&(l.value>=0||e.value===0||Math.abs(e.value)>=1)){let i=Math.pow(l.value,e.value);return isNaN(i)?U():{type:3,value:i}}let t=Oe(l),r=Oe(e);if(t&&r){let i=we(t,r);return de(i)}return U()}}},et={True:{fn:()=>({type:4,value:!0})},False:{fn:()=>({type:4,value:!1})},Int:{fn:l=>({type:3,value:Math.floor(l)})},Rand:{volatile:!0,fn:()=>({type:3,value:Math.random()})},RandArray:{volatile:!0,arguments:[{name:"rows"},{name:"columns"},{name:"min"},{name:"max"},{name:"integer"}],description:"Returns an array of uniformly-distributed random numbers",fn:(l=1,e=1,t=0,r=1,i=!1)=>{let n=[];if(i){let o=r-t+1;for(let a=0;a<e;a++){let s=[];for(let c=0;c<l;c++)s.push({type:3,value:Math.floor(Math.random()*o+t)});n.push(s)}}else{let o=r-t;for(let a=0;a<e;a++){let s=[];for(let c=0;c<l;c++)s.push({type:3,value:Math.random()*o+t});n.push(s)}}return{type:9,value:n}}},RandBetween:{arguments:[{name:"min"},{name:"max"}],volatile:!0,fn:(l=0,e=1)=>{if(l>e){let t=l;l=e,e=t}return{type:3,value:Math.floor(Math.random()*(e+1-l)+l)}}},Sum:{description:"Adds arguments and ranges",arguments:[{boxed:!0,name:"values or ranges",repeat:!0}],fn:(...l)=>{let e={real:0,imaginary:0},t=oe(l);for(let r of t)switch(r.type){case 3:e.real+=r.value;break;case 4:break;case 8:e.real+=r.value.real,e.imaginary+=r.value.imaginary;break;case 7:return r}return de(e)}},SumSQ:{description:"Returns the sum of the squares of all arguments",arguments:[{boxed:!0,name:"values or ranges",repeat:!0}],fn:(...l)=>{let e={real:0,imaginary:0},t=oe(l);for(let r of t)switch(r.type){case 3:e.real+=r.value*r.value;break;case 4:break;case 8:{let i=ne(r.value,r.value);e.real+=i.real,e.imaginary+=i.imaginary}break;case 7:return r}return de(e)}},EDate:{arguments:[{name:"Start date",unroll:!0},{name:"Months",unroll:!0}],fn:(l,e=0)=>{if(typeof l!="number"||typeof e!="number")return M();let t=Un(l,e);return{type:3,value:Ae(t.getTime(),!1)}}},EOMonth:{arguments:[{name:"Start date",unroll:!0},{name:"Months",unroll:!0}],fn:(l,e=0)=>{if(typeof l!="number"||typeof e!="number")return M();let t=Un(l,e);switch(t.getUTCMonth()){case 1:{let i=t.getUTCFullYear();i%4===0&&(i===1900||i%400===0||i%100!==0)?t.setUTCDate(29):t.setUTCDate(28)}break;case 0:case 2:case 4:case 6:case 7:case 9:case 11:t.setUTCDate(31);break;default:t.setUTCDate(30);break}return{type:3,value:Ae(t.getTime(),!1)}}},Now:{description:"Returns current time",volatile:!0,fn:()=>({type:3,value:Ae(new Date().getTime())})},YearFrac:{description:"Returns the fraction of a year between two dates",arguments:[{name:"Start"},{name:"End"},{name:"Basis",default:0}],fn:(l,e,t)=>{if(e<l){let n=l;l=e,e=n}let r=Math.max(0,e-l),i=360;if(t&&t<0||t>4)return M();switch(t){case 1:break;case 2:break;case 3:i=365;break}return{type:3,value:r/i}}},Date:{description:"Constructs a date from year/month/day",arguments:[{name:"year",unroll:!0},{name:"month",unroll:!0},{name:"day",unroll:!0}],fn:(l,e,t)=>{let r=Mn(l,e,t);return r===!1?M():{type:3,value:r}}},Today:{description:"Returns current day",volatile:!0,fn:()=>{let l=new Date;return l.setMilliseconds(0),l.setSeconds(0),l.setMinutes(0),l.setHours(12),{type:3,value:Ae(l.getTime())}}},IfError:{description:"Returns the original value, or the alternate value if the original value contains an error",arguments:[{name:"original value",allow_error:!0,boxed:!0},{name:"alternate value"}],fn:(l,e=0)=>l&&l.type===7?{value:e,type:ge(e)}:l},IsNA:{description:"Checks if another cell contains a #NA error",arguments:[{name:"reference",allow_error:!0,boxed:!0}],fn:(...l)=>{let e=oe(l);for(let t of e)if(t.type===7&&t.value==="N/A")return{type:4,value:!0};return{type:4,value:!1}}},IsErr:{description:"Checks if another cell contains an error",arguments:[{name:"reference",allow_error:!0,boxed:!0}],fn:(...l)=>{let e=oe(l);for(let t of e)if(t.type===7&&t.value!=="N/A")return{type:4,value:!0};return{type:4,value:!1}}},IsError:{description:"Checks if another cell contains an error",arguments:[{name:"reference",allow_error:!0,boxed:!0}],fn:(...l)=>{let e=oe(l);for(let t of e)if(t.type===7)return{type:4,value:!0};return{type:4,value:!1}}},Year:{description:"Returns year from date",arguments:[{name:"date",unroll:!0}],fn:l=>Q(new Date(Re(l)).getUTCFullYear())},Month:{description:"Returns month from date",arguments:[{name:"date",unroll:!0}],fn:l=>Q(new Date(Re(l)).getUTCMonth()+1)},Day:{description:"Returns day of month from date",arguments:[{name:"date",unroll:!0}],fn:l=>Q(new Date(Re(l)).getUTCDate())},Radians:{description:"Converts degrees to radians",arguments:[{name:"Degrees",description:"Angle in degrees",unroll:!0}],fn:l=>Q(l*Math.PI/180)},Degrees:{description:"Converts radians to degrees",arguments:[{name:"Radians",description:"Angle in radians",unroll:!0}],fn:l=>Q(l/Math.PI*180)},CountA:{description:"Counts cells that are not empty",fn:(...l)=>Q(X(l).reduce((e,t)=>typeof t>"u"?e:e+1,0))},Count:{description:"Counts cells that contain numbers",fn:(...l)=>Q(X(l).reduce((e,t)=>typeof t=="number"||me(t)?e+1:e,0))},Or:{fn:(...l)=>{let e=!1;l=X(l);for(let t of l)e=e||!!t;return Q(e)}},And:{fn:(...l)=>{let e=!0;l=X(l);for(let t of l)e=e&&!!t;return Q(e)}},Not:{arguments:[{unroll:!0,boxed:!0}],fn:l=>{let e=!1;if(l)switch(l.type){case 0:e=!1;break;case 2:case 4:case 3:e=!!l.value;break;case 7:return l}return Q(!e)}},If:{arguments:[{name:"test value",boxed:!0},{name:"value if true",boxed:!0,allow_error:!0},{name:"value if false",boxed:!0,allow_error:!0}],fn:(l,e={type:4,value:!0},t={type:4,value:!1})=>{let r=e.type===9,i=t.type===9;return l.type===9?{type:9,value:l.value.map((o,a)=>o.map((s,c)=>(s.type===2?s.value.toLowerCase()!=="false"&&s.value.toLowerCase()!=="f":!!s.value)?r?e.value[a][c]:e:i?t.value[a][c]:t))}:(l.type===2?l.value.toLowerCase()!=="false"&&l.value.toLowerCase()!=="f":!!l.value)?e:t}},Fact:{description:"Returns the factorial of a number",arguments:[{name:"number",unroll:!0}],fn:l=>{l=Math.round(l);let e=1;for(;l>1;)e*=l,l--;return{type:3,value:e}}},Factdouble:{description:"Returns the double factorial of a number",arguments:[{name:"number",unroll:!0}],fn:l=>{l=Math.round(l);let e=1;for(;l>1;)e*=l,l-=2;return{type:3,value:e}}},Power:{description:"Returns base raised to the given power",arguments:[{name:"base",boxed:!0,unroll:!0},{name:"exponent",boxed:!0,unroll:!0}],fn:(l,e)=>{let t=Oe(l),r=Oe(e);if(!t||!r)return U();if(l.type===8||e.type===8)return de(we(t,r));{let i=Math.pow(t.real,r.real);return isNaN(i)?U():{type:3,value:i}}}},Mod:{arguments:[{unroll:!0},{unroll:!0}],fn:(l,e)=>e?Q(l%e):ve()},Large:{description:"Returns the nth numeric value from the data, in descending order",arguments:[{name:"values"},{name:"index",unroll:!0}],fn:(l,e)=>{if(e<=0)return M();let t=te(l);return t.sort((r,i)=>i-r),e<=t.length?{type:3,value:t[e-1]}:M()}},Small:{description:"Returns the nth numeric value from the data, in ascending order",arguments:[{name:"values"},{name:"index",unroll:!0}],fn:(l,e)=>{if(e<=0)return M();let t=te(l);return t.sort((r,i)=>r-i),e<=t.length?{type:3,value:t[e-1]}:M()}},Filter:{description:"Filter an array using a second array.",arguments:[{name:"source",description:"Source array"},{name:"filter",description:"Filter array"}],fn:(l,e)=>{if(typeof l>"u"||typeof e>"u")return M();Array.isArray(l)||(l=[[l]]),Array.isArray(e)||(e=[[e]]);let t=l.length,r=l[0].length,i=e.length,n=e[0].length;if(r===n){let o=[];for(let a=0;a<t;a++)o.push([]);for(let[a,s]of e[0].entries())if(s)for(let c=0;c<t;c++)o[c].push(Q(l[c][a]));return{type:9,value:o}}else if(t===i){let o=[];for(let[a,[s]]of e.entries())s&&o.push(l[a].map(c=>Q(c)));return{type:9,value:o}}return M()}},Sort:{arguments:[{name:"values"}],fn:(...l)=>(l=X(l),l.every(e=>typeof e=="number")?l.sort((e,t)=>e-t):l.sort(),{type:9,value:[l.map(e=>Q(e))]})},Transpose:{description:"Returns transpose of input matrix",arguments:[{name:"matrix",boxed:!0}],fn:l=>l.type===9?{type:9,value:sr(l.value)}:l},Max:{fn:(...l)=>({type:3,value:Math.max.apply(0,te(l))})},Min:{fn:(...l)=>({type:3,value:Math.min.apply(0,te(l))})},SumProduct:{description:"Returns the sum of pairwise products of two or more ranges",fn:(...l)=>{let e=l.map(i=>X(i)),t=Math.max.apply(0,e.map(i=>i.length)),r=0;for(let i=0;i<t;i++)r+=e.reduce((n,o)=>{let a=o[i];return a===!0&&(a=1),typeof a=="number"?n*a:0},1);return{type:3,value:r}}},Row:{arguments:[{name:"reference",metadata:!0}],fn:function(l){if(!l)if(this?.area){let e=[];for(let t=this.area.start.column;t<=this.area.end.column;t++){let r=[];for(let i=this.area.start.row;i<=this.area.end.row;i++)r.push({type:3,value:i+1});e.push(r)}return{type:9,value:e}}else return{type:3,value:this?this.address.row+1:-1};if(l.type===9){let e=l.value,t=e[0][0];if(he(t))return{type:9,value:[e[0].map((r,i)=>({type:3,value:i+t.value.address.row+1}))]}}else if(he(l))return{type:3,value:l.value.address.row+1};return M()}},Column:{arguments:[{name:"reference",metadata:!0}],fn:function(l){if(!l)if(this?.area){let e=[];for(let t=this.area.start.column;t<=this.area.end.column;t++){let r=[];for(let i=this.area.start.row;i<=this.area.end.row;i++)r.push({type:3,value:t+1});e.push(r)}return{type:9,value:e}}else return{type:3,value:this?this.address.column+1:-1};if(l.type===9){let e=l.value,t=e[0][0];if(he(t))return{type:9,value:e.map((r,i)=>[{type:3,value:i+t.value.address.column+1}])}}else if(he(l))return{type:3,value:l.value.address.row+1};return M()}},Choose:{arguments:[{name:"Selected index"},{name:"Choice 1...",metadata:!0}],return_type:"reference",description:"Returns one of a list of choices",fn:(l,...e)=>{if(l<1||l>e.length)return U();let t=e[l-1];if(he(t))return{type:5,value:t.value.address};if(t.type===9){let r=t.value,i=r.length,n=r[0].length,o=r[0][0],a=r[i-1][n-1];if(i===1&&n===1){if(he(o))return{type:5,value:o.value.address}}else if(he(o)&&he(a))return{type:5,value:{type:"range",position:0,id:0,label:"",start:o.value.address,end:a.value.address}}}return{...t}}},XLOOKUP:{arguments:[{name:"Lookup value"},{name:"Lookup array"},{name:"Return array",metadata:!0},{name:"Not found",boxed:!0},{name:"Match mode",default:0},{name:"Search mode",default:1}],return_type:"reference",xlfn:!0,fn:(l,e,t,r,i=0,n=1)=>{if(!t)return M();let o;if(t.type===9){let d=t.value,u=d.length,h=d[0].length,m=d[0][0],f=d[u-1][h-1];he(m)&&he(f)&&(o=new v(m.value.address,f.value.address))}if(!o)return console.info("invalid range"),$();if(!Array.isArray(e))return console.info("lookup is not an array"),U();let a=e[0];if(!Array.isArray(a))return console.info("lookup is not a 2d array"),U();if(e.length!==1&&a.length!==1)return console.info("lookup array has invalid dimensions"),U();let s=e.length===1;s&&(e=ai(e)),n<0&&e.reverse();let c=(d,u)=>{let h,m;if(s?(n<0&&(u=d.rows-1-u),u>=0&&u<d.rows&&(h={type:"address",position:0,id:1,label:"",row:d.start.row+u,column:d.start.column,sheet_id:d.start.sheet_id},m={type:"address",position:0,id:2,label:"",row:d.start.row+u,column:d.end.column,sheet_id:d.start.sheet_id})):(n<0&&(u=d.columns-1-u),u>=0&&u<d.columns&&(h={type:"address",position:0,id:1,label:"",row:d.start.row,column:d.start.column+u,sheet_id:d.start.sheet_id},m={type:"address",position:0,id:2,label:"",row:d.end.row,column:d.start.column+u,sheet_id:d.start.sheet_id})),h&&m){let f={type:"range",position:0,id:0,label:"",start:h,end:m};return{type:5,value:f}}return{type:0}};if(i===2&&typeof l!="string"&&(i=0),(i===1||i===-1)&&typeof l=="number"){let d=0,u=-1;for(let h=0;h<e.length;h++){let m=e[h][0];if(typeof m=="number"){if(m===l)return c(o,h);let f=Math.abs(m-l);(i===1&&m>l||i===-1&&m<l)&&(u<0||f<d)&&(d=f,u=h)}}if(u>=0)return c(o,u)}switch(i){case 2:{let d=vt(l?.toString()||""),u=new RegExp("^"+d+"$","i");for(let h=0;h<e.length;h++){let m=e[h][0];if(typeof m=="string"&&u.exec(m))return c(o,h)}}break;case 0:typeof l=="string"&&(l=l.toLowerCase());for(let d=0;d<e.length;d++){let u=e[d][0];if(typeof u=="string"&&(u=u.toLowerCase()),u===l)return c(o,d)}break}return r&&r.type!==0?r:xe()}},HLookup:{arguments:[...Vn],fn:(l,e,t,r=!0)=>Dn(l,e,t,r,!0)},VLookup:{arguments:[...Vn],fn:(l,e,t,r=!0)=>Dn(l,e,t,r,!1)},Product:{arguments:[{boxed:!0}],fn:(...l)=>{let e={real:1,imaginary:0};l=oe(l);for(let t of l)t.type===8?e=ne(e,t.value):t.type===3&&(e.real*=t.value,e.imaginary*=t.value);return de(e)}},Log:{arguments:[{name:"number",unroll:!0},{name:"base",unroll:!0}],fn:(l,e=10)=>({type:3,value:Math.log(l)/Math.log(e)})},Log10:{arguments:[{name:"number",unroll:!0}],fn:l=>({type:3,value:Math.log(l)/Math.log(10)})},Ln:{arguments:[{name:"number",unroll:!0}],fn:l=>({type:3,value:Math.log(l)})},"Ceiling.Math":{arguments:[{name:"number",unroll:!0},{name:"significance",unroll:!0},{name:"away from zero",unroll:!0}],fn:(l,e=1,t)=>{let r=0;return t&&l<0?r=-Math.ceil(-l/e)*e:r=Math.ceil(l/e)*e,{type:3,value:r}}},"Floor.Math":{arguments:[{name:"number",unroll:!0},{name:"significance",unroll:!0},{name:"away from zero",unroll:!0}],fn:(l,e=1,t)=>{let r=0;return t&&l<0?r=-Math.floor(-l/e)*e:r=Math.floor(l/e)*e,{type:3,value:r}}},Floor:{arguments:[{name:"number",unroll:!0},{name:"significance",unroll:!0}],fn:(l,e=1)=>({type:3,value:Math.floor(l/e)*e})},Ceiling:{arguments:[{name:"number",unroll:!0},{name:"significance",unroll:!0}],fn:(l,e=1)=>({type:3,value:Math.ceil(l/e)*e})},Round:{arguments:[{unroll:!0},{unroll:!0}],fn:(l,e=0)=>{let t=Math.pow(10,e);return{type:3,value:Math.round(t*l)/t}}},RoundDown:{arguments:[{unroll:!0},{unroll:!0}],fn:(l,e=0)=>{let t=Math.pow(10,e),r=l>=0;return{type:3,value:r?Math.floor(t*l)/t:Math.ceil(t*l)/t}}},RoundUp:{arguments:[{unroll:!0},{unroll:!0}],fn:(l,e=0)=>{let t=Math.pow(10,e),r=l>=0;return{type:3,value:r?Math.ceil(t*l)/t:Math.floor(t*l)/t}}},Reverse:{arguments:[{boxed:!0}],fn:l=>l.type===9?(l.value.length===1?l.value[0].reverse():l.value.reverse(),l):{type:2,value:(l.value??"").toString().split("").reverse().join("")}},Exp:{arguments:[{boxed:!0,unroll:!0}],fn:l=>{if(l.type===8){let e=yt(l.value);return de(e)}return l.type!==3?U():{type:3,value:Math.exp(l.value)}}},Abs:{arguments:[{boxed:!0,unroll:!0}],fn:l=>l.type===8?{type:3,value:Math.sqrt(l.value.real*l.value.real+l.value.imaginary*l.value.imaginary)}:l.type!==3?U():{type:3,value:Math.abs(l.value||0)}},Simplify:{arguments:[{name:"value",unroll:!0},{name:"significant digits",unroll:!0}],fn:(l,e=2)=>{if(e=e||2,l===0)return{type:3,value:l};let t=l<0?-1:1;l*=t;let r=Math.pow(10,Math.floor(Math.log10(l))+1-e);return{type:3,value:Math.round(l/r)*r*t}}},Sqrt:{description:"Returns the square root of the argument",arguments:[{boxed:!0,unroll:!0}],fn:l=>{if(l.type===8){let e=we(l.value,{real:.5,imaginary:0});return de(e)}else{if(l.type===0||!l.value)return{type:3,value:0};if(l.type===3)return{type:3,value:Math.sqrt(l.value)}}return U()}},HexToDec:{arguments:[{description:"hexadecimal string",unroll:!0}],fn:l=>({type:3,value:parseInt(l,16)})},DecToHex:{arguments:[{description:"number",unroll:!0}],fn:l=>({type:2,value:l.toString(16)})},Checkbox:{arguments:[{name:"checked"}],click:En,render:Tn,fn:l=>({value:!!l,type:4})},"Sparkline.Column":{arguments:[{name:"data"},{name:"color"},{name:"negative color"}],render:l=>(wt.RenderColumn(l.width,l.height,l.context,l.cell,l.style),{handled:!0}),fn:(...l)=>({type:5,value:l,key:"sparkline-data"})},"Sparkline.Line":{arguments:[{name:"data"},{name:"color"},{name:"line width"}],render:l=>(wt.RenderLine(l.width,l.height,l.context,l.cell,l.style),{handled:!0}),fn:(...l)=>({type:5,value:l,key:"sparkline-data"})},UniqueValues:{arguments:[{name:"range",boxed:!0}],visibility:"internal",fn:l=>{if(l.type===9){let e=n=>{if(n)switch(n.type){case 2:case 3:case 4:return n.value;case 0:return"";default:return console.info("check",n,n.value),n.value?.toString()||""}else return""},t=new Set,r=new Set;for(let n of l.value)for(let o of n){let a=e(o);t.has(a)?r.add(a):t.add(a)}let i=[];for(let n of l.value){let o=[];for(let a of n){let s=e(a);o.push({type:4,value:!r.has(s)})}i.push(o)}return{type:9,value:i}}return{type:4,value:!0}}},Between:{arguments:[{name:"target",boxed:!0,unroll:!0},{name:"min"},{name:"max"}],visibility:"internal",fn:(l,e=0,t=1)=>({type:4,value:l.type===3&&l.value>=e&&l.value<=t})},Gradient:{arguments:[{name:"range",boxed:!0},{name:"min"},{name:"max"},{name:"parameters"}],visibility:"internal",fn:(l,e,t,r)=>{let i=oe([l]),n=0,o=0,a=0;for(let u of i){if(u.type===7)return u;u.type===3&&(n===0&&!r?(o=u.value,a=u.value):(o=Math.min(o,u.value),a=Math.max(a,u.value)),n++)}typeof t=="number"&&(a=t),typeof e=="number"&&(o=e);let s=a-o,c=1,d=1;if(l.type===9){c=l.value.length,d=l.value[0]?.length||0;let u=[];for(let h=0;h<c;h++){let m=[];for(let f=0;f<d;f++){let p=l.value[h][f];if(p.type===3){let b=0;a===o?p.value>a?b=1:p.value<a?b=0:b=.5:s>0&&(b=(p.value-o)/s),r?m.push({type:9,value:[[{type:3,value:b},{type:3,value:(0-o)/s}]]}):m.push({type:3,value:b})}else m.push({type:0})}u.push(m)}return{type:9,value:u}}else return M()}},ATan2:{arguments:[{name:"y",boxed:!0,unroll:!0},{name:"x",boxed:!0,unroll:!0}],fn:(l,e)=>{if(l.type===3&&e.type===3)return{type:3,value:Math.atan2(l.value,e.value)};if(l.type===3&&(l={type:8,value:{real:l.value,imaginary:0}}),e.type===3&&(e={type:8,value:{real:e.value,imaginary:0}}),l.type===8&&e.type===8){let t=gn(l.value,e.value);return t===!1?M():{type:8,value:t}}return M()}},Sin:Le(Math.sin,ir),SinH:Le(Math.sinh,fn),ASin:Le(Math.asin,Zr),Cos:Le(Math.cos,mn),CosH:Le(Math.cosh,hn),ACos:Le(Math.acos,pn),Tan:Le(Math.tan,un),TanH:Le(Math.tanh,dn),ATan:Le(Math.atan,bn),E:{fn:()=>({type:3,value:Math.E})},PI:{fn:()=>({type:3,value:Math.PI})},SQRT2:{fn:()=>({type:3,value:Math.SQRT2})},SQRT1_2:{fn:()=>({type:3,value:Math.SQRT1_2})},Sequence:{arguments:[{name:"rows",boxed:!0},{name:"columns",default:1,boxed:!0},{name:"start",default:1,boxed:!0},{name:"step",default:1,boxed:!0}],fn:(l,e,t,r)=>{let i=dr(l,1),n=dr(e,1),o=dr(r,1),a=dr(t,1);if(i===!1||n===!1||o===!1||a===!1)return M();let s=[];for(let c=0;c<n;c++){let d=[];for(let u=0;u<i;u++)d.push({type:3,value:a+u*o*n+c*o});s.push(d)}return{type:9,value:s}}}},zn={};for(let l of Object.keys(et))zn[l.toLowerCase()]=l;var Aa=["ceil","pow","ln10","ln2","log10","log10e","log1p","log2","log2e","random","imul","clz32","fround","f16round"],Ln={};for(let l of Aa)Ln[l.toLowerCase()]=l;for(let l of Object.getOwnPropertyNames(Math)){let e=l.toLowerCase();if(zn[e]||Ln[e])continue;let t=Object.getOwnPropertyDescriptor(Math,l);if(!t)continue;let r=t.value,i=typeof r;switch(i){case"number":et[l]={fn:()=>({type:3,value:r}),category:["Math Functions"]};break;case"function":et[l]={fn:(...n)=>Q(r(...n)),category:["Math Functions"]};break;default:console.info("unexpected type:",i,l);break}}Math.log10||(Math.log10=l=>Math.log(l)/Math.log(10));var xt=(l,e,t=0,r=0,i=0)=>i?-(t*(l/(1-Math.pow(1+l,-e))))/(1+l)-r*(1/((1+l)*((Math.pow(1+l,e)-1)/l))):-(t*l*Math.pow(1+l,e)+r*l)/(Math.pow(1+l,e)-1),Fn=(l,e,t,r=0,i=0)=>i?(1+l)*-t/l*(Math.pow(1+l,e)-1)-r*Math.pow(1+l,e):-t/l*(Math.pow(1+l,e)-1)-r*Math.pow(1+l,e),ci=(l,e,t,r=0,i=0,n=0)=>{if(e<1)return NaN;if(e===1&&n)return 0;let o=xt(l,t,r,i,n),a=Fn(l,e-1,o,r,n)*l;return n?a/(1+l):a},In=(l,e,t,r=0,i=0,n=0)=>xt(l,t,r,i,n)-ci(l,e,t,r,i,n),Nn={NPV:{description:"Returns the present value of a series of future cashflows",arguments:[{name:"Rate"},{name:"Cashflow"}],fn:(l=0,...e)=>{let t=0,r=X(e);for(let i=0;i<r.length;i++){let n=r[i];typeof n=="number"&&(t+=Math.pow(1+l,-(i+1))*n)}return{type:3,value:t}}},XNPV:{description:"returns the NPV of a nonperiodic stream of payments at a given rate",arguments:[{name:"Discount rate"},{name:"Values"},{name:"Dates"}],fn:(l,e,t)=>{if(typeof l!="number")return M();if(e=X(e),t=X(t),e.length!==t.length)return M();let r=[];for(let o of e){if(typeof o!="number")return M();r.push(o)}let i=[];for(let o of t){if(typeof o!="number")return M();i.push(Math.floor(o))}let n=0;for(let o=0;o<r.length;o++)n+=(r[o]||0)/Math.pow(1+l,(i[o]-i[0])/365);return{type:3,value:n}}},XIRR:{description:"returns the internal rate of return of a nonperiodic stream of payments",arguments:[{name:"Values"},{name:"Dates"},{name:"Guess",default:.1}],fn:(l,e,t=.1)=>{if(l=X(l),e=X(e),l.length!==e.length)return M();let r=0,i=0,n=[];for(let u of l){if(typeof u!="number")return M();u>0&&r++,u<0&&i++,n.push(u)}if(r<=0||i<=0)return M();let o=[];for(let u of e){if(typeof u!="number")return M();o.push(Math.floor(u))}let a=o[0];for(let u of o)if(u<a)return M();let s=.1,c=[{found:!1,value:0},{found:!1,value:0}],d=n.length;for(let u=0;u<100;u++){let h=0;for(let m=0;m<d;m++)h+=(n[m]||0)/Math.pow(1+t,(o[m]-o[0])/365);if(Math.abs(h)<=1e-6)return{type:3,value:t};if(h>0){if(c[0].value=c[0].found?Math.max(c[0].value,t):t,c[0].found=!0,!c[1].found){t+=s;continue}}else if(c[1].value=c[1].found?Math.min(c[1].value,t):t,c[1].found=!0,!c[0].found){t-=s;continue}t=c[0].value+(c[1].value-c[0].value)/2}return U()}},IRR:{description:"Calculates the internal rate of return of a series of cashflows",arguments:[{name:"Cashflows"},{name:"Guess",default:.1}],fn:(l,e=.1)=>{let t=X(l).map(n=>typeof n=="number"?n:0),r=.1,i=[{found:!1,value:0},{found:!1,value:0}];for(let n=0;n<50;n++){let o=0;for(let a=0;a<t.length;a++)o+=Math.pow(1+e,-(a+1))*t[a];if(Math.abs(o)<=.00125)return{type:3,value:e};if(o>0){if(i[0].value=i[0].found?Math.max(i[0].value,e):e,i[0].found=!0,!i[1].found){e+=r;continue}}else if(i[1].value=i[1].found?Math.min(i[1].value,e):e,i[1].found=!0,!i[0].found){e-=r;continue}e=i[0].value+(i[1].value-i[0].value)/2}return{type:7,value:"NUM"}}},CUMPRINC:{description:"Returns cumulative principal paid on a loan between two periods",arguments:[{name:"Rate"},{name:"Periods"},{name:"Present Value"},{name:"Start Period"},{name:"End Period"},{name:"Type",default:0}],fn:(l,e,t,r,i,n=0)=>{let o=0;for(let a=r;a<=i;a++)o+=In(l,a,e,t,0,n);return{type:3,value:o}}},CUMIPMT:{description:"Returns cumulative interest paid on a loan between two periods",arguments:[{name:"Rate"},{name:"Periods"},{name:"Present Value"},{name:"Start Period"},{name:"End Period"},{name:"Type",default:0}],fn:(l,e,t,r,i,n=0)=>{let o=0;for(let a=r;a<=i;a++)o+=ci(l,a,e,t,0,n);return{type:3,value:o}}},IPMT:{description:"Returns the interest portion of a payment",arguments:[{name:"Rate"},{name:"Period"},{name:"Periods"},{name:"Present Value",default:0},{name:"Future Value",default:0},{name:"Type",default:0}],fn:(l,e,t,r=0,i=0,n=0)=>({type:3,value:ci(l,e,t,r,i,n)})},PPMT:{description:"Returns the principal portion of a payment",arguments:[{name:"Rate"},{name:"Period"},{name:"Periods"},{name:"Present Value",default:0},{name:"Future Value",default:0},{name:"Type",default:0}],fn:(l,e,t,r=0,i=0,n=0)=>({type:3,value:In(l,e,t,r,i,n)})},Rate:{description:"Returns the interest rate of a loan",arguments:[{name:"Periods"},{name:"Payment"},{name:"Present Value",default:0},{name:"Future Value",default:0},{name:"Type",default:0}],fn:(l,e,t=0,r=0,i=0)=>{let n=.25,o=[-1,1],a=32,s=1e-6;for(let c=0;c<a;c++){let d=xt(n,l,t,r,i);if(Math.abs(d-e)<=s)return{type:3,value:n};let u=xt(o[1],l,t,r,i);e>=d&&e<=u||e>=u&&e<=d?o[0]=n:o[1]=n,n=o[0]+(o[1]-o[0])/2}return{type:3,value:n}}},FV:{description:"Returns the future value of an investment",arguments:[{name:"Rate"},{name:"Periods"},{name:"Payment"},{name:"Present Value",default:0},{name:"Type",default:0}],fn:(l,e,t,r=0,i=0)=>({type:3,value:Fn(l,e,t,r,i)})},PV:{description:"Returns the present value of an investment",arguments:[{name:"Rate"},{name:"Periods"},{name:"Payment"},{name:"Future Value",default:0},{name:"Type",default:0}],fn:(l,e,t,r=0,i=0)=>i?(t+=r*(1/((1+l)*((Math.pow(1+l,e)-1)/l))),{type:3,value:-(t+t/l*(1-Math.pow(1+l,-(e-1))))}):{type:3,value:-(r+t/l*(Math.pow(1+l,e)-1))/Math.pow(1+l,e)}},NPER:{description:"Returns the number of periods of an investment",arguments:[{name:"Rate"},{name:"Payment"},{name:"Present Value"},{name:"Future Value",default:0},{name:"Type",default:0}],fn:(l,e,t=0,r=0,i=0)=>i?{type:3,value:1+(-Math.log(1+l*(1-t/-e))+Math.log(1+r*l/(-e*(1+l))))/Math.log(1+l)}:{type:3,value:(Math.log(Math.pow(1-t*l/-e,-1))+Math.log(1+r*l/-e))/Math.log(1+l)}},PMT:{description:"Returns the periodic payment of a loan",arguments:[{name:"Rate"},{name:"Periods"},{name:"Present Value"},{name:"Future Value",default:0},{name:"Type",default:0}],fn:(l,e,t,r=0,i=0)=>({type:3,value:xt(l,e,t,r,i)})}};var Pn={Char:{arguments:[{name:"number"}],fn:l=>({type:2,value:String.fromCodePoint(l||32)}),category:["text"]},Code:{arguments:[{name:"string"}],fn:l=>({type:3,value:l.codePointAt(0)||0}),category:["text"]},Value:{arguments:[{name:"text"}],fn:l=>{let e=ye.TryParse(l);return e.type===3?{type:3,value:e.value}:M()},category:["text"]},Text:{arguments:[{name:"value"},{name:"number format"}],fn:(l,e="0.00####")=>({type:2,value:L.Get(e).Format(l||0)}),category:["text"]},WildcardMatch:{visibility:"internal",arguments:[{name:"text",unroll:!0},{name:"text",unroll:!0},{name:"invert"}],fn:(l,e,t=!1)=>{if(typeof l=="string"&&typeof e=="string"){let r=vt(e),i=new RegExp("^"+r+"$","i").exec(l);return{type:4,value:t?!i:!!i}}return{type:4,value:l===e||l?.toString()===e?.toString()}}},Exact:{arguments:[{name:"text",boxed:!0,unroll:!0},{name:"text",boxed:!0,unroll:!0}],category:["text"],fn:(l,e)=>({type:4,value:l?.value?.toString()===e?.value?.toString()})},Len:{arguments:[{name:"string",unroll:!0}],fn:l=>({type:3,value:l.toString().length})},Substitute:{arguments:[{name:"text"},{name:"search"},{name:"replacement"},{name:"index"}],fn:(l,e,t,r)=>{if(typeof r=="number"){if(r<1)return U();let i=1;return{type:2,value:l.replaceAll(e,(...n)=>(console.info(n),i++===r?t:e))}}else return{type:2,value:l.replaceAll(e,t)}}},Left:{arguments:[{name:"string"},{name:"count"}],fn:(l,e=1)=>({type:2,value:l.substr(0,e)}),category:["text"]},Right:{arguments:[{name:"string"},{name:"count"}],fn:(l,e=1)=>({type:2,value:l.slice(-e)}),category:["text"]},Mid:{arguments:[{name:"string"},{name:"left"},{name:"count"}],fn:(l,e=0,t=1)=>({type:2,value:l.substr(Math.max(0,e-1),t)}),category:["text"]},Search:{description:"Find a string (needle) in another string (haystack). Case-insensitive.",arguments:[{name:"Needle"},{name:"Haystack"},{name:"Start",default:1}],fn:(l,e,t=1)=>{if(t>=1){if(!l)return{type:3,value:t};let r=vt(l),i=new RegExp(r,"i").exec(e.substr(t-1));if(i)return{type:3,value:i.index+t}}return U()}},Find:{description:"Find a string (needle) in another string (haystack). Case-sensitive.",arguments:[{name:"Needle"},{name:"Haystack"},{name:"Start",default:1}],fn:(l,e,t=1)=>{if(t>=1){if(!l)return{type:3,value:t};l=l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");let r=new RegExp(l).exec(e.substr(t-1));if(r)return{type:3,value:r.index+t}}return U()}},Upper:{description:"Converts text to upper case",arguments:[{name:"text",unroll:!0}],fn:l=>l==null?{type:0}:{type:2,value:l.toString().toUpperCase()}},Lower:{description:"Converts text to lower case",arguments:[{name:"text",unroll:!0}],fn:l=>l==null?{type:0}:{type:2,value:l.toString().toLowerCase()}},Concat:{description:"Pastes strings together",fn:(...l)=>{let t=X(l).map(r=>{let i=r?.toString()||"";return typeof r=="number"&&F.decimal_separator===","?i.replace(/\./,","):i}).join("");return{type:2,value:t}}}},di={Concatenate:"Concat"};var ur=(l,e)=>({type:4,value:typeof e.value?.value===l}),hr=[{name:"Reference",metadata:!0,unroll:!0}],On={IsBlank:{description:"Returns true if the reference is blank",arguments:hr,fn:ur.bind(0,"undefined")},IsNumber:{description:"Returns true if the reference is a number",arguments:hr,fn:ur.bind(0,"number")},IsLogical:{description:"Returns true if the reference is a logical TRUE or FALSE",arguments:hr,fn:ur.bind(0,"boolean")},IsText:{description:"Returns true if the reference is text",arguments:hr,fn:ur.bind(0,"string")}};var Hn=2220446049250313e-31,ka=l=>{let e=1+l;return Math.log(e)-(e-1-l)/e},mr=(l,e,t,r)=>{let i=2*Number.MIN_VALUE,n=0,o=1,a=1-(l+e)*t/(l+1);Math.abs(a)<i&&(a=Number.NaN),a=1/a,n=a;for(let s=1;s<=512;s++){let c=s*(e-s)*t/((l-1+2*s)*(l+2*s)),d=0;if(a=1+c*a,o=1+c/o,Math.abs(a)<i&&(a=Number.NaN),Math.abs(o)<i&&(o=Number.NaN),a=1/a,d=a*o,n*=d,c=-(l+s)*(l+e+s)*t/((l+2*s)*(l+2*s+1)),a=1+c*a,o=1+c/o,Math.abs(a)<i&&(a=Number.NaN),Math.abs(o)<i&&(o=Number.NaN),a=1/a,d=a*o,n*=d,Math.abs(d-1)<2*Hn||n*Math.abs(d-1)<r)return n}return Number.NaN},ui=(l,e,t)=>{if(e<0||t<0)return Number.NaN;if(l<=0)return 0;if(l>=1)return 1;if(l>.5)return 1-ui(1-l,t,e);let r=e/(e+t),i=0;if(l<.1){let n=(Math.log(e)+ae(e)+ae(t)-ae(e+t)+Math.log(l))/e;n<=0?(i=Math.exp(n),i*=Math.pow(1-i,-(t-1)/e)):i=r,i>r&&(i=r)}else i=r;for(let n=0;n<64;n++){let o=l-mi(i,e,t),a=hi(i,e,t);if(o===0)return i;let s=o/Math.max(2*Math.abs(o/i),a),c=s,d=-((e-1)/i-(t-1)/(1-i))*s*s/2,u=c;if(Math.abs(d)<Math.abs(c)?u+=d:u*=2*Math.abs(c/d),i+u>0&&i+u<1?i+=u:i=Math.sqrt(i)*Math.sqrt(r),Math.abs(c)<=1e-10*i)return i}return i},ae=l=>{let e=l-1,t=e+5.5;t-=(e+.5)*Math.log(t);let r=1,i=[76.18009173,-86.50532033,24.01409822,-1.231739516,.00120858003,-536382e-11];for(let n of i)r+=n/++e;return-t+Math.log(2.50662827465*r)},hi=(l,e,t)=>l<0||l>1?0:Math.exp(ae(e+t)-ae(e)-ae(t))*Math.pow(l,e-1)*Math.pow(1-l,t-1),mi=(l,e,t)=>{if(l<=0)return 0;if(l>=1)return 1;let i=-(ae(e)+ae(t)-ae(e+t))+e*Math.log(l)+t*ka(-l),n=Math.exp(i);if(l<(e+1)/(e+t+2)){let o=mr(e,t,l,0);return n*o/e}else{let o=Math.abs(t/n)*Hn,a=mr(t,e,1-l,o);return 1-n*a/t}},Gn=(l,e,t)=>{if(l<0||l>1)return 0;let r=l===0||l===1?0:Math.exp(ae(e+t)-ae(e)-ae(t)+e*Math.log(l)+t*Math.log(1-l));return l<(e+1)/(e+t+2)?r*mr(e,t,l,0)/e:1-r*mr(t,e,1-l,0)/t};var Bn=l=>{let e=l-1,t=e+5.5;t-=(e+.5)*Math.log(t);let r=1,i=[76.18009173,-86.50532033,24.01409822,-1.231739516,.00120858003,-536382e-11];for(let n of i)r+=n/++e;return-t+Math.log(2.50662827465*r)},Ra=(l,e)=>{let t=Bn(l);if(e===0)return 0;let r=l,i=1/l,n=i;for(let o=1;o<1e3;o++)if(++r,n*=e/r,i+=n,Math.abs(n)<Math.abs(i)*3e-9)return i*Math.exp(-e+l*Math.log(e)-t);return console.error("too many iterations"),!1},Ea=(l,e)=>{let t=Bn(l),r=e+1-l,i=1/1e-30,n=1/r,o=n;for(let a=1;a<=1e3;a++){let s=-a*(a-l);r+=2,n=s*n+r,Math.abs(n)<1e-30&&(n=1e-30),i=r+s/i,Math.abs(i)<1e-30&&(i=1e-30),n=1/n;let c=n*i;if(o*=c,Math.abs(c-1)<3e-9)return Math.exp(-e+l*Math.log(e)-t)*o}return console.error("too many iterations"),!1},fr=(l,e)=>{if(e<0||l<=0)return console.error("invalid parameter"),!1;if(e<l+1)return Ra(l,e);{let t=Ea(l,e);return t===!1?!1:1-t}};var Ct=l=>{if(l===.5)return 0;let e=l<1&&l>.5?1-l:l,t=Math.sqrt(Math.log(1/Math.pow(e,2))),r=t-(2.515517+.802853*t+.010328*Math.pow(t,2))/(1+1.432788*t+.189269*Math.pow(t,2)+.001308*Math.pow(t,3));return l>.5?r:-r};var fi=(l,e)=>{let t=e/(e+l*l),r=e/2,n=Gn(t,r,.5);return l>=0?1-.5*n:.5*n},pi=(l,e)=>{let t=ae((e+1)/2),r=ae(e/2)+.5*Math.log(e*Math.PI),i=-((e+1)/2)*Math.log(1+l*l/e),n=t-r+i;return Math.exp(n)},bi=(l,e)=>{let r=1;{let i=Ct(l),n=(Math.pow(i,3)+i)/4,o=(5*Math.pow(i,5)+16*Math.pow(i,3)+3*i)/96,a=(3*Math.pow(i,7)+19*Math.pow(i,5)+17*Math.pow(i,3)-15*i)/384,s=(79*Math.pow(i,9)+776*Math.pow(i,7)+1482*Math.pow(i,5)-1920*Math.pow(i,3)-945*i)/92160;r=i+n/e+o/Math.pow(e,2)+a/Math.pow(e,3)+s/Math.pow(e,4)}for(let i=0;i<16;i++){let n=fi(r,e)-l;if(Math.abs(n)<1e-12)break;let o=pi(r,e);if(o===0)break;let a=n/o,s=Math.max(-1,Math.min(1,a));r-=s}return r};var jn=l=>{let e=.254829592,t=-.284496736,r=1.421413741,i=-1.453152027,n=1.061405429,o=.3275911;l=Math.abs(l);let a=1/(1+o*l);return 1-((((n*a+i)*a+r)*a+t)*a+e)*a*Math.exp(-1*l*l)},Ta=Math.sqrt(2*Math.PI),gi=(l,e,t,r)=>{let i=0;return r?i=.5*(1+(l<e?-1:1)*jn(Math.abs(l-e)/(t*Math.sqrt(2)))):i=Math.exp(-1/2*Math.pow((l-e)/t,2))/(t*Ta),i},_i=l=>{let e=l.length;return e%2?l[Math.floor(e/2)]:(l[e/2]+l[e/2-1])/2},$n=(l,e=!0)=>{l.sort((i,n)=>i-n);let t=l.length,r=(i,n,o)=>{let a=n*i+o,s=a%1;if(s){let c=l[Math.floor(a)],d=l[Math.ceil(a)];return c+(d-c)*s}else return l[a]};return e?[l[0],r(.25,t-1,0),_i(l),r(.75,t-1,0),l[t-1]]:t%1?[l[0],r(.25,t-2,0),_i(l),r(.75,t-2,1),l[t-1]]:[l[0],r(.25,t-3,0),_i(l),r(.75,t-3,2),l[t-1]]},pr=l=>{let e=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,15056327351493116e-23],t=Math.PI,r=ir,i=Pe,n=ne,o=f=>({real:f,imaginary:0}),a=(f,p)=>({real:f.real+p.real,imaginary:f.imaginary+p.imaginary}),s=we,c=yt,d=f=>({real:-f.real,imaginary:-f.imaginary}),u=_n;if(l.real<.5)return i(o(t),n(r(n(o(t),l)),pr({real:1-l.real,imaginary:-l.imaginary})));l.real-=1;let h=o(e[0]);for(let f=1;f<e.length;f++)h=a(h,i(o(e[f]),a(l,o(f))));let m=a(l,o(7.5));return u(o(Math.sqrt(2*t)),s(m,a(l,o(.5))),c(d(m)),h)},Ma=(l,e,t)=>{let r=pr({real:e,imaginary:0}).real;return Math.pow(l,e-1)*Math.exp(-l/t)/(r*Math.pow(t,e))},Ua=(l,e,t)=>{let r=0,i=e*10,n=1e-6,o=0;for(;i-r>n;){o++;let a=(i+r)/2,s=fr(e,r/t),c=fr(e,a/t);if(s===!1||c===!1)return!1;(c-l)*(s-l)<0?i=a:r=a}return(r+i)/2},Te=(l,e=!1)=>{let t=l.length,r=0,i=0;for(let n=0;n<t;n++)r+=l[n];r/=t;for(let n=0;n<t;n++){let o=l[n]-r;i+=o*o}return e?i/(t-1):i/t},qn={Slope:{arguments:[{name:"known_y"},{name:"known_x"}],fn:(l,e)=>{let t=te(e),r=te(l);if(t.length!==r.length)return M();let i=0,n=0,o=0,a=0;for(let c=0;c<t.length;c++){let d=t[c],u=r[c];o+=d*u,i+=d,n+=u,a+=d*d}let s=(t.length*o-i*n)/(t.length*a-i*i);return{type:3,value:s}}},Intercept:{arguments:[{name:"known_y"},{name:"known_x"}],fn:(l,e)=>{let t=te(e),r=te(l);if(t.length!==r.length)return M();let i=t.length,n=0,o=0,a=0,s=0;for(let d=0;d<i;d++){let u=t[d],h=r[d];a+=u*h,n+=u,o+=h,s+=u*u}let c=i*a-n*o;return c/=i*s-n*n,{type:3,value:(o-c*n)/i}}},Phi:{arguments:[{name:"x",boxed:!0,unroll:!0}],fn:l=>l.type===3?{type:3,value:1/Math.sqrt(Math.PI*2)*Math.exp(-l.value*l.value/2)}:M()},"Z.Test":{arguments:[{name:"Array",boxed:!0},{name:"x",boxed:!0,unroll:!0},{name:"Sigma",boxed:!0,unroll:!0}],fn:(l,e,t)=>{let r=[];if(l.type===9)for(let i of l.value)for(let n of i)n.type===3&&r.push(n.value);else l.type===3&&r.push(l.value);if(r.length&&e.type===3){let i=0,n=r.length;for(let a of r)i+=a;i/=n;let o=t?.type===3?t.value:Math.sqrt(Te(r,!0));return{type:3,value:1-gi((i-e.value)/(o/Math.sqrt(n)),0,1,!0)}}return M()}},"Beta.Dist":{description:"beta distribution",arguments:[{name:"x",unroll:!0},{name:"a"},{name:"b"},{name:"cumulative"}],fn:(l,e,t,r)=>e<0||t<0?M():r?{type:3,value:mi(l,e,t)}:{type:3,value:hi(l,e,t)}},"Beta.Inv":{description:"Inverse of the beta distribution",arguments:[{name:"probability",unroll:!0},{name:"a"},{name:"b"}],fn:(l,e,t)=>e<0||t<0?M():{type:3,value:ui(l,e,t)}},Erf:{fn:l=>({type:3,value:jn(l)})},"Norm.Inv":{description:"Inverse of the normal cumulative distribution",arguments:[{name:"probability"},{name:"mean",default:0},{name:"standard deviation",default:1}],xlfn:!0,fn:(l,e=0,t=1)=>({type:3,value:Ct(l)*t+e})},"Norm.S.Inv":{description:"Inverse of the standard normal cumulative distribution",arguments:[{name:"probability",unroll:!0}],xlfn:!0,fn:l=>({type:3,value:Ct(l)})},"Norm.Dist":{description:"Cumulative normal distribution",arguments:[{name:"value"},{name:"mean",default:0},{name:"standard deviation",default:1},{name:"cumulative",default:!0}],xlfn:!0,fn:(l,e=0,t=1,r=!0)=>({type:3,value:gi(l,e,t,r)})},"Norm.S.Dist":{description:"Cumulative normal distribution",arguments:[{name:"value"},{name:"cumulative",default:!0}],xlfn:!0,fn:(l,e=!0)=>({type:3,value:gi(l,0,1,e)})},"StDev.P":{description:"Returns the standard deviation of a set of values, corresponding to a population",arguments:[{name:"data"}],fn:(...l)=>({type:3,value:Math.sqrt(Te(te(l),!1))})},"StDev.S":{description:"Returns the standard deviation of a set of values, corresponding to a sample of a population",arguments:[{name:"data"}],fn:(...l)=>({type:3,value:Math.sqrt(Te(te(l),!0))})},"Var.P":{description:"Returns the variance of a set of values, corresponding to a population",arguments:[{name:"data"}],fn:(...l)=>({type:3,value:Te(te(l),!1)})},"Var.S":{description:"Returns the variance of a set of values, corresponding to a sample of a population",arguments:[{name:"data"}],fn:(...l)=>({type:3,value:Te(te(l),!0)})},Covar:{description:"Returns the covariance between two ranges of values",arguments:[{name:"A"},{name:"B"}],fn:(l,e)=>{if(!Array.isArray(l)||!Array.isArray(e))return U();if(!Array.isArray(l[0])||!Array.isArray(e[0]))return U();if(l.length!==e.length)return M();let t=0,r=0,i={x:0,y:0},n={x:[],y:[]};for(let o=0;o<l.length;o++){if(!l[o]||!e[o])continue;if(l[o].length!==e[o].length)return M();let a=l[o].length;r+=a;for(let s=0;s<a;s++)i.x+=l[o][s]||0,i.y+=e[o][s]||0,n.x.push(l[o][s]||0),n.y.push(e[o][s]||0)}if(r===0)return xe();i.x/=r,i.y/=r;for(let o=0;o<r;o++)t+=(n.x[o]-i.x)*(n.y[o]-i.y);return{type:3,value:t/r}}},Correl:{description:"Returns the correlation between two ranges of values",arguments:[{name:"A"},{name:"B"}],fn:(l,e)=>{if(!Array.isArray(l)||!Array.isArray(e))return U();if(!Array.isArray(l[0])||!Array.isArray(e[0]))return U();let t=0,r=0,i=0,n=0,o=0,a=0,s=0;for(let c=0;c<l.length;c++){if(!l[c]||!e[c])continue;let d=l[c].length;for(let u=0;u<d;u++){let h=Number(l[c][u]),m=Number(e[c][u]);isNaN(h)||isNaN(m)||(r+=h*m,i+=h,n+=m,o+=h*h,a+=m*m,s++)}}return t=s*r-i*n,t&&(t/=Math.sqrt((s*o-i*i)*(s*a-n*n))),{type:3,value:t}}},GeoMean:{description:"Returns the geometric mean of all numeric arguments",arguments:[{boxed:!0}],fn:(...l)=>{l=oe(l);let e=0,t={real:1,imaginary:0},r=!1,i=!1;for(let n of l)n.type===8?(r=!0,t=ne(t,n.value),e++):n.type===3&&(n.value<0&&(i=!0),e++,t.real*=n.value,t.imaginary*=n.value);if(r){let n=we(t,{real:1/e,imaginary:0});return n.imaginary?{type:8,value:n}:{type:3,value:n.real}}else return i?U():{type:3,value:Math.pow(t.real,1/e)}}},LCM:{description:"Retuns the least common mulitple of the arguments",arguments:[{boxed:!0}],fn:(...l)=>{l=oe(l);let e=[];for(let i of l){if(i.type===7)return i;if(i.type===3)e.push(i.value);else if(i.type!==0)return console.info("RT",i.type),M()}let t=(i,n)=>i%n==0?n:t(n,i%n);if(e.length===0)return{type:3,value:0};let r=e[0];for(let i=1;i<e.length;i++)r=r*e[i]/t(r,e[i]);return{type:3,value:r}}},"Gamma.Inv":{description:"Returns the inverse of the gamma distribution",arguments:[{name:"probability",unroll:!0},{name:"alpha"},{name:"beta"}],fn:(l,e,t)=>{if(l<0||l>1)return M();let r=Ua(l,e,t);return r===!1?U():{type:3,value:r}}},"Gamma.Dist":{fn:(l,e,t,r)=>{if(l<0||e<=0||t<=0)return M();let i=r?fr(e,l/t):Ma(l,e,t);return i===!1?U():{type:3,value:i}}},"T.DIST":{description:"Returns the left-tailed Student's t-distribution",arguments:[{name:"X",unroll:!0,boxed:!0},{name:"degrees of freedom",unroll:!0,boxed:!0},{name:"cumulative",unroll:!0,boxed:!0}],fn:(l,e,t)=>{let r=t?!!t.value:!1;return e.type!==3||l.type!==3||e.value<1?M():{type:3,value:r?fi(l.value,e.value):pi(l.value,e.value)}}},"T.Inv":{description:"Returns the left-tailed inverse of the Student's t-distribution",arguments:[{name:"Probability",boxed:!0,unroll:!0},{name:"Degrees of freedom",boxed:!0,unroll:!0}],fn:(l,e)=>e.type!==3||e.value<1||l.type!==3||l.value<=0||l.value>=1?M():{type:3,value:bi(l.value,e.value)}},"T.Inv.2T":{description:"Returns the two-tailed inverse of the Student's t-distribution",arguments:[{name:"Probability",boxed:!0,unroll:!0},{name:"Degrees of freedom",boxed:!0,unroll:!0}],fn:(l,e)=>e.type!==3||e.value<1||l.type!==3||l.value<=0||l.value>=1?M():{type:3,value:Math.abs(bi(1-l.value/2,e.value))}},GammaLn:{description:"Returns the natural log of the gamma function",arguments:[{name:"value",boxed:!0,unroll:!0}],fn:l=>l.type===3?{type:3,value:ae(l.value)}:M()},"GammaLn.Precise":{description:"Returns the natural log of the gamma function",arguments:[{name:"value",boxed:!0,unroll:!0}],fn:l=>{let e;if(l.type===3?e={real:l.value,imaginary:0}:l.type===8&&(e=l.value),e){let t=pr(e);return de(ei(t))}return M()}},Gamma:{description:"Returns the gamma function for the given value",arguments:[{name:"value",boxed:!0,unroll:!0}],fn:l=>{let e={real:0,imaginary:0};if(l.type===8)e={...l.value};else if(l.type===3)e.real=l.value;else return M();if(e.imaginary===0&&e.real%1===0&&e.real<=0)return U();let t=pr(e);return Math.abs(t.imaginary)<=1e-7?{type:3,value:t.real}:{type:8,value:t}}},Delta:{arguments:[{name:"number"},{name:"number",default:0}],fn:(l,e=0)=>typeof l!="number"||typeof e!="number"?U():{type:3,value:l===e?1:0}},GCD:{description:"Finds the greatest common divisor of the arguments",arguments:[{boxed:!0}],fn:(...l)=>{l=oe(l);let e=[];for(let i of l){if(i.type===7)return i;if(i.type===3)e.push(i.value);else if(i.type!==0)return console.info("RT",i.type),M()}let t=(i,n)=>i%n==0?n:t(n,i%n);if(e.length===0)return U();if(e.length===1)return{type:3,value:e[0]};let r=e[0];for(let i=1;i<e.length;i++)r=t(r,e[i]);return{type:3,value:r}}},HarMean:{description:"Returns the harmonic mean of the arguments",arguments:[{boxed:!0}],fn:(...l)=>{l=oe(l);let e={real:0,imaginary:0},t=0;for(let r of l){if(r.type===7)return r;if(r.type===3&&(e.real+=1/r.value,t++),r.type===8){let i=Pe({real:1,imaginary:0},r.value);e.real+=i.real,e.imaginary+=i.imaginary,t++}}return e.imaginary?{type:8,value:Pe({real:t,imaginary:0},e)}:{type:3,value:t/e.real}}},Average:{description:"Returns the arithmetic mean of all numeric arguments",arguments:[{boxed:!0}],fn:(...l)=>{l=oe(l);let e={real:0,imaginary:0},t=0;for(let r of l){if(r.type===7)return r;r.type===3&&(e.real+=r.value,t++),r.type===8&&(e.real+=r.value.real,e.imaginary+=r.value.imaginary,t++)}return e.real/=t,e.imaginary/=t,e.imaginary?{type:8,value:e}:{type:3,value:e.real}}},Percentile:{description:"Returns the kth percentile value from the range of data",arguments:[{name:"range"},{name:"percentile"}],fn:(l,e)=>{let t=te(l);t.sort((s,c)=>s-c);let r=t.length,i=Math.pow(10,8),n=Math.round((1+(r-1)*e)*i)/i,o=Math.floor(n),a=Math.ceil(n);return{type:3,value:(t[o-1]+t[a-1])/2}}},"Quartile.Inc":{description:"Returns the interpolated quartile of the data set (including median)",arguments:[{name:"range"},{name:"quartile"}],xlfn:!0,fn:(l,e)=>{if(typeof e!="number"||e<0||e>4||e%1)return M();let t=te(l),r=$n(t,!0);return{type:3,value:r[e]}}},"Quartile.Exc":{description:"Returns the interpolated quartile of the data set (excluding median)",arguments:[{name:"range"},{name:"quartile"}],xlfn:!0,fn:(l,e)=>{if(typeof e!="number"||e<1||e>3||e%1)return M();let t=te(l),r=$n(t,!1);return{type:3,value:r[e]}}},Median:{description:"Returns the median value of the range of data",arguments:[{name:"range"}],fn:(...l)=>{let e=te(l);e.sort((o,a)=>o-a);let r=1+(e.length-1)*.5,i=Math.floor(r),n=Math.ceil(r);return{type:3,value:(e[i-1]+e[n-1])/2}}},Rank:{arguments:[{name:"Value"},{name:"Source"},{name:"Order"}],fn:(l,e,t=0)=>{if(typeof l!="number")return M();let r=te(e);r.sort(t?(i,n)=>i-n:(i,n)=>n-i);for(let i=0;i<r.length;i++)if(r[i]===l)return{type:3,value:i+1};return U()}}},yi={Mean:"Average",StDev:"StDev.S",StDevA:"StDev.S",StDevPA:"StDev.P",Var:"Var.S",Quartile:"Quartile.Inc",NormSInv:"Norm.S.Inv",NormSDist:"Norm.S.Dist",NormDist:"Norm.Dist"};var Jn={IsComplex:{description:"Returns true if the reference is a complex number",arguments:[{name:"Reference",metadata:!0,unroll:!0}],fn:l=>({type:4,value:!!l?.value&&me(l.value.value)})},Real:{description:"Returns the real part of a complex number",arguments:[{boxed:!0,unroll:!0}],fn:l=>l.type===3?{...l}:l.type===8?{type:3,value:l.value.real||0}:l.type===0||l.type===2&&l.value===""?{type:3,value:0}:U()},Imaginary:{description:"Returns the imaginary part of a complex number (as real)",arguments:[{boxed:!0,unroll:!0}],fn:l=>l.type===8?{type:3,value:l.value.imaginary||0}:l.type===3||l.type===0||l.type===2&&l.value===""?{type:3,value:0}:U()},Conjugate:{description:"Returns the conjugate of a complex number",arguments:[{boxed:!0,unroll:!0}],fn:l=>{let e=Oe(l);return e?e.imaginary?{type:8,value:{real:e.real,imaginary:-e.imaginary}}:{type:3,value:e.real}:U()}},Arg:{description:"Returns the principal argument of a complex number (in radians)",arguments:[{boxed:!0,unroll:!0}],fn:l=>l.type===8?{type:3,value:Math.atan2(l.value.imaginary,l.value.real)}:l.type===3||l.type===0||l.type===2&&l.value===""?{type:3,value:Math.atan2(0,l.value||0)}:U()},Rectangular:{description:"Converts a complex number in polar form to rectangular form",arguments:[{name:"r"},{name:"\u03B8 in radians"}],fn:(l=0,e=0)=>({type:8,value:{real:l*Math.cos(e),imaginary:l*Math.sin(e)}})},Complex:{description:"Ensures that the given value will be treated as a complex number",arguments:[{boxed:!0,unroll:!0}],fn:l=>{let e=Oe(l);return e?{type:8,value:e}:U()}},ComplexLog:{description:"Returns the principal value Log(z) of a complex number z",arguments:[{boxed:!0,unroll:!0}],fn:l=>{if(l.type===3){if(!l.value)return U();l={type:8,value:{real:l.value,imaginary:0}}}else if(l.type===0||l.type===2&&l.value==="")return U();if(l.type===8){let e=rr(l.value),t={real:Math.log(e.r),imaginary:e.theta};return t.imaginary?{type:8,value:t}:{type:3,value:t.real}}return U()}}};var br=l=>{let e=[];l.type===9?e=l.value:e=[[l]];let t=e.length,r=t?e[0].length:0,i=[];if(!t||!r)return{m:t,n:r,array:i};for(let n=0;n<t;n++){let o=[];for(let a=0;a<r;a++){let s=e[n][a];if(s.type===8)o.push({...s.value});else if(s.type===3)o.push({real:s.value,imaginary:0});else if(s.type===0||s.value==="")o.push({real:0,imaginary:0});else return{m:t,n:r,error:!0,array:[]}}i.push(o)}return{m:t,n:r,array:i}},Wn={MDeterm:{description:"Returns the determinant of a matrix",arguments:[{name:"matrix",boxed:!0}],fn:l=>{let e=br(l);if(!e.array||!e.m||!e.n||e.m!==e.n||e.error)return U();let t=nr(e);return t?de(t):U()}},MInverse:{description:"Returns the inverse matrix",arguments:[{name:"matrix",boxed:!0}],fn:l=>{let e=br(l);if(!e.array||!e.m||!e.n||e.m!==e.n||e.error)return U();let t=nr(e);if(t&&t.real===0&&t?.imaginary===0)return U();let r=vn(e);return r?{type:9,value:r.map(i=>i.map(n=>de(n)))}:U()}},MMult:{description:"Returns the dot product A \u22C5 B",arguments:[{name:"A",boxed:!0},{name:"B",boxed:!0}],fn:(l,e)=>{let t=br(l),r=br(e);if(!t.array||t.error||!r.array||r.error)return U();if(t.m!==r.n)return U();let i=yn(r,t);return{type:9,value:i.map(n=>n.map(o=>de(o)))}}}};var Xn={RegexExtract:{description:"Extract text using a regular expression",arguments:[{name:"text",unroll:!0},{name:"pattern",unroll:!0},{name:"return mode",unroll:!0,default:0},{name:"case insensitive",unroll:!0,default:!1}],fn:(l,e,t=0,r=!1)=>{let i=[];r&&i.push("i"),t===1&&i.push("g");let n=new RegExp(e,i.length?i.join(""):void 0);switch(t){case 0:{let o=l.match(n);return{type:2,value:o===null?"":o[0]??""}}case 1:{let o=Array.from(l.matchAll(n));return console.info({result:o}),{type:9,value:[o.map(a=>({type:2,value:a[0]||""}))]}}case 2:{let o=l.match(n);if(o===null)return{type:2,value:""};let a=Array.from(o).slice(1);return{type:9,value:[a.map(s=>({type:2,value:s}))]}}default:return M()}}},RegexReplace:{arguments:[{name:"text",unroll:!0},{name:"pattern",unroll:!0},{name:"replacement",unroll:!0},{name:"occurrence",unroll:!0,default:0},{name:"case insensitive",unroll:!0,default:!1}],description:"Replace text in a string using a regex",fn:(l,e,t,r=0,i=!1)=>{let n=["g"];i&&n.push("i");let o=new RegExp(e,n.length?n.join(""):void 0);if(r===0)return{type:2,value:l.replaceAll(o,t)};if(r<0){let s=Array.from(l.matchAll(o)).length;r+=s+1}let a=l.replace(o,s=>--r===0?t:s);return{type:2,value:a}}},RegexTest:{arguments:[{name:"text",unroll:!0},{name:"pattern",unroll:!0},{name:"case insensitive",unroll:!0,default:!1}],description:"Match text against a regular expression",fn:(l,e,t=!1)=>{let r=new RegExp(e,t?"i":void 0);return{type:4,value:r.test(l)}}}};var Kn={Lambda:{description:"Creates a function",arguments:[{name:"Argument",repeat:!0,boxed:!0,passthrough:!0},{name:"Function",boxed:!0,passthrough:!0}],fn:(...l)=>({type:6,value:{bindings:l.slice(0,l.length-1),func:l[l.length-1],alt:"LAMBDA",type:"function"}})},Let:{description:"Binds values to names for a calculation",arguments:[{name:"Name",repeat:!0},{name:"Value",repeat:!0},{name:"Calculation",boxed:!0}],create_binding_context:({args:l,descriptors:e})=>{if(l.length%2!==1)return;let t={};for(let r=0;r<l.length-1;r+=2){let i=l[r],n=l[r+1];if(i.type==="identifier")t[i.name]=n;else return}return{context:t,args:l.slice(-1),argument_descriptors:e.slice(-1)}},fn:l=>l||{type:0}}};var Yn={MakeArray:{description:"Create an array using a function",arguments:[{name:"rows"},{name:"columns"},{name:"lambda",description:"Function to apply",boxed:!0}],fp:!0,fn:function(l,e,t){if(l>0&&e>0&&t?.type===6){let r=this?.apply;if(!r)return U();let i=[];for(let n=0;n<e;n++){let o=[];for(let a=0;a<l;a++)o.push(r(t,[{type:3,value:a+1},{type:3,value:n+1}]));i.push(o)}return{type:9,value:i}}return M()}},Reduce:{description:"Accumulates a value by applying a function to a set of values",arguments:[{name:"initial value",boxed:!0},{name:"data",description:"Input data",boxed:!0},{name:"lambda",description:"Function to apply",boxed:!0}],fp:!0,fn:function(l,e,t){if(!this?.apply)return U();if(t.type!==6)return M();e.type!==9&&(e={type:9,value:[[e]]});let r=e.value.length,i=e.value[0].length;for(let n=0;n<i;n++)for(let o=0;o<r;o++){let a=[l,e.value[o][n]];l=this.apply(t,a)}return l}},Scan:{description:"Applies a function to a set of values, iteratively",arguments:[{name:"initial value",boxed:!0},{name:"data",description:"Input data",boxed:!0},{name:"lambda",description:"Function to apply",boxed:!0}],fp:!0,fn:function(l,e,t){if(!this?.apply)return U();if(t.type!==6)return M();e.type!==9&&(e={type:9,value:[[e]]});let r=[],i=e.value.length,n=e.value[0].length;for(let o=0;o<i;o++)r.push([]);for(let o=0;o<n;o++)for(let a=0;a<i;a++){let s=[l,e.value[a][o]],c=this.apply(t,s);r[a][o]=c,l=c}return{type:9,value:r}}},ByRow:{description:"Apply a function to each row in an array",arguments:[{name:"data",description:"Input data",repeat:!0,boxed:!0},{name:"lambda",description:"Function to apply",boxed:!0}],fp:!0,fn:function(l,e){if(!this?.apply)return U();if(e.type!==6)return M();l.type!==9&&(l={type:9,value:[[l]]});let t=l.value.length,r=l.value[0].length,i=[[]];for(let n=0;n<r;n++){let o=[];for(let a=0;a<t;a++)o.push(l.value[a][n]);i[0].push(this.apply(e,[{type:9,value:[o]}]))}return{type:9,value:i}}},ByCol:{description:"Apply a function to each column in an array",arguments:[{name:"data",description:"Input data",repeat:!0,boxed:!0},{name:"lambda",description:"Function to apply",boxed:!0}],fp:!0,fn:function(l,e){if(!this?.apply)return U();if(e.type!==6)return M();l.type!==9&&(l={type:9,value:[[l]]});let t=l.value.length,r=l.value[0].length,i=[];for(let n=0;n<t;n++){let o=[];for(let a=0;a<r;a++)o.push(l.value[n][a]);i.push([this.apply(e,[{type:9,value:[o]}])])}return{type:9,value:i}}},Map:{description:"Apply a function to a set of values",arguments:[{name:"data",description:"Input data",repeat:!0,boxed:!0},{name:"lambda",description:"Function to apply",boxed:!0}],fp:!0,fn:function(...l){if(l.length<2)return M();let e=l[l.length-1];if(e.type!==6)return M();let t=this?.apply;if(!t)return U();for(let n=0;n<l.length-1;n++){let o=l[n];o.type!==9&&(l[n]={type:9,value:[[o]]})}let r=l[0],i=[];if(r.type===9)for(let n=0;n<r.value.length;n++){let o=r.value[n],a=[];for(let s=0;s<o.length;s++){let c=[o[s]];for(let d=1;d<l.length-1;d++){let u=l[d];u.type===9&&c.push(u.value[n][s])}a.push(t(e,c))}i.push(a)}return{type:9,value:i}}}};var tt=class l extends ze{static type="state-leaf-vertex";state_id=0;type=l.type;color=2;Calculate(){if(this.dirty){for(let e of this.edges_in)if(e.dirty)return;this.state_id++,this.dirty=!1}}AddDependent(){throw new Error("leaf vertex cannot have dependents")}};var gr=class l extends ze{static type="calculation-leaf-vertex";type=l.type;address={row:-1,column:-1};use;updated=!1;color=2;Calculate(e){if(!this.dirty)return;for(let r of this.edges_in)if(r.dirty)return;let t=e.CalculationCallback.call(e,this);this.result=t.value,this.dirty=!1,this.updated=!0}AddDependent(){throw new Error("leaf vertex cannot have dependents")}};var Va=l=>{if(typeof l=="string")switch(l=l.toUpperCase(),l){case"AVERAGE":case"MEAN":l=101;break;case"COUNT":l=102;break;case"COUNTA":l=103;break;case"MAX":l=104;break;case"MIN":l=105;break;case"PRODUCT":l=106;break;case"STDEV":l=107;break;case"STDEVP":l=108;break;case"SUM":l=109;break;case"VAR":l=110;break;case"VARP":l=111;break;default:l=0;break}return l},Da={complex_numbers:"off",spill:!1},_r=class extends tr{constructor(t,r={}){super();this.model=t;if(this.expression_calculator=new ar(this.model,this.library,this.parser),this.options={...Da,...r},this.options.complex_numbers==="on"){for(let o of Object.keys(li))et[o]=li[o];Cn()}this.UpdateLocale(),this.library.Register(et,Pn,qn,Nn,On,Jn,Wn,Xn,Kn,Yn);for(let o of Object.keys(yi))this.library.Alias(o,yi[o]);for(let o of Object.keys(di))this.library.Alias(o,di[o]);let i=(o,a,...s)=>{Array.isArray(a)||(a=[[a]]);let c=[];for(let m=0;m<s.length;m+=2){let f=s[m];Array.isArray(f)||(f=[[f]]);{let p=n(f,s[m+1]);if(p.type!==9)return p;for(let[b,g]of p.value[0].entries())c[b]=!!g.value&&c[b]!==!1}}let d=X(a,!0),u=0,h=0;for(let[m,f]of c.entries())if(f){u++;let p=d[m];typeof p=="number"&&(h+=p)}switch(o){case"count":return{type:3,value:u};case"sum":return{type:3,value:h};case"average":return u===0?ve():{type:3,value:h/u}}},n=(o,a)=>{let s=X(o,!0),c,d,u="=";if(typeof a=="string"){a=a.trim();let m=a.match(/^([=<>]+)/);m&&(u=m[1],a=a.substring(u.length));let f=ye.TryParse(a);if(f?.type===2?a=`"${f.value}"`:a=f?.value?.toString()||"",/[?*]/.test(a)){let p=this.parser.argument_separator;if(u==="="||u==="<>"){if(c=this.parser.Parse(`=WildcardMatch({}${p} ${a}${p} ${u==="<>"})`),d=c.expression,c.error||!d)return fe();d?.type==="call"&&d.args[0]?.type==="array"&&(d.args[0].values=[si(s,!0)])}}}else a=(a||0).toString();if(!c){if(c=this.parser.Parse("{}"+u+a),d=c.expression,c.error||!d)return fe();if(d.type!=="binary")return console.warn("invalid expression [1]",d),fe();if(d.left.type!=="array")return console.warn("invalid expression [1]",d),fe();d.right.type==="identifier"&&(console.warn("will never happen"),d.right={...d.right,type:"literal",value:d.right.name}),d.left.values=[si(s,!0)]}return d?this.CalculateExpression(d):U()};this.library.Register({Subtotal:{arguments:[{name:"type"},{name:"range",metadata:!0}],fn:(o,...a)=>{if(o=Va(o),o>100&&(o-=100),o<1||o>11)return M();let s=oe(a),c=[],d=0,u=0,h;for(let f of s){let p=f.value?.address;if(!p)return $();if(!h||h.id!==p.sheet_id){if(!p.sheet_id)return console.warn("invalid reference in metadata"),$();if(h=this.model.sheets.Find(p.sheet_id),!h)return console.warn("invalid sheet in metadata"),$()}if(!h.GetRowHeight(p.row))continue;let g=f.value?.value;typeof g>"u"||(d++,typeof g=="number"&&(u+=g,c.push(g)))}let m=0;switch(o){case 1:if(c.length===0)return ve();m=u/c.length;break;case 2:m=c.length;break;case 3:m=d;break;case 4:if(c.length===0)return U();m=Math.max.apply(0,c);break;case 5:if(c.length===0)return U();m=Math.min.apply(0,c);break;case 6:if(c.length===0)return U();m=1;for(let f of c)m*=f;break;case 7:if(c.length<2)return ve();m=Math.sqrt(Te(c,!0));break;case 8:if(c.length===0)return ve();m=Math.sqrt(Te(c,!1));break;case 9:m=u;break;case 10:if(c.length<2)return ve();m=Te(c,!0);break;case 11:if(c.length===0)return ve();m=Te(c,!1);break}return{type:3,value:m}}},Cell:{description:"Returns data about a cell",arguments:[{name:"type",description:"Type of data to return",unroll:!0},{name:"reference",description:"Cell reference",metadata:!0,unroll:!0}],fn:(o,a)=>{if(!he(a))return $();if(o)switch(o.toString().toLowerCase()){case"format":return a.value.format?{type:2,value:a.value.format}:$();case"address":{let s="";return a.value.address.sheet_id&&(s=this.model.sheets.Find(a.value.address.sheet_id)?.name||""),s&&(Se.test(s)&&(s=`'${s}'`),s+="!"),{type:2,value:"[]"+s+a.value.address.label.replace(/\$/g,"")}}}return{type:7,value:sn.error}}},Address:{arguments:[{name:"row"},{name:"column"},{name:"absolute"},{name:"a1"},{name:"sheet name"}],fn:(o=1,a=1,s=1,c=!0,d)=>{let u={type:"address",id:0,position:0,label:"",row:o-1,column:a-1};switch(s){case 2:u.absolute_row=!0;break;case 3:u.absolute_column=!0;break;case 4:break;default:u.absolute_column=!0,u.absolute_row=!0}return d&&(u.sheet=d),Rn(this.parser.Render(u,{r1c1:!c}))}},CountIfs:{arguments:[{name:"range"},{name:"criteria"},{name:"range"},{name:"criteria"}],fn:(...o)=>i("count",o[0],...o)},AverageIf:{arguments:[{name:"range"},{name:"criteria"}],fn:(o,a,s)=>i("average",s||o,o,a)},AverageIfs:{arguments:[{name:"value range"},{name:"criteria range"},{name:"criteria"},{name:"criteria range"},{name:"criteria"}],fn:(o,...a)=>i("average",o,...a)},SumIf:{arguments:[{name:"range"},{name:"criteria"}],fn:(o,a,s)=>i("sum",s||o,o,a)},SumIfs:{arguments:[{name:"value range"},{name:"criteria range"},{name:"criteria"},{name:"criteria range"},{name:"criteria"}],fn:(o,...a)=>i("sum",o,...a)},CountIf:{arguments:[{name:"range"},{name:"criteria"}],fn:(o,a)=>i("count",o,o,a)},Offset:{arguments:[{name:"reference",description:"Base reference",metadata:!0},{name:"rows",description:"number of rows to offset"},{name:"columns",description:"number of columns to offset"},{name:"height"},{name:"width"}],return_type:"reference",volatile:!0,fn:((o,a=0,s=0,c,d)=>{if(!o)return M();if(o.type===9){let h=typeof c=="number"?a+c:void 0,m=typeof d=="number"?s+d:void 0;return{type:9,value:o.value.slice(a,h).map(p=>p.slice(s,m))}}if(!he(o))return console.info("e2",{reference:o}),$();let u=this.DynamicDependencies(o.value.address,this.expression_calculator.context.address,!0,a,s,d,c);if(!u)return console.info("e1",{check_result:u}),$();if(u.dirty){let h=this.GetVertex(this.expression_calculator.context.address,!0);return h.short_circuit=!0,{type:0,value:void 0}}if(u.area){let h={type:"address",...u.area.start,label:"",position:0,id:0},m={type:"address",...u.area.end,label:"",position:0,id:0},f=u.area.count===1?h:{type:"range",start:h,end:m,label:"",position:0,id:0};return{type:5,value:f}}return U()}).bind(this)},Indirect:{arguments:[{name:"reference",description:"Cell reference (string)"}],return_type:"reference",volatile:!0,fn:(o=>{if(!o||typeof o!="string")return M();let a=this.parser.Parse(o);if(a.error||!a.expression||a.expression.type!=="address"&&a.expression.type!=="range")return $();let s=this.DynamicDependencies(a.expression,this.expression_calculator.context.address);if(!s)return $();if(s.dirty){let c=this.GetVertex(this.expression_calculator.context.address,!0);return c.short_circuit=!0,{type:0,value:void 0}}return{type:5,value:a.expression}}).bind(this)},Match:{arguments:[{name:"value",boxed:!0},{name:"range",boxed:!0},{name:"type"}],fn:(o,a,s=0)=>{if(s)return console.warn("inexact match not supported",{value:o,range:a,type:s}),xe();if(a.type===9){if(a.value.length===1){let c=a.value[0];for(let d=0;d<c.length;d++)if(o.type==c[d].type&&o.value===c[d].value)return{type:3,value:d+1}}else for(let c=0;c<a.value.length;c++){let d=a.value[c];if(d.length!==1)return xe();if(o.type==d[0].type&&o.value===d[0].value)return{type:3,value:c+1}}return xe()}else return o.type===a.type&&o.value===a.value?{type:3,value:1}:xe();return M()}},Index:{return_type:"reference",arguments:[{name:"range",metadata:!0},{name:"row"},{name:"column"}],volatile:!1,fn:(o,a,s)=>{if(!o)return M();if(a===void 0&&s===void 0)return M();a=a||0,s=s||0;let c=[];if(o.type===9)c=o.value;else if(o.type===5){let h=o.value;h.type==="metadata"&&h.address&&c.push([o])}let d=c.length,u=c[0]?.length||0;if(u<=0||d<=0||a>u||s>d||a<0||s<0)return M();if(s===0&&a===0){let h=d===1&&u===1?{...c[0][0].value.address}:{type:"range",start:c[0][0].value.address,end:c[d-1][u-1].value.address,label:"",position:0,id:0};return{type:5,value:h}}if((a||u===1)&&(s||d===1))return{type:5,value:c[s?s-1:0][a?a-1:0].value.address};if(a){let h={type:"range",start:c[0][a-1].value.address,end:c[d-1][a-1].value.address,label:"",position:0,id:0};return{type:5,value:h}}else if(s){let h={type:"range",start:c[s-1][0].value.address,end:c[s-1][u-1].value.address,label:"",position:0,id:0};return{type:5,value:h}}return M()}},Rows:{arguments:[{name:"reference",description:"Array or reference"}],volatile:!1,fn:o=>{if(!o)return M();if(Array.isArray(o)){let a=o[0];return Array.isArray(a)?{type:3,value:a.length}:U()}return{type:3,value:1}}},Columns:{arguments:[{name:"reference",description:"Array or reference"}],volatile:!1,fn:o=>o?Array.isArray(o)?{type:3,value:o.length}:{type:3,value:1}:M()},FormulaText:{description:"Returns a formula as a string",arguments:[{name:"reference",description:"Cell reference",metadata:!0,unroll:!0}],fn:o=>{if(!he(o))return $();let a=this.model.sheets.Find(o.value?.address?.sheet_id||0);if(a){let s=a.cells.GetCell(o.value.address,!1);return{type:2,value:s?.value?.toString()||""}}return $()}},IsFormula:{description:"Returns true if the reference is a formula",arguments:[{name:"Reference",unroll:!0,metadata:!0}],fn:o=>{let a=o?.value?.address,s=this.model.sheets.Find(a?.sheet_id||0);if(a&&s){let c=s.cells.GetCell(a,!1);return{type:4,value:c?.type===1}}return{type:4,value:!1}}}})}get parser(){return this.model.parser}library=new cr;registered_libraries={};expression_calculator;full_rebuild_required=!1;options;grid_expanded=!1;ExportCalculatedValues(){let t={};for(let r of this.model.sheets.list){let i=r.cells.toJSON({calculated_value:!0}).data;t[r.id]=i.filter(n=>n.calculated!==void 0)}return t}ApplyCalculatedValues(t){for(let r of this.model.sheets.list){let i=t[r.id];if(!i)console.info("mismatch",r.id);else for(let n of i)r.cells.data[n.row][n.column].SetCalculatedValue(n.calculated)}}AttachSpillData(t,r){if(r||(r=(t.start.sheet_id?this.model.sheets.Find(t.start.sheet_id):void 0)?.cells),!r)throw console.info({area:t,cells:r}),new Error("invalid sheet ID in attach spill data");let i=new tt,n=0,o=!1;for(let{cell:a,row:s,column:c}of r.IterateRC(t,!0))n++&&(a.type!==0||a.area||a.merge_area||a.table)&&(o=!0),this.AddLeafVertexEdge({row:s,column:c,sheet_id:t.start.sheet_id},i);return this.spill_data.push({area:t,vertex:i}),{vertex:i,area:t,error:o}}SpillCallback(t,r){let{reference:i,address:n}=t,{value:o}=r,a=[];if(!i)return console.error("invalid reference in spill callback"),a;if(!n||!n.sheet_id)return console.error("invalid address in spill callback"),a;if(o.length===1&&o[0].length===1||!this.options.spill)return i.SetCalculatedValue(o[0][0].value),a;let s=this.model.sheets.Find(n.sheet_id),c=s?.cells;if(c){let d=r.value.length,u=r.value[0].length,h=new v(n).Reshape(u,d),{error:m}=this.AttachSpillData(h,c);if(m)return i.SetCalculationError("SPILL"),a;s.rows<h.end.row+1&&(s.cells.EnsureRow(h.end.row+1),this.grid_expanded=!0),s.columns<h.end.column+1&&(s.cells.EnsureColumn(h.end.column+1),this.grid_expanded=!0);let f=n.sheet_id;for(let{row:p,column:b}of c.IterateRC(h)){if(p===n.row&&b===n.column)continue;let g=this.GetVertex({sheet_id:f,row:p,column:b},!1);g&&(g.dirty||a.push(g))}for(let{cell:p,row:b,column:g}of c.IterateRC(h)){p.spill=h,b-=n.row,g-=n.column;let x=r.value[g][b];switch(x.type){case 5:case 9:case 6:break;default:p.SetCalculatedValue(x.value,x.type);break}}return a}return console.error("invalid cell reference in spill callback"),i.SetCalculationError("SPILL"),[]}SpreadCallback(t,r){if(!t.address||!t.address.sheet_id)throw new Error("spread callback called without sheet id");let i=this.model.sheets.Find(t.address.sheet_id)?.cells;if(!i)throw new Error("spread callback called without cells");if(!t||!t.reference)return;let n=t.reference.area;if(n){let o=n.rows,a=n.columns;if(r.type===9){let s=sr(r.value);for(let c=0;c<o;c++)if(s[c]){let d=0;for(;d<a&&d<s[c].length;d++){let u=s[c][d];switch(u.type===9&&(u=u.value[0][0]),u.type){case 9:case 5:case 6:i.data[c+n.start.row][d+n.start.column].SetCalculatedValue(void 0);break;default:i.data[c+n.start.row][d+n.start.column].SetCalculatedValue(u.value,u.type)}}for(;d<a;d++)i.data[c+n.start.row][d+n.start.column].SetCalculatedValue(void 0,0)}else for(let d=0;d<a;d++)i.data[c+n.start.row][d+n.start.column].SetCalculatedValue(void 0,0)}else{let s={...r};(s.type===5||s.type===6)&&(s={type:0,value:void 0});for(let c=0;c<o;c++)for(let d=0;d<a;d++)i.data[c+n.start.row][d+n.start.column].SetCalculatedValue(s.value,s.type)}}}CalculationCallback(t){if(!t.address)throw new Error("vertex missing address");return t.expression_error?{value:Zt()}:this.expression_calculator.Calculate(t.expression,t.address,t.reference?.area)}DynamicDependencies(t,r,i=!1,n=0,o=0,a=1,s=1){let c=this.ResolveExpressionAddress(t,r);if(!c)return;let d=!1,u;if(t.type==="address"||t.type==="range"){let m=t.type==="range"?t.start:t;m.sheet_id?u=this.model.sheets.Find(m.sheet_id):m.sheet&&(u=this.model.sheets.Find(m.sheet))}if(!u&&r?.sheet_id&&(u=this.model.sheets.Find(r.sheet_id)),!u)throw new Error("missing sheet in dynamic dependencies [b21]");c=u.RealArea(c);let h=c.start.sheet_id;i&&(c=new v({column:c.start.column+o,row:c.start.row+n,sheet_id:c.start.sheet_id},{column:c.start.column+o+a-1,row:c.start.row+n+s-1,sheet_id:c.end.sheet_id}));for(let m=c.start.row;m<=c.end.row;m++)for(let f=c.start.column;f<=c.end.column;f++){let p=this.GetVertex({row:m,column:f,sheet_id:h},!1);p&&p.dirty&&(this.AddEdge({row:m,column:f,sheet_id:h},this.expression_calculator.context.address),d=!0)}return{dirty:d,area:c}}UpdateLocale(){F.decimal_separator===","?this.parser.SetLocaleSettings(","):this.parser.SetLocaleSettings(".")}SupportedFunctions(){let t=this.library.List(),r=Object.keys(t).map(i=>{let n=t[i].canonical_name;return n||(n=i.replace(/_/g,".")),{name:n,description:t[i].description,arguments:(t[i].arguments||[]).map(o=>({name:o.name||""})),type:"function"}});for(let i of this.model.macro_functions.values())r.push({name:i.name,description:i.description,arguments:(i.argument_names||[]).map(n=>({name:n})),type:"function"});return r}RegisterLibrary(t,r){return this.registered_libraries[t]?!1:(this.RegisterFunction(r),this.registered_libraries[t]=!0,!0)}RegisterFunction(t){for(let r of Object.keys(t)){let i=t[r];this.library.Register({[r]:i})}}Calculate(t){if(t&&!t.start.sheet_id)throw new Error("CalculateInternal called with subset w/out sheet ID");this.full_rebuild_required&&(t=void 0,this.UpdateAnnotations(),this.UpdateConditionals(),this.UpdateConnectedElements(),this.full_rebuild_required=!1),this.RebuildGraph(t),this.grid_expanded=!1;try{this.Recalculate()}catch(r){console.error(r),console.info("calculation error trapped")}}Reset(){this.FlushTree(),this.full_rebuild_required=!0}DecoratedFunctionList(){let t={},r=this.library.List();for(let i of Object.keys(r)){let n=r[i];n.xlfn?t[i]="_xlfn":n.extension&&(t[i]="_xll")}return t}Evaluate(t,r,i={},n=!1){let o=i?.preparsed;if(!o){this.parser.Save(),i.argument_separator&&(i.argument_separator===","?this.parser.SetLocaleSettings("."):this.parser.SetLocaleSettings(",")),i.r1c1&&(this.parser.flags.r1c1=i.r1c1);let a=this.parser.Parse(t);if(this.parser.Restore(),o=a.expression,a.error)throw new Error(a.error)}if(o){this.parser.Walk(o,s=>{if(s.type==="address"||s.type==="range"){if(s.type==="address"){if(s.offset_column||s.offset_row)throw new Error("Evaluate does not support offset references")}else if(s.start.offset_column||s.start.offset_row||s.end.offset_column||s.end.offset_row)throw new Error("Evaluate does not support offset references");this.model.ResolveSheetID(s,void 0,r)}return!0});let a=this.CalculateExpression(o,i.address);return n?a:a.type===9?a.value.map(s=>s.map(c=>c.value)):a.value}throw new Error("invalid expression")}CalculateExpression(t,r={row:-1,column:-1},i=!1){return this.expression_calculator.Calculate(t,r,void 0,i).value}RebuildClean(t=!1){this.full_rebuild_required=!1,this.RebuildGraph(),this.UpdateAnnotations(),this.UpdateConditionals(),this.UpdateConnectedElements(),this.InitializeGraph(),t&&this.volatile_list.length&&this.Recalculate()}FlattenCellList(t){let r={},i=[];for(let n of t){let o={column:n.column,row:n.row,sheet_id:n.sheet_id},a=v.CellAddressToLabel(o,!0);r[a]||(r[a]=a,i.push(o))}return i}Unresolve(t,r,i=!0,n=!0){let o="",a=N(t)?new v(t):new v(t.start,t.end);if(n){let d=this.model.named.MatchSelection(a);if(d)return d}if(o=a.spreadsheet_label,!i)return o;let s=a.start.sheet_id||r?.id,c=this.ResolveSheetName(s,!0);return c?c+"!"+o:o}ResolveSheetName(t,r=!1){let i=this.model.sheets.Find(t);if(i)return r&&Se.test(i.name)?`'${i.name}'`:i.name}RemoveConditional(t){if(t.type==="expression"){let r=t.internal?.vertex;r&&(r.Reset(),this.RemoveLeafVertex(r))}}RemoveConnectedELement(t){let r=t.internal;return r?.vertex?(this.RemoveLeafVertex(r.vertex),!0):!1}UpdateConnectedElements(t,r){if(t||(t=this.model.sheets.list[0]),r){let n=r.internal;n?.vertex&&this.RemoveLeafVertex(n.vertex)}let i=r?[r]:this.model.connected_elements.values();for(let n of i){let o=n.internal;o||(o={vertex:new tt},n.internal=o);let a=o.vertex;this.AddLeafVertex(a),this.UpdateLeafVertex(a,n.formula,t)}}UpdateConditionals(t,r){if(!t){for(let i of this.model.sheets.list)i.conditional_formats?.length&&this.UpdateConditionals(i.conditional_formats,i);return}if(!r)throw new Error("invalid call to update conditionals without context");t&&!Array.isArray(t)&&(t=[t]);for(let i of t){let n="";switch(i.type){case"cell-match":i.between?n=`BETWEEN(${[this.Unresolve(i.area,r,!0,!1),...i.between].join(", ")})`:n=this.Unresolve(i.area,r,!0,!1)+" "+i.expression;break;case"expression":n=i.expression;break;case"duplicate-values":n=`UniqueValues(${this.Unresolve(i.area,r,!0,!1)})`,i.unique||(n=`NOT(${n})`);break;case"data-bar":case"gradient":n=`=Gradient(${[this.Unresolve(i.area,r,!0,!1),i.min??"",i.max??"",...i.type==="data-bar"?["TRUE"]:[]].join(",")})`;break;default:continue}if(!n)continue;if(i.internal||(i.internal={}),!i.internal.vertex){let a=new gr;a.use="conditional",i.internal.vertex=a;let s={argument_separator:","};i.type!=="gradient"&&i.type!=="duplicate-values"&&i.type!=="data-bar"&&(s={...i.options,...s});let c=this.Evaluate(n,r,s,!0);i.internal.vertex.result=c,i.internal.vertex.updated=!0}let o=i.internal.vertex;this.AddLeafVertex(o),this.UpdateLeafVertex(o,n,r,".")}}RemoveAnnotation(t){let r=t.temp;r.vertex&&(r.vertex.Reset(),this.RemoveLeafVertex(r.vertex))}UpdateAnnotations(t,r){if(!t){for(let i of this.model.sheets.list)this.UpdateAnnotations(i.annotations,i);return}if(!r)throw new Error("invalid call to UpdateAnnotations with list but no sheet");typeof t<"u"&&!Array.isArray(t)&&(t=[t]);for(let i of t)if(i.data.formula){let n=i.temp;n.vertex||(n.vertex=new tt),this.AddLeafVertex(n.vertex),this.UpdateLeafVertex(n.vertex,i.data.formula,r)}}ResolveExpressionAddress(t,r){switch(t.type){case"address":if(this.model.ResolveSheetID(t,r))return new v(t);break;case"range":if(this.model.ResolveSheetID(t,r))return new v(t.start,t.end);break;case"identifier":{let i=this.model.GetName(t.name,r?.sheet_id||0);if(i&&i.type==="range")return new v(i.area.start,i.area.end)}break}}NamedRangeToAddressUnit(t,r){let i=t.name.toUpperCase(),n=this.model.GetName(i,r.sheet_id||0);if(n&&n.type==="range")return n.area.count===1?this.ConstructAddressUnit(n.area.start,i,t.id,t.position):{type:"range",start:this.ConstructAddressUnit(n.area.start,i,t.id,t.position),end:this.ConstructAddressUnit(n.area.end,i,t.id,t.position),label:i,id:t.id,position:t.position}}ConstructAddressUnit(t,r,i,n){return{type:"address",row:t.row,column:t.column,sheet_id:t.sheet_id,label:r,id:i,position:n}}RebuildDependencies(t,r,i,n={addresses:{},ranges:{}},o){if(!i){let a=this.model.sheets.Find(r);a&&(i=a.name)}switch(t.type){case"literal":case"missing":case"operator":break;case"identifier":{let a=this.model.GetName(t.name,o.sheet_id||0);if(a?.type==="expression")this.RebuildDependencies(a.expression,r,i,n,o);else{let s=this.NamedRangeToAddressUnit(t,o);s&&(s.type==="address"?n.addresses[s.label]=s:n.ranges[s.label]=s)}}break;case"structured-reference":{let a=this.model.ResolveStructuredReference(t,o);a&&(a.type==="address"?n.addresses[a.sheet_id+"!"+a.label]=a:n.ranges[a.label]=a);let s=this.model.tables.get(t.table.toLowerCase());if(s){let c=o.row;if(c<s.area.start.row||c>s.area.end.row)break;let d=t.column.toLowerCase(),u=-1;if(s.columns){for(let h=0;h<s.columns.length;h++)if(d===s.columns[h]){u=s.area.start.column+h;break}}if(u>=0){let h={label:t.label,type:"address",row:c,column:u,sheet_id:s.area.start.sheet_id,id:t.id,position:t.position};n.addresses[h.sheet_id+"!"+h.label]=h}}}break;case"address":if(!t.sheet_id)if(t.sheet){let a=this.model.sheets.Find(t.sheet);a&&(t.sheet_id=a.id)}else t.sheet_id=r,t.sheet=i;t.sheet_id?n.addresses[t.sheet_id+"!"+t.label]=t:console.warn("invalid address in range [9d]");break;case"range":if(!t.start.sheet_id)if(t.start.sheet){let a=this.model.sheets.Find(t.start.sheet);a&&(t.start.sheet_id=a.id)}else t.start.sheet_id=r,t.start.sheet=i;t.start.sheet_id?n.ranges[t.start.sheet_id+"!"+t.start.label+":"+t.end.label]=t:console.warn("invalid sheet in range",t);break;case"unary":this.RebuildDependencies(t.operand,r,i,n,o);break;case"binary":this.RebuildDependencies(t.left,r,i,n,o),this.RebuildDependencies(t.right,r,i,n,o);break;case"group":t.elements.forEach(a=>this.RebuildDependencies(a,r,i,n,o));break;case"implicit-call":{for(let a of t.args)this.RebuildDependencies(a,r,i,n,o);this.RebuildDependencies(t.call,r,i,n,o)}break;case"call":{let a=t.args.slice(0),s=this.library.Get(t.name);s&&s.arguments&&s.arguments.forEach((c,d)=>{c&&c.address&&(this.RebuildDependencies(a[d],r,i,void 0,o),a[d]={type:"missing",id:-1})}),a.forEach(c=>this.RebuildDependencies(c,r,i,n,o))}break}return n}UpdateLeafVertex(t,r,i,n){t.Reset(),n&&(this.parser.Save(),this.parser.SetLocaleSettings(n));let o=this.parser.Parse(r);if(o.expression){let a=this.RebuildDependencies(o.expression,i.id,i.name,void 0,{row:0,column:0});for(let s of Object.keys(a.ranges)){let c=a.ranges[s],d=new v(c.start,c.end);d.entire_column||d.entire_row||d.count>1?this.AddLeafVertexArrayEdge(d,t):this.AddLeafVertexEdge(d.start,t)}for(let s of Object.keys(a.addresses)){let c=a.addresses[s];this.AddLeafVertexEdge(c,t)}}t.expression=o.expression||{type:"missing",id:-1},t.expression_error=!o.valid,n&&this.parser.Restore()}RebuildGraphCell(t,r){if(t.spill&&this.options.spill&&(t.spill.start.row===r.row&&t.spill.start.column===r.column?this.AttachSpillData(new v(t.spill.start,t.spill.end)):this.AddEdge(t.spill.start,r)),t.area&&t.area.start.column===r.column&&t.area.start.row===r.row){let{start:i,end:n}=t.area,o=i.sheet_id||r.sheet_id;i.sheet_id||(i.sheet_id=o);for(let a=i.column;a<=n.column;a++)for(let s=i.row;s<=n.row;s++)this.ResetInbound({column:a,row:s,sheet_id:o},!0,!1);this.SetDirty(r);for(let a=i.column;a<=n.column;a++)for(let s=i.row;s<=n.row;s++)s===i.row&&a===i.column||this.AddEdge(i,{...i,row:s,column:a})}if(t.type===1){this.ResetInbound(r,!0);let i=this.parser.Parse(t.value);if(i.expression){if(i.expression.type==="call"){let a=this.library.Get(i.expression.name);a&&(a.render||a.click)&&(t.render_function=a.render,t.click_function=a.click)}let o=this.RebuildDependencies(i.expression,r.sheet_id,"",void 0,r);for(let a of Object.keys(o.ranges)){let s=o.ranges[a],c=new v(s.start,s.end);if(c.entire_row||c.entire_column)this.AddArrayEdge(c,r);else for(let d of c)this.AddEdge(d,r)}for(let a of Object.keys(o.addresses)){let s=o.addresses[a];this.AddEdge(s,r)}}let n=this.GetVertex(r,!0);n&&(n.expression=i.expression||{type:"missing",id:-1},n.expression_error=!i.valid)}else t.value!==t.calculated?this.ResetInbound(r,!0,!1):t.type===0&&this.ResetInbound(r,!0,!1,!0)}RebuildGraph(t){if(t){if(!t.start.sheet_id)throw new Error("subset missing sheet id");let r=this.model.sheets.Find(t.start.sheet_id)?.cells;if(r)for(let i=t.start.row;i<=t.end.row;i++){let n=r.data[i];if(n)for(let o=t.start.column;o<=t.end.column;o++){let a=n[o];a&&this.RebuildGraphCell(a,{row:i,column:o,sheet_id:t.start.sheet_id})}}}else for(let r of this.model.sheets.list||[]){let i=r.cells.data.length;for(let n=0;n<i;n++){let o=r.cells.data[n];if(o){let a=o.length;for(let s=0;s<a;s++){let c=o[s];c&&this.RebuildGraphCell(c,{row:n,column:s,sheet_id:r.id})}}}}}CheckVolatile(t){if(!t.expression||t.expression_error)return!1;let r=!1;return this.parser.Walk(t.expression,i=>{if(i.type==="call"){let n=this.library.Get(i.name);n&&n.volatile&&(r=!0)}return!r}),r}};var yr=class{model={};layout_element;visible_=!1;timeout=0;pending_dialog_resoltion=[];options_={type:"initial"};set options(e){if(e.type==="about"&&(e.close_box=!0,e.icon=!0),this.options_.icon!==e.icon&&(this.model.left.style.display=e.icon?"block":"none"),this.options_.close_box!==e.close_box&&(this.model.close.style.display=e.close_box?"block":"none"),this.options_.message!==e.message&&(this.model.message.textContent=e.message||"",this.model.message.style.display=e.message?"block":"none"),this.options_.title!==e.title&&(this.model.title.textContent=e.title||"",this.model.title.style.display=e.title?"block":"none"),this.options_.type!==e.type){let t=this.model.dialog.className.replace(/dialog-type-\S+/g,"").trim();e.type&&(t+=` dialog-type-${e.type}`),this.model.dialog.className=t,e.type==="about"?this.model.about.style.display="block":this.model.about.style.display="none"}this.options_=e}event_handler=e=>{(e.key==="Escape"||e.key==="Esc")&&(e.stopPropagation(),e.preventDefault(),this.visible=!1)};get visible(){return this.visible_}set visible(e){if(e!==this.visible_)if(this.visible_=e,e)this.layout_element?.setAttribute("dialog",""),window.addEventListener("keydown",this.event_handler);else{this.layout_element?.removeAttribute("dialog"),window.removeEventListener("keydown",this.event_handler);let t=this.pending_dialog_resoltion.slice(0);this.pending_dialog_resoltion=[],Promise.resolve().then(()=>{for(let r of t)r()})}}constructor(e){this.layout_element=e.parentElement;let t=this.layout_element?.querySelector(".treb-dialog-mask");if(t){let r=t.querySelectorAll("[data-bind]");for(let i of Array.from(r)){let n=i.dataset.bind;n&&(this.model[n]=i)}}if(this.model.about){let r=["<div>TREB version 32.9.3"];r.push("<small><a target=_blank href='https://treb.app'>http://treb.app</a></small>"),this.model.about.innerHTML=r.join(`
12
+ `)}this.model.close?.addEventListener("click",r=>{r.stopPropagation(),r.preventDefault(),this.HideDialog()})}Node(e){return this.model[e]}Update(e,t=!0){t&&(e={...this.options_,...e}),this.options=e}HideDialog(){this.visible=!1}ShowDialog(e){return new Promise(t=>{this.pending_dialog_resoltion.push(t),this.options=e,this.visible=!0,this.timeout&&(window.clearTimeout(this.timeout),this.timeout=0),e.timeout&&(this.timeout=window.setTimeout(()=>this.HideDialog(),e.timeout))})}};var vr=class{constructor(e){this.container=e;let t=O.GetInstance(e.ownerDocument);this.node=t.Div("treb-spinner",e,{html:"<div><div></div><div></div><div></div><div></div></div>"})}node;visible=!1;Show(){this.node.classList.add("visible")}Hide(){this.node.classList.remove("visible")}};var Qn={formula_bar:!0,in_cell_editor:!0,undo:!0,scrollbars:!0,headers:!0,export:!0,tab_bar:"auto",resizable:!0,hyperlinks:"_blank",max_file_size:94208,tint_theme_colors:!0,dnd:!1,add_tab:!1,expand_formula_button:!1,expand:!0,markdown:!1,spinner:!1,complex:"off",spill:!0};var Ce=l=>!!l&&typeof l=="object"&&l.key==="metadata"&&!!l.value&&l.value.type==="metadata",vi=l=>!!l&&typeof l=="object"&&l.key==="series"&&typeof l.value=="object",Zn=l=>!!l&&typeof l=="object"&&l.type===9&&Array.isArray(l.value);var G=class{static Scale(e,t,r=6.5,i,n){return Ni(e,t,r,i,n)}static Range(e){let t,r;for(let n of e)typeof n>"u"||((typeof t>"u"||t>n)&&(t=n),(typeof r>"u"||r<n)&&(r=n));let i=typeof t>"u"||typeof r>"u"?0:r-t;return{min:t,max:r,range:i}}static ApplyScale(e,t,r){return t*(e-r.min)/(r.max-r.min)}static Flatten(e){let t=[];if(Array.isArray(e))for(let r of e)Array.isArray(r)?t=t.concat(this.Flatten(r)):t.push(r);else typeof e<"u"&&t.push(e);return t}};var to=l=>{wi(l,0,l.length)},za=(l,e,t)=>{let r=l[t-1],i=e;for(let n=e;n<t-1;n+=1)l[n]<=r&&(eo(l,n,i),i+=1);return eo(l,i,t-1),i},eo=(l,e,t)=>{let r=l[e];l[e]=l[t],l[t]=r},wi=(l,e,t)=>{if(e<t){let r=za(l,e,t);wi(l,e,r),wi(l,r+1,t)}};var xi="#,##0.00",rt=l=>{let e=l[0],t=l[0];for(let r of l)r<e&&(e=r),r>t&&(t=r);return{min:e,max:t}},ro=l=>{let{label:e,x:t,y:r,z:i,index:n,subtype:o,data_labels:a,axis:s}=l,c={x:{data:[]},y:{data:[]}};if(typeof s=="number"&&(c.axis=s),typeof n=="number"&&(c.index=n),o&&(c.subtype=o.toString()),a){let h=G.Flatten(Array.isArray(a)?a:[a]);c.labels=h.map(m=>typeof m>"u"?"":m.toString())}e&&(c.label=e.toString());let d=(h,m=!1)=>{let f;if(Ce(h)&&(h={type:9,value:[[h]]}),Zn(h)){f={data:[]};let p=G.Flatten(h.value);if(f.data=p.map(b=>{if(Ce(b)){if(typeof b.value.value=="number")return b.value.value}else if(b.type===3)return b.value}),Ce(p[0])&&p[0].value?.format&&(f.format=p[0].value.format,m)){let b=L.Get(f.format);f.labels=f.data.map(g=>g===void 0?void 0:b.Format(g))}}return f};c.y=d(r,!0)||{data:[]},c.x=d(t)||{data:[]},c.z=d(i);let u=[c.x,c.y];for(let h of u)if(h.data.length){let m=h.data.filter(f=>f||f===0);h.range=rt(m)}return c},io=l=>{let e={x:{data:[]},y:{data:[]}},t=G.Flatten(l.value),r=[];for(let[n,o]of t.entries()){let a=0;if(typeof o.value=="number")a=o.value,r.push(o.value);else if(Ce(o))if(me(o.value.value))e.x.data[n]=o.value.value.real,a=o.value.value.imaginary;else if(typeof o.value.value=="number")a=o.value.value;else continue;else continue;e.y.data[n]=a,r.push(a)}let i="";if(Ce(t[0])&&(i=t[0].value.format||""),i){e.y.format=i;let n=L.Get(e.y.format||"");e.y.labels=e.y.data.map(o=>o===void 0?void 0:n.Format(o))}if(e.y.range=rt(r),e.x.data.length){let n=e.x.data.filter(o=>typeof o=="number");if(e.x.range=rt(n),i){e.x.format=i;let o=L.Get(e.x.format||"");e.x.labels=e.x.data.map(a=>a===void 0?void 0:o.Format(a))}}return e},St=(l,e)=>{if(!l)return[];let t=[];if(l.type===5){if(l.key==="group"){if(Array.isArray(l.value)){for(let[n,o]of l.value.entries())if(o&&typeof o=="object")if(vi(o)){let a=ro(o.value);typeof a.index>"u"&&(a.index=n+1),t.push(a)}else o.type===9&&t.push(io(o))}}else if(vi(l)){let n=ro(l.value);t.push(n)}}else l.type===9&&t.push(io(l));let r,i=0;if(e?.type===9){let n=G.Flatten(e.value),o="0.00###";Ce(n[0])&&n[0].value.format&&(o=n[0].value.format);let a=n.map(c=>{if(c.type===3)return c.value;if(Ce(c)&&typeof c.value.value=="number")return c.value.value}),s=a.filter(c=>typeof c=="number");r={data:a,format:o,range:rt(s)}}for(let n of t)i=Math.max(i,n.y.data.length),n.x.data.length&&(r||(r=n.x));if(!r){r={data:[],range:{min:0,max:Math.max(0,i-1)}};for(let n=0;n<i;n++)r.data.push(n)}for(let n of t)n.x.data.length||(n.x=r);return t},no=l=>{let e=Math.abs(l.step)%1;if(e){if(Math.log10(Math.abs(e))<-4)return"Scientific";let r=0;for(let n=0;n<l.count;n++){let o=((l.min+l.step*n)%1).toFixed(6).replace(/0+$/,"");r=Math.max(r,o.length-2)}let i="#,##0.";for(let n=0;n<r;n++)i+="0";return i}else return Math.log10(Math.abs(l.step))>=5?"Scientific":"#,##0"},it=(l,e,t,r,i,n)=>{let o="",a="",s="";for(let R of l)R.axis?R.y.format&&!s&&(s=R.y.format):R.y.format&&!a&&(a=R.y.format),R.x.format&&!o&&(o=R.x.format);let c;l.some(R=>R.label&&R.label.length>0)&&(c=l.map((R,z)=>({label:R.label||`Series ${z+1}`,index:typeof R.index=="number"?R.index:z+1})));let d=l.filter(R=>R.x.range),u=Math.min.apply(0,d.map(R=>R.x.range?.min||0)),h=Math.max.apply(0,d.map(R=>R.x.range?.max||0)),m=d.filter(R=>!R.axis),f=d.filter(R=>R.axis),p=Math.min.apply(0,m.map(R=>R.y.range?.min||0)),b=Math.max.apply(0,m.map(R=>R.y.range?.max||0)),g=-1,x=-1;f.length&&(g=Math.min.apply(0,f.map(R=>R.y.range?.min||0)),x=Math.max.apply(0,f.map(R=>R.y.range?.max||0)));for(let R of l)if(R.z){for(let[z,K]of R.z.data.entries())if(typeof K<"u"){let ie=R.x.data[z],pe=Math.max(0,K/2);typeof ie<"u"&&(u=Math.min(u,ie-pe),h=Math.max(h,ie+pe));let T=R.y.data[z];typeof T<"u"&&(p=Math.min(p,T-pe),b=Math.max(b,T+pe))}}typeof r<"u"&&(u=Math.min(u,r)),typeof i<"u"&&(u=Math.max(u,i)),typeof e<"u"&&(p=Math.min(p,e)),typeof t<"u"&&(b=Math.max(b,t));let y=G.Scale(u,h,7),w=G.Scale(p,b,7),_=G.Scale(g,x,7);if(g!==x&&w&&_&&w.count!==_.count){let R=Math.max(w.count,_.count),z=w.count<R?w:_;for(let K=z.count;K<R;K+=2)z.max+=z.step,z.count++,z.count<R&&(z.min-=z.step,z.count++)}let C,S,A;if(o){C=[];let R=L.Get(o);for(let z=0;z<=y.count;z++)C.push(R.Format(y.min+z*y.step))}if(!a&&n&&(a=no(w)),!s&&n&&(s=no(_)),a){S=[];let R=L.Get(a);for(let z=0;z<=w.count;z++)S.push(R.Format(w.min+z*w.step))}if(s){A=[];let R=L.Get(s);for(let z=0;z<=_.count;z++)A.push(R.Format(_.min+z*_.step))}let E={x:{format:o,scale:y,labels:C},y:{format:a,scale:w,labels:S},legend:c};return g!==x&&(E.y2={format:s,scale:_,labels:A}),E},wr=(l,e,t)=>{for(let r of l){let i={x:L.Get(r.x.format||""),y:L.Get(r.y.format||"")};r.y.labels=[];for(let n=0;n<r.y.data.length;n++){let o=t?t[n]:typeof r.x.data[n]=="number"?i.x.Format(r.x.data[n]):"",a=typeof r.y.data[n]=="number"?i.y.Format(r.y.data[n]):"";r.y.labels[n]=e.replace(/\bx\b/g,o).replace(/\by\b/g,a)}}},Ia=l=>{let e=(a,s=0,c=a.length)=>c%2?a[Math.floor(c/2)+s]:(a[c/2+s]+a[c/2-1+s])/2,t=l.length,r=[0,e(l),0];if(t%2){let a=Math.floor(t/2);r[0]=e(l,0,Math.ceil(t/2)),r[2]=e(l,a,l.length-a)}else r[0]=e(l,0,t/2),r[2]=e(l,t/2,l.length-t/2);let i=r[2]-r[0],n=[0,0],o=0;for(let a=0;a<t;a++)o+=l[a];for(let a=0;a<t;a++){let s=l[a];if(s>=r[0]-i*1.5){n[0]=s;break}}for(let a=t-1;a>=0;a--){let s=l[a];if(s<=r[2]+i*1.5){n[1]=s;break}}return{data:l,quartiles:r,whiskers:n,iqr:i,n:t,mean:t?o/t:0,min:l[0],max:l[t-1]}},oo=l=>{let e=St(l[0]),t=it(e,void 0,void 0,void 0,void 0,!0),r=0,i=!!l[2],n=e.map(u=>{let h=[];for(let f of u.y.data)f!==void 0&&h.push(f);to(h);let m=Ia(h);return r=Math.max(r,m.n),i&&(m.whiskers[0]=m.min,m.whiskers[1]=m.max),m}),o=l[1]?.toString()||void 0,a=[],s=[],c=L.Get("#,##0");for(let[u,h]of n.entries()){a.push(c.Format(h.n));let m=e[u];s.push(m.label||`Series ${u+1}`)}return{type:"box",series:e,title:o,max_n:r,data:n,x_labels:a,series_names:e.some(u=>!!u.label)?s:void 0,scale:t.y.scale,y_labels:t.y.labels}},ao=l=>{let e=St(l[0]),t,r;for(let a of e)typeof a.x.range?.min=="number"&&a.x.range.min>0&&a.x.range.min<50&&(r=0),typeof a.y.range?.min=="number"&&a.y.range.min>0&&a.y.range.min<50&&(t=0);let i=it(e,t,void 0,r),n=l[1]?.toString()||void 0;return{legend:i.legend,legend_style:2,type:"bubble",series:e,title:n,x_scale:i.x.scale,x_labels:i.x.labels,y_scale:i.y.scale,y_labels:i.y.labels}},Ci=(l,e="plot")=>{let t=St(l[0]),r=it(t),i=l[1]?.toString()||void 0,n=l[2]?.toString()||void 0,o={legend:r.legend,style:e,type:"scatter2",series:t,title:i,x_scale:r.x.scale,x_labels:r.x.labels,y_scale:r.y.scale,y_labels:r.y.labels,y2_scale:r.y2?.scale,y2_labels:r.y2?.labels,lines:e==="line",points:e==="plot"};if(n){o.markers=/marker/i.test(n),o.smooth=/smooth/i.test(n),o.data_labels=/labels/i.test(n);let a=n.match(/labels="(.*?)"/);a&&o.series?wr(o.series,a[1]):(a=n.match(/labels=([^\s\r\n,]+)(?:\W|$)/),a&&o.series&&wr(o.series,a[1])),a=n.match(/class=([\w_-]+)(?:\W|$)/),a&&(o.class_name=a[1])}return o},Si=(l,e)=>{let[t,r,i,n]=l,o=n?.toString()||void 0,a=/stacked/i.test(o||""),s=St(t),c=it(s),d;if(r){d=(r.type===9?G.Flatten(r.value):G.Flatten(r)).map(g=>!g||!g.value?"":Ce(g)?typeof g.value.value=="number"?L.Get(g.value.format||xi).Format(g.value.value):g.value.value?.toString()||"":typeof g.value=="number"?L.Get(xi).Format(g.value):g.value.toString());let b=s.reduce((g,x)=>Math.max(g,x.y.data.length),0);for(b<d.length&&(d=d.slice(0,b));b>d.length;)d.push("")}let u,h=c.legend;if(a){u=s;let p=new Map;for(let x of s)for(let[y,w]of x.x.data.entries())if(w!==void 0){let _=x.y.data[y]||0;p.set(w,_+(p.get(w)||0))}let b=Array.from(p.keys()).sort((x,y)=>x-y),g=b.map(x=>p.get(x)||0);s=[{x:{data:b,format:u[0]?.x?.format},y:{data:g,format:u[0]?.y?.format}}],s[0].x.range=rt(b),s[0].y.range=rt(g),c=it(s,Math.min(0,...g))}let m=i?.toString()||void 0,f={type:e,legend:h,legend_style:1,series2:s,stacked_series:u,scale:c.y.scale,title:m,y_labels:e==="bar"?d:c.y.labels,x_labels:e==="bar"?c.y.labels:d};if(o){f.stacked=a,f.round=/round/i.test(o),f.data_labels=/labels/i.test(o);let p=o.match(/labels="(.*?)"/);p&&s?wr(s,p[1],d):(p=o.match(/labels=([^\s\r\n,]+)(?:\W|$)/),p&&s&&wr(s,p[1],d)),p=o.match(/class=([\w_-]+)(?:\W|$)/),p&&(f.class_name=p[1])}return f},Ai=(l,e)=>{let t=St(l[0],l[1]),r=it(t,0,0),i=l[2]?.toString()||void 0,n=l[3]?.toString()||void 0,o={legend:r.legend,type:"scatter2",series:t,title:i,x_scale:r.x.scale,x_labels:r.x.labels,y_scale:r.y.scale,y_labels:r.y.labels,lines:!0,filled:e==="area"};if(n){o.smooth=/smooth/i.test(n);let a=n.match(/class=([\w_-]+)(?:\W|$)/);a&&(o.class_name=a[1])}return o},so=(l,e=!1)=>{let[t,r,i,n,o]=l,a=l[0]?.type===9?l[0].value:l[0],s=a?G.Flatten(a):[],c=s.map(_=>{if(Ce(_)&&typeof _.value.value=="number")return _.value.value}),d=l[1]?.type===9?l[1].value:l[1],u=G.Flatten(d||[]).map(_=>Ce(_)?typeof _.value.value=="number"&&_.value.format?L.Get(_.value.format).Format(_.value.value):_.value.value?.toString()||"":_.value?.toString()||""),h=!1;c=c.map(_=>_&&_<0?(h||(console.warn("pie/donut chart does not support negative values (omitted)"),h=!0),0):_);let m=0,f=c.map((_,C)=>(typeof _<"u"&&(m+=_),{value:_||0,label:u[C]||"",index:C+1,percent:0}));if(m)for(let _ of f)_.percent=(_.value||0)/m;let p="";for(let _ of s)if(Ce(_)){p=_.value.format||"";break}let b=L.Get(p||xi),g=L.Get("percent");typeof l[4]>"u"&&l[1]&&(l[4]="label");let x=l[4]||"";if(x)for(let _ of f){let C=b.Format(_.value||0),S=g.Format(_.percent);_.title=x.replace(/value%/ig,g.Format(_.value||0)).replace(/value/ig,C).replace(/percent/ig,S).replace(/label/ig,_.label||"").trim()}let y=(n||"").toUpperCase();if(y==="ASC"||y==="ASCENDING"||y==="INC")f.sort((_,C)=>(_.value||0)-(C.value||0));else if(y==="DESC"||y==="DESCENDING"||y==="DEC")f.sort((_,C)=>(C.value||0)-(_.value||0));else{let _=(n||"").match(/sort=([\w]+)(?:\W|$)/i);_&&(y=_[1],/^(asc|inc)/i.test(y)?f.sort((C,S)=>(C.value||0)-(S.value||0)):/^(desc|dec)/i.test(y)&&f.sort((C,S)=>(S.value||0)-(C.value||0)))}let w={type:e?"pie":"donut",slices:f,title:i||""};if(n){let _=n.match(/class=([_-\w]+)(?:\W|$)/);_&&(w.class_name=_[1])}return w};var Me=class{constructor(e=0,t=0,r=100,i=100){this.left=e;this.top=t;this.right=r;this.bottom=i}get width(){return this.right-this.left}get height(){return this.bottom-this.top}get center(){return{x:this.left+this.width/2,y:this.top+this.height/2}}};var Oa="http://www.w3.org/2000/svg",V=(l,e={},t)=>{let r=document.createElementNS(Oa,l);for(let i of Object.keys(e))if(e[i]!==void 0){let n=e[i]??"";r.setAttribute(i,Array.isArray(n)?n.join(" "):n.toString())}return t&&(r.textContent=t),r},xr=class{parent;svg_node;text_measurement_node;container_group;group;axis_group;label_group;size={width:0,height:0};bounds=new Me;constructor(){this.container_group=V("g"),this.group=V("g"),this.axis_group=V("g",{class:"axis-group"}),this.label_group=V("g",{class:"label-group"}),this.container_group.appendChild(this.axis_group),this.container_group.appendChild(this.group),this.container_group.appendChild(this.label_group)}Initialize(e){this.parent=e,this.svg_node=V("svg",{class:"treb-chart"}),this.svg_node.style.overflow="hidden",this.svg_node.style.position="relative",this.svg_node.style.width="100%",this.svg_node.style.height="100%",this.svg_node.appendChild(this.container_group),this.parent.appendChild(this.svg_node),this.Resize()}Legend(e){let t=V("g");this.group.appendChild(t);let r=V("text");t.appendChild(r),t.setAttribute("class","legend");let i=[[]],n=10,o=e.area.width,a=0,s=0,c=e.area.width,d=e.style===1?14:26,u=e.labels.map((b,g)=>{r.textContent=b.label;let x=r.getBoundingClientRect(),y={width:x.width,height:x.height},w=y.width+d+n;return s=Math.max(s,y.height),e.layout===1?i[g]=[g]:w>o?i[a].length===0?(i[a].push(g),a++,i[a]=[],o=c):(a++,i[a]=[g],o=c-w):(i[a].push(g),o-=w),y});t.removeChild(r);let h=s,m=e.layout||0;m===0&&i.every(b=>b.length<=1)&&(m=0);for(let b=0;b<i.length;b++){let g=i[b].reduce((w,_)=>w+u[_].width+d,(i[b].length-1)*n),x=0,y=m===0?Math.round((c-g)/2):Math.round(n/2);for(let w=0;w<i[b].length;w++){let _=i[b][w],C=u[_],S=e.labels[_],A=h-1,E=!1;typeof navigator<"u"&&(E=/trident/i.test(navigator?.userAgent||""));let R=typeof S.index=="number"?S.index:_+1;switch(t.appendChild(V("text",{"dominant-baseline":"middle",x:y+d,y:h,dy:E?".3em":void 0},S.label)),e.style){case 1:t.appendChild(V("rect",{class:`series-${R}`,x:y,y:A-4,width:8,height:8}));break;case 2:t.appendChild(V("circle",{class:`series-${R}`,cx:y+d-11,cy:A-4+3}));break;default:t.appendChild(V("rect",{class:`series-${R}`,x:y,y:A-1,width:d-3,height:2}));break}x=Math.max(x,C.height),y+=C.width+d+n}h=Math.round(h+x*1.1)}let f=t.getBoundingClientRect(),p={width:f.width,height:f.height+s};switch(e.position){case 1:t.setAttribute("transform",`translate(${e.area.left}, ${e.area.bottom-p.height})`);break;case 2:t.setAttribute("transform",`translate(${e.area.left}, ${e.area.top})`);break;case 3:t.setAttribute("transform",`translate(${e.area.right-p.width}, ${e.area.top})`);break;case 0:default:t.setAttribute("transform",`translate(${e.area.left}, ${e.area.top})`)}e.position===0?e.area.top+=p.height||0:e.position===3?e.area.right-=(p.width||0)+8:e.position===2?e.area.left+=(p.width||0)+8:e.area.bottom-=p.height||0}Clear(e){this.group.textContent="",this.axis_group.textContent="",this.label_group.textContent="",e="treb-chart"+(e?" "+e:""),this.svg_node.setAttribute("class",e)}Resize(){let e=this.svg_node.getBoundingClientRect();this.svg_node.setAttribute("width",e.width.toString()),this.svg_node.setAttribute("height",e.height.toString()),this.size={width:e.width,height:e.height}}Prerender(){let e=this.svg_node.getBoundingClientRect();this.bounds.top=e.top,this.bounds.left=e.left,this.bounds.right=e.right,this.bounds.bottom=e.bottom}RenderTitle(e,t,r,i){let n=V("text",{class:"chart-title",x:Math.round(t.width/2)},e);n.style.textAnchor="middle",this.group.appendChild(n);let o=n.getBoundingClientRect();switch(i){case"bottom":n.setAttribute("y",Math.round(t.bottom-o.height).toString()),t.bottom-=o.height+r;break;default:n.setAttribute("y",Math.round(t.top+r+o.height).toString()),t.top+=o.height+r;break}}MeasureText(e,t,r=!1){this.text_measurement_node||(this.text_measurement_node=V("text",{x:"-100px",y:"-100px"}),this.svg_node.appendChild(this.text_measurement_node)),typeof t<"u"?(typeof t=="string"&&(t=[t]),this.text_measurement_node.setAttribute("class",t.join(" "))):this.text_measurement_node.setAttribute("class",""),this.text_measurement_node.textContent=e;let i=this.text_measurement_node.getBoundingClientRect(),n={width:i.width,height:i.height,y_offset:i.height-(this.bounds.top-i.top-100)};return r&&(n.width=Math.ceil(n.width),n.height=Math.ceil(n.height),n.y_offset=Math.ceil(n.y_offset)),n}RenderTicks(e,t,r,i,n){let o=[],a=e.width/i;for(let s=0;s<i;s++){let c=Math.round(e.left+a/2+a*s)-.5;o.push(`M${c} ${t} L${c} ${r}`)}this.group.appendChild(V("path",{d:o,class:n}))}RenderXAxisBar(e,t,r,i,n){let o=r.length;if(!o)return;let a=4,s=t?e.width/o:e.width/(o-1),c=t?s/2:0,d=1,u=!0;for(;u;){u=!1;let h=0;for(let m=0;m<o;m+=d){let f=Math.round(e.left+c+s*m),p=f-i[m].width/2;if(h&&p<=h){d++,u=!0;break}h=f+i[m].width/2+a}}for(let h=0;h<o;h+=d){let m=Math.round(e.left+c+s*h);this.RenderText(this.axis_group,r[h],"center",{x:m,y:e.bottom},n)}}RenderXAxisTicks(e,t,r){let i=t?e.width/r:e.width/(r-1),n=t?i/2:0,o=[];for(let a=0;a<r;a++){let s=Math.round(e.left+n+i*a)+.5;o.push(`M${s},${e.bottom+.5} v6`)}this.axis_group.appendChild(V("path",{d:o.join(" "),class:"x-axis-tick axis-tick"}))}RenderXAxis(e,t,r,i,n){let o=r.length;if(!o)return;let a=4,s=t?e.width/o:e.width/(o-1),c=t?s/2:0,d=1,u=!0,h=(r.length-1)%2===0,m=(r.length-1)%3===0;for(;u;){u=!1;let f=0;for(let p=0;p<o;p+=d){let b=Math.round(e.left+c+s*p),g=b-i[p].width/2;if(f&&g<=f){d++,u=!0;break}f=b+i[p].width/2+a}}d===3&&!m&&h&&d++;for(let f=0;f<o;f+=d){let p=Math.round(e.left+c+s*f);this.RenderText(this.axis_group,r[f],"center",{x:p,y:e.bottom},n)}}RenderYAxisBar(e,t,r,i){r=r.slice(0),r.reverse();let n=r.length;if(!n)return;let o=e.height/n,a=1,s=!0;for(;s;){s=!1;let c=0;for(let d=0;d<n;d+=a){let u=r[d],h=Math.round(e.bottom-o*(d+.5)+u.metrics.height/4);if(c&&h>=c){a++,s=!0;break}c=h-u.metrics.height}}for(let c=0;c<n;c+=a){let d=r[c],u=Math.round(e.bottom-o*(c+.5)+d.metrics.height/4);this.RenderText(this.axis_group,d.label,"right",{x:t,y:u},i)}}RenderYAxis(e,t,r,i,n="right"){let o=r.length;if(!o)return;let a=e.height/(o-1),s=1,c=!0;for(;c;){c=!1;let d=0;for(let u=0;u<o;u+=s){let h=r[u],m=Math.round(e.bottom-a*u+h.metrics.height/4);if(d&&m>=d){s++,c=!0;break}d=m-h.metrics.height}}for(let d=0;d<o;d+=s){let u=r[d],h=Math.round(e.bottom-a*d+u.metrics.height/4);this.RenderText(this.axis_group,u.label,n,{x:t,y:h},i)}}LineProperties(e,t){let r=t.x-e.x,i=t.y-e.y;return{length:Math.sqrt(r*r+i*i),angle:Math.atan2(i,r)}}RenderSmoothLine(e,t,r=!1,i,n){let o=V("g"),a=[],s=[],c=t.length,d=c-1,u=e.width/c/2,h=[],m=t.map((b,g)=>{if(!(typeof b>"u"))return{x:Math.round(e.left+e.width/d*g),y:e.bottom-b}}),f=[],p=()=>{if(f.length<2)return;let b="",g=f[0],x=f[f.length-1];f.length===2?b=`${f[0].x},${f[0].y} L${f[1].x},${f[1].y}`:f.length>2&&(b=""+this.CatmullRomChain(f).map(w=>`${w.x},${w.y}`).join(" L")),b&&(a.push("M"+b),r&&(s.push(`M ${g.x},${e.bottom} L ${g.x},${g.y}`),s.push("L"+b),s.push(`L ${x.x},${e.bottom}`)))};for(let b of m)b?f.push(b):(p(),f=[]);if(f.length&&p(),r&&o.appendChild(V("path",{class:"fill",d:s})),o.appendChild(V("path",{class:"line",d:a})),typeof n<"u"&&(typeof n=="string"&&(n=[n]),o.setAttribute("class",n.join(" "))),this.group.appendChild(o),i&&h.length){let b=V("g");for(let g of h){let x=V("circle",{cx:g.x,cy:g.y,r:u});x.addEventListener("mouseenter",()=>{this.parent.setAttribute("title",i[g.i]||"")}),x.addEventListener("mouseleave",()=>{this.parent.setAttribute("title","")}),b.appendChild(x)}b.setAttribute("class","mouse-layer"),this.group.appendChild(b)}}RenderLine(e,t,r=!1,i,n){let o=V("g"),a=[],s=[],c=t.length,d=c-1,u=e.width/c/2,h=[],m=0,f=!0,p;for(;m<c;m++){let b=t[m];if(typeof b>"u"){f=!0,r&&typeof p<"u"&&s.push(`L${p} ${e.bottom}Z`),p=void 0;continue}let g=Math.round(+e.left+e.width/d*m);f?(r&&s.push(`M${g} ${e.bottom} L${g} ${e.bottom-b}`),a.push(`M${g} ${e.bottom-b}`)):(a.push(`L${g} ${e.bottom-b}`),s.push(`L${g} ${e.bottom-b}`)),h.push({x:g,y:e.bottom-b,i:m}),p=g,f=!1}if(r&&typeof p<"u"&&s.push(`L${p} ${e.bottom}Z`),r&&o.appendChild(V("path",{class:"fill",d:s})),o.appendChild(V("path",{class:"line",d:a})),typeof n<"u"&&(typeof n=="string"&&(n=[n]),o.setAttribute("class",n.join(" "))),this.group.appendChild(o),i&&h.length){let b=V("g");for(let g of h){let x=V("circle",{cx:g.x,cy:g.y,r:u});x.addEventListener("mouseenter",()=>{this.parent.setAttribute("title",i[g.i]||"")}),x.addEventListener("mouseleave",()=>{this.parent.setAttribute("title","")}),b.appendChild(x)}b.setAttribute("class","mouse-layer"),this.group.appendChild(b)}}RenderBarGrid(e,t,r){let i=[],n=e.width/t;for(let o=0;o<=t;o++){let a=Math.round(e.left+n*o)-.5;i.push(`M${a} ${e.top} L${a} ${e.bottom}`)}this.group.appendChild(V("path",{d:i,class:r}))}RenderGrid(e,t,r=0,i,n){let o=[],a=[],s=e.height/t;for(let c=0;c<=t;c++){let d=Math.round(e.top+s*c)-.5;n&&n[1]===c?a.push(`M${e.left} ${d} L${e.right} ${d}`):o.push(`M${e.left} ${d} L${e.right} ${d}`)}s=e.width/(r-1);for(let c=0;c<r;c++){let d=Math.round(e.left+s*c)-.5;n&&n[0]===c?a.push(`M${d} ${e.top} L${d} ${e.bottom}`):o.push(`M${d} ${e.top} L${d} ${e.bottom}`)}this.group.appendChild(V("path",{d:o,class:i})),a.length&&(i?Array.isArray(i)?i.push("zero"):i=i+" zero":i="zero",this.group.appendChild(V("path",{d:a,class:i})))}MultiplyPoint(e,t){return{x:e.x*t,y:e.y*t}}AddPoints(e,t){return{x:e.x+t.x,y:e.y+t.y}}CatmullRomSpline(e,t){let r=.5;r=r/2;let i=(u,h,m)=>{let{x:f,y:p}=h,{x:b,y:g}=m;return((b-f)**2+(g-p)**2)**r+u},n=0,o=i(n,e[0],e[1]),a=i(o,e[1],e[2]),s=i(a,e[2],e[3]),c=(a-o)/t,d=[];for(let u=0;u<t;u++){let h=o+c*u,m=this.AddPoints(this.MultiplyPoint(e[0],(o-h)/(o-n)),this.MultiplyPoint(e[1],(h-n)/(o-n))),f=this.AddPoints(this.MultiplyPoint(e[1],(a-h)/(a-o)),this.MultiplyPoint(e[2],(h-o)/(a-o))),p=this.AddPoints(this.MultiplyPoint(e[2],(s-h)/(s-a)),this.MultiplyPoint(e[3],(h-a)/(s-a))),b=this.AddPoints(this.MultiplyPoint(m,(a-h)/(a-n)),this.MultiplyPoint(f,(h-n)/(a-n))),g=this.AddPoints(this.MultiplyPoint(f,(s-h)/(s-o)),this.MultiplyPoint(p,(h-o)/(s-o))),x=this.AddPoints(this.MultiplyPoint(b,(a-h)/(a-o)),this.MultiplyPoint(g,(h-o)/(a-o)));d.push(x)}return d}CatmullRomChain(e,t=30){let r=e.slice(0),i=[],n=r.length;if(n){let o=r[n-1].x-r[n-2].x,a=r[n-1].y-r[n-2].y;r.push({x:r[n-1].x+o,y:r[n-1].y+a}),r.push({x:r[n-1].x+o,y:r[n-1].y+a}),o=r[1].x-r[0].x,a=r[1].y-r[0].y,r.unshift({x:r[0].x-o,y:r[0].y-a});for(let s=0;s<r.length-4;s++){let c=r.slice(s,s+4),d=this.CatmullRomSpline(c,t);i.push(...d)}}return i}RenderDataLabels(e,t,r,i,n,o,a){let s=Math.max(t.length,r.length),c=i.max-i.min||1,d=n.max-n.min||1;for(let u=0;u<s;u++){let h=t[u],m=r[u];if(h!==void 0&&m!==void 0){let f={x:e.left+(h-i.min)/c*e.width,y:e.bottom-(m-n.min)/d*e.height},p=o[u];if(p){this.label_group.appendChild(V("circle",{class:"label-target",cx:f.x,cy:f.y,r:10}));let b=V("g",{class:"data-label",transform:`translate(${f.x+10},${f.y})`});this.label_group.appendChild(b);let g=V("circle",{cx:-10,y:0,r:5,class:`marker-highlight series-${a}`});b.appendChild(g);let x=V("text",{x:4,y:0},p);b.appendChild(x);let y=x.getBoundingClientRect(),w=y.height,_=y.width+8;_+15+f.x>=e.right&&(b.setAttribute("transform",`translate(${f.x-_-15},${f.y})`),g.setAttribute("cx",(_+15).toString()));let C=V("path",{d:`M0,5 h${_} v-${w} h-${_} Z`});b.insertBefore(C,x)}}}}RenderBoxAndWhisker(e,t,r,i,n,o,a){let s=V("g",{class:a});this.group.appendChild(s);let c=e.width/o,d=c*.2,h=Math.min(c-2*d,90);i>0&&(h=h*Math.sqrt(t.n)/Math.sqrt(i));let m=g=>e.top+e.height-(g-n.min)/(n.max-n.min)*e.height,f=e.left+r*c+c/2,p=m(t.quartiles[0]),b=m(t.quartiles[2]);s.appendChild(V("rect",{class:"iqr",x:e.left+r*c+(c-h)/2,y:b,width:h,height:p-b})),s.appendChild(V("line",{class:"median",x1:f-h*.5,x2:f+h*.5,y1:m(t.quartiles[1]),y2:m(t.quartiles[1])})),s.appendChild(V("line",{class:"whisker",x1:f-h*.25,x2:f+h*.25,y1:m(t.whiskers[0]),y2:m(t.whiskers[0])})),s.appendChild(V("line",{class:"whisker-extent",x1:f,x2:f,y1:m(t.whiskers[0])-2,y2:m(t.quartiles[0])+2})),s.appendChild(V("line",{class:"whisker",x1:f-h*.25,x2:f+h*.25,y1:m(t.whiskers[1]),y2:m(t.whiskers[1])})),s.appendChild(V("line",{class:"whisker-extent",x1:f,x2:f,y1:m(t.whiskers[1])+2,y2:m(t.quartiles[2])-2}));for(let g of t.data)(g<t.whiskers[0]||g>t.whiskers[1])&&s.appendChild(V("circle",{class:"outlier",cx:f,cy:m(g),r:3}))}RenderBubbleSeries(e,t,r,i,n){let o=r.max-r.min||1,a=i.max-i.min||1,s=[],c=[],d=V("g",{class:n});if(this.group.appendChild(d),t.z)for(let[u,h]of t.z.data.entries()){let m=t.x.data[u],f=t.y.data[u];if(typeof m<"u"&&typeof f<"u"&&typeof h<"u"&&h>0){let p=h/o*e.width,b=h/a*e.height,g=Math.max(p,b),x={x:e.left+(m-r.min)/o*e.width,y:e.bottom-(f-i.min)/a*e.height,z:g};if(s.push(x),t.labels?.[u]){let y=x.z/2;c.push({x:x.x,y:x.y,text:t.labels?.[u]||"",offset:Math.cos(Math.PI/4)*y})}}}for(let u of s)u&&d.appendChild(V("circle",{cx:u.x,cy:u.y,r:u.z/2,class:"point"}));if(c.length){let u=this.label_group.getBoundingClientRect();for(let h of c)if(h.text){let m=this.label_group.appendChild(V("g",{class:"bubble-label"})),f=m.appendChild(V("rect",{x:h.x,y:h.y,class:"label-background"})),b=m.appendChild(V("text",{x:h.x,y:h.y,offset:h.offset,class:"label-text","text-anchor":"middle","alignment-baseline":"middle",style:`--translate-offset: ${Math.round(h.offset)}px`},h.text)).getBoundingClientRect();f.setAttribute("x",(b.left-u.left-2).toString()),f.setAttribute("y",(b.top-u.top-1).toString()),f.style.height=b.height+2+"px",f.style.width=b.width+4+"px"}}}RenderScatterSeries(e,t,r,i,n,o=!0,a=!1,s=!1,c=!1,d=!1,u){let h=Math.max(t.length,r.length),m=i.max-i.min||1,f=n.max-n.min||1,p=[],b=[],g=[],x=V("g",{class:u});this.group.appendChild(x);for(let y=0;y<h;y++){let w=t[y],_=r[y];typeof w>"u"||typeof _>"u"?p.push(void 0):p.push({x:e.left+(w-i.min)/m*e.width,y:e.bottom-(_-n.min)/f*e.height})}if(o){let y=[],w=d?()=>y.length===2?`${y[0].x},${y[0].y} L${y[1].x},${y[1].y}`:y.length>2?this.CatmullRomChain(y).map(C=>`${C.x},${C.y}`).join(" L"):"":()=>y.map(_=>`${_.x},${_.y}`).join(" L");for(let _ of p)if(_)y.push(_);else{if(y.length>=2){let C=w();b.push("M"+C),g.push(`M${y[0].x},${e.bottom}L`+C+`L${y[y.length-1].x},${e.bottom}Z`)}y=[]}if(y.length>=2){let _=w();b.push("M"+_),g.push(`M${y[0].x},${e.bottom}L`+_+`L${y[y.length-1].x},${e.bottom}Z`)}}if(s&&x.appendChild(V("path",{d:g,class:"fill"})),o&&x.appendChild(V("path",{d:b,class:"line"})),a)for(let y of p)y&&x.appendChild(V("circle",{cx:y.x,cy:y.y,r:1,class:"point"}));if(c)for(let y of p)y&&x.appendChild(V("circle",{cx:y.x,cy:y.y,r:3,class:"marker"}))}RenderPoints(e,t,r,i){let n=[];for(let o=0;o<t.length;o++){let a=t[o]*e.width+e.left,s=e.bottom-r[o]*e.height;n.push(`M${a-1},${s-1} L${a+1},${s+1}`),n.push(`M${a-1},${s+1} L${a+1},${s-1}`)}this.group.appendChild(V("path",{d:n,class:i}))}RenderPoint(e,t,r){this.group.appendChild(V("circle",{cx:e,cy:t,r:1,class:r}))}RenderCalloutLines(e){let t=V("g",{class:"callouts"});this.label_group.appendChild(t);for(let r of e)t.appendChild(V("path",{d:`M${r.x1},${r.y1} L${r.x2},${r.y2}`,class:"callout "+(r.classes||"").trim()}))}RenderRectangle(e,t,r,i,n,o){let a="";if(t)if(t[0]&&t[0]===t[1]&&t[0]>=e.height){let c=t[0],d=t[0]-e.height,u=Math.sqrt(c*c-d*d);a=`M${e.left+e.width/2-u},${e.bottom} a${c},${c} 0 0 1 ${u*2},0 z`}else if(t[1]&&t[1]===t[2]&&t[1]>=e.width){let c=t[1],d=t[1]-e.width,u=Math.sqrt(c*c-d*d);a=`M${e.left},${e.top+e.height/2-u} a${c},${c} 0 0 1 0,${u*2} z`}else a=`M${e.left},${e.top+t[0]} a${t[0]},${t[0]} 0 0 1 ${t[0]},${-t[0]} h${e.width-t[0]-t[1]} a${t[1]},${t[1]} 0 0 1 ${t[1]},${t[1]} v${e.height-t[1]-t[2]} a${t[2]},${t[2]} 0 0 1 ${-t[2]},${t[2]} h${-e.width+t[2]+t[3]} a${t[3]},${t[3]} 0 0 1 ${-t[3]},${-t[3]} v${-e.height+t[3]+t[0]} `;else a=`M${e.left},${e.top} h${e.width} v${e.height} h${-e.width} v${-e.height} `;let s=V("path",{d:a,class:r});if(i&&(s.addEventListener("mouseenter",()=>{this.parent.setAttribute("title",i)}),s.addEventListener("mouseleave",()=>{this.parent.setAttribute("title","")})),this.group.appendChild(s),n){this.label_group.appendChild(V("path",{class:"label-target",d:a}));let c=o||{x:Math.round(e.left+e.width/2),y:Math.round(e.top-10)},d=V("g",{class:"data-label",transform:`translate(${c.x},${c.y})`});this.label_group.appendChild(d);let u=V("text",{x:0,y:0},n);d.appendChild(u);let h=u.getBoundingClientRect(),m=h.height,f=h.width+8;c.y-h.height<4&&(c.y-=c.y-h.height-4,d.setAttribute("transform",`translate(${c.x},${c.y})`)),u.setAttribute("x",Math.floor(-h.width/2).toString());let p=Math.ceil(m*.125),b=V("rect",{rx:3,x:-f/2,y:Math.round(-m+p*2/3),width:f,height:m+p});d.insertBefore(b,u)}}RenderText(e,t,r,i,n){let o=V("text",{x:i.x,y:i.y,class:n},t);switch(r){case"right":o.style.textAnchor="end";break;case"center":o.style.textAnchor="middle";break;default:o.style.textAnchor="start";break}(e||this.group).appendChild(o)}RenderDonut(e,t,r,i,n,o,a){let s=-Math.PI/2,c=0;o&&(r*=.8,i*=.7);let d=(u,h,m)=>[Math.cos(m)*h+u.x,Math.sin(m)*h+u.y];for(let u of e){let h=u.title||"",m=u.percent,f=u.index,p=[],b=0,g=d.bind(0,t,r),x=d.bind(0,t,i);if(m>.5){b=s+m/2*Math.PI*2,c=s+m*Math.PI*2;let _=b-s,C=c-b;p.push(`M${g(s)}`,`A${r},${r},${_},0,1,${g(b)}`,`A${r},${r},${C},0,1,${g(c)}`,`L${x(c)}`,`A${i},${i},${C},0,0,${x(b)}`,`A${i},${i},${_},0,0,${x(s)}`,"Z")}else{c=s+m*Math.PI*2,b=(c-s)/2+s;let _=c-s;p.push(`M${g(s)}`,`A${r},${r},${_},0,1,${g(c)}`,`L${x(c)}`,`A${i},${i},${_},0,0,${x(s)}`,"Z")}let y=V("path",{d:p,class:typeof f>"u"?void 0:`series-${f}`});typeof f<"u"&&y.setAttribute("data-index",f.toString());let w=V("g",{class:a});if(w.appendChild(y),this.group.appendChild(w),m>=.05&&h){let _=r-i;p=[];let C=d(t,i+(r-i)/2+_,b);p.push(`M${d(t,i+(r-i)/2,b)}`),p.push(`L${C}`),w.appendChild(V("path",{d:p,class:"callout"}));let S=[],A=V("text",{class:"callout-label"});w.appendChild(A);let E=b+Math.PI/2,R=h;A.textContent=R;let z=A.getBoundingClientRect(),K={width:z.width,height:z.height},[ie,pe]=C;ie+=K.height/2*Math.cos(b),pe+=K.height/4+K.height/2*Math.sin(b);let T=!1;E>Math.PI?ie-K.width<=n.left&&(T=!0):ie+K.width>n.right&&(T=!0);let q=/[\s-]/;if(T&&q.test(R)){let Y=-1,J=1;for(let k=0;k<R.length;k++)if(q.test(R[k])){let P=Math.abs(.5-k/R.length);P<J&&(J=P,Y=k)}Y>0&&(S.push(R.substr(0,Y+1).trim()),S.push(R.substr(Y+1).trim()))}if(S.length){let Y=0,J=0,k=S.map(P=>{A.textContent=P,z=A.getBoundingClientRect();let Z={width:z.width,height:z.height};return J=Math.max(J,Z.width),{text:P,metrics:Z}});A.textContent="";for(let P of k){let Z=V("tspan");Z.textContent=P.text;let be=E>Math.PI?ie-(J-P.metrics.width)/2:ie+(J-P.metrics.width)/2;Z.setAttribute("x",be.toString()),Z.setAttribute("dy",Y.toString()),A.appendChild(Z),Y=P.metrics.height}}let le=E>Math.PI?"end":"start";A.setAttribute("text-anchor",le),A.setAttribute("x",ie.toString()),A.setAttribute("y",pe.toString()),typeof f<"u"&&A.setAttribute("data-index",f.toString())}s=c}}};var Cr=class{renderer=new xr;margin={top:.025,left:.05,bottom:.025,right:.075};Resize(e,t){this.renderer.Resize()}Initialize(e){this.renderer.Initialize(e)}Update(e,t){this.renderer.Resize(),this.renderer.Prerender(),this.renderer.Clear(t.class_name);let r=new Me(0,0,this.renderer.size.width,this.renderer.size.height),i={top:Math.round(r.height)*this.margin.top,bottom:Math.round(r.height)*this.margin.bottom,left:Math.round(r.width)*this.margin.left,right:Math.round(r.width)*this.margin.right},n=t.title;if(n&&this.renderer.RenderTitle(n,r,i.top,t.title_layout||"top"),r.top+=i.top,r.left+=i.left,r.bottom-=i.bottom,r.right-=i.right,t.legend&&t.legend.length){let a=0;t.title&&(!t.title_layout||t.title_layout==="top")&&(a=1);let s=t.legend_position||a;this.renderer.Legend({labels:t.legend,position:s,style:t.legend_style,layout:s===0||s===1?0:1,area:r})}if(t.type==="histogram"||t.type==="line"||t.type==="area"||t.type==="column"||t.type==="histogram2"||t.type==="bar"||t.type==="scatter2"||t.type==="bubble"||t.type==="box"){let a=[],s=0;t.x_labels&&t.x_labels.length&&(a=t.x_labels.map(h=>{let m=this.renderer.MeasureText(h,["axis-label","x-axis-label"],!0);return s=Math.max(s,m.height),m}));let c=[],d=0;t.type==="box"&&t.series_names?.length&&(c=t.series_names.map(h=>{let m=this.renderer.MeasureText(h,["axis-label","x-axis-label","series-name"],!0);return d=Math.max(d,m.height),m}));let u=s&&d?4:0;if(t.y_labels&&t.y_labels.length){let h=[],m=0,f=0,p=t.type==="scatter2"||t.type==="bubble"?t.y_scale:t.scale,b=t.type==="bar"?t.y_labels.length:p.count+1;for(let g=0;g<b;g++){let x=this.renderer.MeasureText(t.y_labels[g],["axis-label","y-axis-label"]);h.push({label:t.y_labels[g],metrics:x}),m=Math.max(m,x.width),f=Math.max(f,x.height)}r.bottom=Math.round(r.bottom-f/2),r.top=Math.round(r.top+f/2),a.length&&(r.bottom-=s+i.bottom),c.length&&(r.bottom-=d+i.bottom),u&&(r.bottom-=u),t.type==="bar"?this.renderer.RenderYAxisBar(r,r.left+m,h,["axis-label","y-axis-label"]):this.renderer.RenderYAxis(r,r.left+m,h,["axis-label","y-axis-label"]),r.left+=m+i.left}if(t.type==="scatter2"&&t.y2_labels&&t.y2_labels.length&&t.y2_scale){let h=[],m=0,f=0,b=t.y2_scale.count+1;for(let g=0;g<b;g++){let x=this.renderer.MeasureText(t.y2_labels[g],["axis-label","y-axis-label"]);h.push({label:t.y2_labels[g],metrics:x}),m=Math.max(m,x.width),f=Math.max(f,x.height)}this.renderer.RenderYAxis(r,r.right-m,h,["axis-label","y-axis-label"],"left"),r.right-=m+i.left}if(a.length&&t.x_labels?.length){let h=t.type==="histogram2",m=t.type!=="line"&&t.type!=="area"&&t.type!=="bar"&&t.type!=="scatter2"&&t.type!=="bubble"&&t.type!=="histogram2";h&&this.renderer.RenderXAxisTicks(r,m,t.x_labels.length),t.y_labels&&(r.bottom+=s+i.bottom),this.renderer.RenderXAxis(r,m,t.x_labels,a,["axis-label","x-axis-label"]),r.bottom-=s+i.bottom}u&&(r.bottom+=u),t.type==="box"&&c.length&&t.series_names?.length&&(t.y_labels&&(r.bottom+=s+d+u+i.bottom),this.renderer.RenderXAxis(r,!0,t.series_names,c,["axis-label","x-axis-label","series-name"]),r.bottom-=s+d+i.bottom+i.bottom)}let o=[];switch(t.type){case"scatter":this.renderer.RenderPoints(r,t.x,t.y,"mc mc-correlation series-1");break;case"box":this.renderer.RenderGrid(r,t.scale.count,void 0,"chart-grid",o);for(let[a,s]of t.data.entries())s.iqr>0&&this.renderer.RenderBoxAndWhisker(r,s,a,t.max_n,t.scale,t.data.length,`box-plot series-${a}`);break;case"bubble":t.x_scale.min<=0&&t.x_scale.max>=0&&(o[0]=Math.round(Math.abs(t.x_scale.min/t.x_scale.step))),t.y_scale.min<=0&&t.y_scale.max>=0&&(o[1]=Math.round(Math.abs(t.y_scale.max/t.y_scale.step))),this.renderer.RenderGrid(r,t.y_scale.count,t.x_scale.count+1,"chart-grid",o);for(let[a,s]of t.series.entries()){let c=typeof s.index=="number"?s.index:a+1;this.renderer.RenderBubbleSeries(r,s,t.x_scale,t.y_scale,`bubble-chart series-${c}`)}break;case"scatter2":if(this.renderer.RenderGrid(r,t.y_scale.count,t.x_scale.count+1,"chart-grid"),t.series){for(let a=0;a<t.series.length;a++){let s=t.series[a],c=!!t.lines,d=!!t.points;s.subtype==="plot"?(d=!0,c=!1):s.subtype==="line"&&(d=!1,c=!0);let u=typeof s.index=="number"?s.index:a+1;this.renderer.RenderScatterSeries(r,s.x.data,s.y.data,t.x_scale,s.axis&&t.y2_scale?t.y2_scale:t.y_scale,c,d,!!t.filled,!!t.markers,!!t.smooth,`scatter-plot series-${u}`)}if(t.data_labels)for(let a=0;a<t.series.length;a++){let s=t.series[a];s.y.labels&&this.renderer.RenderDataLabels(r,s.x.data,s.y.data,t.x_scale,t.y_scale,s.y.labels,a+1)}}break;case"pie":case"donut":{let a=Math.min(r.height,r.width)/2*.9,s=t.type==="pie"?0:a*.8;this.renderer.RenderDonut(t.slices,r.center,a,s,r,!0,"donut")}break;case"line":case"area":{let a=t.scale;if(t.series){let s=t.x_scale?t.x_scale.max:Math.max.apply(0,t.series.map(u=>u.length)),c=t.smooth?this.renderer.RenderSmoothLine:this.renderer.RenderLine;this.renderer.RenderGrid(r,t.scale.count,t.x_scale?t.x_scale.count+1:s,"chart-grid");let d=0;for(let u of t.series){let h=u.map(f=>{if(!(typeof f>"u"))return G.ApplyScale(f,r.height,a)});if(h.length<s)for(let f=h.length;f<s;f++)h.push(void 0);let m=[t.type==="area"?"chart-area":"chart-line",`series-${d+1}`];c.call(this.renderer,r,h,t.type==="area",t.titles,m),d++}}}break;case"bar":{let a;if(this.renderer.RenderBarGrid(r,t.scale.count,"chart-grid"),t.series2){let s=0,c=t.series2.length;for(let p of t.series2)s=Math.max(s,p.y.data.length);let d=r.height/s,u=.7;typeof t.space=="number"&&(u=Math.max(0,Math.min(1,1-t.space)));let h=d*(1-u)/2,m=(d-h*2)/c,f=0;if(t.scale.min<0&&(f=G.ApplyScale(0,r.width,t.scale)),t.round){let p=Math.floor(m/2);a=[0,p,p,0]}for(let p=0;p<c;p++){let b=t.series2[p],g=typeof b.index=="number"?b.index:p+1;for(let x=0;x<b.y.data.length;x++){let y=b.y.data[x];if(typeof y=="number"){let w=Math.round(r.top+x*d+h)+p*m,_=0,C=0;f?y>0?(C=G.ApplyScale(y+t.scale.min,r.width,t.scale),_=r.left+f):(C=G.ApplyScale(t.scale.min-y,r.width,t.scale),_=r.left+f-C):(C=G.ApplyScale(y,r.width,t.scale),_=r.left),C&&this.renderer.RenderRectangle(new Me(_,w,_+C,w+m),a,["chart-column",`series-${g}`],void 0||void 0)}}}}}break;case"column":case"histogram2":if(this.renderer.RenderGrid(r,t.scale.count,0,"chart-grid"),t.series2){let a=0,s=t.series2.length;for(let p of t.series2)a=Math.max(a,p.y.data.length);let c=r.width/a,d=.7;typeof t.space=="number"&&(d=Math.max(0,Math.min(1,1-t.space)));let u=c*(1-d)/2,h=(c-u*2)/s,m=0;if(t.scale.min<0&&(m=G.ApplyScale(0,r.height,t.scale)),t.callouts&&t.x_scale){let p=t.x_scale,b=t.callouts.map((g,x)=>{let y=Math.round(r.left+G.ApplyScale(g.value,r.width,p))+.5;return{x1:y,y1:r.bottom-r.height,x2:y,y2:r.bottom,classes:`callout-${x+1}`}});this.renderer.RenderCalloutLines(b)}let f;if(t.round){let p=Math.floor(h/2);f=[p,p,0,0]}if(t.stacked_series)for(let p=0;p<t.stacked_series[0].y.data.length;p++){let b=r.left+p*c+u,g=0;for(let x=0;x<t.stacked_series.length;x++){let y=t.stacked_series[x],w=typeof y.index=="number"?y.index:x+1,_=0,C=y.y.data[p]||0;x===0&&(g=Math.min(t.scale.min||0,C)),_=G.ApplyScale(C,r.height,t.scale);let S=r.bottom-_-G.ApplyScale(g,r.height,t.scale);this.renderer.RenderRectangle(new Me(b,S,b+h,S+_),f,["chart-column",`series-${w}`],void 0||void 0,void 0,void 0),g+=C}}else for(let p=0;p<s;p++){let b=t.series2[p],g=typeof b.index=="number"?b.index:p+1;for(let x=0;x<b.y.data.length;x++){let y=b.y.data[x];if(typeof y=="number"){let w=r.left+x*c+u+p*h,_=0,C=0;m?y>0?(_=G.ApplyScale(y+t.scale.min,r.height,t.scale),C=r.bottom-_-m):(_=G.ApplyScale(t.scale.min-y,r.height,t.scale),C=r.bottom-m):(_=G.ApplyScale(y,r.height,t.scale),C=r.bottom-_);let S=void 0;if(_){let A=t.data_labels&&b.y.labels?b.y.labels[x]:"",E={x:Math.round(w+h/2),y:Math.round(C-10)};this.renderer.RenderRectangle(new Me(w,C,w+h,C+_),f,["chart-column",`series-${g}`],S||void 0,A,E)}}}}}break;case"histogram":{this.renderer.RenderGrid(r,t.scale.count,0,"chart-grid");let a=r.width/t.count,s=t.column_width,c=a*(1-s)/2;for(let d=0;d<t.count;d++){let u=Math.round(r.left+d*a+c),h=a-c*2,m=G.ApplyScale(t.bins[d],r.height,t.scale),f=r.bottom-m,p=t.titles?t.titles[d]:void 0;this.renderer.RenderRectangle(new Me(u,f,u+h,f+m),void 0,"chart-column series-1",p||void 0)}}break}}};var qe=class{constructor(e=new Cr){this.renderer=e}static functions_registered=!1;chart_data={type:"null"};node;Initialize(e){this.node=e,this.renderer.Initialize(e)}Exec(e,t){let r=t?.value||[];switch(e.toLowerCase()){case"column.chart":this.chart_data=Si(r,"column");break;case"bar.chart":this.chart_data=Si(r,"bar");break;case"line.chart":this.chart_data=Ai(r,"line");break;case"area.chart":this.chart_data=Ai(r,"area");break;case"donut.chart":case"pie.chart":this.chart_data=so(r,e.toLowerCase()==="pie.chart");break;case"scatter.plot":this.chart_data=Ci(r,"plot");break;case"scatter.line":this.chart_data=Ci(r,"line");break;case"bubble.chart":this.chart_data=ao(r);break;case"box.plot":this.chart_data=oo(r);break;default:this.Clear();break}}Clear(){this.chart_data={type:"null"}}Resize(){this.node&&this.renderer.Resize(this.node,this.chart_data)}Update(){this.node&&this.renderer.Update(this.node,this.chart_data)}};var Ue=(...l)=>({type:5,value:l,key:"arguments"}),ki={Group:{arguments:[{name:"Array...",metadata:!0}],fn:(...l)=>({type:5,value:l,key:"group"}),category:["grouping"]},Series:{arguments:[{name:"Label"},{name:"X",metadata:!0},{name:"Y",metadata:!0},{name:"Z",metadata:!0},{name:"Index"},{name:"Subtype"},{name:"Labels",description:"Labels for bubble charts only (atm)"},{name:"Axis",description:"Series axis (scatter plot only)"}],fn:(...l)=>({type:5,value:{label:l[0],x:l[1],y:l[2],z:l[3],index:l[4],subtype:l[5],data_labels:l[6],axis:l[7]},key:"series"}),category:["chart functions"]},"Bar.Chart":{arguments:[{name:"Data",metadata:!0},{name:"Categories",metadata:!0},{name:"ChartTitle"}],fn:Ue,category:["chart functions"]},"Line.Chart":{arguments:[{name:"y",metadata:!0},{name:"x",metadata:!0},{name:"ChartTitle"}],fn:Ue,category:["chart functions"]},"Area.Chart":{arguments:[{name:"y",metadata:!0},{name:"x",metadata:!0},{name:"ChartTitle"}],fn:Ue,category:["chart functions"]},"Pie.Chart":{arguments:[{name:"Values",metadata:!0},{name:"Labels"},{name:"Title"},{name:"Sort"},{name:"Label"}],fn:Ue,category:["chart functions"]},"Donut.Chart":{arguments:[{name:"Values",metadata:!0},{name:"Labels",metadata:!0},{name:"Title"},{name:"Sort"},{name:"Label"}],fn:Ue,category:["chart functions"]},"Scatter.Line":{arguments:[{name:"Data",metadata:!0},{name:"ChartTitle"}],fn:Ue,category:["chart functions"]},"Scatter.Plot":{arguments:[{name:"Data",metadata:!0},{name:"ChartTitle"}],fn:Ue,category:["chart functions"]},"Column.Chart":{arguments:[{name:"Data",metadata:!0},{name:"Categories",metadata:!0},{name:"Chart Title"}],fn:Ue,category:["chart functions"]},"Bubble.Chart":{arguments:[{name:"Data",metadata:!0},{name:"Chart Title"}],fn:Ue,category:["chart functions"]},"Box.Plot":{arguments:[{name:"Data",metadata:!0},{name:"Chart Title"},{name:"Min/Max Style"}],fn:Ue,category:["chart functions"]}};var Sr=class l{static treb_base_path="";static failed_dynamic_modules=[];static one_time_warnings={};static clipboard;DOM=O.GetInstance();loaded=!1;document_styles={number_formats:[],colors:[],theme_colors:[]};selection_state={};options;get Localization(){return F}events=new _e;calculation=0;file_version=0;last_save_version=0;initial_load_source=void 0;calculator;grid;model;dialog;spinner;file_chooser;file_chooser_operation=0;get parser(){return this.model.parser}view_node;key_listener;views=[];focus_target=this;parent_view;export_worker;undo_pointer=0;undo_stack=[];last_selection;get active_sheet(){let e=this.grid.active_sheet.name;return Se.test(e)?`'${e}'`:e}get modified(){return this.undo_stack.length!==1}get document_name(){return this.grid.model.document_name}set document_name(e){this.grid.model.document_name=e,this.DocumentChange()}get user_data(){return this.grid.model.user_data}set user_data(e){this.grid.model.user_data=e,this.DocumentChange()}get scale(){return this.grid.scale}set scale(e){this.grid.scale=e}get headless(){return this.grid.headless}set headless(e){this.grid.headless!==e&&(this.grid.headless=e,e||(this.grid.Update(!0),this.RebuildAllAnnotations()))}get state(){return this.file_version}get can_revert(){return!this.options.inline_document&&!this.options.document?!1:this.initial_load_source==="local-storage"?!0:this.dirty}get dirty(){return this.file_version!==this.last_save_version}set dirty(e){e?this.file_version++:this.last_save_version=this.file_version}get sheet_names(){return this.model.sheets.list.map(e=>e.name)}constructor(e){e.storage_key&&!e.local_storage&&(e.local_storage=e.storage_key),this.options={...Qn,...e,local_storage:this.ResolveStorageKey(e.local_storage,"document")},typeof this.options.imaginary_value=="string"&&(ue.imaginary_character=this.options.imaginary_value),this.options.network_document&&(console.warn("the option `network_document` is deprecated. please use `document` instead."),this.options.document||(this.options.document=this.options.network_document)),this.options.document&&this.options.inline_document&&console.warn("both document and inline-document are provided");let t=this.options.document,r,i;this.options.local_storage&&!this.options.toll_initial_load&&!e.model&&(r=localStorage.getItem(this.options.local_storage)||void 0,r&&(i="local-storage")),!r&&!this.options.toll_initial_load&&!e.model&&e.inline_document&&(r=e.inline_document,i="inline-document"),this.options.local_storage&&!e.model&&window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.options.local_storage&&this.dirty&&this.SaveLocalStorage(this.options.local_storage)});let n;typeof this.options.container=="string"?n=document.querySelector(this.options.container):this.options.container&&(n=this.options.container);let o={in_cell_editor:!0,repaint_on_cell_change:!1,scrollbars:this.options.scrollbars,markdown:!!this.options.markdown,formula_bar:this.options.formula_bar,expand_formula_button:this.options.expand_formula_button,tab_bar:this.options.tab_bar,add_tab:this.options.add_tab,expand:this.options.expand,support_font_stacks:!!this.options.font_stack};if(this.options.scale&&(o.initial_scale=this.options.scale),this.options.stats&&(o.stats=this.options.stats,o.tab_bar=!0),this.options.scale_control&&(o.scale_control=!0,o.tab_bar=!0,this.options.persist_scale&&(o.persist_scale_key=this.ResolveStorageKey(this.options.persist_scale,"scale"),o.persist_scale_key))){let a=localStorage.getItem(o.persist_scale_key);if(a)try{let s=JSON.parse(a);o.initial_scale=s.scale||1}catch{console.warn("parsing persisted scale failed")}}if(e.model?(this.model=e.model.model,this.calculator=e.model.calculator,this.DOM=e.model.DOM):(this.model=new _t,this.model.sheets.Add(re.Blank(this.model.theme_style_properties)),this.calculator=this.CreateCalculator(this.model,this.options)),n&&(this.DOM=O.GetInstance(n.ownerDocument)),this.grid=new gt(o,this.model,void 0,!!n,this.DOM),this.options.headless&&(this.grid.headless=!0),this.LoadLanguage(e.language),n){this.DOM=O.GetInstance(n.ownerDocument),this.parent_view||(j.is_windows?n.parentElement?.classList.add("treb-ua-windows"):j.is_mac&&n.parentElement?.classList.add("treb-ua-osx"),j.is_iphone&&n.parentElement?.classList.add("treb-ua-iphone"));let a=n.querySelector(".treb-view-template");this.view_node=a.content.firstElementChild?.cloneNode(!0),n.prepend(this.view_node),this.view_node.addEventListener("focusin",()=>{this.focus_target!==this&&(this.Publish({type:"focus-view"}),this.focus_target=this)}),this.key_listener=c=>this.HandleKeyDown(c),n.addEventListener("keydown",this.key_listener);let s=!!(r||this.options.document);this.grid.Initialize(this.view_node,s),this.options.dnd&&(this.view_node.addEventListener("dragenter",c=>this.HandleDrag(c)),this.view_node.addEventListener("dragover",c=>this.HandleDrag(c)),this.view_node.addEventListener("drop",c=>this.HandleDrop(c))),this.grid.grid_events.Subscribe(c=>{switch(c.type){case"error":this.dialog?.ShowDialog({type:"error",...this.TranslateGridError(c.code),timeout:3e3,close_box:!0});break;case"selection":this.UpdateSelection(c.selection),this.UpdateSelectionStyle(c.selection);break;case"sheet-change":this.OnSheetChange(c),this.UpdateSelectionStyle();break;case"scale":this.RebuildAllAnnotations(),this.Publish({type:"view-change"});break;case"cell-event":this.HandleCellEvent(c);break;case"composite":{let d=this.last_selection;this.calculation===0&&this.Recalculate(c),this.DocumentChange(d),this.UpdateDocumentStyles(),this.UpdateSelectionStyle()}break;case"data":{let d=this.last_selection;this.calculation===0&&this.Recalculate(c),this.DocumentChange(d)}break;case"style":this.DocumentChange(),this.UpdateDocumentStyles(),this.UpdateSelectionStyle();break;case"annotation":if(c.annotation){let d=c.annotation.view[this.grid.view_index]||{},u=!1;if(c.event==="select")u=!0;else switch(this.DocumentChange(),c.event){case"create":this.InflateAnnotation(c.annotation),this.calculator.UpdateAnnotations(c.annotation,this.grid.active_sheet),this.grid.AnnotationUpdated(c.annotation),u=c.annotation===this.grid.selected_annotation;break;case"delete":this.calculator.RemoveAnnotation(c.annotation);break;case"update":d.update_callback?(d.update_callback(),this.grid.AnnotationUpdated(c.annotation)):console.info("annotation update event without update callback"),this.calculator.UpdateAnnotations(c.annotation,this.grid.active_sheet),u=c.annotation===this.grid.selected_annotation;break;case"resize":d.resize_callback&&(d.resize_callback(),this.grid.AnnotationUpdated(c.annotation));break}if(u){this.UpdateSelectionStyleAnnotation(c.annotation),this.Publish({type:"annotation-selection"});break}}else console.info("annotation event without annotation");break;case"structure":{let d=this.last_selection;c.conditional_format&&(this.calculator.UpdateConditionals(),this.ApplyConditionalFormats(this.grid.active_sheet,!1)),c.rebuild_required?(this.calculator.Reset(),this.calculation===0&&this.Recalculate(c),this.DocumentChange(d)):this.DocumentChange(d)}this.UpdateSelectionStyle();break}}),this.options.prompt_save&&window.addEventListener("beforeunload",c=>{this.last_save_version!==this.file_version&&(c.preventDefault(),c.returnValue="")})}else l.one_time_warnings.headless||(l.one_time_warnings.headless=!0,console.info("not initializing layout; don't call UI functions"));if(e.preload&&e.preload.call(0,this),r?(typeof r=="string"&&(r=JSON.parse(r)),r?this.LoadDocument(r,{recalculate:!!this.options.recalculate,source:i}):this.UpdateDocumentStyles()):t||(this.calculator.RebuildClean(!0),this.UpdateDocumentStyles()),this.FlushUndo(),this.grid.ShowHeaders(this.options.headers),this.options.scroll&&!this.options.document){let a=this.options.scroll;requestAnimationFrame(()=>{this.ScrollTo(a)})}this.UpdateAC(),this.options.global_name&&(self[this.options.global_name]=this),n&&this.options.spinner&&(this.spinner=new vr(n)),t&&!e.model&&!r&&this.LoadNetworkDocument(t,this.options),n&&(this.dialog=new yr(n))}UpdateAC(){let e=this.calculator.SupportedFunctions();if(this.model.language_model?.functions){let t={};for(let r of this.model.language_model.functions||[])t[r.base.toUpperCase()]=r;e=e.map(r=>{let i=t[r.name.toUpperCase()];if(i){let n=JSON.parse(JSON.stringify({...r,name:i.name}));if(i.description&&(n.description=i.description),i.arguments&&n.arguments)for(let[o,a]of i.arguments.entries())n.arguments[o]&&(n.arguments[o].name=a);return n}return r})}this.grid.SetAutocompleteFunctions(e)}CreateCalculator(e,t){return new _r(e,{complex_numbers:t.complex,spill:t.spill})}TranslateGridError(e){switch(e){case 0:return{message:"No error"};case 2:return{message:"You can't change part of an array"};case 5:return{message:"Invalid area for paste"};case 4:return{message:"Invalid area for table"};case 3:return{message:"Invalid value (data validation)"};default:return{message:`Unknown error (${e})`}}}CreateView(){let e=new l({...this.options,global_name:void 0,model:this});return e.parent_view=this,e}Unsplit(){let e=this.views.pop();if(e){let t=e.view;t.grid.grid_events.CancelAll(),t.events.CancelAll(),t.view_node?.parentElement&&(t.key_listener&&t.view_node.parentElement.removeEventListener("keydown",t.key_listener),t.view_node.parentElement.removeChild(t.view_node)),this.view_node?.focus(),this.Resize()}}ExternalEditor(e){this.grid.ExternalEditor(e)}Split(){let e=this.CreateView();e.grid.EnsureActiveSheet(!0),e.view_node?.addEventListener("focusin",()=>{this.focus_target!==e&&(this.Publish({type:"focus-view"}),this.focus_target=e)}),e.grid.grid_events.Subscribe(r=>{r.type==="structure"&&(this.grid.EnsureActiveSheet(),this.grid.UpdateLayout(),this.grid.UpdateTabBar(),r.update_annotations&&(this.grid.RefreshAnnotations(),this.InflateAnnotations()))}),e.Subscribe(r=>{switch(r.type){case"selection":break;default:e.UpdateAnnotations(),this.grid.Update(!0),this.grid.UpdateAnnotations()}}),this.grid.grid_events.Subscribe(r=>{r.type==="structure"&&(e.grid.EnsureActiveSheet(),e.grid.UpdateLayout(),e.grid.UpdateTabBar(),r.update_annotations&&(e.grid.RefreshAnnotations(),e.InflateAnnotations()))});let t=this.Subscribe(r=>{switch(r.type){case"selection":break;case"load":case"reset":e.grid.EnsureActiveSheet(!0),e.UpdateAnnotations(),e.grid.UpdateAnnotations(),e.grid.Update(!0);break;default:e.UpdateAnnotations(),e.grid.Update(!0),e.grid.UpdateAnnotations()}});this.views.push({view:e,subscription:t})}ListConditionalFormats(e){return(typeof e>"u"?this.grid.active_sheet:this.model.sheets.Find(e))?.conditional_formats||[]}ConditionalFormatDuplicateValues(e,t){return this.AddConditionalFormat({type:"duplicate-values",area:this.RangeOrSelection(e,"invalid range (no selection)"),...t})}ConditionalFormatGradient(e,t){let r=this.RangeOrSelection(e,"invalid range (no selection)"),i=typeof t=="object"?{type:"gradient",area:r,...t}:{type:"gradient",area:r,...an[t]};return this.AddConditionalFormat(i),i}ConditionalFormatDataBars(e,t){let i={type:"data-bar",area:this.RangeOrSelection(e,"invalid range (no selection)"),fill:{theme:4,tint:.5},...t};return this.AddConditionalFormat(i),i}ConditionalFormatCellMatch(e,t){let r={type:"cell-match",area:this.RangeOrSelection(e,"invalid range (no selection)"),...t};return this.AddConditionalFormat(r),r}ConditionalFormatExpression(e,t){let r={type:"expression",area:this.RangeOrSelection(e,"invalid range (no selection)"),...t};return this.AddConditionalFormat(r),r}AddConditionalFormat(e){return this.grid.AddConditionalFormat(e),e}RemoveConditionalFormat(e){this.grid.RemoveConditionalFormat({format:e})}RemoveConditionalFormats(e){let t=this.RangeOrSelection(e);t&&this.grid.RemoveConditionalFormat({area:t})}HandleToolbarMessage(e){if(this.focus_target!==this){this.focus_target.HandleToolbarMessage(e);return}let t={};if(this.grid.AnnotationSelected()){switch(e.command){case"adjust-font-scale":{let i=Number(e.delta||0),n=this.grid.GetAnnotationStyle()?.font_size;(!n||n.unit!=="em")&&(n={unit:"em",value:1}),n&&(n.value+=i,t.font_size=n,this.grid.ApplyAnnotationStyle(t))}break;case"font-scale":{let i=Number(e.scale||1);i&&!isNaN(i)&&(t.font_size={unit:"em",value:i},this.grid.ApplyAnnotationStyle(t))}break;case"font-stack":e.font_stack&&(t.font_face="stack:"+e.font_stack),this.grid.ApplyAnnotationStyle(t);break}this.Focus();return}let r=i=>{let n=this.grid.GetSelection();if(n&&!n.empty){let o=n.area.spreadsheet_label;i==="Scatter.Plot"||i==="Scatter.Line"||i==="Box.Plot"?this.InsertAnnotation(`=${i}(Series(,,${o}),"${o}")`,void 0,void 0,","):this.InsertAnnotation(`=${i}(${o},,"${o}")`,void 0,void 0,",")}};if(/^border-/.test(e.command))if(e.command==="border-color")try{t.border_top_fill=t.border_bottom_fill=t.border_left_fill=t.border_right_fill=e.color||{}}catch(i){console.error(i)}else{let i=1,n=e.command.substring(7);e.command==="border-double-bottom"&&(n="bottom",i=2),this.grid.ApplyBorders2(void 0,n,e.color||{},i)}else switch(e.command){case"about":this.About();break;case"number-format":t.number_format=e.format||"General";break;case"font-stack":e.font_stack&&(t.font_face="stack:"+e.font_stack);break;case"adjust-font-scale":{let i=this.selection_state.style?.font_size,n=this.grid.GetSelection(),o=this.grid.active_sheet.RealArea(n.area),a=Number(e.delta||0);if((!i||i.unit!=="em")&&(i={unit:"em",value:1}),i&&a&&!isNaN(a)){i.value+=a,this.grid.ApplyStyle(void 0,{font_size:i},!0);let s=[];for(let c=o.start.row;c<=o.end.row;c++)s.push(c);this.selection_state?.merge||this.grid.SetRowHeight(s,void 0,!1)}}break;case"font-scale":{let i=this.grid.GetSelection(),n=this.grid.active_sheet.RealArea(i.area),o=Number(e.scale||1);if(o&&!isNaN(o)){this.grid.ApplyStyle(void 0,{font_size:{unit:"em",value:o}},!0);let a=[];for(let s=n.start.row;s<=n.end.row;s++)a.push(s);this.selection_state?.merge||this.grid.SetRowHeight(a,void 0,!1)}}break;case"update-comment":this.SetNote(void 0,e.comment||"");break;case"clear-comment":this.SetNote(void 0,"");break;case"text-color":case"fill-color":try{let i=e.color||{};e.command==="text-color"?t.text=i:e.command==="fill-color"&&(t.fill=i)}catch(i){console.error(i)}break;case"insert-table":this.InsertTable();break;case"remove-table":this.RemoveTable();break;case"insert-row":this.InsertRows();break;case"insert-column":this.InsertColumns();break;case"delete-row":this.DeleteRows();break;case"delete-column":this.DeleteColumns();break;case"insert-sheet":this.grid.InsertSheet();break;case"delete-sheet":this.grid.DeleteSheet();break;case"freeze-panes":{let i=this.grid.GetFreeze();i.rows||i.columns?this.Freeze(0,0):this.FreezeSelection()}break;case"insert-image":this.InsertImage();break;case"insert-donut-chart":r("Donut.Chart");break;case"insert-column-chart":r("Column.Chart");break;case"insert-bar-chart":r("Bar.Chart");break;case"insert-line-chart":r("Line.Chart");break;case"insert-scatter-plot":r("Scatter.Plot");break;case"insert-box-plot":r("Box.Plot");break;case"increase-precision":case"decrease-precision":if(this.selection_state?.style){let i=L.Get(this.selection_state.style.number_format||"General");if(i.date_format)break;let n=new ue(i.pattern);if(i.magic_decimal){let o=0,a=this.GetRange();Array.isArray(a)||(a=[[a]]);e:for(let s=0;s<a.length;s++)for(let c=0;c<a[s].length;c++){let d=a[s][c];if(typeof d<"u"&&me(d)){let u=L.Get(this.selection_state.style.number_format||"General",!0),h=u.BaseFormat(d.real),m=u.BaseFormat(d.imaginary);h.parts&&typeof h.parts[1]=="string"&&(o=h.parts[1].length),m.parts&&typeof m.parts[1]=="string"&&(o=Math.max(o,m.parts[1].length));break e}else if(typeof d=="number"){let u=i.BaseFormat(d);u.parts&&typeof u.parts[1]=="string"&&(o=u.parts[1].length);break e}}e.command==="increase-precision"?n.SetDecimal(o+1):n.SetDecimal(Math.max(0,o-1))}else e.command==="increase-precision"?n.IncreaseDecimal():n.DecreaseDecimal();t.number_format=n.toString()}break;case"merge-cells":this.grid.MergeCells();break;case"unmerge-cells":this.grid.UnmergeCells();break;case"lock-cells":t={locked:this.selection_state?.style?!this.selection_state.style.locked:!0};break;case"wrap-text":t={wrap:this.selection_state?.style?!this.selection_state?.style.wrap:!0};break;case"justify-left":t={horizontal_align:"left"};break;case"justify-center":t={horizontal_align:"center"};break;case"justify-right":t={horizontal_align:"right"};break;case"align-top":t={vertical_align:"top"};break;case"align-middle":t={vertical_align:"middle"};break;case"align-bottom":t={vertical_align:"bottom"};break;case"reset":this.Reset();break;case"import-file":this.LoadLocalFile();break;case"save-json":this.SaveToDesktop();break;case"save-csv":this.SaveToDesktop("csv");break;case"export-xlsx":this.Export();break;case"revert":this.Revert();break;case"recalculate":this.Recalculate();break;case"toggle-toolbar":case"show-toolbar":case"hide-toolbar":this.ShowToolbar(e.command==="toggle-toolbar"?void 0:e.command==="show-toolbar");break;case"toggle-sidebar":case"show-sidebar":case"hide-sidebar":this.ShowSidebar(e.command==="toggle-sidebar"?void 0:e.command==="show-sidebar");break;case"revert-indicator":this.dialog?.ShowDialog({title:`This is a modified version of the document.
13
13
  You can revert to the original or save your
14
- changes in the sidebar.`,close_box:!0,timeout:5e3,type:"info"});break;case"indent":case"outdent":this.grid.Indent(void 0,e.command==="indent"?1:-1);break;default:console.info("unhandled",e.command);break}Object.keys(t).length&&this.grid.ApplyStyle(void 0,t,!0),this.Focus()}ShowToolbar(e){if(this.options.toolbar&&this.options.container instanceof HTMLElement){let t=this.options.container.parentElement;t&&(e===void 0&&(e=!t.hasAttribute("toolbar")),e?t.setAttribute("toolbar",""):t.removeAttribute("toolbar"))}}ShowSidebar(e){if(this.options.toolbar&&this.options.container instanceof HTMLElement){let t=this.options.container.parentElement;t&&(e===void 0&&(e=t.hasAttribute("collapsed")),e?t.removeAttribute("collapsed"):t.setAttribute("collapsed",""))}}CreateChart(){return this.calculator.RegisterLibrary("treb-charts",wi)&&this.UpdateAC(),this.options.chart_renderer?typeof this.options.chart_renderer=="function"?new qe(this.options.chart_renderer()):new qe(this.options.chart_renderer):new qe}async LoadLanguage(e=""){(!e||e==="locale")&&(e=(F.locale||"").split(/-/).map(o=>o.toLowerCase())[0]),e=e.toLowerCase();let t;if(e&&["es","fr","pt","nl","de","pl","sv","no","da","it"].includes(e))try{t=await import(`./languages/treb-i18n-${e}.mjs`)}catch(i){console.error(i)}t?this.model.SetLanguage(t.LanguageMap):this.model.SetLanguage(),this.grid.Reselect(),this.grid.Update(!0),this.UpdateAC()}Batch(e,t=!1){let r=this.last_selection,i=this.grid.Batch(e,t),n=!1,o=!1;for(let a of i)switch(a.type){case"composite":case"data":n=!0;break;case"structure":a.rebuild_required&&(o=!0);break;default:}o&&this.calculator.Reset(),(n||o)&&(this.Recalculate(),this.DocumentChange(r))}Freeze(e=0,t=0){this.grid.Freeze(e,t,!0)}FreezeSelection(){let e=this.grid.GetSelection();if(e.empty)this.grid.Freeze(0,0);else{let t=e.area;t.entire_sheet||(t.entire_row?this.grid.Freeze(t.end.row+1,0):t.entire_column?this.grid.Freeze(0,t.end.column+1):this.grid.Freeze(t.end.row+1,t.end.column+1))}}GetFreeze(){return this.grid.GetFreeze()}UpdateTheme(){this.grid.UpdateTheme(void 0),this.UpdateDocumentStyles();for(let e of this.model.sheets.list){for(let t of e.conditional_formats)t.internal=void 0;for(let t of e.annotations)if(t.view&&t.data.type==="textbox"){let r=t.view[this.grid.view_index]||{};r.update_callback&&r.update_callback()}}this.calculator.UpdateConditionals(),this.ApplyConditionalFormats(this.grid.active_sheet,!1),this.grid.Update(!0),this.Publish({type:"theme-change"})}GetSheetID(e){if(typeof e=="number"){let t=this.grid.model.sheets.list[e];if(t)return t.id}else{let t=this.model.sheets.Find(e);if(t)return t.id}}InsertTable(e,t={}){let r=e?this.model.ResolveArea(e,this.grid.active_sheet):this.GetSelectionReference().area,i=t.theme;typeof i=="number"&&(i=Jt(i)),this.grid.InsertTable(r,t.totals_row,t.sortable,i)}RemoveTable(e){let t=this.ResolveTable(e||this.GetSelectionReference().target);t&&this.grid.RemoveTable(t)}UpdateTableStyle(e,t=4){let r=this.ResolveTable(e||this.GetSelectionReference().target);r&&(typeof t=="number"&&(t=Jt(t)),r.theme=t,this.grid.active_sheet.FlushCellStyles(),this.grid.Update(!0),this.PushUndo())}SetTabColor(e,t){let r=typeof e>"u"?this.grid.active_sheet:this.model.sheets.Find(e);r&&this.grid.TabColor(r,t)}AddSheet(e){this.grid.AddSheet(e);let t=this.model.sheets.list[this.model.sheets.list.length-1];return this.calculator.Reset(),t.id}RemoveConnectedChart(e){let t=this.model.RemoveConnectedElement(e);if(t){let r=this.calculator.RemoveConnectedELement(t)}}UpdateConnectedChart(e,t){let r=this.model.connected_elements.get(e);if(r){r.formula=t;let i=r.internal;i?.state&&(i.state=void 0),this.calculator.UpdateConnectedElements(this.grid.active_sheet,r),r.update&&r.update.call(0,r)}}CreateConnectedFormula(e,t,r={}){let i=r?.r1c1||!1,n=r?.argument_separator||this.parser.argument_separator;this.parser.Save(),this.parser.flags.r1c1=i,n===","?this.parser.SetLocaleSettings("."):this.parser.SetLocaleSettings(",");let o=this.parser.Parse(e);if(this.parser.Restore(),o.expression)e="="+this.parser.Render(o.expression,{missing:""});else throw console.warn("invalid formula",o.error),new Error("invalid formula");let a=this.model.AddConnectedElement({formula:e,update:t?s=>{t.call(0,s)}:void 0});return this.calculator.UpdateConnectedElements(this.grid.active_sheet),this.UpdateConnectedElements(),a}CreateConnectedChart(e,t,r){let i=this.CreateChart();i.Initialize(t);let n=o=>{let a=this.parser.Parse(o.formula);if(a&&a.expression&&a.expression.type==="call"){this.parser.Walk(a.expression,d=>((d.type==="address"||d.type==="range")&&this.model.ResolveSheetID(d,void 0,this.grid.active_sheet),!0));let s=a.expression.name.toLowerCase(),c=this.calculator.CalculateExpression(a.expression);i.Exec(s,c)}i.Update()};return this.CreateConnectedFormula(e,n,r)}InsertAnnotation(e,t="treb-chart",r,i){let n,o,a=!1;if(typeof i=="object"?(o=i.argument_separator,a=!!i.r1c1):(i===","||i===";")&&(o=i),r&&(n=B.IsRectangle(r)?r:this.model.ResolveArea(r,this.grid.active_sheet)),o&&o!==this.parser.argument_separator||a){this.parser.Save(),o===","?this.parser.SetLocaleSettings("."):this.parser.SetLocaleSettings(","),this.parser.flags.r1c1=!!a;let h=this.parser.Parse(e);this.parser.Restore(),h.expression&&(e="="+this.parser.Render(h.expression,{missing:""}))}let{x:s,y:c}=this.grid.GetScrollOffset(),d=this.grid.scale||1,u={width:301,height:301};this.grid.CreateAnnotation({type:t,formula:e},void 0,void 0,void 0,n||{top:c/d+30,left:s/d+30,...u})}InsertImage(){this.SelectFile2(".png, .jpg, .jpeg, .gif, .svg",2)}RenameSheet(e,t){let r;typeof e=="number"?r=this.grid.model.sheets.list[e]:typeof e=="string"?r=this.model.sheets.Find(e):r=this.grid.active_sheet,r&&this.grid.RenameSheet(r,t)}DeleteSheet(e){if(typeof e=="string"){let t=this.model.sheets.Find(e);t&&this.grid.DeleteSheetID(t.id)}else this.grid.DeleteSheet(e);this.calculator.Reset()}HideSheet(e=0,t=!0){this.grid.ShowSheet(e,!t)}ListSheets(){return this.model.sheets.list.map(e=>{let t={name:e.name};return e.visible||(t.hidden=!0),t})}ShowSheet(e=0,t=!0){this.grid.ShowSheet(e,t)}ActivateSheet(e){this.grid.ActivateSheet(e)}SetColumnWidth(e,t){this.grid.SetColumnWidth(e,t)}SetRowHeight(e,t){this.grid.SetRowHeight(e,t)}InsertRows(e,t=1){if(typeof e>"u"){let r=this.grid.GetSelection();if(r.empty)return;let i=r.area;e=i.entire_column?0:i.start.row}this.grid.InsertRows(e,t)}InsertColumns(e,t=1){if(typeof e>"u"){let r=this.grid.GetSelection();if(r.empty)return;let i=r.area;e=i.entire_row?0:i.start.column}this.grid.InsertColumns(e,t)}DeleteRows(e,t=1){if(typeof e>"u"){let r=this.grid.GetSelection();if(r.empty)return;let i=r.area;e=i.entire_column?0:i.start.row,t=i.rows}this.grid.InsertRows(e,-t)}DeleteColumns(e,t=1){if(typeof e>"u"){let r=this.grid.GetSelection();if(r.empty)return;let i=r.area;e=i.entire_row?0:i.start.column,t=i.columns}this.grid.InsertColumns(e,-t)}FilterTable(e,t=0,r){let i=this.ResolveTable(e);if(!i)throw new Error("invalid table reference");r?this.grid.FilterTable(i,t,n=>r.call(0,n.value,n.calculated||void 0,JSON.parse(JSON.stringify(n.style||{})))):this.grid.FilterTable(i,0,()=>!0)}SortTable(e,t={}){let r=this.ResolveTable(e);if(!r)throw new Error("invalid table reference");this.grid.SortTable(r,t)}MergeCells(e){this.grid.MergeCells(e?this.model.ResolveArea(e,this.grid.active_sheet):void 0)}UnmergeCells(e){this.grid.UnmergeCells(e?this.model.ResolveArea(e,this.grid.active_sheet):void 0)}async ExportBlob(e){return this.export_worker||(this.export_worker=await this.LoadWorker()),new Promise((t,r)=>{this.export_worker?(this.export_worker.onmessage=i=>{t(i.data?i.data.blob:void 0)},this.export_worker.onerror=i=>{console.error("export worker error"),console.info(i),r(i)},e||(e=this.Serialize({rendered_values:!0,expand_arrays:!0,export_colors:!0,decorated_cells:!0,tables:!0,share_resources:!1,export_functions:!0,apply_row_pattern:!0})),e.decimal_mark=F.decimal_separator,this.export_worker.postMessage({command:"export",sheet:e,decorated:this.calculator.DecoratedFunctionList()})):r("worker failed")})}Revert(){if(this.options.inline_document){this.LoadDocument(this.options.inline_document),this.initial_load_source="inline-document",this.options.local_storage&&(this.SaveLocalStorage("reverted_backup"),localStorage.removeItem(this.options.local_storage));return}let e=this.options.document;if(e){this.LoadNetworkDocument(e),this.initial_load_source="network-file",this.options.local_storage&&(this.SaveLocalStorage("reverted_backup"),localStorage.removeItem(this.options.local_storage));return}console.warn("to revert, there must be a document set in options"),this.dialog?.ShowDialog({title:"Can't revert -- no document is set in options",close_box:!0,timeout:3e3,type:"error"})}Export(){this.ExportBlob().then(e=>{let t="export";this.grid.model.document_name&&(t=this.grid.model.document_name.toLowerCase().replace(/\s+/g,"-")),e&&(this.SaveAs(e,t+".xlsx"),this.last_save_version=this.file_version)}).catch(e=>{throw/invalid uri/i.test(e.message)&&this.dialog?.ShowDialog({title:"Error exporting file",close_box:!0,message:"The worker cannot run from the filesystem, please use a web server.",timeout:3e3,type:"error"}),e})}GetSelectionReference(){return this.grid.GetSelection()}Focus(){this.grid.Focus()}Resize(){this.grid.UpdateLayout();for(let e of this.views)e.view.grid.UpdateLayout();this.Publish({type:"resize"})}Reset(){if(this.parent_view)return this.parent_view.Reset();this.grid.Reset(),this.ResetInternal(),this.UpdateAC(),this.Publish({type:"reset"})}LoadFromLocalStorage(e){this.options.local_storage=e;let t=localStorage.getItem(e);if(t)try{let r=JSON.parse(t);return this.LoadDocument(r,{source:"local-storage"}),!0}catch(r){console.error(r)}return!1}async LoadNetworkDocument(e,t){let r=t?t.scroll:void 0,i=t?!!t.recalculate:!1,n=t?t.sheet:void 0,o=/csv(?:$|\?|&)/i.test(e),a=/tsv(?:$|\?|&)/i.test(e);try{this.spinner?.Show();let s=await fetch(e);if(this.spinner?.Hide(),!s.ok)throw new Error("network error");let c=await s.text();if(typeof c=="string")if(o)this.LoadCSV(c,"network-file");else{if(a)throw new Error("tsv not supported (TODO)");{c.substr(0,11)==="&&&START&&&"?c=c.substr(11):c.substr(0,8)==="for(;;);"&&(c=c.substr(8));let d=JSON.parse(c);this.LoadDocument(d,{scroll:r,recalculate:i,override_sheet:n,source:"network-file"})}}}catch(s){console.info("error loading network document",e),console.error(s),this.dialog?.ShowDialog({title:"Error loading file",close_box:!0,message:"The network document returned an error",type:"error",timeout:3e3}),this.Reset()}}async LoadLocalFile(){this.SelectFile2(".treb, .csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/json",1)}ExportDelimited(e={}){if(e={delimiter:",",...e},!e.delimiter||e.delimiter!==","&&e.delimiter!==" ")throw new Error("invalid delimiter");let t=this.grid.active_sheet;switch(typeof e.sheet){case"undefined":break;case"string":t=this.model.sheets.Find(e.sheet);break;case"number":t=this.grid.model.sheets.list[e.sheet];break;default:t=void 0;break}if(!t)throw new Error("invalid sheet identifier");let r=t.cells.toJSON({nested:!1,expand_arrays:!0,calculated_value:!0}),i=[];for(let a=0;a<r.columns;a++)i.push("");let n=[];for(let a=0;a<r.rows;a++)n.push(i.slice(0));let o=new RegExp(`[
15
- \r"${e.delimiter}]`);if(ht(r.data))for(let a of r.data){let s="";!e.formulas&&typeof a.calculated<"u"?s=he(a.calculated)?Xe(a.calculated):a.calculated.toString():typeof a.value=="string"&&a.value[0]==="'"?s=a.value.substr(1):typeof a.value<"u"&&(s=he(a.value)?Xe(a.value):a.value.toString()),o.test(s)&&(s=s.replace(/"/g,'""'),s='"'+s+'"'),n[a.row][a.column]=s}return n.map(a=>a.join(e.delimiter)).join(`\r
16
- `)}SaveLocalFile(e="treb.json",t={}){this.SaveToDesktop(e,t)}SaveToDesktop(e="treb.json",t={}){let r=this.grid.model.document_name||"document",i,n,o=e.split(/\./).filter(s=>s.trim().length),a=o.length?o[o.length-1].toLowerCase():"treb";if(o.length<=1||e==="treb.json")if(e==="treb.json"&&(a=e),(a==="csv"||a==="tsv")&&this.grid.model.sheets.length>1){let s=this.grid.active_sheet.name;e=(r+"-"+s).toLowerCase().replace(/\W+/g,"-")+"."+a}else e=r.toLowerCase().replace(/\W+/g,"-")+"."+a;switch(a){case"csv":n=this.ExportDelimited({delimiter:","});break;case"tsv":n=this.ExportDelimited({delimiter:" "});break;case"treb":case"json":case"treb.json":i=this.SerializeDocument({...t}),n=JSON.stringify(i,void 0,t.pretty?2:void 0),this.last_save_version=this.file_version;break;default:throw new Error("invalid file type")}if(n&&e){let s=new Blob([n],{type:"text/plain;charset=utf-8"});this.SaveAs(s,e)}}LoadCSV(e,t){if(this.parent_view)return this.parent_view.LoadCSV(e,t);this.grid.FromCSV(e),this.ResetInternal(),this.grid.Update(!0),this.Publish({type:"load",source:t}),this.UpdateDocumentStyles()}ScrollOffset(e){return this.grid.ScrollOffset(e)}LoadDocument(e,t={}){if(this.parent_view)return this.parent_view.LoadDocument(e,t);if(this.initial_load_source||(this.initial_load_source=t.source),t={flush:!0,recalculate:!1,...t},t.override_selection&&e.sheet_data){let r=Array.isArray(e.sheet_data)?e.sheet_data:[e.sheet_data];for(let i of r)if(i.id===t.override_selection.target.sheet_id){i.selection=t.override_selection;break}}if(this.ImportDocumentData(e,t.override_sheet),this.calculator.Reset(),e.rendered_values&&!t.recalculate?(this.calculator.RebuildClean(!0),this.ApplyConditionalFormats(this.grid.active_sheet,!1),this.grid.Update()):this.Recalculate(),this.InflateAnnotations(),t.flush&&this.FlushUndo(),this.Publish({type:"load",source:t.source}),this.UpdateDocumentStyles(),this.loaded=!0,t.scroll){let r=t.scroll;Promise.resolve().then(()=>this.ScrollTo(r))}}SetNote(e,t){if(typeof e=="string"){let r=this.model.ResolveAddress(e,this.grid.active_sheet);e=N(r)?r:r.start}this.grid.SetNote(e,t)}SetValidation(e,t,r){if(typeof e=="string"){let i=this.model.ResolveAddress(e,this.grid.active_sheet);e=ut(i)?new v(i.start,i.end):new v(i)}if(N(e)&&(e=new v(e)),typeof t>"u"||Array.isArray(t))this.grid.SetValidation(e,t,r);else{let i=this.model.ResolveArea(t,this.grid.active_sheet);this.grid.SetValidation(e,i,r)}}RemoveFunction(e){let t=e.toUpperCase();this.model.macro_functions.delete(t),this.UpdateAC()}DefineFunction(e,t="",r="0"){if(!e.length||/^[^A-Za-z]/.test(e)||/[^\w_.]/.test(e))throw new Error("invalid function name");typeof t=="string"&&(t=t?t.split(this.parser.argument_separator).map(i=>i.trim()):[]);for(let i of t)if(!i.length||/^[^A-Za-z]/.test(i)||/[^\w_.]/.test(i))throw new Error("invalid argument name");this.RemoveFunction(e),this.grid.model.macro_functions.set(e.toUpperCase(),{name:e,function_def:r,argument_names:t,expression:this.parser.Parse(r).expression}),this.UpdateAC()}SerializeDocument(e={}){e={share_resources:!0,shrink:!0,...e};let t=this.Serialize(e),r={app:"@trebco/treb",version:"32.8.1",revision:this.file_version,name:this.grid.model.document_name,user_data:this.grid.model.user_data,decimal_mark:F.decimal_separator,...t};if(e.share_resources){let i=1,n=new Map,o=Array.isArray(r.sheet_data)?r.sheet_data:[r.sheet_data],a=c=>{let d=n.get(c);return d||(d=(i++).toString(),n.set(c,d)),`resource:${d}`};for(let c of o)if(c){c.background_image&&(c.background_image=a(c.background_image));for(let d of c.annotations||[])d.type==="image"&&d.data?.src&&(d.data.src=a(d.data.src))}let s={};for(let[c,d]of n.entries())s[d]=c;r.shared_resources=s}return e.rendered_values&&(r.rendered_values=!0),r}Recalculate(e){let t;switch(e?.type){case"data":t=e.area;break;case"composite":t=e.data_area;break}this.calculator.Calculate(t),this.calculator.grid_expanded&&this.grid.UpdateLayout(),this.ApplyConditionalFormats(this.grid.active_sheet,!1),this.grid.Update(!0),this.UpdateAnnotations(),this.Publish({type:"data"}),this.grid.UpdateStats()}SaveLocalStorage(e=this.options.local_storage){if(!e){console.warn("not saving, no key");return}let t=JSON.stringify(this.SerializeDocument({rendered_values:!0,expand_arrays:!0}));localStorage.setItem(e,t)}Undo(){if(this.parent_view)return this.parent_view.Undo();if(this.undo_pointer<=1){console.warn("nothing to undo");return}let e=this.undo_stack[--this.undo_pointer-1],t=e.selection?JSON.parse(e.selection):void 0;this.LoadDocument(JSON.parse(e.data),{flush:!1,override_selection:t,source:"undo"})}About(){this.dialog?.ShowDialog({type:"about"})}ScrollIntoView(e,t=!1){if(typeof e=="string"){let r=this.model.ResolveAddress(e,this.grid.active_sheet);e=N(r)?r:r.start}this.grid.ScrollIntoView(e,t)}ScrollTo(e,t={}){if(typeof e=="string"){let r=this.model.ResolveAddress(e,this.grid.active_sheet);e=N(r)?r:r.start}t={x:!0,y:!0,smooth:!1,...t},this.grid.ScrollTo(e,t.x,t.y,t.smooth)}Resolve(e,t){let r=this.model.ResolveAddress(e,this.grid.active_sheet,t);return N(r)?r.sheet_id?r:void 0:r.start.sheet_id?r:void 0}Unresolve(e,t=!0,r=!0){if(typeof e=="string"){let i=this.Resolve(e);if(!i)throw new Error("invalid reference");e=i}return this.calculator.Unresolve(e,this.grid.active_sheet,t,r)}Evaluate(e,t={}){return this.calculator.Evaluate(e,this.grid.active_sheet,t)}GetSelection(e=!0){let t=this.grid.GetSelection();if(t.empty)return"";let r="";if(t.area.count>1?r=v.CellAddressToLabel(t.area.start)+":"+v.CellAddressToLabel(t.area.end):r=v.CellAddressToLabel(t.area.start),!e)return r;let i=t.area.start.sheet_id||this.grid.active_sheet.id,n=this.calculator.ResolveSheetName(i,!0);return n?n+"!"+r:r}ParseNumber(e){return _e.TryParse(e).value}FormatNumber(e,t="General"){return he(e)?de.FormatPartsAsText(L.Get(t).FormatComplex(e)):L.Get(t).Format(e)}SpreadsheetDate(e){return e instanceof Date&&(e=e.getTime()),Se(e,!0)}JavascriptDate(e){return Re(e).getTime()}ApplyBorders(e,t,r=1){this.grid.ApplyBorders2(e?this.model.ResolveArea(e,this.grid.active_sheet):void 0,t,{},r)}ApplyStyle(e,t={},r=!0){this.grid.ApplyStyle(e?this.model.ResolveArea(e,this.grid.active_sheet):void 0,t,r)}ClearName(e){this.grid.SetName(e)}ListNames(){return this.model.SerializeNames()}DefineName(e,t,r,i=!1){if(typeof t>"u"||t===null)throw new Error("invalid value (null or undefined)");if(typeof r=="string"){let n=this.model.sheets.ID(r);if(typeof n=="number")r=n;else throw new Error("invalid scope; use a sheet name or sheet id")}if(typeof t=="object"&&(N(t)||ut(t))){this.grid.SetName(e,this.model.ResolveArea(t,this.grid.active_sheet),void 0,r,i);return}if(typeof t=="string"){let n=this.parser.Parse(t);if(!n.expression)throw new Error("invalid expression");switch(n.expression.type){case"address":case"range":this.grid.SetName(e,this.model.ResolveArea(n.expression,this.grid.active_sheet),void 0,r,i);return}this.grid.SetName(e,void 0,t,r,i)}else this.grid.SetName(e,void 0,t.toString(),r,i)}SetLink(e,t=""){if(typeof e=="string"){let r=this.model.ResolveAddress(e,this.grid.active_sheet);e=N(r)?r:r.start}if(!e){let r=this.GetSelectionReference();if(r.empty)return;e=r.target}this.grid.SetLink(e,t)}Select(e){let t;e&&(t=this.model.ResolveArea(e,this.grid.active_sheet),t.start.sheet_id&&t.start.sheet_id!==this.grid.active_sheet.id&&this.grid.ActivateSheetID(t.start.sheet_id)),this.grid.SelectRange(t)}Paste(e,...t){let r=l.clipboard,i={};switch(t.length){case 1:Array.isArray(t[0])?r=t[0]:typeof t[0]=="object"&&(i=t[0]);break;case 2:t[0]&&Array.isArray(t[0])&&(r=t[0]),t[1]&&typeof t[1]=="object"&&(i=t[1]);break}if(!r)throw new Error("no clipboad data");this.grid.PasteArea(this.RangeOrSelection(e,"no range and no selection"),r,i)}Copy(e){let t=this.RangeOrSelection(e),r=t?this.grid.CopyArea(t,"copy"):[];return l.clipboard=structuredClone(r),r}Cut(e){let t=this.RangeOrSelection(e),r=t?this.grid.CopyArea(t,"cut"):[];return l.clipboard=structuredClone(r),r}GetRange(e,t={}){let r=this.RangeOrSelection(e);if(!r)return;let i=t.type;return i||(t.formatted&&(i="formatted"),t.formula&&(i="A1")),i==="formula"&&(i="A1"),this.grid.GetRange(r,i)}GetStyle(e,t=!1){let r=this.RangeOrSelection(e);if(r)return this.grid.GetRangeStyle(r,t)}SetRange(e,t=void 0,r={}){let i=this.RangeOrSelection(e);if(i){if(r.spill&&Array.isArray(t)){let n=t.length,o=Math.max(0,...t.map(s=>s.length)),a={row:i.start.row+n+1,column:i.start.column+o+1};i.ConsumeAddress(a)}return this.grid.SetRange(i,t,r)}}Subscribe(e){return this.events.Subscribe(e)}Cancel(e){this.events.Cancel(e)}RangeOrSelection(e,t){if(!e){let r=this.GetSelectionReference();if(r.empty){if(t)throw t;return}else return r.area.Clone()}return this.model.ResolveArea(e,this.grid.active_sheet)}Serialize(e={}){let t=this.grid.active_sheet;t.selection=JSON.parse(JSON.stringify(this.grid.GetSelection()));let r=this.grid.ScrollOffset();r&&(t.scroll_offset=r);let i=this.model.sheets.list.map(s=>s.toJSON(e)),n;this.model.tables.size>0&&(n=Array.from(this.model.tables.values()));let o;if(this.model.macro_functions.size){o=[];for(let s of this.model.macro_functions.values())o.push({...s,expression:void 0})}let a=this.model.SerializeNames(t);return{sheet_data:i,active_sheet:t.id,named:a.length?a:void 0,macro_functions:o,tables:n}}ApplyConditionalFormats(e,t){let r=[];if(e.conditional_formats.length||e.flush_conditional_formats){for(let i of e.conditional_formats)switch(r.push(i.area),i.type){case"gradient":i.internal||(i.internal={}),i.internal.gradient||(i.internal.gradient=new Wt(i.stops,this.grid.theme,i.color_space));break;case"data-bar":i.internal||(i.internal={});break}e.ApplyConditionalFormats()}t&&this.grid.Update(!0,r)}ResolveTable(e){let t;if(typeof e=="string"){let r=e.toLowerCase();this.model.tables.has(r)&&(t=this.model.tables.get(r))}if(!t){let r=this.model.ResolveAddress(e,this.grid.active_sheet);N(r)||(r=r.start),t=this.grid.GetTableReference(r)}return t}SaveAs(e,t){let r=this.DOM.Create("a");r.href=URL.createObjectURL(e),r.download=t,r.click(),URL.revokeObjectURL(r.href)}Publish(e){this.events.Publish(e)}async ImportXLSX(e,t){return this.parent_view?this.parent_view.ImportXLSX(e,t):(this.export_worker||(this.export_worker=await this.LoadWorker()),new Promise((r,i)=>{this.export_worker?(this.dialog?.ShowDialog({message:"Importing XLSX..."}),this.export_worker.onmessage=n=>{if(n.data){if(n.data.status==="error")return i(n.data.error||"unknown error");if(this.parser.decimal_mark!=="."){let o=this.parser.decimal_mark,a=this.parser.argument_separator;this.parser.Save(),this.parser.SetLocaleSettings(".");let s=c=>{let d=this.parser.Parse(c);if(d.expression)return"="+this.parser.Render(d.expression,{missing:"",convert_decimal:o,convert_argument_separator:a})};for(let c of n.data.results)c.expression=s(c.expression);for(let c of n.data.results.sheets||[]){for(let d of c.cells||[])d.type==="formula"&&d.value&&(d.value=s(d.value));if(c.annotations)for(let d of c.annotations)d.formula&&(d.formula=s(d.formula))}this.parser.Restore()}this.grid.FromImportData(n.data.results),this.ResetInternal(),this.grid.Update(),this.UpdateAC(),this.Publish({type:"load",source:t}),this.UpdateDocumentStyles(),this.InflateAnnotations(),this.calculator.UpdateConditionals(),this.ApplyConditionalFormats(this.grid.active_sheet,!1)}else return i("unknown error (missing data)");this.dialog?.HideDialog(),r()},this.export_worker.onerror=n=>{console.error("import worker error"),console.info(n),i(n)},this.export_worker.postMessage({command:"import",data:e})):i("worker failed")}))}ResetInternal(){this.calculator.Reset(),this.FlushUndo(),this.file_version=this.last_save_version=0}HandleCellEvent(e){if(e.data?.type==="hyperlink"){let t="hyperlink invalid target",r=e.data.reference||"";if(typeof r=="string"){if(/^https{0,1}:\/\//i.test(r)){if(!this.options.hyperlinks){console.warn("hyperlinks are disabled");return}let i=this.DOM.Create("a");i.setAttribute("target",this.options.hyperlinks),i.setAttribute("href",r),i.setAttribute("noreferrer","true"),i.setAttribute("nofollow","true"),i.click();return}else{let i=this.parser.Parse(r);if(i.expression){if(i.expression.type==="address"){(i.expression.sheet||i.expression.sheet_id)&&this.ActivateSheet(i.expression.sheet||i.expression.sheet_id),this.Select(r);return}else if(i.expression.type==="range"){(i.expression.start.sheet||i.expression.start.sheet_id)&&this.ActivateSheet(i.expression.start.sheet||i.expression.start.sheet_id),this.Select(r);return}}}console.warn(t,2);return}}}OnSheetChange(e){for(let t of e.activate.annotations)this.InflateAnnotation(t),this.calculator.UpdateAnnotations(t,e.activate);this.UpdateAnnotations(),this.calculator.UpdateConditionals(),this.ApplyConditionalFormats(e.activate,!0)}HandleDrag(e){if(e.dataTransfer&&e.dataTransfer.types){if(e.dataTransfer.types.some&&e.dataTransfer.types.some(t=>t==="Files"))e.preventDefault();else for(let t=0;t<e.dataTransfer.types.length;t++)if(e.dataTransfer.types[t]==="files"){e.preventDefault();return}}}HandleDrop(e){if(e.dataTransfer&&e.dataTransfer.files&&e.dataTransfer.files.length){e.preventDefault();let t=e.dataTransfer.files[0];/^image/.test(t.type)?this.InsertImageInternal(t):this.LoadFileInternal(t,"drag-and-drop").catch(()=>{})}}SelectFile2(e,t){if(!this.file_chooser){let r=this.DOM.Create("input",void 0,void 0,{attrs:{type:"file"},events:{change:()=>{if(r.files&&r.files[0]){let i=r.files[0];switch(r.value="",this.file_chooser_operation){case 2:this.InsertImageInternal(i);break;case 1:this.LoadFileInternal(i,"local-file",!0);break;default:console.warn("file chooser: no operation");break}}}}});this.file_chooser=r}if(!this.file_chooser)throw new Error("could not create file chooser");this.file_chooser_operation=t,this.file_chooser.accept=e||"",this.file_chooser.click()}async InsertImageInternal(e){if(this.options.max_file_size&&e.size>this.options.max_file_size){this.dialog?.ShowDialog({type:"error",message:"This file exceeds the allowed image size. Please try a smaller image.",title:"Error adding image",timeout:3e3,close_box:!0});return}let t=e;await new Promise((r,i)=>{let n=new FileReader;n.onload=async()=>{try{if(n.result){let o;if(typeof n.result=="string")o=n.result;else{o="";let s=new Uint8Array(n.result);for(let c=0;c<s.byteLength;c++)o+=String.fromCharCode(s[c])}let a=this.DOM.Create("img");a.src=o,await Promise.resolve(),this.grid.CreateAnnotation({type:"image",formula:"",data:{scale:"",src:o,original_size:{width:a.width||300,height:a.height||300}}},void 0,void 0,void 0,{top:30,left:30,width:a.width||300,height:a.height||300})}r()}catch(o){i(o)}},n.onabort=()=>{i("Aborted")},n.onerror=()=>{i("File error")},setTimeout(()=>{n.readAsDataURL(t)},100)})}LoadFileInternal(e,t,r=!0){if(!e)return Promise.resolve();let i=new FileReader;return new Promise((n,o)=>{let a=s=>{i.onload=null,i.onabort=null,i.onerror=null,s?(r&&(this.dialog?.ShowDialog({title:"Error reading file",close_box:!0,message:"Please make sure your file is a valid XLSX, CSV or TREB file.",type:"error",timeout:3e3}),console.error(s)),o(s)):n()};i.onload=()=>{try{if(i.result)if(/\.csv$/i.test(e.name))this.LoadCSV(i.result,t);else if(/\.xls[xm]$/i.test(e.name)){typeof i.result=="string"?a("Unsupported file"):this.ImportXLSX(i.result,t).then(()=>a()).catch(s=>a(s));return}else{let s=JSON.parse(i.result);this.LoadDocument(s,{source:t})}a()}catch(s){a(s?.toString())}},i.onabort=()=>{a("Aborted")},i.onerror=()=>{a("File error")},setTimeout(()=>{/\.xls[xm]$/i.test(e.name)?i.readAsArrayBuffer(e):i.readAsText(e)},100)})}UpdateAnnotations(){for(let e of this.grid.active_sheet.annotations){let t=e.temp;if(t.vertex&&t.vertex.state_id!==t.state){t.state=t.vertex.state_id;for(let i of e.view)i&&(i.dirty=!0)}let r=e.view[this.grid.view_index]||{};r.dirty&&(r.dirty=!1,r.update_callback&&r.update_callback(),this.grid.AnnotationUpdated(e))}this.UpdateConnectedElements()}UpdateConnectedElements(){for(let e of this.model.connected_elements.values()){let t=e.internal;if(t?.vertex&&t.vertex.state_id!==t.state){t.state=t.vertex.state_id;let r=e.update;r&&Promise.resolve().then(()=>r.call(0,e))}}}RebuildAllAnnotations(){for(let e of this.grid.active_sheet.annotations){this.InflateAnnotation(e);let t=e.view[this.grid.view_index]||{};t.resize_callback&&t.resize_callback(),t.update_callback&&t.update_callback()}}InflateAnnotations(){for(let e of this.grid.active_sheet.annotations)this.InflateAnnotation(e)}InflateAnnotation(e){if(this.grid.headless)return;let t=e.view[this.grid.view_index]||{};if(t.inflated){e.dirty&&(t.resize_callback&&t.resize_callback(),e.dirty=!1);return}if(t.inflated=!0,e.dirty&&(e.dirty=!1),t.content_node){if(e.data.type==="treb-chart"){let r=this.CreateChart();r.Initialize(t.content_node);let i=()=>{if(e.data.formula){let n=this.parser.Parse(e.data.formula);if(n&&n.expression&&n.expression.type==="call"){this.parser.Walk(n.expression,s=>((s.type==="address"||s.type==="range")&&this.model.ResolveSheetID(s,void 0,this.grid.active_sheet),!0));let o=n.expression.name.toLowerCase(),a=this.calculator.CalculateExpression(n.expression);r.Exec(o,a)}}r.Update()};t.resize_callback=()=>{this.grid.headless||(r.Resize(),r.Update())},t.update_callback=()=>{this.grid.headless||i()},t.node?.parentElement&&(this.grid.headless||i())}else if(e.data.type==="image"){if(typeof e.data.data?.src=="string"){let r=Mt(e.data.data.src);if(r){let i=this.DOM.Create("img");i.src=r,e.data.data.scale==="fixed"?(i.style.position="relative",i.style.left="50%",i.style.top="50%",i.style.transform="translate(-50%, -50%)"):(i.style.width="100%",i.style.height="100%"),t.content_node.appendChild(i)}}}else if(e.data.type==="textbox"&&e.data.data){let r,i=document.createElement("div");i.classList.add("treb-annotation-textbox");for(let n of e.data.data.paragraphs){let o=document.createElement("p");n.style&&(n.style.horizontal_align==="right"||n.style.horizontal_align==="center")&&(o.style.textAlign=n.style.horizontal_align);for(let a of n.content){let s=document.createElement("span");if(r||(r=s),e.data.formula||(s.textContent=a.text||""),a.style?.bold&&(s.style.fontWeight="600"),a.style?.italic&&(s.style.fontStyle="italic"),o.appendChild(s),e.data.formula)break}if(i.append(o),e.data.formula)break}if(t.content_node.append(i),e.data.data.style){let n=e.data.data.style,o=()=>{if(n.fill){let a=D(this.grid.theme,n.fill);i.style.background=a}};t.update_callback=()=>{if(this.grid.headless||o(),r&&e.data.formula){let a=this.parser.Parse(e.data.formula);if(a&&a.expression){this.parser.Walk(a.expression,u=>((u.type==="address"||u.type==="range")&&this.model.ResolveSheetID(u,void 0,this.grid.active_sheet),!0));let s=this.calculator.CalculateExpression(a.expression),c=L.Get("General"),d;switch(a.expression.type){case"address":d=a.expression;break;case"range":d=a.expression.start;break}if(d){let h=(d.sheet_id?this.model.sheets.Find(d.sheet_id):this.grid.active_sheet)?.CellStyleData(d);h?.number_format&&(c=L.Get(h.number_format))}switch(s.type){case 3:case 2:case 8:r.textContent=c.Format(s.value);break;default:r.textContent=s.value?.toString()||""}}}},t.update_callback()}}}}DocumentChange(e){Promise.resolve().then(()=>{this.file_version++,this.file_version>=65536&&(this.file_version=1);let t=JSON.stringify(this.SerializeDocument({optimize:"size",rendered_values:!0,expand_arrays:!0}));this.options.undo&&this.PushUndo(t,e,!1),this.Publish({type:"document-change"})})}ResolveStorageKey(e,t=""){if(e){if(e===!0){let r=0,i=document.location.href;for(let o=0,a=i.length;o<a;o++)r=(r<<5)-r+i.charCodeAt(o),r|=0;let n=Math.abs(r).toString(16);return t?t+"-"+n:n}return e}}PushUndo(e,t,r=!0){let i=t||this.last_selection;this.undo_stack[this.undo_pointer-1]&&(this.undo_stack[this.undo_pointer-1].selection=i),r&&(this.file_version++,this.file_version>=65536&&(this.file_version=1)),e||(e=JSON.stringify(this.SerializeDocument({optimize:"size",rendered_values:!0,expand_arrays:!0}))),this.undo_stack[this.undo_pointer++]={data:e,selection:void 0};let n=this.undo_stack.length;if(n>16){let o=n-16;this.undo_stack=this.undo_stack.slice(o),this.undo_pointer-=o}}FlushUndo(e=!0){this.undo_stack=[],this.undo_pointer=0,this.last_save_version=this.file_version,e&&this.PushUndo(void 0,void 0,!1)}UpdateSelection(e){this.last_selection=JSON.stringify(e),this.Publish({type:"selection"})}UpdateSelectionStyleAnnotation(e){let t={style:JSON.parse(JSON.stringify(e.data.style||{}))};t.style&&(t.style.font_face||(t.style.font_face="stack:ui"),t.style.font_size||(t.style.font_size={unit:"em",value:1})),t.relative_font_size=I.RelativeFontSize(t.style||{},this.grid.theme.grid_cell||{}),this.selection_state=t}UpdateSelectionStyle(e){let t=this.grid.GetFreeze(),r={frozen:!!t.rows||!!t.columns};if(e||(e=this.grid.GetSelection()),e&&!e.empty){r.selection=e;let i=this.grid.active_sheet.CellData(e.target);r.table=!!i.table,r.merge=!!i.merge_area,r.merge&&i.merge_area&&(i.merge_area.start.row!==e.target.row||i.merge_area.start.column!==e.target.column)&&(i=this.grid.active_sheet.CellData(i.merge_area.start)),r.comment=i.note,r.style=i.style?{...i.style}:void 0,r.relative_font_size=I.RelativeFontSize(r.style||{},this.grid.theme.grid_cell||{}),r.empty=typeof i.value>"u"&&!i.style?.font_face}this.grid?.edit_state&&(this.grid.edit_state.font_face=r.style?.font_face||void 0),this.selection_state=r}UpdateDocumentStyles(){let e={},t={};for(let i of this.grid.model.sheets.list)i.NumberFormatsAndColors(t,e);this.document_styles.colors=Object.keys(t),this.document_styles.number_formats=Object.keys(e),this.document_styles.theme_colors=[];let r=[.5,.25,0,-.25,-.5];for(let i=0;i<10;i++)this.document_styles.theme_colors.push(r.map(n=>{let o={theme:i,tint:n},a=D(this.grid.theme,o);return{color:o,resolved:a}}))}ConvertLocale(e){let t=new We;t.flags={...this.parser.flags};let r,i;e.decimal_mark==="."?(t.SetLocaleSettings("."),r=",",i=";"):(t.SetLocaleSettings(","),r=".",i=",");let n=o=>{let a=t.Parse(o);if(a.expression)return"="+t.Render(a.expression,{missing:"",convert_decimal:r,convert_argument_separator:i})};if(e.macro_functions)for(let o of e.macro_functions){let a=n(o.function_def);a&&(o.function_def=a)}if(e.named)for(let o of e.named){let a=n(o.expression);a&&(o.expression=a)}if(e.sheet_data){let o=Array.isArray(e.sheet_data)?e.sheet_data:[e.sheet_data];for(let a of o){if(a.annotations){for(let s of a.annotations)if(s.formula){let c=n(s.formula);c&&(s.formula=c)}}if(a.data?.length)for(let s of a.data){let c=Fr(s)?[s]:s.cells;for(let d of c)if(d.value&&typeof d.value=="string"&&d.value[0]==="="){let u=n(d.value.slice(1));u&&(d.value=u)}}}}}CompareVersions(e="",t=""){let r=e.split(".").map(a=>Number(a)||0).concat([0,0,0]),i=t.split(".").map(a=>Number(a)||0).concat([0,0,0]),n=[0,1,2],o={match:0};for(let a=0;a<3;a++)if(r[a]!==i[a]){o.match=r[a]>i[a]?1:-1,o.level=n[a];break}return o}ImportDocumentData(e,t){this.file_version=e.revision||0;let r=[],i=this.CompareVersions(e.version,"32.8.1");if(i.match>0&&(i.level===0||i.level===1)&&console.warn(`The file you are opening was created with a newer version of TREB (${e.version} vs 32.8.1).
17
- You may encounter compatibility errors.`),e.sheet_data&&(Array.isArray(e.sheet_data)?r=e.sheet_data:r.push(e.sheet_data)),e.shared_resources){let o=e.shared_resources,a=s=>/^resource:/.test(s)?o[s.substring(9)]||"":s;for(let s of r){s.background_image&&(s.background_image=a(s.background_image));for(let c of s.annotations||[])c.type==="image"&&c.data?.src&&(c.data.src=a(c.data.src))}}e.decimal_mark&&e.decimal_mark!==F.decimal_separator&&this.ConvertLocale(e);let n=this.grid.model;if(n.tables.clear(),e.tables)for(let o of e.tables)n.tables.set(o.name.toLowerCase(),o);this.grid.UpdateSheets(r,void 0,t||e.active_sheet);for(let o of this.model.tables.values())if(o.area.start.sheet_id){let a=n.sheets.Find(o.area.start.sheet_id);if(a)for(let s=o.area.start.row;s<=o.area.end.row;s++)for(let c=o.area.start.column;c<=o.area.end.column;c++){let d=a.cells.GetCell({row:s,column:c},!0);d.table=o}}if(n.document_name=e.name,n.user_data=e.user_data,n.named.Reset(),e.named)this.model.UnserializeNames(e.named,this.grid.active_sheet);else{let o=e.named_ranges;if(!o&&r[0]&&r[0].named_ranges&&(o=r[0].named_ranges),o)for(let[a,s]of Object.entries(o))n.named.SetNamedRange(a,new v(s.start,s.end));if(e.named_expressions)for(let a of e.named_expressions)this.model.UnserializeNames([{name:a.name,expression:a.expression}],this.grid.active_sheet)}if(n.macro_functions.clear(),e.macro_functions)for(let o of e.macro_functions)n.macro_functions.set(o.name.toUpperCase(),{...o,expression:this.parser.Parse(o.function_def||"").expression});this.UpdateAC()}async LoadWorker(){try{return await(await import("./treb-export-worker.mjs")).CreateWorker()}catch(e){throw console.error(e),e}}HandleKeyDown(e){e.key==="z"?(j.is_mac&&e.metaKey||e.ctrlKey)&&(e.stopPropagation(),e.preventDefault(),this.Undo()):e.key==="F9"&&this.options.recalculate_on_f9&&(e.stopPropagation(),e.preventDefault(),this.Recalculate())}};var no=`@charset "UTF-8";.treb-main.treb-main .treb-mouse-mask{background:transparent;bottom:0;display:none;left:0;position:fixed;right:0;top:0;z-index:9999}.treb-main.treb-main .treb-mouse-mask.column-resize{cursor:col-resize}.treb-main.treb-main .treb-mouse-mask.row-resize{cursor:row-resize}.treb-main.treb-main .treb-mouse-mask.nub-select{cursor:crosshair}.treb-main.treb-main .treb-mouse-mask.move{cursor:move}.treb-main.treb-main .treb-mouse-mask.nw-resize{cursor:nw-resize}.treb-main.treb-main .treb-note{max-width:15em;min-width:15em}.treb-main.treb-main .treb-hover-title,.treb-main.treb-main .treb-note{background:var(--treb-note-background,#fff);border:1px solid var(--treb-note-border-color,var(--treb-ui-border-color,#ddd));border-radius:2px;box-shadow:0 1px 4px 2px hsla(0,0%,43%,.2);color:var(--treb-note-color,#333);font-family:BlinkMacSystemFont,Segoe UI,Roboto,Oxygen-Sans,Ubuntu,Cantarell,Helvetica Neue,"sans-serif";font-size:10.5pt;left:100px;line-height:normal;opacity:0;padding:7px 10px;position:fixed;top:100px;transition:opacity .2s;white-space:pre-line;z-index:39}.treb-main.treb-main .treb-hover-title{min-width:10em;pointer-events:none}.treb-main.treb-main .treb-sort-button{background:#fff;border:1px solid #ccc;border-radius:2px;height:1em;left:100px;opacity:0;pointer-events:none;position:absolute;top:100px;transition:opacity .1s ease;width:1em;z-index:39}.treb-main.treb-main .treb-sort-button:after{box-sizing:border-box}.treb-main.treb-main .treb-sort-button.asc:after{border:.4em solid transparent;border-top-color:currentcolor;content:"";height:.8em;left:50%;opacity:.5;position:absolute;top:50%;transform:translate(-50%,-25%);width:.8em}.treb-main.treb-main .treb-sort-button.desc:after{border:.4em solid transparent;border-bottom-color:currentcolor;content:"";height:.8em;left:50%;opacity:.5;position:absolute;top:50%;transform:translate(-50%,-80%);width:.8em}.treb-main.treb-main .treb-tooltip{border-radius:2px;box-shadow:0 1px 4px 2px hsla(0,0%,43%,.2);display:none;line-height:normal;padding:2px 10px;pointer-events:none;position:fixed;z-index:39}.treb-main.treb-main .treb-tooltip.arrow-up:after{border:4px solid transparent;border-bottom-color:inherit;box-sizing:border-box;content:" ";height:8px;left:calc(50% - 4px);overflow:hidden;position:absolute;top:-8px;width:8px}.treb-main.treb-main .treb-tooltip.arrow-left:after{border:4px solid transparent;border-right-color:inherit;box-sizing:border-box;content:" ";height:8px;left:-8px;overflow:hidden;position:absolute;top:calc(50% - 4px);width:8px}.treb-main.treb-main .treb-dropdown-caret{background:var(--treb-dropdown-caret-background,#fff);border:1px solid var(--treb-dropdown-caret-border-color,#ccc);border-radius:2px;box-shadow:0 1px 4px 2px hsla(0,0%,43%,.2);display:none;height:20px;position:absolute;width:20px;z-index:39}.treb-main.treb-main .treb-dropdown-caret path{fill:none;stroke:var(--treb-dropdown-caret-color,#444);stroke-linecap:round;stroke-linejoin:round;stroke-width:2}.treb-main.treb-main .treb-dropdown-list{background:var(--treb-dropdown-background,#fff);border:1px solid var(--treb-dropdown-border-color,unset);box-shadow:0 1px 4px 2px hsla(0,0%,43%,.2);color:var(--treb-dropdown-color,inherit);display:none;font-size:10pt;max-height:10em;outline:none;overflow-y:auto;position:absolute;text-align:left;z-index:39}.treb-main.treb-main .treb-dropdown-list div{cursor:default;padding:2px}.treb-main.treb-main .treb-dropdown-list div.selected{background:var(--treb-dropdown-selected-background,#555);color:var(--treb-dropdown-selected-color,#fff)}.treb-main.treb-main .treb-dropdown-caret.active{background:var(--treb-dropdown-caret-active-background,#eee)}.treb-main.treb-main .treb-dropdown-caret.active+.treb-dropdown-list{display:block}.treb-main.treb-main .treb-error-highlight{background:rgba(255,0,0,.25);opacity:0;pointer-events:none;position:absolute;transition:opacity .15s ease-in-out;z-index:40}.treb-main.treb-main .treb-autocomplete{box-sizing:border-box;font-size:inherit;font-weight:400;line-height:normal;max-height:10em;overflow-y:auto;position:fixed;text-align:left;top:-1000px;z-index:39}.treb-main.treb-main .treb-autocomplete *{box-sizing:border-box}.treb-main.treb-main .treb-autocomplete ul{list-style-type:none}.treb-main.treb-main .treb-autocomplete ul,.treb-main.treb-main .treb-autocomplete ul li{font-size:inherit;font-weight:inherit;margin:0;padding:0}.treb-main.treb-main .treb-autocomplete ul li a{color:inherit;cursor:default;display:inline-block;font-size:inherit;font-weight:inherit;padding:3px 6px;text-decoration:none;width:100%}.treb-main.treb-main .treb-autocomplete-tooltip{position:fixed;top:-1000px;white-space:pre;z-index:39}.treb-main.treb-main .treb-formula-bar{display:flex;flex-direction:row;gap:.5em;grid-area:1/1/2/2;max-width:100%;overflow-x:hidden;padding:0 2px 12px;text-align:left}.treb-main.treb-main .treb-formula-bar[hidden]{display:none}.treb-main.treb-main .treb-formula-bar .treb-address-label{border:1px solid var(--treb-formula-bar-border-color,var(--treb-ui-border-color,#ccc));border-radius:2px;display:flex;flex-direction:column;height:1.75em;justify-content:center;min-height:1.5em;min-width:95px;padding-left:3px;width:95px}.treb-main.treb-main .treb-formula-bar .treb-address-label>div{outline:none;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.treb-main.treb-main .treb-formula-bar .treb-insert-function-button{background:transparent;border:1px solid var(--treb-formula-bar-border-color,var(--treb-ui-border-color,#ccc));border-radius:2px;height:1.75em;min-height:1.5em}.treb-main.treb-main .treb-formula-bar .treb-insert-function-button[hidden]{display:none}.treb-main.treb-main .treb-formula-bar .expand-button{background:transparent;border:0;border-radius:2px;height:1.75em;margin-left:2px;outline:none;padding:1px}.treb-main.treb-main .treb-formula-bar .expand-button:after{border:5px solid transparent;border-top-color:#999;content:" ";display:inline-block;margin:0;padding:0;position:relative;top:-6px;transition:transform .15s ease}.treb-main.treb-main .treb-formula-bar[expanded] .expand-button:after{transform:rotate(180deg) translateY(6px)}.treb-main.treb-main .treb-formula-bar .treb-editor-container{border:1px solid var(--treb-formula-bar-border-color,var(--treb-ui-border-color,#ccc));border-radius:2px;display:flex;flex-direction:column;flex-grow:1;height:1.75em;justify-content:center;min-width:0}.treb-main.treb-main .treb-formula-bar .treb-editor-container>.treb-editor-shadow{opacity:.4}.treb-main.treb-main .treb-formula-bar[expanded] .treb-editor-container{height:4.5em;transition:height .1s ease-in-out}.treb-main.treb-main .treb-formula-bar[expanded] .treb-editor-container>div{overflow-y:auto}.treb-main.treb-main .treb-formula-bar .treb-editor-container>div{flex-grow:1;line-height:1.35;margin:2px;min-height:1em;outline:none;overflow-x:hidden;overflow-y:hidden;white-space:pre-wrap;width:100%}.treb-main.treb-main .treb-mouse-mask .ghost-tab{position:fixed}.treb-main.treb-main .treb-spreadsheet-footer{align-items:center;grid-area:3/1/4/2}.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tab-container{align-self:flex-start;height:2.2em;overflow:hidden}.treb-main.treb-main .treb-spreadsheet-footer,.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs{color:var(--treb-ui-color,inherit);display:flex;flex-direction:row;height:2.2em;list-style-type:none;max-width:100%;padding-inline-start:0;z-index:2}.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs{height:auto;margin-block-start:0;margin:0;overflow-x:scroll;overflow-y:hidden;scrollbar-width:none}.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs::-webkit-scrollbar{display:none}.treb-main.treb-main .treb-spreadsheet-footer[hidden]{display:none}.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li{display:inline-block;margin:0;position:relative}.treb-main.treb-main .treb-spreadsheet-footer .treb-add-tab,.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab,.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li{align-items:center;border-bottom-left-radius:5px;border-bottom-right-radius:5px;border-top-width:1px;border:1px solid var(--treb-tab-bar-tab-border-color,var(--treb-ui-border-color,#ccc));border-top:0 solid var(--treb-tab-bar-tab-border-color,var(--treb-ui-border-color,#ccc));color:var(--treb-tab-bar-tab-color,var(--treb-ui-color,#fff));cursor:default;display:inline-flex;font-size:inherit;height:100%;justify-content:center;margin-right:-2px;overflow:hidden;padding:0 .75em;z-index:1}.treb-main.treb-main .treb-spreadsheet-footer .treb-add-tab:active,.treb-main.treb-main .treb-spreadsheet-footer .treb-add-tab:focus,.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab:active,.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab:focus,.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li:active,.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li:focus{z-index:3}.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li{height:2.2em;overflow:visible;overflow-x:visible}.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li:last-of-type{margin-right:0}.treb-main.treb-main .treb-spreadsheet-footer .treb-add-tab{margin-left:-1px}.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li{white-space:nowrap}.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li[selected]{z-index:2}.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control{align-items:center;display:flex;flex-direction:row;font-size:inherit;height:2.2em;justify-content:center;position:relative;width:5em}.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control .treb-scale-input{background:transparent;border:1px solid transparent;border-radius:2px;color:inherit;font-family:inherit;font-size:inherit;padding:initial;text-align:center;transition:border-color .25s ease,background-color .25s ease;width:4em}.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control .treb-slider-container{accent-color:var(--treb-scale-slider-accent-color,undefined);align-items:center;background:var(--treb-scale-slider-background,#fff);border:1px solid var(--treb-scale-slider-border-color,var(--treb-ui-border-color,#ccc));display:flex;flex-direction:row;height:4em;justify-content:center;left:.5em;opacity:0;pointer-events:none;position:absolute;top:0;transform:rotate(-90deg);transform-origin:left top;transition:opacity .25s ease;width:10em;z-index:40}.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control .treb-scale-input:focus,.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control:hover .treb-scale-input{border-color:var(--treb-ui-border-color,#ccc)}.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control .treb-slider-container>input[type=range]{width:8.5em}.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control .treb-scale-input:focus+.treb-slider-container,.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control .treb-slider-container:focus-within,.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control:hover .treb-slider-container{opacity:.85;pointer-events:auto}.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab{align-items:center;background:transparent;border:none;border-bottom-left-radius:5px;border-bottom-right-radius:5px;border-top:0;color:currentColor;cursor:default;display:inline-flex;flex-direction:row;font-size:inherit;margin-right:-2px;min-width:2.5em;padding:.25em .75em;z-index:1}.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab svg{height:1em;opacity:.75;pointer-events:none;transition:opacity .125s ease-in-out;width:1em}.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab:hover svg{opacity:.75}.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab path{stroke:currentColor;stroke-width:1.5px;stroke-linecap:round}.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab:active,.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab:focus{z-index:3}.treb-main.treb-main .treb-spreadsheet-footer .treb-stats-panel{flex:1 1;overflow:hidden;text-align:end;text-overflow:ellipsis;white-space:nowrap}.treb-main.treb-main .treb-spreadsheet-footer .treb-stats-panel>*{margin-left:.5em}.treb-main.treb-main .treb-spreadsheet-footer .treb-stats-panel .treb-stats-value{background:var(--treb-stats-value-background,#f8f8ff);border:1px solid var(--treb-stats-value-border-color,var(--treb-ui-border-color,#ddd));border-radius:3px;padding:0 .3em}.treb-main.treb-main .treb-grid .treb-overlay-container{margin:0;opacity:0;outline:none;padding:0;position:absolute;z-index:24}.treb-main.treb-main .treb-grid .treb-overlay-container.align-right .treb-overlay-inset{padding-right:3px;right:0;text-align:right}.treb-main.treb-main .treb-grid .treb-overlay-container.align-center .treb-overlay-inset{left:50%;text-align:center;transform:translateX(-50%)}.treb-main.treb-main .treb-grid .treb-overlay-inset{display:flex;flex-direction:column;height:100%;justify-content:flex-end;margin:0;min-width:100%;padding:0 4px;position:absolute}.treb-main.treb-main .treb-grid .treb-overlay-editor{outline:none;position:relative;white-space:nowrap;white-space:pre}.treb-main.treb-main .treb-grid .treb-overlay-editor.firefox:before{content:"\u200B"}.treb-main.treb-main .treb-spill-border{pointer-events:none;position:absolute;transform:translateZ(0)}.treb-main.treb-main .treb-spill-border rect{stroke:var(--treb-spill-border-color,#5c5ce0);stroke-dasharray:var(--treb-spill-border-dasharray,0);fill:none;stroke-width:var(--treb-spill-border-width,1px);filter:var(--treb-spill-border-filter,drop-shadow(3px 3px 2px rgba(0,0,0,.5)));z-index:35}.treb-main.treb-main .treb-buffer-canvas{display:none;position:absolute}.treb-main.treb-main .treb-spreadsheet-body{grid-area:2/1/3/2;-webkit-overflow-scrolling:touch;-webkit-tap-highlight-color:transparent;display:flex;overflow:hidden;position:relative;z-index:1}.treb-main.treb-main .treb-grid{flex-grow:1;order:2;overflow:scroll;position:relative;-webkit-overflow-scrolling:touch;-webkit-tap-highlight-color:transparent;display:grid;grid-template-columns:100px auto;grid-template-rows:20px auto;outline:none;overscroll-behavior:none}.treb-main.treb-main .treb-grid .tile-cover.grid-cover{grid-area:2/2/3/3}.treb-main.treb-main .treb-grid .tile-cover.column-header-cover{grid-area:1/2/2/3;position:-webkit-sticky;position:sticky;top:0}.treb-main.treb-main .treb-grid .tile-cover.row-header-cover{grid-area:2/1/3/2;left:0;position:-webkit-sticky;position:sticky}.treb-main.treb-main .treb-grid .treb-grid-selection{grid-area:1/1/2/2}.treb-main.treb-main .treb-grid .treb-corner{grid-area:1/1/2/2;position:-webkit-sticky;position:sticky}.treb-main.treb-main .treb-grid .treb-left-header{display:grid;grid-area:2/1/3/2;grid-template-columns:auto;grid-template-rows:auto;position:-webkit-sticky;position:sticky}.treb-main.treb-main .treb-grid .treb-top-header{display:grid;grid-area:1/2/2/3;grid-template-columns:auto;grid-template-rows:auto;position:-webkit-sticky;position:sticky}.treb-main.treb-main .treb-grid .treb-contents{display:grid;grid-area:2/2/3/3;grid-template-columns:auto;grid-template-rows:auto}.treb-main.treb-main .treb-grid.safari::-webkit-scrollbar{-webkit-appearance:none;height:7px;width:7px}.treb-main.treb-main .treb-grid.safari::-webkit-scrollbar-thumb{background-color:rgba(0,0,0,.25);border-radius:4px;-webkit-box-shadow:0 0 1px hsla(0,0%,100%,.5)}.treb-main.treb-main .treb-grid canvas{background:transparent;border:0;margin:0;padding:0}.treb-main.treb-main .treb-grid .nub-select{cursor:crosshair}.treb-main.treb-main .treb-grid .link-pointer{cursor:pointer}.treb-main.treb-main .treb-grid .mock-selection-node{background:red;left:-100px;position:fixed;top:-100px}.treb-main.treb-main .treb-grid .tile-cover{background:transparent;position:relative;z-index:14}.treb-main.treb-main .treb-grid .tile-cover.column-header-cover{z-index:22}.treb-main.treb-main .treb-grid .tile-cover.column-header-cover.resize{cursor:col-resize}.treb-main.treb-main .treb-grid .tile-cover.row-header-cover{z-index:22}.treb-main.treb-main .treb-grid .tile-cover.row-header-cover.resize{cursor:row-resize}.treb-main.treb-main .treb-grid .frozen-annotation-container,.treb-main.treb-main .treb-grid .treb-annotation-container{left:0;pointer-events:none;position:absolute;top:0;z-index:16}.treb-main.treb-main .treb-grid .frozen-annotation-container .annotation,.treb-main.treb-main .treb-grid .treb-annotation-container .annotation{background:hsla(0,0%,100%,.5);border:1px solid #999;overflow:hidden;pointer-events:auto;position:absolute;z-index:1}.treb-main.treb-main .treb-grid .frozen-annotation-container .annotation .annotation-content,.treb-main.treb-main .treb-grid .treb-annotation-container .annotation .annotation-content{font-family:inherit;font-size:inherit;height:100%;left:0;position:absolute;top:0;width:100%;z-index:1}.treb-main.treb-main .treb-grid .frozen-annotation-container .annotation .annotation-move-target,.treb-main.treb-main .treb-grid .treb-annotation-container .annotation .annotation-move-target{cursor:move;height:10%;left:0;min-height:14px;position:absolute;top:0;width:100%;z-index:2}.treb-main.treb-main .treb-grid .frozen-annotation-container .annotation .annotation-resize-target,.treb-main.treb-main .treb-grid .treb-annotation-container .annotation .annotation-resize-target{bottom:0;cursor:nwse-resize;height:10%;min-height:14px;min-width:14px;position:absolute;right:0;width:10%;z-index:3}.treb-main.treb-main .treb-grid .frozen-annotation-container .annotation.clone-focus,.treb-main.treb-main .treb-grid .frozen-annotation-container .annotation.retain-focus,.treb-main.treb-main .treb-grid .frozen-annotation-container .annotation:focus,.treb-main.treb-main .treb-grid .treb-annotation-container .annotation.clone-focus,.treb-main.treb-main .treb-grid .treb-annotation-container .annotation.retain-focus,.treb-main.treb-main .treb-grid .treb-annotation-container .annotation:focus{box-shadow:0 0 0 3px rgba(14,165,233,.33)}.treb-main.treb-main .treb-grid .frozen-annotation-container .move-buffer,.treb-main.treb-main .treb-grid .treb-annotation-container .move-buffer{border:1px solid red;cursor:move;height:10%;left:0;position:absolute;top:0;width:100%}.treb-main.treb-main .treb-grid .treb-grid-selection{background:transparent;position:absolute;transform:translateZ(0);-moz-transform:scale(1);z-index:10}.treb-main.treb-main .treb-grid .frozen-selection{overflow:hidden;pointer-events:none;position:absolute;transform:translateZ(0);-moz-transform:scale(1);transition:background .33s;z-index:12}.treb-main.treb-main .treb-grid .frozen-selection.frozen-selection-rows{border-bottom:1px solid transparent}.treb-main.treb-main .treb-grid .frozen-selection.frozen-selection-columns{border-right:1px solid transparent}.treb-main.treb-main .treb-grid .frozen-annotation-container{height:100%;left:0;overflow:hidden;position:absolute;top:0;width:100%}.treb-main.treb-main .treb-grid .treb-corner{left:0;top:0;z-index:20}.treb-main.treb-main .treb-grid .treb-corner canvas{left:0;pointer-events:none;position:absolute;top:0}.treb-main.treb-main .treb-grid .treb-left-header{left:0;pointer-events:none;z-index:18}.treb-main.treb-main .treb-grid .treb-top-header{pointer-events:none;top:0;z-index:18}.treb-main.treb-main .treb-grid .treb-contents{height:2000px;width:2000px}.treb-main.treb-main{--alternate-selection-color-1:#fbb13c;--alternate-selection-color-2:#40c040;--alternate-selection-color-3:#b66d0d;--alternate-selection-color-4:#2176ae;--alternate-selection-color-5:#fe6847;--text-reference-color-1:#e08a00;--text-reference-color-2:#3aad3a;--text-reference-color-3:#b66d0d;--text-reference-color-4:#2176ae;--text-reference-color-5:#fe2f01}.treb-main.treb-main:focus-within .treb-grid-selection .primary-selection,.treb-main.treb-main:focus-within .treb-header-overlay{color:var(--treb-selection-color,#4caaf1)}.treb-main.treb-main .theme-color-1{color:var(--treb-theme-color-1,#e7e6e6)}.treb-main.treb-main .theme-color-2{color:var(--treb-theme-color-2,#44546a)}.treb-main.treb-main .theme-color-3{color:var(--treb-theme-color-3,#4472c4)}.treb-main.treb-main .theme-color-4{color:var(--treb-theme-color-4,#ed7d31)}.treb-main.treb-main .theme-color-5{color:var(--treb-theme-color-5,#a5a5a5)}.treb-main.treb-main .theme-color-6{color:var(--treb-theme-color-6,#ffc000)}.treb-main.treb-main .theme-color-7{color:var(--treb-theme-color-7,#5b9bd5)}.treb-main.treb-main .theme-color-8{color:var(--treb-theme-color-8,#70ad47)}.treb-main.treb-main .theme-color-9{color:var(--treb-theme-color-9,#0563c1)}.treb-main.treb-main .theme-color-10{color:var(--treb-theme-color-10,#954f72)}.treb-main.treb-main .treb-offset-dark{color:#000}.treb-main.treb-main .treb-offset-light{color:#fff}.treb-main.treb-main .note-marker{background:var(--treb-note-marker-color,#6fab20)}.treb-main.treb-main .grid-headers{background:var(--treb-grid-header-background,#eeeef2);color:var(--treb-grid-header-color,var(--treb-grid-default-color,#666));font-family:var(--treb-grid-header-font-family,inherit);font-size:var(--treb-grid-header-font-size,10pt);font-style:var(--treb-grid-header-font-style,normal);font-weight:var(--treb-grid-header-font-weight,normal);stroke:var(--treb-grid-header-grid-color,var(--treb-grid-grid-color,#ccccd4))}.treb-main.treb-main .grid-cells{color:var(--treb-grid-default-color,inherit);font-family:var(--treb-grid-font-family,inherit);font-size:var(--treb-grid-font-size,14px);stroke:var(--treb-grid-grid-color,#ccccd4);background:var(--treb-grid-background,#fff)}.treb-main.treb-main .frozen-selection.highlight-area{background:rgba(87,184,255,.25);border-bottom-color:#2176ae;border-left-color:#2176ae}.treb-main.treb-main .treb-autocomplete-tooltip{background:var(--treb-autocomplete-tooltip-background,#fffbb5);border:1px solid var(--treb-autocomplete-tooltip-border-color,unset);border-radius:2px;color:var(--treb-autocomplete-tooltip-color,inherit);font-size:14px;line-height:normal;margin:4px 0;padding:3px 8px}.treb-main.treb-main .treb-autocomplete-tooltip .active-argument{font-weight:700}.treb-main.treb-main .treb-autocomplete-tooltip .function-description{font-style:italic}.treb-main.treb-main .treb-autocomplete{background:var(--treb-autocomplete-background,#fff);border:1px solid var(--treb-autocomplete-border-color,var(--treb-ui-border-color,#ccc));border-radius:2px;box-shadow:0 1px 4px 2px hsla(0,0%,43%,.2);font-size:14px}.treb-main.treb-main .treb-autocomplete li{color:var(--treb-autocomplete-entry-color,#333)}.treb-main.treb-main .treb-autocomplete li a.selected{background:var(--treb-autocomplete-selected-entry-background,#2e8dd6);color:var(--treb-autocomplete-selected-entry-color,#fff)}.treb-main.treb-main .treb-header-overlay{stroke:none;color:var(--treb-selection-color-unfocused,var(--treb-selection-color,#4caaf1))}.treb-main.treb-main .treb-header-overlay .treb-overlay{fill:#000;stroke:none;opacity:.05}.treb-main.treb-main .treb-header-overlay .treb-highlight{fill:currentColor}.treb-main.treb-main .treb-editor-container>div [data-highlight-index="1"],.treb-main.treb-main .treb-overlay-editor [data-highlight-index="1"]{color:var(--text-reference-color-1)}.treb-main.treb-main .treb-editor-container>div [data-highlight-index="2"],.treb-main.treb-main .treb-overlay-editor [data-highlight-index="2"]{color:var(--text-reference-color-2)}.treb-main.treb-main .treb-editor-container>div [data-highlight-index="3"],.treb-main.treb-main .treb-overlay-editor [data-highlight-index="3"]{color:var(--text-reference-color-3)}.treb-main.treb-main .treb-editor-container>div [data-highlight-index="4"],.treb-main.treb-main .treb-overlay-editor [data-highlight-index="4"]{color:var(--text-reference-color-4)}.treb-main.treb-main .treb-editor-container>div [data-highlight-index="5"],.treb-main.treb-main .treb-overlay-editor [data-highlight-index="5"]{color:var(--text-reference-color-5)}.treb-main.treb-main .treb-editor-container>div span.highlight-1,.treb-main.treb-main .treb-overlay-editor span.highlight-1{color:var(--text-reference-color-1)}.treb-main.treb-main .treb-editor-container>div span.highlight-2,.treb-main.treb-main .treb-overlay-editor span.highlight-2{color:var(--text-reference-color-2)}.treb-main.treb-main .treb-editor-container>div span.highlight-3,.treb-main.treb-main .treb-overlay-editor span.highlight-3{color:var(--text-reference-color-3)}.treb-main.treb-main .treb-editor-container>div span.highlight-4,.treb-main.treb-main .treb-overlay-editor span.highlight-4{color:var(--text-reference-color-4)}.treb-main.treb-main .treb-editor-container>div span.highlight-5,.treb-main.treb-main .treb-overlay-editor span.highlight-5{color:var(--text-reference-color-5)}.treb-main.treb-main .frozen-selection .selection,.treb-main.treb-main .treb-grid-selection .selection{stroke-width:var(--treb-selection-stroke-width,2px)}.treb-main.treb-main .frozen-selection .selection .treb-selection-outline,.treb-main.treb-main .treb-grid-selection .selection .treb-selection-outline{stroke:currentColor;fill:none}.treb-main.treb-main .frozen-selection .selection .treb-selection-fill,.treb-main.treb-main .treb-grid-selection .selection .treb-selection-fill{stroke:none;fill:currentColor;opacity:var(--treb-selection-fill-opacity,.1)}.treb-main.treb-main .frozen-selection .alternate-selection,.treb-main.treb-main .treb-grid-selection .alternate-selection{stroke-dasharray:var(--treb-alternate-selection-dasharray,3 2)}.treb-main.treb-main .frozen-selection .alternate-selection:nth-of-type(1n),.treb-main.treb-main .treb-grid-selection .alternate-selection:nth-of-type(1n){color:var(--alternate-selection-color-1)}.treb-main.treb-main .frozen-selection .alternate-selection:nth-of-type(2n),.treb-main.treb-main .treb-grid-selection .alternate-selection:nth-of-type(2n){color:var(--alternate-selection-color-2)}.treb-main.treb-main .frozen-selection .alternate-selection:nth-of-type(3n),.treb-main.treb-main .treb-grid-selection .alternate-selection:nth-of-type(3n){color:var(--alternate-selection-color-3)}.treb-main.treb-main .frozen-selection .alternate-selection:nth-of-type(4n),.treb-main.treb-main .treb-grid-selection .alternate-selection:nth-of-type(4n){color:var(--alternate-selection-color-4)}.treb-main.treb-main .frozen-selection .alternate-selection:nth-of-type(5n),.treb-main.treb-main .treb-grid-selection .alternate-selection:nth-of-type(5n){color:var(--alternate-selection-color-5)}.treb-main.treb-main .frozen-selection .primary-selection,.treb-main.treb-main .treb-grid-selection .primary-selection{color:var(--treb-selection-color-unfocused,var(--treb-selection-color,#4caaf1))}.treb-main.treb-main .frozen-selection .primary-selection .treb-selection-nub,.treb-main.treb-main .treb-grid-selection .primary-selection .treb-selection-nub{stroke:#fff;fill:currentColor;stroke-width:1px}.treb-main.treb-main .treb-tooltip{background:var(--treb-resize-tooltip-background,rgba(0,0,0,.8));border-color:var(--treb-resize-tooltip-background,rgba(0,0,0,.8));color:var(--treb-resize-tooltip-color,#fff);font-size:11pt}.treb-main.treb-main .treb-spreadsheet-footer .treb-add-tab,.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li{background:var(--treb-tab-bar-tab-background,#eeeef2);color:var(--treb-tab-bar-tab-color,var(--treb-ui-color,inherit))}.treb-main.treb-main .treb-spreadsheet-footer .treb-add-tab[selected],.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li[selected]{background:var(--treb-tab-bar-active-tab-background,#fff);border-bottom-color:var(--treb-tab-bar-active-tab-border-color,currentColor);color:var(--treb-tab-bar-active-tab-color,var(--treb-ui-color,inherit))}.treb-main.treb-main .treb-formula-bar .treb-address-label,.treb-main.treb-main .treb-formula-bar .treb-editor-container{background:var(--treb-formula-bar-background,transparent);color:var(--treb-formula-bar-color,var(--treb-ui-color,inherit))}.treb-main.treb-main .treb-formula-bar .treb-address-label[locked],.treb-main.treb-main .treb-formula-bar .treb-editor-container[locked]{background:var(--treb-formula-bar-locked-background,#eef4fc);position:relative}.treb-main.treb-main .treb-formula-bar .treb-address-label[locked]:after,.treb-main.treb-main .treb-formula-bar .treb-editor-container[locked]:after{content:"";height:12px;opacity:.4;position:absolute;right:2px;top:2px;width:12px;--icon:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'%3E%3Cpath fill='currentColor' d='M416 224h-16v-80C400 65 335 0 256 0S112 65 112 144v80H96c-35 0-64 29-64 64v160c0 35 29 64 64 64h320c35 0 64-29 64-64V288c0-35-29-64-64-64m-240-80c0-44 36-80 80-80s80 36 80 80v80H176z'/%3E%3C/svg%3E");background:var(--treb-formula-bar-lock-icon-color,currentColor);mask-image:var(--icon);-webkit-mask-image:var(--icon);mask-position:center;-webkit-mask-position:center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;mask-size:12px 12px;-webkit-mask-size:12px 12px}.treb-main.treb-main .treb-annotation-textbox{background:Canvas;height:100%;left:0;overflow:hidden;padding:.5em;position:relative;top:0;width:100%}.treb-main.treb-main .treb-annotation-textbox p{margin-block-end:0;margin-block-start:0}.treb-dark-theme{--treb-autocomplete-background:#333;--treb-autocomplete-border-color:#fff;--treb-autocomplete-entry-color:#fff;--treb-autocomplete-selected-entry-background:darkred;--treb-autocomplete-tooltip-background:darkred;--treb-autocomplete-tooltip-border-color:#fff;--treb-autocomplete-tooltip-color:#fff;--treb-chart-background:#000;--treb-chart-grid-color:#976;--treb-chart-grid-zero-color:#fdd;--treb-chart-text-color:#fff;--treb-dialog-background:#000;--treb-dialog-color:#fff;--treb-dropdown-background:#000;--treb-dropdown-border-color:#fff;--treb-dropdown-caret-active-background:darkred;--treb-dropdown-caret-background:#444;--treb-dropdown-caret-border-color:#fff;--treb-dropdown-caret-color:#fff;--treb-dropdown-color:#fff;--treb-dropdown-selected-background:darkred;--treb-grid-background:#000;--treb-grid-default-color:#fff;--treb-grid-grid-color:#444;--treb-grid-header-background:#444;--treb-grid-header-grid-color:#000;--treb-note-background:#333;--treb-note-border-color:#aaa;--treb-note-color:#fff;--treb-note-marker-color:pink;--treb-resize-tooltip-background:#fff;--treb-resize-tooltip-color:#000;--treb-scale-slider-accent-color:#fff;--treb-scale-slider-background:#333;--treb-scale-slider-border-color:#aaa;--treb-selection-color:#ff0;--treb-selection-fill-opacity:.2;--treb-sidebar-button-background:#000;--treb-sidebar-button-border-color:#888;--treb-stats-value-background:#223;--treb-tab-bar-tab-background:#000;--treb-tab-bar-tab-color:#fff;--treb-theme-color-1:#222;--treb-theme-color-2:#ddd;--treb-toolbar-active-button-background:#555;--treb-toolbar-button-background:#000;--treb-toolbar-hover-button-background:#444;--treb-ui-color:#fff;--treb-table-header-background:#334;--treb-table-odd-background:#122;--treb-table-header-font-weight:700;--treb-table-header-border-top:#889;--treb-table-header-border-bottom:#889;--treb-table-footer-border-bottom:#889;--treb-table-odd-border-top:#889;--treb-table-odd-border-bottom:#889;--treb-table-even-border-top:#889;--treb-table-even-border-bottom:#889;--treb-table-total-border-top:#889;--treb-table-total-border-bottom:#889;--treb-table-total-background:#334;--treb-table-total-font-weight:700;--treb-color-scheme:dark;--treb-resize-handle-color:#add8e6;--treb-resize-frame-color:#add8e6;--treb-formula-bar-locked-background:#234;--treb-grid-background:#1e1e1e;--treb-grid-header-background:#565656;--treb-grid-header-color:#ddd;--treb-tab-bar-active-tab-background:#444;--treb-tab-bar-tab-background:transparent;--treb-tab-bar-tab-border-color:#444;--treb-ui-border-color:#aaa;--treb-toolbar-button-background:#565656;--treb-toolbar-button-background:#212121;--treb-toolbar-border-color:#434343;--treb-toolbar-color:#ddd;--treb-spill-border-color:pink;--treb-spill-border-filter:drop-shadow(3px 3px 2px hsla(0,0%,100%,.95))}@media (prefers-color-scheme:dark){.treb-light-dark-theme{--treb-autocomplete-background:#333;--treb-autocomplete-border-color:#fff;--treb-autocomplete-entry-color:#fff;--treb-autocomplete-selected-entry-background:darkred;--treb-autocomplete-tooltip-background:darkred;--treb-autocomplete-tooltip-border-color:#fff;--treb-autocomplete-tooltip-color:#fff;--treb-chart-background:#000;--treb-chart-grid-color:#976;--treb-chart-grid-zero-color:#fdd;--treb-chart-text-color:#fff;--treb-dialog-background:#000;--treb-dialog-color:#fff;--treb-dropdown-background:#000;--treb-dropdown-border-color:#fff;--treb-dropdown-caret-active-background:darkred;--treb-dropdown-caret-background:#444;--treb-dropdown-caret-border-color:#fff;--treb-dropdown-caret-color:#fff;--treb-dropdown-color:#fff;--treb-dropdown-selected-background:darkred;--treb-grid-background:#000;--treb-grid-default-color:#fff;--treb-grid-grid-color:#444;--treb-grid-header-background:#444;--treb-grid-header-grid-color:#000;--treb-note-background:#333;--treb-note-border-color:#aaa;--treb-note-color:#fff;--treb-note-marker-color:pink;--treb-resize-tooltip-background:#fff;--treb-resize-tooltip-color:#000;--treb-scale-slider-accent-color:#fff;--treb-scale-slider-background:#333;--treb-scale-slider-border-color:#aaa;--treb-selection-color:#ff0;--treb-selection-fill-opacity:.2;--treb-sidebar-button-background:#000;--treb-sidebar-button-border-color:#888;--treb-stats-value-background:#223;--treb-tab-bar-tab-background:#000;--treb-tab-bar-tab-color:#fff;--treb-theme-color-1:#222;--treb-theme-color-2:#ddd;--treb-toolbar-active-button-background:#555;--treb-toolbar-button-background:#000;--treb-toolbar-hover-button-background:#444;--treb-ui-color:#fff;--treb-table-header-background:#334;--treb-table-odd-background:#122;--treb-table-header-font-weight:700;--treb-table-header-border-top:#889;--treb-table-header-border-bottom:#889;--treb-table-footer-border-bottom:#889;--treb-table-odd-border-top:#889;--treb-table-odd-border-bottom:#889;--treb-table-even-border-top:#889;--treb-table-even-border-bottom:#889;--treb-table-total-border-top:#889;--treb-table-total-border-bottom:#889;--treb-table-total-background:#334;--treb-table-total-font-weight:700;--treb-color-scheme:dark;--treb-resize-handle-color:#add8e6;--treb-resize-frame-color:#add8e6;--treb-formula-bar-locked-background:#234;--treb-grid-background:#1e1e1e;--treb-grid-header-background:#565656;--treb-grid-header-color:#ddd;--treb-tab-bar-active-tab-background:#444;--treb-tab-bar-tab-background:transparent;--treb-tab-bar-tab-border-color:#444;--treb-ui-border-color:#aaa;--treb-toolbar-button-background:#565656;--treb-toolbar-button-background:#212121;--treb-toolbar-border-color:#434343;--treb-toolbar-color:#ddd;--treb-spill-border-color:pink;--treb-spill-border-filter:drop-shadow(3px 3px 2px hsla(0,0%,100%,.95))}}.treb-chart,.treb-main.treb-main .treb-chart{background:var(--treb-chart-background,#fff)}.treb-main.treb-main .treb-inherit-font .treb-chart{font-family:inherit}.treb-chart{--segment-2-offset:-20;--segment-3-offset:10;--segment-4-offset:-10;--segment-5-offset:20;--segment-6-offset:-25}.treb-chart .series-1{color:var(--treb-applied-theme-color-1)}.treb-chart .series-2{color:var(--treb-applied-theme-color-2)}.treb-chart .series-3{color:var(--treb-applied-theme-color-3)}.treb-chart .series-4{color:var(--treb-applied-theme-color-4)}.treb-chart .series-5{color:var(--treb-applied-theme-color-5)}.treb-chart .series-6{color:var(--treb-applied-theme-color-6)}.treb-chart .series-7{color:lch(from var(--treb-applied-theme-color-1) calc(l + var(--segment-2-offset)) c h)}.treb-chart .series-8{color:lch(from var(--treb-applied-theme-color-2) calc(l + var(--segment-2-offset)) c h)}.treb-chart .series-9{color:lch(from var(--treb-applied-theme-color-3) calc(l + var(--segment-2-offset)) c h)}.treb-chart .series-10{color:lch(from var(--treb-applied-theme-color-4) calc(l + var(--segment-2-offset)) c h)}.treb-chart .series-11{color:lch(from var(--treb-applied-theme-color-5) calc(l + var(--segment-2-offset)) c h)}.treb-chart .series-12{color:lch(from var(--treb-applied-theme-color-6) calc(l + var(--segment-2-offset)) c h)}.treb-chart .series-13{color:lch(from var(--treb-applied-theme-color-1) calc(l + var(--segment-3-offset)) c h)}.treb-chart .series-14{color:lch(from var(--treb-applied-theme-color-2) calc(l + var(--segment-3-offset)) c h)}.treb-chart .series-15{color:lch(from var(--treb-applied-theme-color-3) calc(l + var(--segment-3-offset)) c h)}.treb-chart .series-16{color:lch(from var(--treb-applied-theme-color-4) calc(l + var(--segment-3-offset)) c h)}.treb-chart .series-17{color:lch(from var(--treb-applied-theme-color-5) calc(l + var(--segment-3-offset)) c h)}.treb-chart .series-18{color:lch(from var(--treb-applied-theme-color-6) calc(l + var(--segment-3-offset)) c h)}.treb-chart .series-19{color:lch(from var(--treb-applied-theme-color-1) calc(l + var(--segment-4-offset)) c h)}.treb-chart .series-20{color:lch(from var(--treb-applied-theme-color-2) calc(l + var(--segment-4-offset)) c h)}.treb-chart .series-21{color:lch(from var(--treb-applied-theme-color-3) calc(l + var(--segment-4-offset)) c h)}.treb-chart .series-22{color:lch(from var(--treb-applied-theme-color-4) calc(l + var(--segment-4-offset)) c h)}.treb-chart .series-23{color:lch(from var(--treb-applied-theme-color-5) calc(l + var(--segment-4-offset)) c h)}.treb-chart .series-24{color:lch(from var(--treb-applied-theme-color-6) calc(l + var(--segment-4-offset)) c h)}.treb-chart .series-25{color:lch(from var(--treb-applied-theme-color-1) calc(l + var(--segment-5-offset)) c h)}.treb-chart .series-26{color:lch(from var(--treb-applied-theme-color-2) calc(l + var(--segment-5-offset)) c h)}.treb-chart .series-27{color:lch(from var(--treb-applied-theme-color-3) calc(l + var(--segment-5-offset)) c h)}.treb-chart .series-28{color:lch(from var(--treb-applied-theme-color-4) calc(l + var(--segment-5-offset)) c h)}.treb-chart .series-29{color:lch(from var(--treb-applied-theme-color-5) calc(l + var(--segment-5-offset)) c h)}.treb-chart .series-30{color:lch(from var(--treb-applied-theme-color-6) calc(l + var(--segment-5-offset)) c h)}.treb-chart .series-31{color:lch(from var(--treb-applied-theme-color-1) calc(l + var(--segment-6-offset)) c h)}.treb-chart .series-32{color:lch(from var(--treb-applied-theme-color-2) calc(l + var(--segment-6-offset)) c h)}.treb-chart .series-33{color:lch(from var(--treb-applied-theme-color-3) calc(l + var(--segment-6-offset)) c h)}.treb-chart .series-34{color:lch(from var(--treb-applied-theme-color-4) calc(l + var(--segment-6-offset)) c h)}.treb-chart .series-35{color:lch(from var(--treb-applied-theme-color-5) calc(l + var(--segment-6-offset)) c h)}.treb-chart .series-36{color:lch(from var(--treb-applied-theme-color-6) calc(l + var(--segment-6-offset)) c h)}.treb-chart .chart-title{font-size:1.4em}.treb-chart .axis-group{font-size:.9em}.treb-chart .axis-group .series-name{font-size:1.3em}.treb-chart text{fill:var(--treb-chart-text-color,#000);stroke:none}.treb-chart .legend{font-size:1.05em}.treb-chart .legend rect{fill:currentColor}.treb-chart .legend circle{fill:currentColor;fill-opacity:.5;stroke:currentColor;stroke-width:2px;r:.25em}.treb-chart .chart-grid,.treb-chart .chart-ticks{stroke:var(--treb-chart-grid-color,#ddd)}.treb-chart .chart-grid.zero,.treb-chart .chart-ticks.zero{stroke:var(--treb-chart-grid-zero-color,var(--treb-chart-grid-color,#999))}.treb-chart .label-target{stroke:none;fill:transparent}.treb-chart path.label-target{transition:fill .2s}.treb-chart path.label-target:hover{fill:rgba(0,0,0,.15)}.treb-chart .data-label{opacity:0;pointer-events:none;transition:opacity .2s ease-in-out}.treb-chart .data-label text{fill:#fff}.treb-chart .data-label path{fill:#000}.treb-chart .data-label .marker-highlight{fill:currentColor;stroke:none}.treb-chart .label-target:hover+.data-label{opacity:1}.treb-chart .chart-line{stroke:currentColor;fill:none;stroke-width:2}.treb-chart .chart-area .line{stroke:currentColor;stroke-width:2px;fill:none}.treb-chart .chart-area .fill{fill:currentColor;opacity:.5}.treb-chart .box-plot .iqr{fill:none;stroke:CanvasText;stroke-width:1px}.treb-chart .box-plot .median{stroke-width:3px;stroke:CanvasText;fill:none}.treb-chart .box-plot .outlier{r:3}.treb-chart .box-plot .outlier,.treb-chart .box-plot .whisker,.treb-chart .box-plot .whisker-extent{stroke-width:1px;stroke:CanvasText;fill:none}.treb-chart .box-plot .whisker-extent{stroke-dasharray:3 3}.treb-chart .bubble-chart{stroke-width:3;fill:color-mix(in srgb,currentColor 75%,transparent);stroke:currentColor}.treb-chart .bubble-label .label-background{stroke:none;fill:none}.treb-chart .bubble-label .label-text{transform:translate(var(--translate-offset),var(--translate-offset))}.treb-chart .scatter-plot{stroke-width:3;fill:none;stroke:currentColor}.treb-chart .scatter-plot .fill{fill:currentColor;opacity:.5;stroke:none}.treb-chart .scatter-plot .marker{stroke-width:2.5px;fill:#fff;transition:stroke-width .15s ease-in}.treb-chart .scatter-plot .marker:hover{stroke-width:5px}.treb-chart .donut path{fill:currentColor}.treb-chart .donut path.callout{fill:none;stroke:#999;stroke-dasharray:2 2}.treb-chart .donut text.callout-label{font-size:1em}.treb-chart .chart-column{fill:currentColor;stroke:none}.treb-chart .mc-correlation{stroke:currentColor;stroke-width:1}.treb-main.treb-main{--treb-icon-svg:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='153.073' height='133.742' viewBox='0.673 4.629 153.073 133.742'%3E%3ClinearGradient id='a' x1='.673' x2='153.746' y1='71.5' y2='71.5' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0' style='stop-color:%235cb5ff'/%3E%3Cstop offset='1' style='stop-color:%230059b9'/%3E%3C/linearGradient%3E%3Cpath fill='url(%23a)' d='M91.656 28.313c-4.989 0-17.266 6.249-21.305 8.504-2.344-2.473-2.603-6.162-3.036-10.933-2.344 2.429-.824 9.806 0 12.496-10.238 7.635-18.83 15.531-27.597 24.471-2.992-4.729-5.031-8.593-5.726-17.183-3.038 6.509.867 15.057 3.121 19.784-9.674 12.193-19.263 25.297-27.03 37.834-35.488-74.973 72.853-119.534 143.663-88.855-43.867 29.199-55.192 121.353-132.248 96.843-5.423 7.809-9.069 18.006-13.538 27.072-3.73.263-6.334-1.646-7.288-3.12 7.506-18.181 17.183-34.192 27.075-49.984 10.718.306 21.346.478 30.198-1.04-7.681-2.038-16.877-.78-26.032-3.123C37.51 70.361 45.667 62.203 53.78 54.004c8.808.782 17.746 3.21 27.074 1.041-8.111-1.431-15.966-1.952-22.909-4.165 7.594-8.378 22.777-17.491 33.711-22.567'/%3E%3C/svg%3E")}.treb-main.treb-main .treb-icon-64{background:no-repeat 50%/100% var(--treb-icon-svg);height:64px;width:64px}.treb-main.treb-main .treb-dialog-mask{align-items:center;display:flex;height:100%;justify-content:center;left:0;opacity:0;pointer-events:none;position:absolute;top:0;transition:opacity .2s;width:100%;z-index:1000}.treb-main.treb-main .treb-embed-dialog{align-items:center;background:var(--treb-dialog-background,#fff);border:1px solid var(--treb-dialog-border-color,var(--treb-ui-border-color,#999));border-radius:3px;border-top:3px solid #999;box-shadow:0 4px 6px -4px rgba(0,0,0,.3);color:var(--treb-dialog-color,#000);display:flex;flex-direction:row;font-size:var(--treb-dialog-font-size,16px);line-height:1.6em;padding:1rem;position:relative;text-align:left}.treb-main.treb-main .treb-embed-dialog>*{display:none}.treb-main.treb-main .treb-embed-dialog>div{position:relative}.treb-main.treb-main .treb-embed-dialog>:nth-child(2){display:block;flex-grow:1;padding:2px 20px 2px 12px}.treb-main.treb-main .treb-embed-dialog>.treb-close-box{background:transparent;border:0;padding:4px;position:absolute;right:0;top:0}.treb-main.treb-main .treb-embed-dialog>.treb-close-box>svg{fill:#73828c;cursor:default;height:20px;width:20px}.treb-main.treb-main .treb-embed-dialog>.treb-close-box>svg:active,.treb-main.treb-main .treb-embed-dialog>.treb-close-box>svg:hover{fill:#049cfb}.treb-main.treb-main .treb-embed-dialog small{display:block;font-size:.9em}.treb-main.treb-main .treb-embed-dialog a{color:inherit;text-decoration:none}.treb-main.treb-main .treb-embed-dialog a:active,.treb-main.treb-main .treb-embed-dialog a:hover{color:#049cfb}.treb-main.treb-main .treb-embed-dialog.dialog-type-success{border-top-color:#44d926;border-top-width:3px}.treb-main.treb-main .treb-embed-dialog.dialog-type-about{border-top-color:#009dff;border-top-width:3px}.treb-main.treb-main .treb-embed-dialog.dialog-type-error{border-top-color:#f92f06;border-top-width:3px}.treb-main.treb-main .treb-embed-dialog.dialog-type-info{border-top-color:#009dff;border-top-width:3px}.treb-main.treb-main .treb-embed-dialog .treb-embed-dialog-message,.treb-main.treb-main .treb-embed-dialog .treb-embed-dialog-title{white-space:pre}.treb-main.treb-main .treb-embed-dialog .treb-embed-progress-container{border:1px solid #ddd;height:6px;margin:1rem auto .5rem;position:relative;width:100%}.treb-main.treb-main .treb-embed-dialog .treb-embed-progress-bar{background:#52880b;height:100%;left:0;position:relative;top:0}.treb-main.treb-main .treb-spinner{align-items:center;background:transparent;display:flex;height:100%;justify-content:center;left:0;opacity:0;position:absolute;top:0;transition:visibility .25s,opacity .25s ease;visibility:collapse;width:100%;z-index:1000}.treb-main.treb-main .treb-spinner.visible{opacity:1;transition:visibility 0s,opacity 1s ease;visibility:visible}.treb-main.treb-main .treb-spinner>div{display:inline-block;height:80px;position:relative;width:80px}.treb-main.treb-main .treb-spinner>div div{animation:treb-spinner 1.2s cubic-bezier(.5,0,.5,1) infinite;border:8px solid #fff;border-color:var(--treb-spinner-color,currentColor) transparent transparent transparent;border-radius:50%;box-sizing:border-box;display:block;height:64px;margin:8px;position:absolute;width:64px}.treb-main.treb-main .treb-spinner>div div:first-child{animation-delay:-.45s}.treb-main.treb-main .treb-spinner>div div:nth-child(2){animation-delay:-.3s}.treb-main.treb-main .treb-spinner>div div:nth-child(3){animation-delay:-.15s}@keyframes treb-spinner{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}.treb-main.treb-main{--icon-x:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708"/></svg>');--icon-popout:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 28 28"><path fill="currentColor" d="M22 14.5v5c0 2.484-2.016 4.5-4.5 4.5h-13A4.5 4.5 0 0 1 0 19.5v-13C0 4.016 2.016 2 4.5 2h11c.281 0 .5.219.5.5v1c0 .281-.219.5-.5.5h-11A2.507 2.507 0 0 0 2 6.5v13C2 20.875 3.125 22 4.5 22h13c1.375 0 2.5-1.125 2.5-2.5v-5c0-.281.219-.5.5-.5h1c.281 0 .5.219.5.5M28 1v8c0 .547-.453 1-1 1a1 1 0 0 1-.703-.297l-2.75-2.75L13.36 17.14c-.094.094-.234.156-.359.156s-.266-.063-.359-.156l-1.781-1.781c-.094-.094-.156-.234-.156-.359s.063-.266.156-.359L21.048 4.454l-2.75-2.75a1 1 0 0 1-.297-.703c0-.547.453-1 1-1h8c.547 0 1 .453 1 1z"/></svg>');--icon-toolbar:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 28"><path fill="currentColor" d="M5.5 22v2H0v-2zm5.5-2c.547 0 1 .453 1 1v4c0 .547-.453 1-1 1H7c-.547 0-1-.453-1-1v-4c0-.547.453-1 1-1zm2.5-6v2H0v-2zm-10-8v2H0V6zM24 22v2H12.5v-2zM9 4c.547 0 1 .453 1 1v4c0 .547-.453 1-1 1H5c-.547 0-1-.453-1-1V5c0-.547.453-1 1-1zm10 8c.547 0 1 .453 1 1v4c0 .547-.453 1-1 1h-4c-.547 0-1-.453-1-1v-4c0-.547.453-1 1-1zm5 2v2h-3.5v-2zm0-8v2H10.5V6z"/></svg>');--icon-export:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 26 28"><path fill="currentColor" d="M20 21c0-.547-.453-1-1-1s-1 .453-1 1 .453 1 1 1 1-.453 1-1m4 0c0-.547-.453-1-1-1s-1 .453-1 1 .453 1 1 1 1-.453 1-1m2-3.5v5a1.5 1.5 0 0 1-1.5 1.5h-23A1.5 1.5 0 0 1 0 22.5v-5A1.5 1.5 0 0 1 1.5 16h7.266l2.109 2.125c.578.562 1.328.875 2.125.875s1.547-.313 2.125-.875L17.25 16h7.25a1.5 1.5 0 0 1 1.5 1.5m-5.078-8.891a.98.98 0 0 1-.219 1.094l-7 7c-.187.203-.453.297-.703.297s-.516-.094-.703-.297l-7-7a.98.98 0 0 1-.219-1.094C5.234 8.25 5.594 8 6 8h4V1c0-.547.453-1 1-1h4c.547 0 1 .453 1 1v7h4c.406 0 .766.25.922.609"/></svg>');--icon-reset:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 28"><path fill="currentColor" d="M23.609 16.5c0 .031 0 .078-.016.109C22.265 22.14 17.702 26 11.937 26c-3.047 0-6-1.203-8.219-3.313l-2.016 2.016A1 1 0 0 1 .999 25c-.547 0-1-.453-1-1v-7c0-.547.453-1 1-1h7c.547 0 1 .453 1 1a1 1 0 0 1-.297.703l-2.141 2.141A7.99 7.99 0 0 0 11.998 22a7.98 7.98 0 0 0 6.813-3.813c.375-.609.562-1.203.828-1.828.078-.219.234-.359.469-.359h3c.281 0 .5.234.5.5zM24 4v7c0 .547-.453 1-1 1h-7c-.547 0-1-.453-1-1a1 1 0 0 1 .297-.703l2.156-2.156A8.04 8.04 0 0 0 12 6a7.98 7.98 0 0 0-6.813 3.813c-.375.609-.562 1.203-.828 1.828-.078.219-.234.359-.469.359H.781a.503.503 0 0 1-.5-.5v-.109C1.625 5.844 6.234 2 12 2c3.063 0 6.047 1.219 8.266 3.313l2.031-2.016A1 1 0 0 1 23 3c.547 0 1 .453 1 1"/></svg>');--icon-about:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 28"><path fill="currentColor" d="M14 21.5v-3c0-.281-.219-.5-.5-.5h-3c-.281 0-.5.219-.5.5v3c0 .281.219.5.5.5h3c.281 0 .5-.219.5-.5M18 11c0-2.859-3-5-5.688-5-2.547 0-4.453 1.094-5.797 3.328a.49.49 0 0 0 .125.656l2.063 1.563a.48.48 0 0 0 .297.094.5.5 0 0 0 .391-.187c.734-.938 1.047-1.219 1.344-1.437.266-.187.781-.375 1.344-.375 1 0 1.922.641 1.922 1.328 0 .812-.422 1.219-1.375 1.656-1.109.5-2.625 1.797-2.625 3.313v.562c0 .281.219.5.5.5h3c.281 0 .5-.219.5-.5 0-.359.453-1.125 1.188-1.547 1.188-.672 2.812-1.578 2.812-3.953zm6 3c0 6.625-5.375 12-12 12S0 20.625 0 14 5.375 2 12 2s12 5.375 12 12"/></svg>');--icon-chevron-left:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 21 28"><path fill="currentColor" d="M18.297 4.703 10 13l8.297 8.297a.99.99 0 0 1 0 1.406l-2.594 2.594a.99.99 0 0 1-1.406 0L2.703 13.703a.99.99 0 0 1 0-1.406L14.297.703a.99.99 0 0 1 1.406 0l2.594 2.594a.99.99 0 0 1 0 1.406"/></svg>');--icon-chevron-right:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 19 28"><path fill="currentColor" d="M17.297 13.703 5.703 25.297a.99.99 0 0 1-1.406 0l-2.594-2.594a.99.99 0 0 1 0-1.406L10 13 1.703 4.703a.99.99 0 0 1 0-1.406L4.297.703a.99.99 0 0 1 1.406 0l11.594 11.594a.99.99 0 0 1 0 1.406"/></svg>');--icon-revert:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 28"><path fill="currentColor" d="M24 14c0 6.609-5.391 12-12 12a11.97 11.97 0 0 1-9.234-4.328.52.52 0 0 1 .031-.672l2.141-2.156a.6.6 0 0 1 .391-.141.5.5 0 0 1 .359.187A7.91 7.91 0 0 0 12 21.999c4.406 0 8-3.594 8-8s-3.594-8-8-8A7.95 7.95 0 0 0 6.563 8.14l2.141 2.156a.96.96 0 0 1 .219 1.078 1 1 0 0 1-.922.625h-7c-.547 0-1-.453-1-1v-7c0-.406.25-.766.625-.922a.96.96 0 0 1 1.078.219l2.031 2.016c2.203-2.078 5.187-3.313 8.266-3.313 6.609 0 12 5.391 12 12zM14 9.5v7c0 .281-.219.5-.5.5h-5a.494.494 0 0 1-.5-.5v-1c0-.281.219-.5.5-.5H12V9.5c0-.281.219-.5.5-.5h1c.281 0 .5.219.5.5"/></svg>');--icon-text-indent:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-text-indent-left" viewBox="0 0 16 16"><path d="M2 3.5a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5m.646 2.146a.5.5 0 0 1 .708 0l2 2a.5.5 0 0 1 0 .708l-2 2a.5.5 0 0 1-.708-.708L4.293 8 2.646 6.354a.5.5 0 0 1 0-.708M7 6.5a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1h-6a.5.5 0 0 1-.5-.5m0 3a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1h-6a.5.5 0 0 1-.5-.5m-5 3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5"/></svg>');--icon-text-outdent:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-text-indent-right" viewBox="0 0 16 16"><path d="M2 3.5a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5m10.646 2.146a.5.5 0 0 1 .708.708L11.707 8l1.647 1.646a.5.5 0 0 1-.708.708l-2-2a.5.5 0 0 1 0-.708zM2 6.5a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1h-6a.5.5 0 0 1-.5-.5m0 3a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1h-6a.5.5 0 0 1-.5-.5m0 3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5"/></svg>');--icon-text-align-left:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M2 12.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5m0-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5m0-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5m0-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5"/></svg>');--icon-text-align-center:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M4 12.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5m-2-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5m2-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5m-2-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5"/></svg>');--icon-text-align-right:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M6 12.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5m-4-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5m4-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5m-4-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5"/></svg>');--icon-text-align-top:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='16' height='16' viewBox='0 0 16 16'%3E%3Cpath d='M8 15a.5.5 0 0 0 .5-.5V5.707l3.146 3.146a.5.5 0 0 0 .707-.707l-4-4a.5.5 0 0 0-.706-.001l-.001.001-4 4a.5.5 0 0 0 .708.707L7.5 5.707V14.5a.5.5 0 0 0 .5.5'/%3E%3Cpath fill='none' stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-miterlimit='10' d='M3 1.5h10'/%3E%3C/svg%3E");--icon-text-align-middle:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M1 8a.5.5 0 0 1 .5-.5h13a.5.5 0 0 1 0 1h-13A.5.5 0 0 1 1 8m7-8a.5.5 0 0 1 .5.5v3.793l1.146-1.147a.5.5 0 0 1 .708.708l-2 2a.5.5 0 0 1-.708 0l-2-2a.5.5 0 1 1 .708-.708L7.5 4.293V.5A.5.5 0 0 1 8 0m-.5 11.707-1.146 1.147a.5.5 0 0 1-.708-.708l2-2a.5.5 0 0 1 .708 0l2 2a.5.5 0 0 1-.708.708L8.5 11.707V15.5a.5.5 0 0 1-1 0z"/></svg>');--icon-text-align-bottom:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='16' height='16' viewBox='0 0 16 16'%3E%3Cpath d='M8 1a.5.5 0 0 0-.5.5v8.793L4.354 7.146a.5.5 0 0 0-.707.707l4 4a.5.5 0 0 0 .707.001l.001-.001 4-4a.5.5 0 0 0-.708-.707L8.5 10.293V1.5A.5.5 0 0 0 8 1'/%3E%3Cpath fill='none' stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-miterlimit='10' d='M13 14.5H3'/%3E%3C/svg%3E");--icon-file-menu:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M.54 3.87.5 3a2 2 0 0 1 2-2h3.672a2 2 0 0 1 1.414.586l.828.828A2 2 0 0 0 9.828 3h3.982a2 2 0 0 1 1.992 2.181l-.637 7A2 2 0 0 1 13.174 14H2.826a2 2 0 0 1-1.991-1.819l-.637-7a2 2 0 0 1 .342-1.31zM2.19 4a1 1 0 0 0-.996 1.09l.637 7a1 1 0 0 0 .995.91h10.348a1 1 0 0 0 .995-.91l.637-7A1 1 0 0 0 13.81 4zm4.69-1.707A1 1 0 0 0 6.172 2H2.5a1 1 0 0 0-1 .981l.006.139q.323-.119.684-.12h5.396z"/></svg>');--icon-wrap-text:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M4 5h8a.5.5 0 0 0 0-1H4a.5.5 0 0 0 0 1M10 8H4a.5.5 0 0 0 0 1h6a1.5 1.5 0 0 1 0 3v-1.203l-2.953 1.707L10 14.203V13a2.5 2.5 0 1 0 0-5M3.75 12.5a.5.5 0 0 0 .5.5H6v-1H4.25a.5.5 0 0 0-.5.5"/></svg>');--icon-unmerge-cells:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M1.5 1a.5.5 0 0 0-.5.5v4a.5.5 0 0 1-1 0v-4A1.5 1.5 0 0 1 1.5 0h4a.5.5 0 0 1 0 1zM10 .5a.5.5 0 0 1 .5-.5h4A1.5 1.5 0 0 1 16 1.5v4a.5.5 0 0 1-1 0v-4a.5.5 0 0 0-.5-.5h-4a.5.5 0 0 1-.5-.5M.5 10a.5.5 0 0 1 .5.5v4a.5.5 0 0 0 .5.5h4a.5.5 0 0 1 0 1h-4A1.5 1.5 0 0 1 0 14.5v-4a.5.5 0 0 1 .5-.5m15 0a.5.5 0 0 1 .5.5v4a1.5 1.5 0 0 1-1.5 1.5h-4a.5.5 0 0 1 0-1h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 1 .5-.5"/></svg>');--icon-merge-cells:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M5.5 0a.5.5 0 0 1 .5.5v4A1.5 1.5 0 0 1 4.5 6h-4a.5.5 0 0 1 0-1h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 1 .5-.5m5 0a.5.5 0 0 1 .5.5v4a.5.5 0 0 0 .5.5h4a.5.5 0 0 1 0 1h-4A1.5 1.5 0 0 1 10 4.5v-4a.5.5 0 0 1 .5-.5M0 10.5a.5.5 0 0 1 .5-.5h4A1.5 1.5 0 0 1 6 11.5v4a.5.5 0 0 1-1 0v-4a.5.5 0 0 0-.5-.5h-4a.5.5 0 0 1-.5-.5m10 1a1.5 1.5 0 0 1 1.5-1.5h4a.5.5 0 0 1 0 1h-4a.5.5 0 0 0-.5.5v4a.5.5 0 0 1-1 0z"/></svg>');--icon-lock:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M8 1a2 2 0 0 1 2 2v4H6V3a2 2 0 0 1 2-2m3 6V3a3 3 0 0 0-6 0v4a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2M5 8h6a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1"/></svg>');--icon-comment:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M14 1a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1h-2.5a2 2 0 0 0-1.6.8L8 14.333 6.1 11.8a2 2 0 0 0-1.6-.8H2a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1zM2 0a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2.5a1 1 0 0 1 .8.4l1.9 2.533a1 1 0 0 0 1.6 0l1.9-2.533a1 1 0 0 1 .8-.4H14a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2z"/></svg>');--icon-fill-color:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M6.192 2.78c-.458-.677-.927-1.248-1.35-1.643a3 3 0 0 0-.71-.515c-.217-.104-.56-.205-.882-.02-.367.213-.427.63-.43.896-.003.304.064.664.173 1.044.196.687.556 1.528 1.035 2.402L.752 8.22c-.277.277-.269.656-.218.918.055.283.187.593.36.903.348.627.92 1.361 1.626 2.068.707.707 1.441 1.278 2.068 1.626.31.173.62.305.903.36.262.05.64.059.918-.218l5.615-5.615c.118.257.092.512.05.939-.03.292-.068.665-.073 1.176v.123h.003a1 1 0 0 0 1.993 0H14v-.057a1 1 0 0 0-.004-.117c-.055-1.25-.7-2.738-1.86-3.494a4 4 0 0 0-.211-.434c-.349-.626-.92-1.36-1.627-2.067S8.857 3.052 8.23 2.704c-.31-.172-.62-.304-.903-.36-.262-.05-.64-.058-.918.219l-.217.216zM4.16 1.867c.381.356.844.922 1.311 1.632l-.704.705c-.382-.727-.66-1.402-.813-1.938a3.3 3.3 0 0 1-.131-.673q.137.09.337.274m.394 3.965c.54.852 1.107 1.567 1.607 2.033a.5.5 0 1 0 .682-.732c-.453-.422-1.017-1.136-1.564-2.027l1.088-1.088q.081.181.183.365c.349.627.92 1.361 1.627 2.068.706.707 1.44 1.278 2.068 1.626q.183.103.365.183l-4.861 4.862a1 1 0 0 1-.068-.01c-.137-.027-.342-.104-.608-.252-.524-.292-1.186-.8-1.846-1.46s-1.168-1.32-1.46-1.846c-.147-.265-.225-.47-.251-.607a1 1 0 0 1-.01-.068zm2.87-1.935a2.4 2.4 0 0 1-.241-.561c.135.033.324.11.562.241.524.292 1.186.8 1.846 1.46.45.45.83.901 1.118 1.31a3.5 3.5 0 0 0-1.066.091 11 11 0 0 1-.76-.694c-.66-.66-1.167-1.322-1.458-1.847z"/></svg>');--icon-text-color:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="16" height="16" viewBox="0 0 16 16"><path d="m12.259 14.001-1.389-3.727H5.465l-1.354 3.727h-1.3L7.609 1.397h1.178l4.772 12.604zM8.418 3.604a6 6 0 0 1-.127-.387 4 4 0 0 1-.11-.501h-.035a5.5 5.5 0 0 1-.247.888L5.86 9.211h4.614z"/></svg>');--icon-border-bottom:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M.969 0H0v.969h.5V1h.469V.969H1V.5H.969zm.937 1h.938V0h-.938zm1.875 0h.938V0H3.78v1zm1.875 0h.938V0h-.938zM7.531.969V1h.938V.969H8.5V.5h-.031V0H7.53v.5H7.5v.469zM9.406 1h.938V0h-.938zm1.875 0h.938V0h-.938zm1.875 0h.938V0h-.938zm1.875 0h.469V.969h.5V0h-.969v.5H15v.469h.031zM1 2.844v-.938H0v.938zm6.5-.938v.938h1v-.938zm7.5 0v.938h1v-.938zM1 4.719V3.78H0v.938h1zm6.5-.938v.938h1V3.78h-1zm7.5 0v.938h1V3.78h-1zM1 6.594v-.938H0v.938zm6.5-.938v.938h1v-.938zm7.5 0v.938h1v-.938zM.5 8.5h.469v-.031H1V7.53H.969V7.5H.5v.031H0v.938h.5zm1.406 0h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm2.813 0v-.031H8.5V7.53h-.031V7.5H7.53v.031H7.5v.938h.031V8.5zm.937 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.469v-.031h.5V7.53h-.5V7.5h-.469v.031H15v.938h.031zM0 9.406v.938h1v-.938zm7.5 0v.938h1v-.938zm8.5.938v-.938h-1v.938zm-16 .937v.938h1v-.938zm7.5 0v.938h1v-.938zm8.5.938v-.938h-1v.938zm-16 .937v.938h1v-.938zm7.5 0v.938h1v-.938zm8.5.938v-.938h-1v.938zM0 15h16v1H0z"/></svg>');--icon-border-top:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M0 0v1h16V0zm1 2.844v-.938H0v.938zm6.5-.938v.938h1v-.938zm7.5 0v.938h1v-.938zM1 4.719V3.78H0v.938h1zm6.5-.938v.938h1V3.78h-1zm7.5 0v.938h1V3.78h-1zM1 6.594v-.938H0v.938zm6.5-.938v.938h1v-.938zm7.5 0v.938h1v-.938zM.5 8.5h.469v-.031H1V7.53H.969V7.5H.5v.031H0v.938h.5zm1.406 0h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm2.813 0v-.031H8.5V7.53h-.031V7.5H7.53v.031H7.5v.938h.031V8.5zm.937 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.469v-.031h.5V7.53h-.5V7.5h-.469v.031H15v.938h.031zM0 9.406v.938h1v-.938zm7.5 0v.938h1v-.938zm8.5.938v-.938h-1v.938zm-16 .937v.938h1v-.938zm7.5 0v.938h1v-.938zm8.5.938v-.938h-1v.938zm-16 .937v.938h1v-.938zm7.5 0v.938h1v-.938zm8.5.938v-.938h-1v.938zM0 16h.969v-.5H1v-.469H.969V15H.5v.031H0zm1.906 0h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm1.875-.5v.5h.938v-.5H8.5v-.469h-.031V15H7.53v.031H7.5v.469zm1.875.5h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875-.5v.5H16v-.969h-.5V15h-.469v.031H15v.469z"/></svg>');--icon-border-left:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M0 0v16h1V0zm1.906 1h.938V0h-.938zm1.875 0h.938V0H3.78v1zm1.875 0h.938V0h-.938zM7.531.969V1h.938V.969H8.5V.5h-.031V0H7.53v.5H7.5v.469zM9.406 1h.938V0h-.938zm1.875 0h.938V0h-.938zm1.875 0h.938V0h-.938zm1.875 0h.469V.969h.5V0h-.969v.5H15v.469h.031zM7.5 1.906v.938h1v-.938zm7.5 0v.938h1v-.938zM7.5 3.781v.938h1V3.78h-1zm7.5 0v.938h1V3.78h-1zM7.5 5.656v.938h1v-.938zm7.5 0v.938h1v-.938zM1.906 8.5h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm2.813 0v-.031H8.5V7.53h-.031V7.5H7.53v.031H7.5v.938h.031V8.5zm.937 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.469v-.031h.5V7.53h-.5V7.5h-.469v.031H15v.938h.031zM7.5 9.406v.938h1v-.938zm8.5.938v-.938h-1v.938zm-8.5.937v.938h1v-.938zm8.5.938v-.938h-1v.938zm-8.5.937v.938h1v-.938zm8.5.938v-.938h-1v.938zM1.906 16h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm1.875-.5v.5h.938v-.5H8.5v-.469h-.031V15H7.53v.031H7.5v.469zm1.875.5h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875-.5v.5H16v-.969h-.5V15h-.469v.031H15v.469z"/></svg>');--icon-border-right:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M.969 0H0v.969h.5V1h.469V.969H1V.5H.969zm.937 1h.938V0h-.938zm1.875 0h.938V0H3.78v1zm1.875 0h.938V0h-.938zM7.531.969V1h.938V.969H8.5V.5h-.031V0H7.53v.5H7.5v.469zM9.406 1h.938V0h-.938zm1.875 0h.938V0h-.938zm1.875 0h.938V0h-.938zM16 0h-1v16h1zM1 2.844v-.938H0v.938zm6.5-.938v.938h1v-.938zM1 4.719V3.78H0v.938h1zm6.5-.938v.938h1V3.78h-1zM1 6.594v-.938H0v.938zm6.5-.938v.938h1v-.938zM.5 8.5h.469v-.031H1V7.53H.969V7.5H.5v.031H0v.938h.5zm1.406 0h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm2.813 0v-.031H8.5V7.53h-.031V7.5H7.53v.031H7.5v.938h.031V8.5zm.937 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zM0 9.406v.938h1v-.938zm7.5 0v.938h1v-.938zM0 11.281v.938h1v-.938zm7.5 0v.938h1v-.938zM0 13.156v.938h1v-.938zm7.5 0v.938h1v-.938zM0 16h.969v-.5H1v-.469H.969V15H.5v.031H0zm1.906 0h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm1.875-.5v.5h.938v-.5H8.5v-.469h-.031V15H7.53v.031H7.5v.469zm1.875.5h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938z"/></svg>');--icon-border-double-bottom:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M.969 0H0v.969h.5V1h.469V.969H1V.5H.969zm.937 1h.938V0h-.938zm1.875 0h.938V0H3.78v1zm1.875 0h.938V0h-.938zM7.531.969V1h.938V.969H8.5V.5h-.031V0H7.53v.5H7.5v.469zM9.406 1h.938V0h-.938zm1.875 0h.938V0h-.938zm1.875 0h.938V0h-.938zm1.875 0h.469V.969h.5V0h-.969v.5H15v.469h.031zM1 2.844v-.938H0v.938zm6.5-.938v.938h1v-.938zm7.5 0v.938h1v-.938zM1 4.719V3.78H0v.938zm6.5-.938v.938h1V3.78h-1zm7.5 0v.938h1V3.78h-1zM1 6.594v-.938H0v.938zm6.5-.938v.938h1v-.938zm7.5 0v.938h1v-.938zM.5 8.5h.469v-.031H1V7.53H.969V7.5H.5v.031H0v.938h.5zm1.406 0h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm2.813 0v-.031H8.5V7.53h-.031V7.5H7.53v.031H7.5v.938h.031V8.5zm.937 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.469v-.031h.5V7.53h-.5V7.5h-.469v.031H15v.938h.031zM0 9.406v.938h1v-.938zm7.5 0v.938h1v-.938zm8.5.938v-.938h-1v.938zm-16 .937v.938h1v-.938zm7.5 0v.938h1v-.938zm8.5.938v-.938h-1v.938zM0 15h16v1H0zm0-2h16v1H0z"/></svg>');--icon-border-all:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M0 0h16v16H0zm1 1v6.5h6.5V1zm7.5 0v6.5H15V1zM15 8.5H8.5V15H15zM7.5 15V8.5H1V15z"/></svg>');--icon-border-outer:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M7.5 1.906v.938h1v-.938zm0 1.875v.938h1V3.78h-1zm0 1.875v.938h1v-.938zM1.906 8.5h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm2.813 0v-.031H8.5V7.53h-.031V7.5H7.53v.031H7.5v.938h.031V8.5zm.937 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zM7.5 9.406v.938h1v-.938zm0 1.875v.938h1v-.938zm0 1.875v.938h1v-.938z"/><path d="M0 0v16h16V0zm1 1h14v14H1z"/></svg>');--icon-border-none:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M0 0h.969v.5H1v.469H.969V1H.5V.969H0zm2.844 1h-.938V0h.938zm1.875 0H3.78V0h.938v1zm1.875 0h-.938V0h.938zm.937 0V.969H7.5V.5h.031V0h.938v.5H8.5v.469h-.031V1zm2.813 0h-.938V0h.938zm1.875 0h-.938V0h.938zm1.875 0h-.938V0h.938zM15.5 1h-.469V.969H15V.5h.031V0H16v.969h-.5zM1 1.906v.938H0v-.938zm6.5.938v-.938h1v.938zm7.5 0v-.938h1v.938zM1 3.78v.938H0V3.78zm6.5.938V3.78h1v.938zm7.5 0V3.78h1v.938zM1 5.656v.938H0v-.938zm6.5.938v-.938h1v.938zm7.5 0v-.938h1v.938zM.969 8.5H.5v-.031H0V7.53h.5V7.5h.469v.031H1v.938H.969zm1.875 0h-.938v-1h.938zm1.875 0H3.78v-1h.938v1zm1.875 0h-.938v-1h.938zm1.875-.031V8.5H7.53v-.031H7.5V7.53h.031V7.5h.938v.031H8.5v.938zm1.875.031h-.938v-1h.938zm1.875 0h-.938v-1h.938zm1.875 0h-.938v-1h.938zm1.406 0h-.469v-.031H15V7.53h.031V7.5h.469v.031h.5v.938h-.5zM0 10.344v-.938h1v.938zm7.5 0v-.938h1v.938zm8.5-.938v.938h-1v-.938zM0 12.22v-.938h1v.938zm7.5 0v-.938h1v.938zm8.5-.938v.938h-1v-.938zM0 14.094v-.938h1v.938zm7.5 0v-.938h1v.938zm8.5-.938v.938h-1v-.938zM.969 16H0v-.969h.5V15h.469v.031H1v.469H.969zm1.875 0h-.938v-1h.938zm1.875 0H3.78v-1h.938v1zm1.875 0h-.938v-1h.938zm.937 0v-.5H7.5v-.469h.031V15h.938v.031H8.5v.469h-.031v.5zm2.813 0h-.938v-1h.938zm1.875 0h-.938v-1h.938zm1.875 0h-.938v-1h.938zm.937 0v-.5H15v-.469h.031V15h.469v.031h.5V16z"/></svg>');--icon-palette:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M0 .5A.5.5 0 0 1 .5 0h5a.5.5 0 0 1 .5.5v5.277l4.147-4.131a.5.5 0 0 1 .707 0l3.535 3.536a.5.5 0 0 1 0 .708L10.261 10H15.5a.5.5 0 0 1 .5.5v5a.5.5 0 0 1-.5.5H3a3 3 0 0 1-2.121-.879A3 3 0 0 1 0 13.044m6-.21 7.328-7.3-2.829-2.828L6 7.188zM4.5 13a1.5 1.5 0 1 0-3 0 1.5 1.5 0 0 0 3 0M15 15v-4H9.258l-4.015 4zM0 .5v12.495zM0 12.995V13z"/></svg>');--icon-layout:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="20" height="20" viewBox="0 0 20 20"><path d="m3 0 17 17.156v-.114z"/><path d="M3 0H0v16h1V1h1.585L19 17.455V19H4v1h16v-2.844z"/><path d="M6.886 3.922 5.343 5.465a.5.5 0 0 0 .708.707l1.539-1.54zM9.702 6.763l-1.53 1.53A.5.5 0 0 0 8.879 9l1.526-1.526zM12.517 9.604 11 11.121a.5.5 0 0 0 .707.707l1.514-1.514zM15.332 12.445l-1.504 1.504a.5.5 0 0 0 .707.707l1.501-1.5zM1 16H0a4 4 0 0 0 4 4v-1c-1.654 0-3-1.346-3-3M5 9v6h6zm1 2.414L8.586 14H6z"/></svg>');--icon-freeze:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M8 16a.5.5 0 0 1-.5-.5v-1.293l-.646.647a.5.5 0 0 1-.707-.708L7.5 12.793V8.866l-3.4 1.963-.496 1.85a.5.5 0 1 1-.966-.26l.237-.882-1.12.646a.5.5 0 0 1-.5-.866l1.12-.646-.884-.237a.5.5 0 1 1 .26-.966l1.848.495L7 8 3.6 6.037l-1.85.495a.5.5 0 0 1-.258-.966l.883-.237-1.12-.646a.5.5 0 1 1 .5-.866l1.12.646-.237-.883a.5.5 0 1 1 .966-.258l.495 1.849L7.5 7.134V3.207L6.147 1.854a.5.5 0 1 1 .707-.708l.646.647V.5a.5.5 0 1 1 1 0v1.293l.647-.647a.5.5 0 1 1 .707.708L8.5 3.207v3.927l3.4-1.963.496-1.85a.5.5 0 1 1 .966.26l-.236.882 1.12-.646a.5.5 0 0 1 .5.866l-1.12.646.883.237a.5.5 0 1 1-.26.966l-1.848-.495L9 8l3.4 1.963 1.849-.495a.5.5 0 0 1 .259.966l-.883.237 1.12.646a.5.5 0 0 1-.5.866l-1.12-.646.236.883a.5.5 0 1 1-.966.258l-.495-1.849-3.4-1.963v3.927l1.353 1.353a.5.5 0 0 1-.707.708l-.647-.647V15.5a.5.5 0 0 1-.5.5z"/></svg>');--icon-column-chart:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="20" height="20" viewBox="0 0 20 20"><path d="M4.5 17.5a.5.5 0 0 1-1 0v-5a.5.5 0 0 1 1 0zM12.5 17.5a.5.5 0 0 1-1 0v-9a.5.5 0 0 1 1 0zM16.5 17.5a.5.5 0 0 1-1 0v-13a.5.5 0 0 1 1 0zM8.5 17.5a.5.5 0 0 1-1 0v-14a.5.5 0 0 1 1 0z"/></svg>');--icon-donut-chart:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="20" height="20" viewBox="0 0 20 20"><path d="M12 1.23v1.548c2.526.701 4.5 2.699 5.203 5.222h1.565A9.01 9.01 0 0 0 12 1.23M2.5 10c0-3.51 2.426-6.456 5.688-7.27V1.183A9 9 0 0 0 1 10c0 1.761.513 3.397 1.387 4.784l1.093-1.093A7.43 7.43 0 0 1 2.5 10M17.221 12c-.878 3.166-3.778 5.5-7.221 5.5a7.45 7.45 0 0 1-3.692-.979l-1.093 1.093A8.96 8.96 0 0 0 10 19c4.282 0 7.859-2.993 8.77-7z"/></svg>');--icon-bar-chart:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="20" height="20" viewBox="0 0 20 20"><path d="M2.5 4.5a.5.5 0 0 1 0-1h5a.5.5 0 0 1 0 1zM2.5 12.5a.5.5 0 0 1 0-1h9a.5.5 0 0 1 0 1zM2.5 16.5a.5.5 0 0 1 0-1h13a.5.5 0 0 1 0 1zM2.5 8.5a.5.5 0 0 1 0-1h14a.5.5 0 0 1 0 1z"/></svg>');--icon-line-chart:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="20" height="20" viewBox="0 0 20 20"><path d="m1 8 3-3 7 5 8-8v2l-8 8-7-5-3 3z"/></svg>');--icon-image:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M6.002 5.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0"/><path d="M2.002 1a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2zm12 1a1 1 0 0 1 1 1v6.5l-3.777-1.947a.5.5 0 0 0-.577.093l-3.71 3.71-2.66-1.772a.5.5 0 0 0-.63.062L1.002 12V3a1 1 0 0 1 1-1z"/></svg>');--icon-recalculate:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="20" height="20" viewBox="0 0 20 20"><path d="M9.478 4.022c2.402-.209 4.583 1.047 5.711 3.014l1.083-.095c-1.233-2.528-3.912-4.175-6.881-3.916-2.97.26-5.321 2.347-6.098 5.051l1.083-.095c.768-2.132 2.698-3.748 5.102-3.959M10.523 15.977c-2.403.211-4.585-1.047-5.712-3.013l-1.08.095c1.234 2.527 3.91 4.175 6.879 3.914 2.971-.259 5.32-2.347 6.095-5.05l-1.08.095c-.769 2.132-2.699 3.749-5.102 3.959"/><path d="m2.272 15.616 5.197-3-4.098-1.097zM17.728 4.384l-5.197 3 4.098 1.098z"/></svg>');--icon-check:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M13.854 3.646a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708 0l-3.5-3.5a.5.5 0 1 1 .708-.708L6.5 10.293l6.646-6.647a.5.5 0 0 1 .708 0"/></svg>');--icon-table:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M0 2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2zm15 2h-4v3h4zm0 4h-4v3h4zm0 4h-4v3h3a1 1 0 0 0 1-1zm-5 3v-3H6v3zm-5 0v-3H1v2a1 1 0 0 0 1 1zm-4-4h4V8H1zm0-4h4V4H1zm5-3v3h4V4zm4 4H6v3h4z"/></svg>')}.treb-main.treb-main .treb-layout-header{overflow:hidden;overflow-x:scroll;position:relative;-ms-overflow-style:none;scrollbar-width:none}.treb-main.treb-main .treb-layout-header::-webkit-scrollbar{display:none}.treb-main.treb-main .treb-toolbar{color:var(--treb-toolbar-color,var(--treb-ui-color,#333));display:flex;flex-direction:row;font-size:var(--treb-toolbar-font-size,inherit);gap:.5rem}.treb-main.treb-main .treb-toolbar>div{display:flex;flex-direction:row}.treb-main.treb-main .treb-toolbar>div>input,.treb-main.treb-main .treb-toolbar>input{background-color:var(--treb-toolbar-button-background,transparent);border:1px solid var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));height:32px;overflow:hidden;padding-left:.5em;padding-right:.5em;text-overflow:ellipsis}.treb-main.treb-main .treb-toolbar>.treb-menu>button{border-radius:3px}.treb-main.treb-main .treb-toolbar>.group>.treb-menu+button,.treb-main.treb-main .treb-toolbar>.group>button+.treb-menu>button,.treb-main.treb-main .treb-toolbar>.group>button+button,.treb-main.treb-main .treb-toolbar>.group>input+.treb-menu>button,.treb-main.treb-main .treb-toolbar>.group>input+button,.treb-main.treb-main .treb-toolbar>[composite]>.treb-menu+button,.treb-main.treb-main .treb-toolbar>[composite]>button+.treb-menu>button,.treb-main.treb-main .treb-toolbar>[composite]>button+button,.treb-main.treb-main .treb-toolbar>[composite]>input+.treb-menu>button,.treb-main.treb-main .treb-toolbar>[composite]>input+button{border-left-width:0}.treb-main.treb-main .treb-toolbar>.group>button:first-child,.treb-main.treb-main .treb-toolbar>.group>input:first-child,.treb-main.treb-main .treb-toolbar>[composite]>button:first-child,.treb-main.treb-main .treb-toolbar>[composite]>input:first-child{border-bottom-left-radius:3px;border-top-left-radius:3px}.treb-main.treb-main .treb-toolbar>.group>.treb-menu:last-child>button,.treb-main.treb-main .treb-toolbar>.group>button:last-child,.treb-main.treb-main .treb-toolbar>[composite]>.treb-menu:last-child>button,.treb-main.treb-main .treb-toolbar>[composite]>button:last-child{border-bottom-right-radius:3px;border-top-right-radius:3px}.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button,.treb-main.treb-main .treb-toolbar .treb-menu>button,.treb-main.treb-main .treb-toolbar button[data-icon],.treb-main.treb-main .treb-toolbar>button,.treb-main.treb-main .treb-toolbar>div>button{align-items:center;background-color:var(--treb-toolbar-button-background,transparent);border:1px solid var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));display:flex;flex-direction:column;height:32px;justify-content:center;position:relative;width:32px}.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button[dropdown],.treb-main.treb-main .treb-toolbar .treb-menu>button[dropdown],.treb-main.treb-main .treb-toolbar button[data-icon][dropdown],.treb-main.treb-main .treb-toolbar>button[dropdown],.treb-main.treb-main .treb-toolbar>div>button[dropdown]{width:16px}.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button[dropdown]:after,.treb-main.treb-main .treb-toolbar .treb-menu>button[dropdown]:after,.treb-main.treb-main .treb-toolbar button[data-icon][dropdown]:after,.treb-main.treb-main .treb-toolbar>button[dropdown]:after,.treb-main.treb-main .treb-toolbar>div>button[dropdown]:after{border:5px solid transparent;border-top-color:currentcolor;box-sizing:content-box;content:"";height:0;left:50%;position:absolute;top:18px;transform:translate(-50%,-50%);width:0}.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button:hover,.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button[active],.treb-main.treb-main .treb-toolbar .treb-menu>button:hover,.treb-main.treb-main .treb-toolbar .treb-menu>button[active],.treb-main.treb-main .treb-toolbar button[data-icon]:hover,.treb-main.treb-main .treb-toolbar button[data-icon][active],.treb-main.treb-main .treb-toolbar>button:hover,.treb-main.treb-main .treb-toolbar>button[active],.treb-main.treb-main .treb-toolbar>div>button:hover,.treb-main.treb-main .treb-toolbar>div>button[active]{background-color:var(--treb-toolbar-hover-button-background,#f3f4f6)}.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button[data-color-bar]:after,.treb-main.treb-main .treb-toolbar .treb-menu>button[data-color-bar]:after,.treb-main.treb-main .treb-toolbar button[data-icon][data-color-bar]:after,.treb-main.treb-main .treb-toolbar>button[data-color-bar]:after,.treb-main.treb-main .treb-toolbar>div>button[data-color-bar]:after{background:var(--treb-color-bar-color,var(--treb-default-color,unset));border:1px solid var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));box-sizing:border-box;content:"";display:block;height:6px;position:relative;width:20px}.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button[data-command]:before,.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button[data-icon]:before,.treb-main.treb-main .treb-toolbar .treb-menu>button[data-command]:before,.treb-main.treb-main .treb-toolbar .treb-menu>button[data-icon]:before,.treb-main.treb-main .treb-toolbar button[data-icon][data-command]:before,.treb-main.treb-main .treb-toolbar button[data-icon][data-icon]:before,.treb-main.treb-main .treb-toolbar>button[data-command]:before,.treb-main.treb-main .treb-toolbar>button[data-icon]:before,.treb-main.treb-main .treb-toolbar>div>button[data-command]:before,.treb-main.treb-main .treb-toolbar>div>button[data-icon]:before{background:currentColor;content:"";display:block;height:20px;mask-image:var(--icon);-webkit-mask-image:var(--icon);mask-position:center;-webkit-mask-position:center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;mask-size:var(--icon-size,16px 16px);-webkit-mask-size:var(--icon-size,16px 16px);position:relative;width:20px}.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button[data-command].treb-font-stack:before,.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button[data-icon].treb-font-stack:before,.treb-main.treb-main .treb-toolbar .treb-menu>button[data-command].treb-font-stack:before,.treb-main.treb-main .treb-toolbar .treb-menu>button[data-icon].treb-font-stack:before,.treb-main.treb-main .treb-toolbar button[data-icon][data-command].treb-font-stack:before,.treb-main.treb-main .treb-toolbar button[data-icon][data-icon].treb-font-stack:before,.treb-main.treb-main .treb-toolbar>button[data-command].treb-font-stack:before,.treb-main.treb-main .treb-toolbar>button[data-icon].treb-font-stack:before,.treb-main.treb-main .treb-toolbar>div>button[data-command].treb-font-stack:before,.treb-main.treb-main .treb-toolbar>div>button[data-icon].treb-font-stack:before{display:none}.treb-main.treb-main .treb-toolbar .treb-split{display:flex;flex-direction:column;gap:0}.treb-main.treb-main .treb-toolbar .treb-split button[data-command]{font-size:10px}.treb-main.treb-main .treb-toolbar .treb-split button[data-command]:before{display:none}.treb-main.treb-main .treb-toolbar .treb-split>button{align-items:center;display:flex;height:16px;justify-content:center}.treb-main.treb-main .treb-toolbar .treb-split>button:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.treb-main.treb-main .treb-toolbar .treb-split>button:last-child{border-bottom-left-radius:3px;border-bottom-right-radius:3px;border-top:0}.treb-main.treb-main .treb-toolbar .treb-font-stack{align-items:flex-start;overflow:hidden;width:8em}.treb-main.treb-main .treb-toolbar .treb-font-stack:before{display:none}.treb-main.treb-main .treb-toolbar .treb-menu{outline:none}.treb-main.treb-main .treb-toolbar .treb-menu>div{background:var(--treb-toolbar-button-background,#fff);border:1px solid var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));border-radius:3px;box-shadow:0 4px 6px -4px rgba(0,0,0,.4);display:none;flex-direction:column;margin-top:.5rem;position:fixed;top:48px;z-index:20}.treb-main.treb-main .treb-toolbar .treb-menu>div button{background:transparent;border:0;margin:3px 0;padding:.4rem 1rem;text-align:left;transition:background-color .125s ease;white-space:nowrap}.treb-main.treb-main .treb-toolbar .treb-menu>div button:hover{background:var(--treb-toolbar-hover-button-background,#f3f4f6)}.treb-main.treb-main .treb-toolbar .treb-menu>div.treb-icon-buttons>.treb-menu>button,.treb-main.treb-main .treb-toolbar .treb-menu>div.treb-icon-buttons>button{padding:0}.treb-main.treb-main .treb-toolbar .treb-menu>div>[separator]{background:var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));height:1px;margin:2px 0}.treb-main.treb-main .treb-toolbar .treb-menu.visible>div,.treb-main.treb-main .treb-toolbar .treb-menu:focus-within>div{display:flex}.treb-main.treb-main .treb-toolbar [data-icon=file-menu]{--icon:var(--icon-file-menu)}.treb-main.treb-main .treb-toolbar [data-command=justify-left]{--icon:var(--icon-text-align-left)}.treb-main.treb-main .treb-toolbar [data-command=justify-right]{--icon:var(--icon-text-align-right)}.treb-main.treb-main .treb-toolbar [data-command=justify-center]{--icon:var(--icon-text-align-center)}.treb-main.treb-main .treb-toolbar [data-command=indent]{--icon:var(--icon-text-indent)}.treb-main.treb-main .treb-toolbar [data-command=outdent]{--icon:var(--icon-text-outdent)}.treb-main.treb-main .treb-toolbar [data-command=align-top]{--icon:var(--icon-text-align-top)}.treb-main.treb-main .treb-toolbar [data-command=align-middle]{--icon:var(--icon-text-align-middle)}.treb-main.treb-main .treb-toolbar [data-command=align-bottom]{--icon:var(--icon-text-align-bottom)}.treb-main.treb-main .treb-toolbar [data-command=merge-cells]{--icon:var(--icon-merge-cells)}.treb-main.treb-main .treb-toolbar [data-command=unmerge-cells]{--icon:var(--icon-unmerge-cells)}.treb-main.treb-main .treb-toolbar [data-command=fill-color]{--icon:var(--icon-fill-color)}.treb-main.treb-main .treb-toolbar [data-command=text-color]{--icon:var(--icon-text-color)}.treb-main.treb-main .treb-toolbar [data-command=lock-cells]{--icon:var(--icon-lock)}.treb-main.treb-main .treb-toolbar [data-command=wrap-text]{--icon:var(--icon-wrap-text)}.treb-main.treb-main .treb-toolbar [data-icon=comment]{--icon:var(--icon-comment)}.treb-main.treb-main .treb-toolbar [data-icon=table]{--icon:var(--icon-table)}.treb-main.treb-main .treb-toolbar [data-icon=layout]{--icon:var(--icon-layout)}.treb-main.treb-main .treb-toolbar [data-command=freeze-panes]{--icon:var(--icon-freeze)}.treb-main.treb-main .treb-toolbar [data-command=insert-column-chart]{--icon:var(--icon-column-chart)}.treb-main.treb-main .treb-toolbar [data-command=insert-donut-chart]{--icon:var(--icon-donut-chart)}.treb-main.treb-main .treb-toolbar [data-command=insert-bar-chart]{--icon:var(--icon-bar-chart)}.treb-main.treb-main .treb-toolbar [data-command=insert-line-chart]{--icon:var(--icon-line-chart)}.treb-main.treb-main .treb-toolbar [data-command=insert-image]{--icon:var(--icon-image)}.treb-main.treb-main .treb-toolbar [data-command=border-bottom]{--icon:var(--icon-border-bottom)}.treb-main.treb-main .treb-toolbar [data-command=border-left]{--icon:var(--icon-border-left)}.treb-main.treb-main .treb-toolbar [data-command=border-right]{--icon:var(--icon-border-right)}.treb-main.treb-main .treb-toolbar [data-command=border-top]{--icon:var(--icon-border-top)}.treb-main.treb-main .treb-toolbar [data-command=border-outside]{--icon:var(--icon-border-outer)}.treb-main.treb-main .treb-toolbar [data-command=border-all]{--icon:var(--icon-border-all)}.treb-main.treb-main .treb-toolbar [data-command=border-none]{--icon:var(--icon-border-none)}.treb-main.treb-main .treb-toolbar [data-command=border-double-bottom]{--icon:var(--icon-border-double-bottom)}.treb-main.treb-main .treb-toolbar [data-icon=palette]{--icon:var(--icon-palette)}.treb-main.treb-main .treb-toolbar [data-command=recalculate]{--icon:var(--icon-recalculate);--icon-size:20px 20px}.treb-main.treb-main .treb-toolbar .treb-font-scale{width:4em}.treb-main.treb-main .treb-toolbar .treb-number-format{width:8em}.treb-main.treb-main .treb-toolbar .treb-color-chooser button[data-command=set-color]{align-items:center;display:flex;justify-content:center;padding:0;width:32px}.treb-main.treb-main .treb-toolbar .treb-color-chooser button[data-command=set-color]>svg{pointer-events:none}.treb-main.treb-main .treb-toolbar .treb-color-chooser>div{padding:.75rem}.treb-main.treb-main .treb-toolbar .treb-color-chooser>div+div{padding-top:0}.treb-main.treb-main .treb-toolbar .treb-color-chooser>div:last-child{align-items:center;display:flex;flex-direction:row;gap:.5rem}.treb-main.treb-main .treb-toolbar .treb-color-chooser>div:last-child input{flex-grow:1;padding:0 .5rem}.treb-main.treb-main .treb-toolbar .treb-color-chooser>div:last-child button,.treb-main.treb-main .treb-toolbar .treb-color-chooser>div:last-child input{border:1px solid var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));border-radius:3px;height:32px}.treb-main.treb-main .treb-toolbar .treb-color-chooser .treb-default-swatch button,.treb-main.treb-main .treb-toolbar .treb-color-chooser .treb-swatches button{border:1px solid var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));border-radius:2px;height:18px;margin:0;padding:0;width:18px}.treb-main.treb-main .treb-toolbar .treb-color-chooser .treb-default-swatch .treb-default-color:before,.treb-main.treb-main .treb-toolbar .treb-color-chooser .treb-swatches .treb-default-color:before{background:currentColor;content:"";display:block;height:100%;mask-image:var(--icon-x);-webkit-mask-image:var(--icon-x);mask-position:center;-webkit-mask-position:center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;mask-size:24px 24px;-webkit-mask-size:24px 24px;opacity:.7;position:relative;width:100%}.treb-main.treb-main .treb-toolbar .treb-color-chooser .treb-default-swatch{align-items:center;display:grid;gap:.5rem;grid-template-columns:auto 1fr}.treb-main.treb-main .treb-toolbar .treb-color-chooser .treb-swatches{display:grid;gap:.5rem;grid-template-columns:repeat(10,1fr)}.treb-main.treb-main .treb-toolbar .treb-comment-box textarea{border:1px solid var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));font:inherit;height:10rem;line-height:1.5;margin:.5rem;padding:.25rem;resize:both}.treb-main.treb-main .treb-toolbar .treb-comment-box textarea+div{align-items:center;display:flex;flex-direction:row;gap:.5rem;justify-content:center;padding:0 0 .5rem}.treb-main.treb-main .treb-toolbar .treb-comment-box textarea+div button{border:1px solid var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));border-radius:3px}.treb-main.treb-main .treb-toolbar .treb-font-scale{padding-left:2em;text-align:right;width:5em}.treb-main.treb-main .treb-toolbar [composite][font-scale]{position:relative}.treb-main.treb-main .treb-toolbar .treb-font-scale-icon{border-radius:3px;left:.5em;line-height:1;opacity:.9;pointer-events:none;position:absolute;top:50%;transform:translateY(-50%)}.treb-main.treb-main .treb-toolbar .treb-font-scale-icon:after,.treb-main.treb-main .treb-toolbar .treb-font-scale-icon:before{content:"A";position:relative}.treb-main.treb-main .treb-toolbar .treb-font-scale-icon:before{font-size:1.2em}.treb-main.treb-main .treb-toolbar .treb-font-scale-icon:after{font-size:.9em;left:-.125em}.treb-main.treb-main{--treb-font-stack-default-size:14px;--treb-font-stack-calibri-size:16px;--treb-font-stack-tscu-comic-size:16px;--treb-font-stack-helvetica-neue-size:13px;--treb-font-stack-cambria-size:16px;--treb-font-stack-sitka-text-variant:lining-nums tabular-nums}.treb-main.treb-main.treb-ua-osx{--treb-font-stack-system-ui-size:10pt}.treb-main.treb-main .treb-font-stack-default{font-family:calibri,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen-Sans,Ubuntu,Cantarell,Helvetica Neue,"sans-serif"}.treb-main.treb-main .treb-font-stack-transitional{font-family:Charter,Bitstream Charter,Cambria,serif}.treb-main.treb-main .treb-font-stack-old-style{font-family:Iowan Old Style,Palatino Linotype,URW Palladio L,P052,serif}.treb-main.treb-main .treb-font-stack-handwritten{font-family:Segoe Print,Bradley Hand,Chilanka,TSCu_Comic,casual,cursive}.treb-main.treb-main .treb-font-stack-industrial{font-family:Bahnschrift,DIN Alternate,Franklin Gothic Medium,Nimbus Sans Narrow,sans-serif-condensed,sans-serif}.treb-main.treb-main .treb-font-stack-monospace{font-family:ui-monospace,Cascadia Code,Source Code Pro,Menlo,Consolas,DejaVu Sans Mono,monospace}.treb-main.treb-main .treb-font-stack-ui{font-family:system-ui,sans-serif}.treb-main.treb-main{all:revert;box-sizing:border-box;color:inherit;color-scheme:var(--treb-color-scheme,unset);display:grid;font-family:var(--treb-default-font,system-ui,"BlinkMacSystemFont","Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue","sans-serif");font-family:BlinkMacSystemFont,Segoe UI,Roboto,Oxygen-Sans,Ubuntu,Cantarell,Helvetica Neue,"sans-serif";font-size:14px;font-style:normal;font-weight:400;grid-template-columns:minmax(0,1fr) auto;grid-template-rows:auto minmax(0,1fr);height:100%;line-height:normal;position:relative;text-align:start;width:100%}.treb-main.treb-main a,.treb-main.treb-main button,.treb-main.treb-main div,.treb-main.treb-main input,.treb-main.treb-main li,.treb-main.treb-main ol,.treb-main.treb-main svg,.treb-main.treb-main textarea,.treb-main.treb-main ul{all:revert;box-sizing:border-box;font-family:var(--treb-default-font,system-ui,"BlinkMacSystemFont","Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue","sans-serif")}.treb-main.treb-main button,.treb-main.treb-main input{color:inherit;font:inherit}.treb-main.treb-main *{box-sizing:border-box}.treb-main.treb-main [contenteditable]{-webkit-user-modify:read-write;-moz-user-modify:read-write}.treb-main.treb-main[animate] .treb-layout-header{transition:height var(--treb-sidebar-transition,.2s ease),opacity var(--treb-sidebar-transition,.2s ease)}.treb-main.treb-main .treb-layout-header{grid-column:1/3;grid-row:1;height:1px;opacity:0}.treb-main.treb-main[toolbar] .treb-layout-header{height:42px;opacity:1}.treb-main.treb-main[dialog] .treb-layout-header,.treb-main.treb-main[dialog]>*{opacity:.6}.treb-main.treb-main[dialog] .treb-dialog-mask{opacity:1;pointer-events:auto}.treb-main.treb-main .treb-layout-spreadsheet{display:flex;flex-direction:row;gap:1em;grid-column:1;grid-row:2;position:relative;transition:opacity .2s ease;z-index:5}.treb-main.treb-main .treb-views.treb-can-revert .treb-view .treb-revert-indicator{opacity:1;pointer-events:auto}.treb-main.treb-main .treb-view{display:grid;flex:1 1 0px;grid-template-columns:minmax(0,1fr);grid-template-rows:auto minmax(0,1fr) auto;position:relative}.treb-main.treb-main .treb-view .treb-spreadsheet-backdrop{box-shadow:0 4px 6px -4px rgba(0,0,0,.4);grid-column:1;grid-row:2;z-index:2}.treb-main.treb-main .treb-view .treb-spreadsheet-body{position:relative;z-index:4}.treb-main.treb-main .treb-view .treb-spreadsheet-footer{position:relative;z-index:5}.treb-main.treb-main .treb-view .treb-layout-resize-handle,.treb-main.treb-main .treb-view .treb-revert-indicator{display:none}.treb-main.treb-main .treb-view:first-of-type .treb-revert-indicator{align-self:start;border-color:orange transparent transparent orange;border-style:solid;border-width:.5em;display:block;grid-area:2/1/3/2;height:1rem;justify-self:start;opacity:0;overflow:hidden;pointer-events:none;position:relative;transition:opacity .125s ease;width:1rem;z-index:20}.treb-main.treb-main .treb-view:last-of-type .treb-layout-resize-handle{align-self:end;border-bottom:.5rem solid var(--treb-resize-handle-color,#0059b9);border-left:.5rem solid transparent;border-right:.5rem solid var(--treb-resize-handle-color,#0059b9);border-top:.5rem solid transparent;cursor:nw-resize;display:block;grid-area:2/1/3/2;height:1rem;justify-self:end;width:1rem;z-index:20}.treb-main.treb-main[animate] .treb-layout-sidebar{transition:width var(--treb-sidebar-transition,.2s ease),opacity var(--treb-sidebar-transition,.2s ease)}.treb-main.treb-main .treb-layout-sidebar{align-items:center;display:flex;flex-direction:column;gap:.75rem;grid-column:2;grid-row:2;justify-content:flex-start;overflow:hidden;padding-top:3rem;width:2.5rem;width:3rem}.treb-main.treb-main[collapsed] .treb-layout-sidebar{opacity:0;width:0}.treb-main.treb-main[collapsed] .treb-toggle-sidebar-button{background:var(--treb-toolbar-button-background,#fff);border-bottom-right-radius:0;border-color:var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));border-right-color:var(--treb-toolbar-button-background,transparent);border-top-right-radius:0;right:0}.treb-main.treb-main[collapsed] .treb-toggle-sidebar-button:after{mask-image:var(--icon-chevron-left);-webkit-mask-image:var(--icon-chevron-left)}.treb-main.treb-main .treb-layout-sidebar>button,.treb-main.treb-main .treb-toggle-sidebar-button{background:transparent;border:0;margin:0;padding:0}.treb-main.treb-main .treb-layout-sidebar>button:after,.treb-main.treb-main .treb-toggle-sidebar-button:after{background:#ccc;content:"";display:block;height:24px;mask-image:var(--icon);-webkit-mask-image:var(--icon);mask-position:center;-webkit-mask-position:center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;transition:background-color .1s ease;width:24px}.treb-main.treb-main .treb-layout-sidebar>button[data-can-revert=false],.treb-main.treb-main .treb-toggle-sidebar-button[data-can-revert=false]{display:none}.treb-main.treb-main .treb-layout-sidebar>button:hover:after,.treb-main.treb-main .treb-toggle-sidebar-button:hover:after{background:#666}.treb-main.treb-main .treb-layout-sidebar>button[data-command=recalculate],.treb-main.treb-main .treb-toggle-sidebar-button[data-command=recalculate]{--icon:var(--icon-reset)}.treb-main.treb-main .treb-layout-sidebar>button[data-command=toggle-toolbar],.treb-main.treb-main .treb-toggle-sidebar-button[data-command=toggle-toolbar]{--icon:var(--icon-toolbar)}.treb-main.treb-main .treb-layout-sidebar>button[data-command=revert],.treb-main.treb-main .treb-toggle-sidebar-button[data-command=revert]{--icon:var(--icon-revert)}.treb-main.treb-main .treb-layout-sidebar>button[data-command=export-xlsx],.treb-main.treb-main .treb-toggle-sidebar-button[data-command=export-xlsx]{--icon:var(--icon-export)}.treb-main.treb-main .treb-layout-sidebar>button[data-command=about],.treb-main.treb-main .treb-toggle-sidebar-button[data-command=about]{--icon:var(--icon-about)}.treb-main.treb-main .treb-toggle-sidebar-button{align-items:center;background:transparent;border:1px solid transparent;border-radius:12px;bottom:6rem;display:flex;height:24px;justify-content:center;margin:0;padding:0;position:absolute;right:.5rem;right:calc(1.5rem - 12px);width:24px;z-index:39}.treb-main.treb-main .treb-toggle-sidebar-button:after{height:12px;mask-image:var(--icon-chevron-right);-webkit-mask-image:var(--icon-chevron-right);width:12px}.treb-main.treb-main .treb-resize-rect{border:1px dotted var(--treb-resize-frame-color,blue);display:block;height:100%;left:0;position:fixed;top:0;width:100%;z-index:9998}.treb-main.treb-main .treb-resize-mask{height:100vh;left:0;position:fixed;top:0;width:100vw;z-index:9999}treb-spreadsheet{display:block;overflow:hidden;position:relative}.treb-default-size{height:550px;width:800px}`;var oo='<div class="treb-main treb-theme"><div class="treb-layout-header treb-animate"><div class="treb-toolbar"></div></div><div class="treb-dialog-mask"><div data-bind="dialog" class="treb-embed-dialog"><div data-bind="left"><a href="https://treb.app" target="_blank"><div class="treb-icon-64"></div></a></div><div data-bind="middle"><div data-bind="title" class="treb-embed-dialog-title"></div><div data-bind="message" class="treb-embed-dialog-message"></div><div data-bind="about" class="treb-embed-dialog-body"></div></div><button type="button" data-title="close_dialog" data-bind="close" class="treb-close-box"><svg viewBox="0 0 16 16"><path d="M11.854 4.146a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708-.708l7-7a.5.5 0 0 1 .708 0z"/><path d="M4.146 4.146a.5.5 0 0 0 0 .708l7 7a.5.5 0 0 0 .708-.708l-7-7a.5.5 0 0 0-.708 0z"/></svg></button></div></div><div class="treb-layout-spreadsheet treb-views"><template class="treb-view-template"><div class="treb-view"><div class="treb-formula-bar notranslate" hidden><div class="treb-address-label"><div></div></div><button class="treb-insert-function-button" data-title="insert_function" data-conditional="insert-function">\u{1D453}<small>(x)</small></button><div class="treb-editor-container"><div contenteditable="true"></div></div></div><div class="treb-spreadsheet-backdrop"></div><div class="treb-spreadsheet-body" role="grid"><div class="treb-grid" tabindex="-1"><div class="treb-overlay-container notranslate" translate="no"><div class="treb-overlay-inset"><div class="treb-overlay-editor" contenteditable tabindex="-1" spellcheck="true" role="gridcell"></div></div></div></div></div><div class="treb-spreadsheet-footer" hidden><button class="treb-delete-tab" data-title="delete_sheet" data-command="delete-tab" data-conditional="delete-tab"><svg tabindex="-1" viewbox="0 0 16 16"><path d="M4,4 L12,12 M12,4 L4,12"/></svg></button><div class="treb-spreadsheet-tab-container"><ol class="treb-spreadsheet-tabs" role="tablist"></ol></div><button class="treb-add-tab" data-command="add-tab" data-conditional="add-tab" data-title="add_sheet">+</button><div class="treb-stats-panel"></div><div class="treb-scale-control" data-conditional="scale-control"></div></div><div class="treb-layout-resize-handle" data-conditional="resize"></div><div class="treb-revert-indicator" data-command="revert-indicator" data-title="document_modified"></div></div></template></div><div class="treb-layout-sidebar treb-animate"><button data-command="recalculate" data-title="recalculate"></button> <button data-command="toggle-toolbar" data-conditional="toolbar" data-title="toggle_toolbar"></button> <button data-command="export-xlsx" data-conditional="export" data-title="export"></button> <button data-command="revert" data-conditional="revert" data-title="revert"></button> <button data-command="about" data-title="about"></button></div><button class="treb-toggle-sidebar-button" data-title="toggle_sidebar"></button></div>';var ao='<div class="treb-menu" title="File menu" file-menu><button data-icon="file-menu" menu-target></button><div><button data-command="reset">New document</button><div separator></div><button data-command="import-file">Open file...</button> <button data-command="save-json">Save JSON</button><div separator xlsx-support></div><button data-command="export-xlsx" xlsx-support>Export XLSX</button></div></div><div composite narrow><button data-command="justify-left" data-target="justify" title="Left-align text"></button><div class="treb-menu"><button dropdown title="Text justify options"></button><div class="treb-icon-buttons" data-replace="justify"><button data-command="justify-left" title="Left-align text"></button> <button data-command="justify-center" title="Center-align text"></button> <button data-command="justify-right" title="Right-align text"></button></div></div></div><div composite narrow><button data-command="align-top" data-target="align" title="Align to top"></button><div class="treb-menu"><button dropdown title="Text align options"></button><div class="treb-icon-buttons" data-replace="align"><button data-command="align-top" title="Align to top"></button> <button data-command="align-middle" title="Align to middle"></button> <button data-command="align-bottom" title="Align to bottom"></button></div></div></div><div class="group" wide><button data-command="justify-left" title="Left-align text"></button> <button data-command="justify-center" title="Center-align text"></button> <button data-command="justify-right" title="Right-align text"></button></div><div class="group" wide><button data-command="align-top" title="Align to top"></button> <button data-command="align-middle" title="Align to middle"></button> <button data-command="align-bottom" title="Align to bottom"></button></div><div class="group" wide indent-group><button data-command="outdent" title="Decrease indent"></button> <button data-command="indent" title="Incrase indent"></button></div><div class="group"><button data-command="wrap-text" title="Wrap text"></button> <button data-command="merge-cells" data-id="merge" data-inactive-title="Merge cells" data-active-title="Unmerge cells"></button> <button data-command="lock-cells" data-inactive-title="Lock cells" data-active-title="Unlock cells"></button> <button data-command="freeze-panes" data-inactive-title="Freeze panes" data-active-title="Unfreeze panes" freeze-button></button> <button data-command="insert-table" data-icon="table" data-inactive-title="Insert table" data-active-title="Remove table" table-button></button><div class="treb-menu"><button data-icon="comment" data-inactive-title="Comment" data-active-title="Update comment"></button><div class="treb-comment-box"><textarea></textarea><div><button data-command="clear-comment">Clear</button> <button data-command="update-comment">Save</button></div></div></div></div><div composite><button data-command="border-bottom" data-target="border" title="Bottom border"></button><div class="treb-menu"><button dropdown title="Border options"></button><div class="treb-icon-buttons" data-replace="border"><button data-command="border-top" title="Top border"></button> <button data-command="border-left" title="Left border"></button> <button data-command="border-right" title="Right border"></button> <button data-command="border-bottom" title="Bottom border"></button> <button data-command="border-double-bottom" title="Double bottom border"></button> <button data-command="border-outside" title="Outside borders"></button> <button data-command="border-all" title="All borders"></button> <button data-command="border-none" title="Clear borders"></button><div separator></div><div class="treb-menu treb-color-menu treb-submenu" data-color-command="border-color" data-replace-color="border" title="Border color" data-default-color-text="Default border color"><button data-icon="palette" data-color-bar="border" data-color="{}"></button></div></div></div></div><div composite><button data-command="fill-color" data-color-bar="fill" data-color="{}" title="Fill color"></button><div class="treb-menu treb-color-menu" data-color-command="fill-color" data-replace-color="fill" data-default-color-text="No fill"><button dropdown title="Color options"></button><div class="treb-color-chooser"><div class="treb-caption">Theme colors</div><div class="treb-swatches"></div><div class="treb-caption">No color</div><div class="treb-default-swatch"><button class="treb-default-color" data-command="set-color" data-color="{}"></button> <span class="treb-default-color-label" data-command="set-color" data-color="{}">...</span></div><div class="treb-caption">Other colors</div><div class="treb-swatches"></div><div><input placeholder="New color" class="treb-color-input"> <button data-command="set-color" data-color=""><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 16 16"><path d="M13.854 3.646a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708 0l-3.5-3.5a.5.5 0 1 1 .708-.708L6.5 10.293l6.646-6.647a.5.5 0 0 1 .708 0z"/></svg></button></div></div></div></div><div composite><button data-command="text-color" data-color-bar="text" data-color="{}" title="Text color"></button><div class="treb-menu treb-color-menu" data-color-command="text-color" data-replace-color="text" data-default-color-text="Default text color"><button dropdown title="Color options"></button></div></div><div composite font-scale><div class="treb-font-scale-icon"></div><input class="treb-font-scale" title="Font scale"><div class="treb-menu"><button dropdown title="Font scale options"></button><div><button data-command="font-scale" data-scale="0.8">0.80</button> <button data-command="font-scale" data-scale="0.9">0.90</button> <button data-command="font-scale" data-scale="1.0">1.00</button> <button data-command="font-scale" data-scale="1.1">1.10</button> <button data-command="font-scale" data-scale="1.25">1.25</button> <button data-command="font-scale" data-scale="1.5">1.50</button> <button data-command="font-scale" data-scale="2.0">2.00</button></div></div></div><div composite font-stack><button class="treb-font-stack" data-command="font-stack" data-font-stack="" title="Font stack"></button><div class="treb-menu"><button dropdown title="Font stack options"></button><div><button data-command="font-stack" data-font-stack="default"></button> <button data-command="font-stack" data-font-stack="transitional"></button> <button data-command="font-stack" data-font-stack="monospace"></button> <button data-command="font-stack" data-font-stack="handwritten"></button> <button data-command="font-stack" data-font-stack="ui"></button></div></div></div><div composite><input class="treb-number-format" title="Number format"><div class="treb-menu"><button dropdown title="Number formats"></button><div class="treb-number-format-menu"></div></div></div><div class="treb-split"><button data-command="decrease-precision" title="Decrease precision"></button> <button data-command="increase-precision" title="Increase precision"></button></div><div class="treb-menu"><button data-icon="layout" title="Rows & columns"></button><div><button data-command="insert-row">Insert row</button> <button data-command="insert-column">Insert column</button> <button data-command="delete-row">Delete row</button> <button data-command="delete-column">Delete column</button><div separator add-remove-sheet></div><button data-command="insert-sheet" add-remove-sheet>Add sheet</button> <button data-command="delete-sheet" add-remove-sheet>Delete sheet</button></div></div><div composite chart-menu><button data-command="insert-column-chart" data-target="annotation" title="Insert column chart"></button><div class="treb-menu"><button dropdown title="Chart options"></button><div class="treb-icon-buttons" data-replace="annotation"><button data-command="insert-column-chart" title="Insert column chart"></button> <button data-command="insert-donut-chart" title="Insert donut chart"></button> <button data-command="insert-bar-chart" title="Insert bar chart"></button> <button data-command="insert-line-chart" title="Insert line chart"></button><div separator></div><button data-command="insert-image" title="Insert image"></button></div></div></div><button data-command="recalculate" title="Recalculate" recalculate-button></button>';var so={close_dialog:"Close dialog",insert_function:"Insert function...",delete_sheet:"Delete current sheet",add_sheet:"Add sheet",document_modified:"This document has been modified from the original version.",recalculate:"Recalculate",toggle_toolbar:"Toggle toolbar",export:"Export as XLSX",revert:"Revert to original version",about:"What's this?",toggle_sidebar:"Toggle sidebar"},nt=class{root;sheet;border_color;color_bar_elements={};replace_targets={};layout_element;views;revert_button;revert_state=!1;toolbar_controls={};swatch_lists={};DOM;constructor(e){typeof e=="string"&&(e=document.querySelector(e)),this.DOM=O.GetInstance(e?.ownerDocument),this.DOM.view&&e instanceof this.DOM.view.HTMLElement&&(this.root=e,this.DOM.doc?.head.querySelector("style[treb-stylesheet]")||this.DOM.doc?.head.prepend(this.DOM.Create("style",void 0,void 0,{text:no,attrs:{"treb-stylesheet":""}})))}CoerceAttributeValue(e){if(e===null||e.toString().toLowerCase()==="true"||e==="")return!0;if(e.toLowerCase()==="false")return!1;{let t=Number(e);if(!isNaN(t))return t}return e||""}ParseOptionAttributes(){let e={};if(this.root){let t=this.root.getAttributeNames();for(let r of t){switch(r){case"class":case"style":case"id":continue;case"data-options":case"options":{let n=(this.root.getAttribute(r)||"").split(",");for(let o of n){let a=o.split(/=/);a.length===1?e[a[0]]=!0:e[a[0]]=this.CoerceAttributeValue(a[1])}}continue;case"data-treb":continue;case"inline-document":continue;case"src":e.document=this.root.getAttribute("src")||void 0;continue}e[r.replace(/-/g,"_")]=this.CoerceAttributeValue(this.root.getAttribute(r))}}return{...e}}AttachElement(e={}){if(e={...this.ParseOptionAttributes(),...e},this.root){if(!e.headless){let t=this.root.getBoundingClientRect();(!t.width||!t.height)&&this.root.classList.add("treb-default-size")}if(this.root.hasAttribute("inline-document")){let t=this.root.getAttribute("inline-document")||"";for(let r of Array.from(this.root.children))if(this.DOM.view&&r instanceof this.DOM.view.HTMLScriptElement&&r.type==="application/json"){let i=r.getAttribute("name")||"";if(i===t||!i&&t==="true"){let n=r.textContent;if(n)try{e.inline_document=JSON.parse(n)}catch(o){console.error(o)}break}}e.inline_document||console.warn("inline document failed")}this.root.innerHTML=oo,e.container=this.root.querySelector(".treb-layout-spreadsheet")}this.sheet=new xr(e),this.root&&this.CreateLayout(this.sheet,this.root)}CreateLayout(e,t){new ResizeObserver(()=>e.Resize()).observe(t),this.layout_element=t.querySelector(".treb-main");let i=t.querySelector(".treb-toggle-sidebar-button");if(i&&this.layout_element){let c=this.layout_element;i.addEventListener("click",()=>{let d=c.getAttribute("collapsed");typeof d=="string"&&(d===""||d==="true")?c.removeAttribute("collapsed"):c.setAttribute("collapsed","")})}(e.options.toolbar==="show"||e.options.toolbar==="show-narrow")&&this.layout_element?.setAttribute("toolbar",""),e.options.collapsed&&this.layout_element?.setAttribute("collapsed","");let n=t.querySelector("[data-command=revert-indicator]");this.DOM.view&&n instanceof this.DOM.view.HTMLElement&&(e.options.revert_indicator?n.addEventListener("click",()=>{e.HandleToolbarMessage({command:"revert-indicator"})}):n.style.display="none"),t.querySelector(".treb-layout-sidebar")?.addEventListener("click",c=>{let d=c.target;if(d.dataset.command)switch(d.dataset.command){case"toggle-toolbar":this.ToggleToolbar();break;default:e.HandleToolbarMessage({command:d.dataset.command});break}}),e.options.toolbar&&this.AttachToolbar(e,t);let a={"table-button":!!e.options.table_button,revert:!!e.options.revert_button,toolbar:!!e.options.toolbar,export:!!e.options.export,"insert-function":!!e.options.insert_function_button,resize:!!e.options.resizable,"add-tab":!!e.options.add_tab,"delete-tab":!!e.options.delete_tab||!!e.options.add_tab};for(let[c,d]of Object.entries(a))if(!d){let u=this.layout_element.querySelectorAll(`[data-conditional=${c}]`);for(let h of Array.from(u))h.style.display="none"}if(e.options.revert_button&&(this.revert_button=this.layout_element.querySelector("[data-command=revert]")||void 0),e.options.resizable){let c={width:0,height:0},d={x:0,y:0},u={x:0,y:0};this.views=t.querySelector(".treb-views")||void 0;let h,f,m=t.querySelector(".treb-layout-resize-handle"),p=()=>g(),b=x=>{x.buttons===0?g():(u.x=x.screenX-d.x,u.y=x.screenY-d.y,f&&(f.style.width=c.width+u.x+"px",f.style.height=c.height+u.y+"px"))},g=()=>{if(u.x||u.y){let x=t.getBoundingClientRect();e.options.constrain_width||(t.style.width=x.width+u.x+"px"),t.style.height=x.height+u.y+"px"}h&&(h.removeEventListener("mouseup",p),h.removeEventListener("mousemove",b),h.parentElement?.removeChild(h),h=void 0),f?.parentElement?.removeChild(f),f=void 0};m.addEventListener("mousedown",x=>{x.stopPropagation(),x.preventDefault();let y=t.querySelector(".treb-main");f=this.DOM.Div("treb-resize-rect",y),h=this.DOM.Div("treb-resize-mask",y,{attrs:{style:"cursor: nw-resize;"},events:{mouseup:p,mousemove:b}}),d.x=x.screenX,d.y=x.screenY,u.x=0,u.y=0;let w=this.views?.querySelectorAll(".treb-spreadsheet-body"),_=Array.from(w||[]).map(C=>C.getBoundingClientRect());if(_.length){let C=JSON.parse(JSON.stringify(_.shift()));for(let E of _)C.top=Math.min(E.top,C.top),C.left=Math.min(E.left,C.left),C.right=Math.max(E.right,C.right),C.bottom=Math.max(E.bottom,C.bottom);let S=C.right-C.left,A=C.bottom-C.top;f.style.top=C.top+"px",f.style.left=C.left+"px",f.style.width=S+"px",f.style.height=A+"px",c.width=S,c.height=A}})}let s=Array.from(this.layout_element.querySelectorAll("[data-title]"));for(let c of s)if(c instanceof HTMLElement){if(c.dataset.activeTitle)continue;c.dataset.title&&so[c.dataset.title]&&(c.title=so[c.dataset.title])}setTimeout(()=>this.layout_element?.setAttribute("animate",""),250)}ToggleToolbar(){if(this.layout_element){let e=this.layout_element.getAttribute("toolbar");typeof e=="string"&&(e===""||e==="true")?this.layout_element.removeAttribute("toolbar"):this.layout_element.setAttribute("toolbar","")}}UpdateSelectionStyle(e,t,r){let i=e.selection_state;r.value="";for(let s of Object.values(this.toolbar_controls))s&&(s.removeAttribute("active"),s.dataset.inactiveTitle&&(s.title=s.dataset.inactiveTitle));let n=s=>{s&&(s.setAttribute("active",""),s.dataset.activeTitle&&(s.title=s.dataset.activeTitle))};if(i.comment&&(n(this.toolbar_controls.comment),r.value=i.comment),i.style?.locked&&n(this.toolbar_controls.locked),i.frozen&&n(this.toolbar_controls.freeze),i.style?.wrap&&n(this.toolbar_controls.wrap),this.toolbar_controls.table&&(i.table?(n(this.toolbar_controls.table),this.toolbar_controls.table.dataset.command="remove-table"):this.toolbar_controls.table.dataset.command="insert-table"),this.toolbar_controls.merge&&(i.merge?(n(this.toolbar_controls.merge),this.toolbar_controls.merge.dataset.command="unmerge-cells"):this.toolbar_controls.merge.dataset.command="merge-cells"),this.toolbar_controls.stack)if(i.style?.font_face)if(i.style.font_face.startsWith("stack:")){let s=i.style.font_face.substring(6);this.toolbar_controls.stack.textContent=qt[s]||"",this.toolbar_controls.stack.dataset.fontStack=s}else this.toolbar_controls.stack.textContent="",this.toolbar_controls.stack.dataset.fontStack="";else this.toolbar_controls.stack.textContent=qt.default||"",this.toolbar_controls.stack.dataset.fontStack="default";let o=this.toolbar_controls.format;o&&(i.style?.number_format?o.value=L.SymbolicName(i.style.number_format)||i.style.number_format:o.value="General");let a=this.toolbar_controls.scale;switch(a&&(a.value=e.FormatNumber(i.relative_font_size||1,"0.00")),i.style?.horizontal_align){case"left":n(this.toolbar_controls.left);break;case"center":n(this.toolbar_controls.center);break;case"right":n(this.toolbar_controls.right);break}switch(i.style?.vertical_align){case"top":n(this.toolbar_controls.top);break;case"middle":n(this.toolbar_controls.middle);break;case"bottom":n(this.toolbar_controls.bottom);break}}UpdateDocumentStyles(e,t){{let a=this.DOM.Fragment(),s=e.document_styles.theme_colors.length,c=["Background","Text","Background","Text","Accent"];if(s){let f=e.document_styles.theme_colors[0].length;for(let m=0;m<f;m++)for(let p=0;p<s;p++){let b=e.document_styles.theme_colors[p][m],g=`background: ${b.resolved};`,x=c[p]||c[4];Ke(b.color)&&b.color.tint?x+=` (${(b.color.tint>0?"+":"")+b.color.tint*100}%)`:p===0?this.color_bar_elements.fill?.style.setProperty("--treb-default-color",b.resolved):p===1&&(this.color_bar_elements.text?.style.setProperty("--treb-default-color",b.resolved),this.color_bar_elements.border?.style.setProperty("--treb-default-color",b.resolved)),this.DOM.Create("button",void 0,a,{attrs:{style:g,title:x},data:{command:"set-color",color:JSON.stringify(b.color)}})}}this.swatch_lists.theme?.replaceChildren(a),a=this.DOM.Fragment();let d=["Black","White","Gray","Red","Orange","Yellow","Green","Blue","Indigo","Violet"],u=d.map(f=>f.toLowerCase()),h=e.document_styles.colors.filter(f=>!u.includes(f.toLowerCase()));for(let f of[...d,...h]){let m=`background: ${f.toLowerCase()};`;this.DOM.Create("button",void 0,a,{attrs:{style:m,title:f},data:{command:"set-color",color:JSON.stringify({text:f.toLowerCase()})}})}this.swatch_lists.other?.replaceChildren(a)}let r=["General","Number","Integer","Percent","Fraction","Accounting","Currency","Scientific"],i=["Timestamp","Long Date","Short Date"];for(let a of e.document_styles.number_formats){if(L.SymbolicName(L.Translate(a)))continue;L.Get(a).date_format?i.push(a):r.push(a)}let n=a=>this.DOM.Create("button",void 0,void 0,{text:a,data:{format:a,command:"number-format"}}),o=this.DOM.Fragment();o.append(...r.map(a=>n(a))),o.append(this.DOM.Div(void 0,void 0,{attrs:{separator:""}})),o.append(...i.map(a=>n(a))),t.textContent="",t.append(o)}UpdateRevertState(e){let t=e.can_revert;this.revert_state!==t&&(this.revert_state=t,(this.revert_button||e.options.revert_indicator)&&(this.revert_state?this.views?.classList.add("treb-can-revert"):this.views?.classList.remove("treb-can-revert"),this.revert_button&&(this.revert_button.dataset.canRevert=t?"true":"false",t?(this.revert_button.classList.remove("sidebar-disabled"),this.revert_button.title="Revert to original version"):(this.revert_button.classList.add("sidebar-disabled"),this.revert_button.title="This is the original version of the document"))))}ReplaceTemplate(e,t,r=!0){let i=e.querySelector(t);if(i&&i.parentElement){for(let n of Array.from(i.content.children))i.parentElement.insertBefore(n,i);r&&i.parentElement.removeChild(i)}else console.warn("template not found",t)}AttachToolbar(e,t){let r=t.querySelector(".treb-layout-header"),i=t.querySelector(".treb-toolbar");i.innerHTML=ao;let n=[];if(e.options.toolbar==="narrow"||e.options.toolbar==="show-narrow"?n.push(...Array.from(i.querySelectorAll("[wide]"))):n.push(...Array.from(i.querySelectorAll("[narrow]"))),e.options.file_menu||n.push(i.querySelector("[file-menu]")),e.options.indent_buttons||n.push(i.querySelector("[indent-group]")),e.options.font_scale||n.push(i.querySelector("[font-scale]")),!e.options.font_stack)n.push(i.querySelector("[font-stack]"));else{let y=i.querySelectorAll("[font-stack] button[data-font-stack]");for(let w of y)if(w.dataset.fontStack){let _=qt[w.dataset.fontStack];w.textContent=_||""}}e.options.chart_menu||n.push(i.querySelector("[chart-menu]")),e.options.freeze_button||n.push(i.querySelector("[freeze-button]")),e.options.table_button||n.push(i.querySelector("[table-button]")),!e.options.add_tab&&!e.options.delete_tab&&n.push(...Array.from(i.querySelectorAll("[add-remove-sheet]"))),e.options.toolbar_recalculate_button||n.push(i.querySelector("[recalculate-button]"));for(let y of n)y&&y.parentElement?.removeChild(y);let o=i.querySelector(".treb-color-chooser"),a=i.querySelector(".treb-comment-box textarea");for(let[y,w]of Object.entries({top:"[wide] [data-command=align-top]",middle:"[wide] [data-command=align-middle]",bottom:"[wide] [data-command=align-bottom]",left:"[wide] [data-command=justify-left]",right:"[wide] [data-command=justify-right]",center:"[wide] [data-command=justify-center]",wrap:"[data-command=wrap-text]",merge:"[data-id=merge]",comment:"[data-icon=comment]",locked:"[data-command=lock-cells]",freeze:"[data-command=freeze-panes]",table:"[data-icon=table]",format:"input.treb-number-format",scale:"input.treb-font-scale",stack:"button.treb-font-stack"})){let _=i.querySelector(w);_&&(this.toolbar_controls[y]=_)}let s=o.querySelectorAll(".treb-swatches");this.swatch_lists={theme:s[0],other:s[1]};let c=t.querySelector("[data-command=increase-precision");c&&(c.textContent=this.sheet?.FormatNumber(0,"0.00")||""),c=t.querySelector("[data-command=decrease-precision"),c&&(c.textContent=this.sheet?.FormatNumber(0,"0.0")||""),c=i.querySelector("[data-command=update-comment]"),a.addEventListener("keydown",y=>{y.key==="Enter"&&(y.shiftKey||y.ctrlKey)&&c.click()});for(let y of["border","annotation","align","justify"])this.replace_targets[y]=i.querySelector(`[data-target=${y}`);for(let y of["fill","text","border"])this.color_bar_elements[y]=i.querySelector(`[data-color-bar=${y}]`);i.addEventListener("click",y=>{let w=y.target,_={format:w.dataset.format,scale:w.dataset.scale,font_stack:w.dataset.fontStack},C=w?.dataset.command;if(C){let S=w.parentElement?.dataset.replace;if(S){let A=this.replace_targets[S];A&&(A.dataset.command=C,A.title=w.title||"")}switch(/^border-/.test(C)&&(_.color=this.border_color||{}),C){case"text-color":case"fill-color":_.color={};try{_.color=JSON.parse(w.dataset.color||"{}")}catch(A){console.error(A)}break;case"set-color":C=o.dataset.colorCommand||"",_.color={};try{_.color=JSON.parse(w.dataset.color||"{}")}catch(A){console.error(A)}if(C==="border-color"&&(this.border_color=_.color),o.dataset.target){let A=this.color_bar_elements[o.dataset.target];A&&(A.style.setProperty("--treb-color-bar-color",w.style.backgroundColor),A.dataset.color=w.dataset.color||"{}")}break;case"update-comment":_.comment=a.value;break}e.HandleToolbarMessage({command:C,..._})}});let d=(y,w)=>{let _=i.querySelector(y);if(_){let C="";_.addEventListener("focusin",()=>C=_.value),_.addEventListener("keydown",S=>{switch(S.key){case"Escape":_.value=C,e.Focus();break;case"Enter":w(_.value)||(_.value=C,e.Focus());break;default:return}S.stopPropagation(),S.preventDefault()})}};d("input.treb-number-format",y=>y?(e.HandleToolbarMessage({command:"number-format",format:y}),!0):!1),d("input.treb-font-scale",y=>{let w=Number(y);return!w||isNaN(w)?(console.warn("invalid scale value"),!1):(e.HandleToolbarMessage({command:"font-scale",scale:w}),!0)});let u=o.querySelector("input"),h=o.querySelector("input + button");u.addEventListener("input",y=>{if(y instanceof InputEvent&&y.isComposing)return;h.style.background=u.value||"";let w=h.style.backgroundColor||"#fff",_=ae.MeasureColor(w),C=W.RGBToHSL(_[0],_[1],_[2]);h.style.color=C.l>.5?"#000":"#fff",h.dataset.color=JSON.stringify(h.style.backgroundColor?{text:h.style.backgroundColor}:{})}),u.addEventListener("keydown",y=>{y.key==="Enter"&&(y.stopPropagation(),y.preventDefault(),h.click())}),/firefox/i.test(navigator.userAgent)?r.addEventListener("scroll",()=>{this.DOM.view&&this.DOM.doc?.activeElement instanceof this.DOM.view.HTMLElement&&this.DOM.doc.activeElement?.blur()}):r.addEventListener("scroll",()=>e.Focus());let f=!1,m=y=>{y.key==="Escape"&&(y.stopPropagation(),y.preventDefault(),Promise.resolve().then(()=>e.Focus()))},p=y=>{if(f){if(y.relatedTarget instanceof Node&&i.contains(y.relatedTarget))return;i.removeEventListener("keydown",m),i.removeEventListener("focusout",p),f=!1}},b=y=>{let w=y.target,_=w?.parentElement;if(w?.classList.contains("treb-menu")){_=w;for(let C of Array.from(_.children))if(C.tagName==="BUTTON"){w=C;break}}else if(!_?.classList.contains("treb-menu"))return;if(w&&_){if(f||(i.addEventListener("focusout",p),i.addEventListener("keydown",m),f=!0),_.dataset.colorCommand){o.querySelector(".treb-default-color")?.setAttribute("title",_.dataset.defaultColorText||"Default color");let ie=o.querySelector(".treb-default-color-label");ie&&(ie.textContent=_.dataset.defaultColorText||"Default color"),_.appendChild(o),o.dataset.colorCommand=_.dataset.colorCommand,o.dataset.target=_.dataset.replaceColor||""}let C=_.querySelector("div"),S=r.getBoundingClientRect(),A=w.getBoundingClientRect(),{left:E}=A,R=_.parentElement;R?.hasAttribute("composite")&&(E=R.firstElementChild.getBoundingClientRect().left);let z=C.getBoundingClientRect();_.classList.contains("treb-submenu")?(C.style.top=A.top-z.height/2+"px",E+A.width+6+z.width>S.right?C.style.left=E-6-z.width+"px":C.style.left=E+A.width+6+"px"):(C.style.top=A.bottom+"px",E+z.width>S.right-6?C.style.left=A.right-z.width+"px":C.style.left=E+"px");let K=C.querySelector("textarea");K&&requestAnimationFrame(()=>K.focus())}},g=this.root?.querySelector(".treb-number-format-menu");g&&(this.UpdateDocumentStyles(e,g),this.UpdateSelectionStyle(e,i,a),e.Subscribe(y=>{switch(y.type){case"focus-view":break;case"data":case"document-change":case"load":case"reset":this.UpdateDocumentStyles(e,g),this.UpdateSelectionStyle(e,i,a),this.UpdateRevertState(e);break;case"theme-change":this.UpdateDocumentStyles(e,g),this.UpdateSelectionStyle(e,i,a);break;case"annotation-selection":case"selection":this.UpdateSelectionStyle(e,i,a);break}}));let x=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);if(i.addEventListener("focusin",y=>{b(y)}),x){let y=Array.from(i.querySelectorAll(".treb-menu"));for(let w of y)w.tabIndex=0;i.addEventListener("mousedown",w=>{b(w)})}}};var Cr=class{version="32.8.1";CreateSpreadsheet(e){let t=e.container,r=new nt(t);if(r.AttachElement(e),!r.sheet)throw new Error("construction failed");return r.sheet}},Oa=new Cr;if(typeof HTMLElement<"u"){class l extends HTMLElement{get sheet(){return this.instance.sheet}instance;constructor(){super(),this.instance=new nt(this)}connectedCallback(){this.instance.AttachElement()}}typeof customElements<"u"&&(customElements.get("treb-spreadsheet")?console.info("custom element treb-spreadsheet is already defined."):customElements.define("treb-spreadsheet",l))}export{Oa as TREB,Cr as TREBGlobal};
14
+ changes in the sidebar.`,close_box:!0,timeout:5e3,type:"info"});break;case"indent":case"outdent":this.grid.Indent(void 0,e.command==="indent"?1:-1);break;default:console.info("unhandled",e.command);break}Object.keys(t).length&&this.grid.ApplyStyle(void 0,t,!0),this.Focus()}ShowToolbar(e){if(this.options.toolbar&&this.options.container instanceof HTMLElement){let t=this.options.container.parentElement;t&&(e===void 0&&(e=!t.hasAttribute("toolbar")),e?t.setAttribute("toolbar",""):t.removeAttribute("toolbar"))}}ShowSidebar(e){if(this.options.toolbar&&this.options.container instanceof HTMLElement){let t=this.options.container.parentElement;t&&(e===void 0&&(e=t.hasAttribute("collapsed")),e?t.removeAttribute("collapsed"):t.setAttribute("collapsed",""))}}CreateChart(){return this.calculator.RegisterLibrary("treb-charts",ki)&&this.UpdateAC(),this.options.chart_renderer?typeof this.options.chart_renderer=="function"?new qe(this.options.chart_renderer()):new qe(this.options.chart_renderer):new qe}async LoadLanguage(e=""){(!e||e==="locale")&&(e=(F.locale||"").split(/-/).map(o=>o.toLowerCase())[0]),e=e.toLowerCase();let t;if(e&&["es","fr","pt","nl","de","pl","sv","no","da","it"].includes(e))try{t=await import(`./languages/treb-i18n-${e}.mjs`)}catch(i){console.error(i)}t?this.model.SetLanguage(t.LanguageMap):this.model.SetLanguage(),this.grid.Reselect(),this.grid.Update(!0),this.UpdateAC()}Batch(e,t=!1){let r=this.last_selection,i=this.grid.Batch(e,t),n=!1,o=!1;for(let a of i)switch(a.type){case"composite":case"data":n=!0;break;case"structure":a.rebuild_required&&(o=!0);break;default:}o&&this.calculator.Reset(),(n||o)&&(this.Recalculate(),this.DocumentChange(r))}Freeze(e=0,t=0){this.grid.Freeze(e,t,!0)}FreezeSelection(){let e=this.grid.GetSelection();if(e.empty)this.grid.Freeze(0,0);else{let t=e.area;t.entire_sheet||(t.entire_row?this.grid.Freeze(t.end.row+1,0):t.entire_column?this.grid.Freeze(0,t.end.column+1):this.grid.Freeze(t.end.row+1,t.end.column+1))}}GetFreeze(){return this.grid.GetFreeze()}UpdateTheme(){this.grid.UpdateTheme(void 0),this.UpdateDocumentStyles();for(let e of this.model.sheets.list){for(let t of e.conditional_formats)t.internal=void 0;for(let t of e.annotations)if(t.view&&t.data.type==="textbox"){let r=t.view[this.grid.view_index]||{};r.update_callback&&r.update_callback()}}this.calculator.UpdateConditionals(),this.ApplyConditionalFormats(this.grid.active_sheet,!1),this.grid.Update(!0),this.Publish({type:"theme-change"})}GetSheetID(e){if(typeof e=="number"){let t=this.grid.model.sheets.list[e];if(t)return t.id}else{let t=this.model.sheets.Find(e);if(t)return t.id}}InsertTable(e,t={}){let r=e?this.model.ResolveArea(e,this.grid.active_sheet):this.GetSelectionReference().area,i=t.theme;typeof i=="number"&&(i=Wt(i)),this.grid.InsertTable(r,t.totals_row,t.sortable,i)}RemoveTable(e){let t=this.ResolveTable(e||this.GetSelectionReference().target);t&&this.grid.RemoveTable(t)}UpdateTableStyle(e,t=4){let r=this.ResolveTable(e||this.GetSelectionReference().target);r&&(typeof t=="number"&&(t=Wt(t)),r.theme=t,this.grid.active_sheet.FlushCellStyles(),this.grid.Update(!0),this.PushUndo())}SetTabColor(e,t){let r=typeof e>"u"?this.grid.active_sheet:this.model.sheets.Find(e);r&&this.grid.TabColor(r,t)}AddSheet(e){this.grid.AddSheet(e);let t=this.model.sheets.list[this.model.sheets.list.length-1];return this.calculator.Reset(),t.id}RemoveConnectedChart(e){let t=this.model.RemoveConnectedElement(e);if(t){let r=this.calculator.RemoveConnectedELement(t)}}UpdateConnectedChart(e,t){let r=this.model.connected_elements.get(e);if(r){r.formula=t;let i=r.internal;i?.state&&(i.state=void 0),this.calculator.UpdateConnectedElements(this.grid.active_sheet,r),r.update&&r.update.call(0,r)}}CreateConnectedFormula(e,t,r={}){let i=r?.r1c1||!1,n=r?.argument_separator||this.parser.argument_separator;this.parser.Save(),this.parser.flags.r1c1=i,n===","?this.parser.SetLocaleSettings("."):this.parser.SetLocaleSettings(",");let o=this.parser.Parse(e);if(this.parser.Restore(),o.expression)e="="+this.parser.Render(o.expression,{missing:""});else throw console.warn("invalid formula",o.error),new Error("invalid formula");let a=this.model.AddConnectedElement({formula:e,update:t?s=>{t.call(0,s)}:void 0});return this.calculator.UpdateConnectedElements(this.grid.active_sheet),this.UpdateConnectedElements(),a}CreateConnectedChart(e,t,r){let i=this.CreateChart();i.Initialize(t);let n=o=>{let a=this.parser.Parse(o.formula);if(a&&a.expression&&a.expression.type==="call"){this.parser.Walk(a.expression,d=>((d.type==="address"||d.type==="range")&&this.model.ResolveSheetID(d,void 0,this.grid.active_sheet),!0));let s=a.expression.name.toLowerCase(),c=this.calculator.CalculateExpression(a.expression);i.Exec(s,c)}i.Update()};return this.CreateConnectedFormula(e,n,r)}InsertAnnotation(e,t="treb-chart",r,i){let n,o,a=!1;if(typeof i=="object"?(o=i.argument_separator,a=!!i.r1c1):(i===","||i===";")&&(o=i),r&&(n=B.IsRectangle(r)?r:this.model.ResolveArea(r,this.grid.active_sheet)),o&&o!==this.parser.argument_separator||a){this.parser.Save(),o===","?this.parser.SetLocaleSettings("."):this.parser.SetLocaleSettings(","),this.parser.flags.r1c1=!!a;let h=this.parser.Parse(e);this.parser.Restore(),h.expression&&(e="="+this.parser.Render(h.expression,{missing:""}))}let{x:s,y:c}=this.grid.GetScrollOffset(),d=this.grid.scale||1,u={width:301,height:301};this.grid.CreateAnnotation({type:t,formula:e},void 0,void 0,void 0,n||{top:c/d+30,left:s/d+30,...u})}InsertImage(){this.SelectFile2(".png, .jpg, .jpeg, .gif, .svg",2)}RenameSheet(e,t){let r;typeof e=="number"?r=this.grid.model.sheets.list[e]:typeof e=="string"?r=this.model.sheets.Find(e):r=this.grid.active_sheet,r&&this.grid.RenameSheet(r,t)}DeleteSheet(e){if(typeof e=="string"){let t=this.model.sheets.Find(e);t&&this.grid.DeleteSheetID(t.id)}else this.grid.DeleteSheet(e);this.calculator.Reset()}HideSheet(e=0,t=!0){this.grid.ShowSheet(e,!t)}ListSheets(){return this.model.sheets.list.map(e=>{let t={name:e.name};return e.visible||(t.hidden=!0),t})}ShowSheet(e=0,t=!0){this.grid.ShowSheet(e,t)}ActivateSheet(e){this.grid.ActivateSheet(e)}SetColumnWidth(e,t){this.grid.SetColumnWidth(e,t)}SetRowHeight(e,t){this.grid.SetRowHeight(e,t)}InsertRows(e,t=1){if(typeof e>"u"){let r=this.grid.GetSelection();if(r.empty)return;let i=r.area;e=i.entire_column?0:i.start.row}this.grid.InsertRows(e,t)}InsertColumns(e,t=1){if(typeof e>"u"){let r=this.grid.GetSelection();if(r.empty)return;let i=r.area;e=i.entire_row?0:i.start.column}this.grid.InsertColumns(e,t)}DeleteRows(e,t=1){if(typeof e>"u"){let r=this.grid.GetSelection();if(r.empty)return;let i=r.area;e=i.entire_column?0:i.start.row,t=i.rows}this.grid.InsertRows(e,-t)}DeleteColumns(e,t=1){if(typeof e>"u"){let r=this.grid.GetSelection();if(r.empty)return;let i=r.area;e=i.entire_row?0:i.start.column,t=i.columns}this.grid.InsertColumns(e,-t)}FilterTable(e,t=0,r){let i=this.ResolveTable(e);if(!i)throw new Error("invalid table reference");r?this.grid.FilterTable(i,t,n=>r.call(0,n.value,n.calculated||void 0,JSON.parse(JSON.stringify(n.style||{})))):this.grid.FilterTable(i,0,()=>!0)}SortTable(e,t={}){let r=this.ResolveTable(e);if(!r)throw new Error("invalid table reference");this.grid.SortTable(r,t)}MergeCells(e){this.grid.MergeCells(e?this.model.ResolveArea(e,this.grid.active_sheet):void 0)}UnmergeCells(e){this.grid.UnmergeCells(e?this.model.ResolveArea(e,this.grid.active_sheet):void 0)}async ExportBlob(e){return this.export_worker||(this.export_worker=await this.LoadWorker()),new Promise((t,r)=>{this.export_worker?(this.export_worker.onmessage=i=>{t(i.data?i.data.blob:void 0)},this.export_worker.onerror=i=>{console.error("export worker error"),console.info(i),r(i)},e||(e=this.Serialize({rendered_values:!0,expand_arrays:!0,export_colors:!0,decorated_cells:!0,tables:!0,share_resources:!1,export_functions:!0,apply_row_pattern:!0})),e.decimal_mark=F.decimal_separator,this.export_worker.postMessage({command:"export",sheet:e,decorated:this.calculator.DecoratedFunctionList()})):r("worker failed")})}Revert(){if(this.options.inline_document){this.LoadDocument(this.options.inline_document),this.initial_load_source="inline-document",this.options.local_storage&&(this.SaveLocalStorage("reverted_backup"),localStorage.removeItem(this.options.local_storage));return}let e=this.options.document;if(e){this.LoadNetworkDocument(e),this.initial_load_source="network-file",this.options.local_storage&&(this.SaveLocalStorage("reverted_backup"),localStorage.removeItem(this.options.local_storage));return}console.warn("to revert, there must be a document set in options"),this.dialog?.ShowDialog({title:"Can't revert -- no document is set in options",close_box:!0,timeout:3e3,type:"error"})}Export(){this.ExportBlob().then(e=>{let t="export";this.grid.model.document_name&&(t=this.grid.model.document_name.toLowerCase().replace(/\s+/g,"-")),e&&(this.SaveAs(e,t+".xlsx"),this.last_save_version=this.file_version)}).catch(e=>{throw/invalid uri/i.test(e.message)&&this.dialog?.ShowDialog({title:"Error exporting file",close_box:!0,message:"The worker cannot run from the filesystem, please use a web server.",timeout:3e3,type:"error"}),e})}GetSelectionReference(){return this.grid.GetSelection()}Focus(){this.grid.Focus()}Resize(){this.grid.UpdateLayout();for(let e of this.views)e.view.grid.UpdateLayout();this.Publish({type:"resize"})}Reset(){if(this.parent_view)return this.parent_view.Reset();this.grid.Reset(),this.ResetInternal(),this.UpdateAC(),this.Publish({type:"reset"})}LoadFromLocalStorage(e){this.options.local_storage=e;let t=localStorage.getItem(e);if(t)try{let r=JSON.parse(t);return this.LoadDocument(r,{source:"local-storage"}),!0}catch(r){console.error(r)}return!1}async LoadNetworkDocument(e,t){let r=t?t.scroll:void 0,i=t?!!t.recalculate:!1,n=t?t.sheet:void 0,o=/csv(?:$|\?|&)/i.test(e),a=/tsv(?:$|\?|&)/i.test(e);try{this.spinner?.Show();let s=await fetch(e);if(this.spinner?.Hide(),!s.ok)throw new Error("network error");let c=await s.text();if(typeof c=="string")if(o)this.LoadCSV(c,"network-file");else{if(a)throw new Error("tsv not supported (TODO)");{c.substr(0,11)==="&&&START&&&"?c=c.substr(11):c.substr(0,8)==="for(;;);"&&(c=c.substr(8));let d=JSON.parse(c);this.LoadDocument(d,{scroll:r,recalculate:i,override_sheet:n,source:"network-file"})}}}catch(s){console.info("error loading network document",e),console.error(s),this.dialog?.ShowDialog({title:"Error loading file",close_box:!0,message:"The network document returned an error",type:"error",timeout:3e3}),this.Reset()}}async LoadLocalFile(){this.SelectFile2(".treb, .csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/json",1)}ExportDelimited(e={}){if(e={delimiter:",",...e},!e.delimiter||e.delimiter!==","&&e.delimiter!==" ")throw new Error("invalid delimiter");let t=this.grid.active_sheet;switch(typeof e.sheet){case"undefined":break;case"string":t=this.model.sheets.Find(e.sheet);break;case"number":t=this.grid.model.sheets.list[e.sheet];break;default:t=void 0;break}if(!t)throw new Error("invalid sheet identifier");let r=t.cells.toJSON({nested:!1,expand_arrays:!0,calculated_value:!0}),i=[];for(let a=0;a<r.columns;a++)i.push("");let n=[];for(let a=0;a<r.rows;a++)n.push(i.slice(0));let o=new RegExp(`[
15
+ \r"${e.delimiter}]`);if(ht(r.data))for(let a of r.data){let s="";!e.formulas&&typeof a.calculated<"u"?s=me(a.calculated)?Xe(a.calculated):a.calculated.toString():typeof a.value=="string"&&a.value[0]==="'"?s=a.value.substr(1):typeof a.value<"u"&&(s=me(a.value)?Xe(a.value):a.value.toString()),o.test(s)&&(s=s.replace(/"/g,'""'),s='"'+s+'"'),n[a.row][a.column]=s}return n.map(a=>a.join(e.delimiter)).join(`\r
16
+ `)}SaveLocalFile(e="treb.json",t={}){this.SaveToDesktop(e,t)}SaveToDesktop(e="treb.json",t={}){let r=this.grid.model.document_name||"document",i,n,o=e.split(/\./).filter(s=>s.trim().length),a=o.length?o[o.length-1].toLowerCase():"treb";if(o.length<=1||e==="treb.json")if(e==="treb.json"&&(a=e),(a==="csv"||a==="tsv")&&this.grid.model.sheets.length>1){let s=this.grid.active_sheet.name;e=(r+"-"+s).toLowerCase().replace(/\W+/g,"-")+"."+a}else e=r.toLowerCase().replace(/\W+/g,"-")+"."+a;switch(a){case"csv":n=this.ExportDelimited({delimiter:","});break;case"tsv":n=this.ExportDelimited({delimiter:" "});break;case"treb":case"json":case"treb.json":i=this.SerializeDocument({...t}),n=JSON.stringify(i,void 0,t.pretty?2:void 0),this.last_save_version=this.file_version;break;default:throw new Error("invalid file type")}if(n&&e){let s=new Blob([n],{type:"text/plain;charset=utf-8"});this.SaveAs(s,e)}}LoadCSV(e,t){if(this.parent_view)return this.parent_view.LoadCSV(e,t);this.grid.FromCSV(e),this.ResetInternal(),this.grid.Update(!0),this.Publish({type:"load",source:t}),this.UpdateDocumentStyles()}ScrollOffset(e){return this.grid.ScrollOffset(e)}LoadDocument(e,t={}){if(this.parent_view)return this.parent_view.LoadDocument(e,t);if(this.initial_load_source||(this.initial_load_source=t.source),t={flush:!0,recalculate:!1,...t},t.override_selection&&e.sheet_data){let r=Array.isArray(e.sheet_data)?e.sheet_data:[e.sheet_data];for(let i of r)if(i.id===t.override_selection.target.sheet_id){i.selection=t.override_selection;break}}if(this.ImportDocumentData(e,t.override_sheet),this.calculator.Reset(),e.rendered_values&&!t.recalculate?(this.calculator.RebuildClean(!0),this.ApplyConditionalFormats(this.grid.active_sheet,!1),this.grid.Update()):this.Recalculate(),this.InflateAnnotations(),t.flush&&this.FlushUndo(),this.Publish({type:"load",source:t.source}),this.UpdateDocumentStyles(),this.loaded=!0,t.scroll){let r=t.scroll;Promise.resolve().then(()=>this.ScrollTo(r))}}SetNote(e,t){if(typeof e=="string"){let r=this.model.ResolveAddress(e,this.grid.active_sheet);e=N(r)?r:r.start}this.grid.SetNote(e,t)}SetValidation(e,t,r){if(typeof e=="string"){let i=this.model.ResolveAddress(e,this.grid.active_sheet);e=ut(i)?new v(i.start,i.end):new v(i)}if(N(e)&&(e=new v(e)),typeof t>"u"||Array.isArray(t))this.grid.SetValidation(e,t,r);else{let i=this.model.ResolveArea(t,this.grid.active_sheet);this.grid.SetValidation(e,i,r)}}RemoveFunction(e){let t=e.toUpperCase();this.model.macro_functions.delete(t),this.UpdateAC()}DefineFunction(e,t="",r="0"){if(!e.length||/^[^A-Za-z]/.test(e)||/[^\w_.]/.test(e))throw new Error("invalid function name");typeof t=="string"&&(t=t?t.split(this.parser.argument_separator).map(i=>i.trim()):[]);for(let i of t)if(!i.length||/^[^A-Za-z]/.test(i)||/[^\w_.]/.test(i))throw new Error("invalid argument name");this.RemoveFunction(e),this.grid.model.macro_functions.set(e.toUpperCase(),{name:e,function_def:r,argument_names:t,expression:this.parser.Parse(r).expression}),this.UpdateAC()}SerializeDocument(e={}){e={share_resources:!0,shrink:!0,...e};let t=this.Serialize(e),r={app:"@trebco/treb",version:"32.9.3",revision:this.file_version,name:this.grid.model.document_name,user_data:this.grid.model.user_data,decimal_mark:F.decimal_separator,...t};if(e.share_resources){let i=1,n=new Map,o=Array.isArray(r.sheet_data)?r.sheet_data:[r.sheet_data],a=c=>{let d=n.get(c);return d||(d=(i++).toString(),n.set(c,d)),`resource:${d}`};for(let c of o)if(c){c.background_image&&(c.background_image=a(c.background_image));for(let d of c.annotations||[])d.type==="image"&&d.data?.src&&(d.data.src=a(d.data.src))}let s={};for(let[c,d]of n.entries())s[d]=c;r.shared_resources=s}return e.rendered_values&&(r.rendered_values=!0),r}Recalculate(e){let t;switch(e?.type){case"data":t=e.area;break;case"composite":t=e.data_area;break}this.calculator.Calculate(t),this.calculator.grid_expanded&&this.grid.UpdateLayout(),this.ApplyConditionalFormats(this.grid.active_sheet,!1),this.grid.Update(!0),this.UpdateAnnotations(),this.Publish({type:"data"}),this.grid.UpdateStats()}SaveLocalStorage(e=this.options.local_storage){if(!e){console.warn("not saving, no key");return}let t=JSON.stringify(this.SerializeDocument({rendered_values:!0,expand_arrays:!0}));localStorage.setItem(e,t)}Undo(){if(this.parent_view)return this.parent_view.Undo();if(this.undo_pointer<=1){console.warn("nothing to undo");return}let e=this.undo_stack[--this.undo_pointer-1],t=e.selection?JSON.parse(e.selection):void 0;this.LoadDocument(JSON.parse(e.data),{flush:!1,override_selection:t,source:"undo"})}About(){this.dialog?.ShowDialog({type:"about"})}ScrollIntoView(e,t=!1){if(typeof e=="string"){let r=this.model.ResolveAddress(e,this.grid.active_sheet);e=N(r)?r:r.start}this.grid.ScrollIntoView(e,t)}ScrollTo(e,t={}){if(typeof e=="string"){let r=this.model.ResolveAddress(e,this.grid.active_sheet);e=N(r)?r:r.start}t={x:!0,y:!0,smooth:!1,...t},this.grid.ScrollTo(e,t.x,t.y,t.smooth)}Resolve(e,t){let r=this.model.ResolveAddress(e,this.grid.active_sheet,t);return N(r)?r.sheet_id?r:void 0:r.start.sheet_id?r:void 0}Unresolve(e,t=!0,r=!0){if(typeof e=="string"){let i=this.Resolve(e);if(!i)throw new Error("invalid reference");e=i}return this.calculator.Unresolve(e,this.grid.active_sheet,t,r)}Evaluate(e,t={}){return this.calculator.Evaluate(e,this.grid.active_sheet,t)}GetSelection(e=!0){let t=this.grid.GetSelection();if(t.empty)return"";let r="";if(t.area.count>1?r=v.CellAddressToLabel(t.area.start)+":"+v.CellAddressToLabel(t.area.end):r=v.CellAddressToLabel(t.area.start),!e)return r;let i=t.area.start.sheet_id||this.grid.active_sheet.id,n=this.calculator.ResolveSheetName(i,!0);return n?n+"!"+r:r}ParseNumber(e){return ye.TryParse(e).value}FormatNumber(e,t="General"){return me(e)?ue.FormatPartsAsText(L.Get(t).FormatComplex(e)):L.Get(t).Format(e)}SpreadsheetDate(e){return e instanceof Date&&(e=e.getTime()),Ae(e,!0)}JavascriptDate(e){return Re(e).getTime()}ApplyBorders(e,t,r=1){this.grid.ApplyBorders2(e?this.model.ResolveArea(e,this.grid.active_sheet):void 0,t,{},r)}ApplyStyle(e,t={},r=!0){this.grid.ApplyStyle(e?this.model.ResolveArea(e,this.grid.active_sheet):void 0,t,r)}ClearName(e){this.grid.SetName(e)}ListNames(){return this.model.SerializeNames()}DefineName(e,t,r,i=!1){if(typeof t>"u"||t===null)throw new Error("invalid value (null or undefined)");if(typeof r=="string"){let n=this.model.sheets.ID(r);if(typeof n=="number")r=n;else throw new Error("invalid scope; use a sheet name or sheet id")}if(typeof t=="object"&&(N(t)||ut(t))){this.grid.SetName(e,this.model.ResolveArea(t,this.grid.active_sheet),void 0,r,i);return}if(typeof t=="string"){let n=this.parser.Parse(t);if(!n.expression)throw new Error("invalid expression");switch(n.expression.type){case"address":case"range":this.grid.SetName(e,this.model.ResolveArea(n.expression,this.grid.active_sheet),void 0,r,i);return}this.grid.SetName(e,void 0,t,r,i)}else this.grid.SetName(e,void 0,t.toString(),r,i)}SetLink(e,t=""){if(typeof e=="string"){let r=this.model.ResolveAddress(e,this.grid.active_sheet);e=N(r)?r:r.start}if(!e){let r=this.GetSelectionReference();if(r.empty)return;e=r.target}this.grid.SetLink(e,t)}Select(e){let t;e&&(t=this.model.ResolveArea(e,this.grid.active_sheet),t.start.sheet_id&&t.start.sheet_id!==this.grid.active_sheet.id&&this.grid.ActivateSheetID(t.start.sheet_id)),this.grid.SelectRange(t)}Paste(e,...t){let r=l.clipboard,i={};switch(t.length){case 1:Array.isArray(t[0])?r=t[0]:typeof t[0]=="object"&&(i=t[0]);break;case 2:t[0]&&Array.isArray(t[0])&&(r=t[0]),t[1]&&typeof t[1]=="object"&&(i=t[1]);break}if(!r)throw new Error("no clipboad data");this.grid.PasteArea(this.RangeOrSelection(e,"no range and no selection"),r,i)}Copy(e){let t=this.RangeOrSelection(e),r=t?this.grid.CopyArea(t,"copy"):[];return l.clipboard=structuredClone(r),r}Cut(e){let t=this.RangeOrSelection(e),r=t?this.grid.CopyArea(t,"cut"):[];return l.clipboard=structuredClone(r),r}GetRange(e,t={}){let r=this.RangeOrSelection(e);if(!r)return;let i=t.type;return i||(t.formatted&&(i="formatted"),t.formula&&(i="A1")),i==="formula"&&(i="A1"),this.grid.GetRange(r,i)}GetStyle(e,t=!1){let r=this.RangeOrSelection(e);if(r)return this.grid.GetRangeStyle(r,t)}SetRange(e,t=void 0,r={}){let i=this.RangeOrSelection(e);if(i){if(r.spill&&Array.isArray(t)){let n=t.length,o=Math.max(0,...t.map(s=>s.length)),a={row:i.start.row+n+1,column:i.start.column+o+1};i.ConsumeAddress(a)}return this.grid.SetRange(i,t,r)}}Subscribe(e){return this.events.Subscribe(e)}Cancel(e){this.events.Cancel(e)}RangeOrSelection(e,t){if(!e){let r=this.GetSelectionReference();if(r.empty){if(t)throw t;return}else return r.area.Clone()}return this.model.ResolveArea(e,this.grid.active_sheet)}Serialize(e={}){let t=this.grid.active_sheet;t.selection=JSON.parse(JSON.stringify(this.grid.GetSelection()));let r=this.grid.ScrollOffset();r&&(t.scroll_offset=r);let i=this.model.sheets.list.map(s=>s.toJSON(e)),n;this.model.tables.size>0&&(n=Array.from(this.model.tables.values()));let o;if(this.model.macro_functions.size){o=[];for(let s of this.model.macro_functions.values())o.push({...s,expression:void 0})}let a=this.model.SerializeNames(t);return{sheet_data:i,active_sheet:t.id,named:a.length?a:void 0,macro_functions:o,tables:n}}ApplyConditionalFormats(e,t){let r=[];if(e.conditional_formats.length||e.flush_conditional_formats){for(let i of e.conditional_formats)switch(r.push(i.area),i.type){case"gradient":i.internal||(i.internal={}),i.internal.gradient||(i.internal.gradient=new Xt(i.stops,this.grid.theme,i.color_space));break;case"data-bar":i.internal||(i.internal={});break}e.ApplyConditionalFormats()}t&&this.grid.Update(!0,r)}ResolveTable(e){let t;if(typeof e=="string"){let r=e.toLowerCase();this.model.tables.has(r)&&(t=this.model.tables.get(r))}if(!t){let r=this.model.ResolveAddress(e,this.grid.active_sheet);N(r)||(r=r.start),t=this.grid.GetTableReference(r)}return t}SaveAs(e,t){let r=this.DOM.Create("a");r.href=URL.createObjectURL(e),r.download=t,r.click(),URL.revokeObjectURL(r.href)}Publish(e){this.events.Publish(e)}async ImportXLSX(e,t){return this.parent_view?this.parent_view.ImportXLSX(e,t):(this.export_worker||(this.export_worker=await this.LoadWorker()),new Promise((r,i)=>{this.export_worker?(this.dialog?.ShowDialog({message:"Importing XLSX..."}),this.export_worker.onmessage=n=>{if(n.data){if(n.data.status==="error")return i(n.data.error||"unknown error");if(this.parser.decimal_mark!=="."){let o=this.parser.decimal_mark,a=this.parser.argument_separator;this.parser.Save(),this.parser.SetLocaleSettings(".");let s=c=>{let d=this.parser.Parse(c);if(d.expression)return"="+this.parser.Render(d.expression,{missing:"",convert_decimal:o,convert_argument_separator:a})};for(let c of n.data.results)c.expression=s(c.expression);for(let c of n.data.results.sheets||[]){for(let d of c.cells||[])d.type==="formula"&&d.value&&(d.value=s(d.value));if(c.annotations)for(let d of c.annotations)d.formula&&(d.formula=s(d.formula))}this.parser.Restore()}this.grid.FromImportData(n.data.results),this.ResetInternal(),this.grid.Update(),this.UpdateAC(),this.Publish({type:"load",source:t}),this.UpdateDocumentStyles(),this.InflateAnnotations(),this.calculator.UpdateConditionals(),this.ApplyConditionalFormats(this.grid.active_sheet,!1)}else return i("unknown error (missing data)");this.dialog?.HideDialog(),r()},this.export_worker.onerror=n=>{console.error("import worker error"),console.info(n),i(n)},this.export_worker.postMessage({command:"import",data:e})):i("worker failed")}))}ResetInternal(){this.calculator.Reset(),this.FlushUndo(),this.file_version=this.last_save_version=0}HandleCellEvent(e){if(e.data?.type==="hyperlink"){let t="hyperlink invalid target",r=e.data.reference||"";if(typeof r=="string"){if(/^https{0,1}:\/\//i.test(r)){if(!this.options.hyperlinks){console.warn("hyperlinks are disabled");return}let i=this.DOM.Create("a");i.setAttribute("target",this.options.hyperlinks),i.setAttribute("href",r),i.setAttribute("noreferrer","true"),i.setAttribute("nofollow","true"),i.click();return}else{let i=this.parser.Parse(r);if(i.expression){if(i.expression.type==="address"){(i.expression.sheet||i.expression.sheet_id)&&this.ActivateSheet(i.expression.sheet||i.expression.sheet_id),this.Select(r);return}else if(i.expression.type==="range"){(i.expression.start.sheet||i.expression.start.sheet_id)&&this.ActivateSheet(i.expression.start.sheet||i.expression.start.sheet_id),this.Select(r);return}}}console.warn(t,2);return}}}OnSheetChange(e){for(let t of e.activate.annotations)this.InflateAnnotation(t),this.calculator.UpdateAnnotations(t,e.activate);this.UpdateAnnotations(),this.calculator.UpdateConditionals(),this.ApplyConditionalFormats(e.activate,!0)}HandleDrag(e){if(e.dataTransfer&&e.dataTransfer.types){if(e.dataTransfer.types.some&&e.dataTransfer.types.some(t=>t==="Files"))e.preventDefault();else for(let t=0;t<e.dataTransfer.types.length;t++)if(e.dataTransfer.types[t]==="files"){e.preventDefault();return}}}HandleDrop(e){if(e.dataTransfer&&e.dataTransfer.files&&e.dataTransfer.files.length){e.preventDefault();let t=e.dataTransfer.files[0];/^image/.test(t.type)?this.InsertImageInternal(t):this.LoadFileInternal(t,"drag-and-drop").catch(()=>{})}}SelectFile2(e,t){if(!this.file_chooser){let r=this.DOM.Create("input",void 0,void 0,{attrs:{type:"file"},events:{change:()=>{if(r.files&&r.files[0]){let i=r.files[0];switch(r.value="",this.file_chooser_operation){case 2:this.InsertImageInternal(i);break;case 1:this.LoadFileInternal(i,"local-file",!0);break;default:console.warn("file chooser: no operation");break}}}}});this.file_chooser=r}if(!this.file_chooser)throw new Error("could not create file chooser");this.file_chooser_operation=t,this.file_chooser.accept=e||"",this.file_chooser.click()}async InsertImageInternal(e){if(this.options.max_file_size&&e.size>this.options.max_file_size){this.dialog?.ShowDialog({type:"error",message:"This file exceeds the allowed image size. Please try a smaller image.",title:"Error adding image",timeout:3e3,close_box:!0});return}let t=e;await new Promise((r,i)=>{let n=new FileReader;n.onload=async()=>{try{if(n.result){let o;if(typeof n.result=="string")o=n.result;else{o="";let s=new Uint8Array(n.result);for(let c=0;c<s.byteLength;c++)o+=String.fromCharCode(s[c])}let a=this.DOM.Create("img");a.src=o,await Promise.resolve(),this.grid.CreateAnnotation({type:"image",formula:"",data:{scale:"",src:o,original_size:{width:a.width||300,height:a.height||300}}},void 0,void 0,void 0,{top:30,left:30,width:a.width||300,height:a.height||300})}r()}catch(o){i(o)}},n.onabort=()=>{i("Aborted")},n.onerror=()=>{i("File error")},setTimeout(()=>{n.readAsDataURL(t)},100)})}LoadFileInternal(e,t,r=!0){if(!e)return Promise.resolve();let i=new FileReader;return new Promise((n,o)=>{let a=s=>{i.onload=null,i.onabort=null,i.onerror=null,s?(r&&(this.dialog?.ShowDialog({title:"Error reading file",close_box:!0,message:"Please make sure your file is a valid XLSX, CSV or TREB file.",type:"error",timeout:3e3}),console.error(s)),o(s)):n()};i.onload=()=>{try{if(i.result)if(/\.csv$/i.test(e.name))this.LoadCSV(i.result,t);else if(/\.xls[xm]$/i.test(e.name)){typeof i.result=="string"?a("Unsupported file"):this.ImportXLSX(i.result,t).then(()=>a()).catch(s=>a(s));return}else{let s=JSON.parse(i.result);this.LoadDocument(s,{source:t})}a()}catch(s){a(s?.toString())}},i.onabort=()=>{a("Aborted")},i.onerror=()=>{a("File error")},setTimeout(()=>{/\.xls[xm]$/i.test(e.name)?i.readAsArrayBuffer(e):i.readAsText(e)},100)})}UpdateAnnotations(){for(let e of this.grid.active_sheet.annotations){let t=e.temp;if(t.vertex&&t.vertex.state_id!==t.state){t.state=t.vertex.state_id;for(let i of e.view)i&&(i.dirty=!0)}let r=e.view[this.grid.view_index]||{};r.dirty&&(r.dirty=!1,r.update_callback&&r.update_callback(),this.grid.AnnotationUpdated(e))}this.UpdateConnectedElements()}UpdateConnectedElements(){for(let e of this.model.connected_elements.values()){let t=e.internal;if(t?.vertex&&t.vertex.state_id!==t.state){t.state=t.vertex.state_id;let r=e.update;r&&Promise.resolve().then(()=>r.call(0,e))}}}RebuildAllAnnotations(){for(let e of this.grid.active_sheet.annotations){this.InflateAnnotation(e);let t=e.view[this.grid.view_index]||{};t.resize_callback&&t.resize_callback(),t.update_callback&&t.update_callback()}}InflateAnnotations(){for(let e of this.grid.active_sheet.annotations)this.InflateAnnotation(e)}InflateAnnotation(e){if(this.grid.headless)return;let t=e.view[this.grid.view_index]||{};if(t.inflated){e.dirty&&(t.resize_callback&&t.resize_callback(),e.dirty=!1);return}if(t.inflated=!0,e.dirty&&(e.dirty=!1),t.content_node){if(e.data.type==="treb-chart"){let r=this.CreateChart();r.Initialize(t.content_node);let i=()=>{if(e.data.formula){let n=this.parser.Parse(e.data.formula);if(n&&n.expression&&n.expression.type==="call"){this.parser.Walk(n.expression,s=>((s.type==="address"||s.type==="range")&&this.model.ResolveSheetID(s,void 0,this.grid.active_sheet),!0));let o=n.expression.name.toLowerCase(),a=this.calculator.CalculateExpression(n.expression);r.Exec(o,a)}}r.Update()};t.resize_callback=()=>{this.grid.headless||(r.Resize(),r.Update())},t.update_callback=()=>{this.grid.headless||i()},t.node?.parentElement&&(this.grid.headless||i())}else if(e.data.type==="image"){if(typeof e.data.data?.src=="string"){let r=Ut(e.data.data.src);if(r){let i=this.DOM.Create("img");i.src=r,e.data.data.scale==="fixed"?(i.style.position="relative",i.style.left="50%",i.style.top="50%",i.style.transform="translate(-50%, -50%)"):(i.style.width="100%",i.style.height="100%"),t.content_node.appendChild(i)}}}else if(e.data.type==="textbox"&&e.data.data){let r,i=document.createElement("div");i.classList.add("treb-annotation-textbox");for(let n of e.data.data.paragraphs){let o=document.createElement("p");n.style&&(n.style.horizontal_align==="right"||n.style.horizontal_align==="center")&&(o.style.textAlign=n.style.horizontal_align);for(let a of n.content){let s=document.createElement("span");if(r||(r=s),e.data.formula||(s.textContent=a.text||""),a.style?.bold&&(s.style.fontWeight="600"),a.style?.italic&&(s.style.fontStyle="italic"),o.appendChild(s),e.data.formula)break}if(i.append(o),e.data.formula)break}if(t.content_node.append(i),e.data.data.style){let n=e.data.data.style,o=()=>{if(n.fill){let a=D(this.grid.theme,n.fill);i.style.background=a}};t.update_callback=()=>{if(this.grid.headless||o(),r&&e.data.formula){let a=this.parser.Parse(e.data.formula);if(a&&a.expression){this.parser.Walk(a.expression,u=>((u.type==="address"||u.type==="range")&&this.model.ResolveSheetID(u,void 0,this.grid.active_sheet),!0));let s=this.calculator.CalculateExpression(a.expression),c=L.Get("General"),d;switch(a.expression.type){case"address":d=a.expression;break;case"range":d=a.expression.start;break}if(d){let h=(d.sheet_id?this.model.sheets.Find(d.sheet_id):this.grid.active_sheet)?.CellStyleData(d);h?.number_format&&(c=L.Get(h.number_format))}switch(s.type){case 3:case 2:case 8:r.textContent=c.Format(s.value);break;default:r.textContent=s.value?.toString()||""}}}},t.update_callback()}}}}DocumentChange(e){Promise.resolve().then(()=>{this.file_version++,this.file_version>=65536&&(this.file_version=1);let t=JSON.stringify(this.SerializeDocument({optimize:"size",rendered_values:!0,expand_arrays:!0}));this.options.undo&&this.PushUndo(t,e,!1),this.Publish({type:"document-change"})})}ResolveStorageKey(e,t=""){if(e){if(e===!0){let r=0,i=document.location.href;for(let o=0,a=i.length;o<a;o++)r=(r<<5)-r+i.charCodeAt(o),r|=0;let n=Math.abs(r).toString(16);return t?t+"-"+n:n}return e}}PushUndo(e,t,r=!0){let i=t||this.last_selection;this.undo_stack[this.undo_pointer-1]&&(this.undo_stack[this.undo_pointer-1].selection=i),r&&(this.file_version++,this.file_version>=65536&&(this.file_version=1)),e||(e=JSON.stringify(this.SerializeDocument({optimize:"size",rendered_values:!0,expand_arrays:!0}))),this.undo_stack[this.undo_pointer++]={data:e,selection:void 0};let n=this.undo_stack.length;if(n>16){let o=n-16;this.undo_stack=this.undo_stack.slice(o),this.undo_pointer-=o}}FlushUndo(e=!0){this.undo_stack=[],this.undo_pointer=0,this.last_save_version=this.file_version,e&&this.PushUndo(void 0,void 0,!1)}UpdateSelection(e){this.last_selection=JSON.stringify(e),this.Publish({type:"selection"})}UpdateSelectionStyleAnnotation(e){let t={style:JSON.parse(JSON.stringify(e.data.style||{}))};t.style&&(t.style.font_face||(t.style.font_face="stack:ui"),t.style.font_size||(t.style.font_size={unit:"em",value:1})),t.relative_font_size=I.RelativeFontSize(t.style||{},this.grid.theme.grid_cell||{}),this.selection_state=t}UpdateSelectionStyle(e){let t=this.grid.GetFreeze(),r={frozen:!!t.rows||!!t.columns};if(e||(e=this.grid.GetSelection()),e&&!e.empty){r.selection=e;let i=this.grid.active_sheet.CellData(e.target);r.table=!!i.table,r.merge=!!i.merge_area,r.merge&&i.merge_area&&(i.merge_area.start.row!==e.target.row||i.merge_area.start.column!==e.target.column)&&(i=this.grid.active_sheet.CellData(i.merge_area.start)),r.comment=i.note,r.style=i.style?{...i.style}:void 0,r.relative_font_size=I.RelativeFontSize(r.style||{},this.grid.theme.grid_cell||{}),r.empty=typeof i.value>"u"&&!i.style?.font_face}this.grid?.edit_state&&(this.grid.edit_state.font_face=r.style?.font_face||void 0),this.selection_state=r}UpdateDocumentStyles(){let e={},t={};for(let i of this.grid.model.sheets.list)i.NumberFormatsAndColors(t,e);this.document_styles.colors=Object.keys(t),this.document_styles.number_formats=Object.keys(e),this.document_styles.theme_colors=[];let r=[.5,.25,0,-.25,-.5];for(let i=0;i<10;i++)this.document_styles.theme_colors.push(r.map(n=>{let o={theme:i,tint:n},a=D(this.grid.theme,o);return{color:o,resolved:a}}))}ConvertLocale(e){let t=new We;t.flags={...this.parser.flags};let r,i;e.decimal_mark==="."?(t.SetLocaleSettings("."),r=",",i=";"):(t.SetLocaleSettings(","),r=".",i=",");let n=o=>{let a=t.Parse(o);if(a.expression)return"="+t.Render(a.expression,{missing:"",convert_decimal:r,convert_argument_separator:i})};if(e.macro_functions)for(let o of e.macro_functions){let a=n(o.function_def);a&&(o.function_def=a)}if(e.named)for(let o of e.named){let a=n(o.expression);a&&(o.expression=a)}if(e.sheet_data){let o=Array.isArray(e.sheet_data)?e.sheet_data:[e.sheet_data];for(let a of o){if(a.annotations){for(let s of a.annotations)if(s.formula){let c=n(s.formula);c&&(s.formula=c)}}if(a.data?.length)for(let s of a.data){let c=Pr(s)?[s]:s.cells;for(let d of c)if(d.value&&typeof d.value=="string"&&d.value[0]==="="){let u=n(d.value.slice(1));u&&(d.value=u)}}}}}CompareVersions(e="",t=""){let r=e.split(".").map(a=>Number(a)||0).concat([0,0,0]),i=t.split(".").map(a=>Number(a)||0).concat([0,0,0]),n=[0,1,2],o={match:0};for(let a=0;a<3;a++)if(r[a]!==i[a]){o.match=r[a]>i[a]?1:-1,o.level=n[a];break}return o}ImportDocumentData(e,t){this.file_version=e.revision||0;let r=[],i=this.CompareVersions(e.version,"32.9.3");if(i.match>0&&(i.level===0||i.level===1)&&console.warn(`The file you are opening was created with a newer version of TREB (${e.version} vs 32.9.3).
17
+ You may encounter compatibility errors.`),e.sheet_data&&(Array.isArray(e.sheet_data)?r=e.sheet_data:r.push(e.sheet_data)),e.shared_resources){let o=e.shared_resources,a=s=>/^resource:/.test(s)?o[s.substring(9)]||"":s;for(let s of r){s.background_image&&(s.background_image=a(s.background_image));for(let c of s.annotations||[])c.type==="image"&&c.data?.src&&(c.data.src=a(c.data.src))}}e.decimal_mark&&e.decimal_mark!==F.decimal_separator&&this.ConvertLocale(e);let n=this.grid.model;if(n.tables.clear(),e.tables)for(let o of e.tables)n.tables.set(o.name.toLowerCase(),o);this.grid.UpdateSheets(r,void 0,t||e.active_sheet);for(let o of this.model.tables.values())if(o.area.start.sheet_id){let a=n.sheets.Find(o.area.start.sheet_id);if(a)for(let s=o.area.start.row;s<=o.area.end.row;s++)for(let c=o.area.start.column;c<=o.area.end.column;c++){let d=a.cells.GetCell({row:s,column:c},!0);d.table=o}}if(n.document_name=e.name,n.user_data=e.user_data,n.named.Reset(),e.named)this.model.UnserializeNames(e.named,this.grid.active_sheet);else{let o=e.named_ranges;if(!o&&r[0]&&r[0].named_ranges&&(o=r[0].named_ranges),o)for(let[a,s]of Object.entries(o))n.named.SetNamedRange(a,new v(s.start,s.end));if(e.named_expressions)for(let a of e.named_expressions)this.model.UnserializeNames([{name:a.name,expression:a.expression}],this.grid.active_sheet)}if(n.macro_functions.clear(),e.macro_functions)for(let o of e.macro_functions)n.macro_functions.set(o.name.toUpperCase(),{...o,expression:this.parser.Parse(o.function_def||"").expression});this.UpdateAC()}async LoadWorker(){try{return await(await import("./treb-export-worker.mjs")).CreateWorker()}catch(e){throw console.error(e),e}}HandleKeyDown(e){e.key==="z"?(j.is_mac&&e.metaKey||e.ctrlKey)&&(e.stopPropagation(),e.preventDefault(),this.Undo()):e.key==="F9"&&this.options.recalculate_on_f9&&(e.stopPropagation(),e.preventDefault(),this.Recalculate())}};var lo=`@charset "UTF-8";.treb-main.treb-main .treb-mouse-mask{background:transparent;bottom:0;display:none;left:0;position:fixed;right:0;top:0;z-index:9999}.treb-main.treb-main .treb-mouse-mask.column-resize{cursor:col-resize}.treb-main.treb-main .treb-mouse-mask.row-resize{cursor:row-resize}.treb-main.treb-main .treb-mouse-mask.nub-select{cursor:crosshair}.treb-main.treb-main .treb-mouse-mask.move{cursor:move}.treb-main.treb-main .treb-mouse-mask.nw-resize{cursor:nw-resize}.treb-main.treb-main .treb-note{max-width:15em;min-width:15em}.treb-main.treb-main .treb-hover-title,.treb-main.treb-main .treb-note{background:var(--treb-note-background,#fff);border:1px solid var(--treb-note-border-color,var(--treb-ui-border-color,#ddd));border-radius:2px;box-shadow:0 1px 4px 2px hsla(0,0%,43%,.2);color:var(--treb-note-color,#333);font-family:BlinkMacSystemFont,Segoe UI,Roboto,Oxygen-Sans,Ubuntu,Cantarell,Helvetica Neue,"sans-serif";font-size:10.5pt;left:100px;line-height:normal;opacity:0;padding:7px 10px;position:fixed;top:100px;transition:opacity .2s;white-space:pre-line;z-index:39}.treb-main.treb-main .treb-hover-title{min-width:10em;pointer-events:none}.treb-main.treb-main .treb-sort-button{background:#fff;border:1px solid #ccc;border-radius:2px;height:1em;left:100px;opacity:0;pointer-events:none;position:absolute;top:100px;transition:opacity .1s ease;width:1em;z-index:39}.treb-main.treb-main .treb-sort-button:after{box-sizing:border-box}.treb-main.treb-main .treb-sort-button.asc:after{border:.4em solid transparent;border-top-color:currentcolor;content:"";height:.8em;left:50%;opacity:.5;position:absolute;top:50%;transform:translate(-50%,-25%);width:.8em}.treb-main.treb-main .treb-sort-button.desc:after{border:.4em solid transparent;border-bottom-color:currentcolor;content:"";height:.8em;left:50%;opacity:.5;position:absolute;top:50%;transform:translate(-50%,-80%);width:.8em}.treb-main.treb-main .treb-tooltip{border-radius:2px;box-shadow:0 1px 4px 2px hsla(0,0%,43%,.2);display:none;line-height:normal;padding:2px 10px;pointer-events:none;position:fixed;z-index:39}.treb-main.treb-main .treb-tooltip.arrow-up:after{border:4px solid transparent;border-bottom-color:inherit;box-sizing:border-box;content:" ";height:8px;left:calc(50% - 4px);overflow:hidden;position:absolute;top:-8px;width:8px}.treb-main.treb-main .treb-tooltip.arrow-left:after{border:4px solid transparent;border-right-color:inherit;box-sizing:border-box;content:" ";height:8px;left:-8px;overflow:hidden;position:absolute;top:calc(50% - 4px);width:8px}.treb-main.treb-main .treb-dropdown-caret{background:var(--treb-dropdown-caret-background,#fff);border:1px solid var(--treb-dropdown-caret-border-color,#ccc);border-radius:2px;box-shadow:0 1px 4px 2px hsla(0,0%,43%,.2);display:none;height:20px;position:absolute;width:20px;z-index:39}.treb-main.treb-main .treb-dropdown-caret path{fill:none;stroke:var(--treb-dropdown-caret-color,#444);stroke-linecap:round;stroke-linejoin:round;stroke-width:2}.treb-main.treb-main .treb-dropdown-list{background:var(--treb-dropdown-background,#fff);border:1px solid var(--treb-dropdown-border-color,unset);box-shadow:0 1px 4px 2px hsla(0,0%,43%,.2);color:var(--treb-dropdown-color,inherit);display:none;font-size:10pt;max-height:10em;outline:none;overflow-y:auto;position:absolute;text-align:left;z-index:39}.treb-main.treb-main .treb-dropdown-list div{cursor:default;padding:2px}.treb-main.treb-main .treb-dropdown-list div.selected{background:var(--treb-dropdown-selected-background,#555);color:var(--treb-dropdown-selected-color,#fff)}.treb-main.treb-main .treb-dropdown-caret.active{background:var(--treb-dropdown-caret-active-background,#eee)}.treb-main.treb-main .treb-dropdown-caret.active+.treb-dropdown-list{display:block}.treb-main.treb-main .treb-error-highlight{background:rgba(255,0,0,.25);opacity:0;pointer-events:none;position:absolute;transition:opacity .15s ease-in-out;z-index:40}.treb-main.treb-main .treb-autocomplete{box-sizing:border-box;font-size:inherit;font-weight:400;line-height:normal;max-height:10em;overflow-y:auto;position:fixed;text-align:left;top:-1000px;z-index:39}.treb-main.treb-main .treb-autocomplete *{box-sizing:border-box}.treb-main.treb-main .treb-autocomplete ul{list-style-type:none}.treb-main.treb-main .treb-autocomplete ul,.treb-main.treb-main .treb-autocomplete ul li{font-size:inherit;font-weight:inherit;margin:0;padding:0}.treb-main.treb-main .treb-autocomplete ul li a{color:inherit;cursor:default;display:inline-block;font-size:inherit;font-weight:inherit;padding:3px 6px;text-decoration:none;width:100%}.treb-main.treb-main .treb-autocomplete-tooltip{position:fixed;top:-1000px;white-space:pre;z-index:39}.treb-main.treb-main .treb-formula-bar{display:flex;flex-direction:row;gap:.5em;grid-area:1/1/2/2;max-width:100%;overflow-x:hidden;padding:0 2px 12px;text-align:left}.treb-main.treb-main .treb-formula-bar[hidden]{display:none}.treb-main.treb-main .treb-formula-bar .treb-address-label{border:1px solid var(--treb-formula-bar-border-color,var(--treb-ui-border-color,#ccc));border-radius:2px;display:flex;flex-direction:column;height:1.75em;justify-content:center;min-height:1.5em;min-width:95px;padding-left:3px;width:95px}.treb-main.treb-main .treb-formula-bar .treb-address-label>div{outline:none;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.treb-main.treb-main .treb-formula-bar .treb-insert-function-button{background:transparent;border:1px solid var(--treb-formula-bar-border-color,var(--treb-ui-border-color,#ccc));border-radius:2px;height:1.75em;min-height:1.5em}.treb-main.treb-main .treb-formula-bar .treb-insert-function-button[hidden]{display:none}.treb-main.treb-main .treb-formula-bar .expand-button{background:transparent;border:0;border-radius:2px;height:1.75em;margin-left:2px;outline:none;padding:1px}.treb-main.treb-main .treb-formula-bar .expand-button:after{border:5px solid transparent;border-top-color:#999;content:" ";display:inline-block;margin:0;padding:0;position:relative;top:-6px;transition:transform .15s ease}.treb-main.treb-main .treb-formula-bar[expanded] .expand-button:after{transform:rotate(180deg) translateY(6px)}.treb-main.treb-main .treb-formula-bar .treb-editor-container{border:1px solid var(--treb-formula-bar-border-color,var(--treb-ui-border-color,#ccc));border-radius:2px;display:flex;flex-direction:column;flex-grow:1;height:1.75em;justify-content:center;min-width:0}.treb-main.treb-main .treb-formula-bar .treb-editor-container>.treb-editor-shadow{opacity:.4}.treb-main.treb-main .treb-formula-bar[expanded] .treb-editor-container{height:4.5em;transition:height .1s ease-in-out}.treb-main.treb-main .treb-formula-bar[expanded] .treb-editor-container>div{overflow-y:auto}.treb-main.treb-main .treb-formula-bar .treb-editor-container>div{flex-grow:1;line-height:1.35;margin:2px;min-height:1em;outline:none;overflow-x:hidden;overflow-y:hidden;white-space:pre-wrap;width:100%}.treb-main.treb-main .treb-mouse-mask .ghost-tab{position:fixed}.treb-main.treb-main .treb-spreadsheet-footer{align-items:center;grid-area:3/1/4/2}.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tab-container{align-self:flex-start;height:2.2em;overflow:hidden}.treb-main.treb-main .treb-spreadsheet-footer,.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs{color:var(--treb-ui-color,inherit);display:flex;flex-direction:row;height:2.2em;list-style-type:none;max-width:100%;padding-inline-start:0;z-index:2}.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs{height:auto;margin-block-start:0;margin:0;overflow-x:scroll;overflow-y:hidden;scrollbar-width:none}.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs::-webkit-scrollbar{display:none}.treb-main.treb-main .treb-spreadsheet-footer[hidden]{display:none}.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li{display:inline-block;margin:0;position:relative}.treb-main.treb-main .treb-spreadsheet-footer .treb-add-tab,.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab,.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li{align-items:center;border-bottom-left-radius:5px;border-bottom-right-radius:5px;border-top-width:1px;border:1px solid var(--treb-tab-bar-tab-border-color,var(--treb-ui-border-color,#ccc));border-top:0 solid var(--treb-tab-bar-tab-border-color,var(--treb-ui-border-color,#ccc));color:var(--treb-tab-bar-tab-color,var(--treb-ui-color,#fff));cursor:default;display:inline-flex;font-size:inherit;height:100%;justify-content:center;margin-right:-2px;overflow:hidden;padding:0 .75em;z-index:1}.treb-main.treb-main .treb-spreadsheet-footer .treb-add-tab:active,.treb-main.treb-main .treb-spreadsheet-footer .treb-add-tab:focus,.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab:active,.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab:focus,.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li:active,.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li:focus{z-index:3}.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li{height:2.2em;overflow:visible;overflow-x:visible}.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li:last-of-type{margin-right:0}.treb-main.treb-main .treb-spreadsheet-footer .treb-add-tab{margin-left:-1px}.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li{white-space:nowrap}.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li[selected]{z-index:2}.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control{align-items:center;display:flex;flex-direction:row;font-size:inherit;height:2.2em;justify-content:center;position:relative;width:5em}.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control .treb-scale-input{background:transparent;border:1px solid transparent;border-radius:2px;color:inherit;font-family:inherit;font-size:inherit;padding:initial;text-align:center;transition:border-color .25s ease,background-color .25s ease;width:4em}.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control .treb-slider-container{accent-color:var(--treb-scale-slider-accent-color,undefined);align-items:center;background:var(--treb-scale-slider-background,#fff);border:1px solid var(--treb-scale-slider-border-color,var(--treb-ui-border-color,#ccc));display:flex;flex-direction:row;height:4em;justify-content:center;left:.5em;opacity:0;pointer-events:none;position:absolute;top:0;transform:rotate(-90deg);transform-origin:left top;transition:opacity .25s ease;width:10em;z-index:40}.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control .treb-scale-input:focus,.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control:hover .treb-scale-input{border-color:var(--treb-ui-border-color,#ccc)}.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control .treb-slider-container>input[type=range]{width:8.5em}.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control .treb-scale-input:focus+.treb-slider-container,.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control .treb-slider-container:focus-within,.treb-main.treb-main .treb-spreadsheet-footer .treb-scale-control:hover .treb-slider-container{opacity:.85;pointer-events:auto}.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab{align-items:center;background:transparent;border:none;border-bottom-left-radius:5px;border-bottom-right-radius:5px;border-top:0;color:currentColor;cursor:default;display:inline-flex;flex-direction:row;font-size:inherit;margin-right:-2px;min-width:2.5em;padding:.25em .75em;z-index:1}.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab svg{height:1em;opacity:.75;pointer-events:none;transition:opacity .125s ease-in-out;width:1em}.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab:hover svg{opacity:.75}.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab path{stroke:currentColor;stroke-width:1.5px;stroke-linecap:round}.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab:active,.treb-main.treb-main .treb-spreadsheet-footer .treb-delete-tab:focus{z-index:3}.treb-main.treb-main .treb-spreadsheet-footer .treb-stats-panel{flex:1 1;overflow:hidden;text-align:end;text-overflow:ellipsis;white-space:nowrap}.treb-main.treb-main .treb-spreadsheet-footer .treb-stats-panel>*{margin-left:.5em}.treb-main.treb-main .treb-spreadsheet-footer .treb-stats-panel .treb-stats-value{background:var(--treb-stats-value-background,#f8f8ff);border:1px solid var(--treb-stats-value-border-color,var(--treb-ui-border-color,#ddd));border-radius:3px;padding:0 .3em}.treb-main.treb-main .treb-grid .treb-overlay-container{margin:0;opacity:0;outline:none;padding:0;position:absolute;z-index:24}.treb-main.treb-main .treb-grid .treb-overlay-container.align-right .treb-overlay-inset{padding-right:3px;right:0;text-align:right}.treb-main.treb-main .treb-grid .treb-overlay-container.align-center .treb-overlay-inset{left:50%;text-align:center;transform:translateX(-50%)}.treb-main.treb-main .treb-grid .treb-overlay-inset{display:flex;flex-direction:column;height:100%;justify-content:flex-end;margin:0;min-width:100%;padding:0 4px;position:absolute}.treb-main.treb-main .treb-grid .treb-overlay-editor{outline:none;position:relative;white-space:nowrap;white-space:pre}.treb-main.treb-main .treb-grid .treb-overlay-editor.firefox:before{content:"\u200B"}.treb-main.treb-main .treb-spill-border{pointer-events:none;position:absolute;transform:translateZ(0)}.treb-main.treb-main .treb-spill-border rect{stroke:var(--treb-spill-border-color,#5c5ce0);stroke-dasharray:var(--treb-spill-border-dasharray,0);fill:none;stroke-width:var(--treb-spill-border-width,1px);filter:var(--treb-spill-border-filter,drop-shadow(3px 3px 2px rgba(0,0,0,.5)));z-index:35}.treb-main.treb-main .treb-buffer-canvas{display:none;position:absolute}.treb-main.treb-main .treb-spreadsheet-body{grid-area:2/1/3/2;-webkit-overflow-scrolling:touch;-webkit-tap-highlight-color:transparent;display:flex;overflow:hidden;position:relative;z-index:1}.treb-main.treb-main .treb-grid{flex-grow:1;order:2;overflow:scroll;position:relative;-webkit-overflow-scrolling:touch;-webkit-tap-highlight-color:transparent;display:grid;grid-template-columns:100px auto;grid-template-rows:20px auto;outline:none;overscroll-behavior:none}.treb-main.treb-main .treb-grid .tile-cover.grid-cover{grid-area:2/2/3/3}.treb-main.treb-main .treb-grid .tile-cover.column-header-cover{grid-area:1/2/2/3;position:-webkit-sticky;position:sticky;top:0}.treb-main.treb-main .treb-grid .tile-cover.row-header-cover{grid-area:2/1/3/2;left:0;position:-webkit-sticky;position:sticky}.treb-main.treb-main .treb-grid .treb-grid-selection{grid-area:1/1/2/2}.treb-main.treb-main .treb-grid .treb-corner{grid-area:1/1/2/2;position:-webkit-sticky;position:sticky}.treb-main.treb-main .treb-grid .treb-left-header{display:grid;grid-area:2/1/3/2;grid-template-columns:auto;grid-template-rows:auto;position:-webkit-sticky;position:sticky}.treb-main.treb-main .treb-grid .treb-top-header{display:grid;grid-area:1/2/2/3;grid-template-columns:auto;grid-template-rows:auto;position:-webkit-sticky;position:sticky}.treb-main.treb-main .treb-grid .treb-contents{display:grid;grid-area:2/2/3/3;grid-template-columns:auto;grid-template-rows:auto}.treb-main.treb-main .treb-grid.safari::-webkit-scrollbar{-webkit-appearance:none;height:7px;width:7px}.treb-main.treb-main .treb-grid.safari::-webkit-scrollbar-thumb{background-color:rgba(0,0,0,.25);border-radius:4px;-webkit-box-shadow:0 0 1px hsla(0,0%,100%,.5)}.treb-main.treb-main .treb-grid canvas{background:transparent;border:0;margin:0;padding:0}.treb-main.treb-main .treb-grid .nub-select{cursor:crosshair}.treb-main.treb-main .treb-grid .link-pointer{cursor:pointer}.treb-main.treb-main .treb-grid .mock-selection-node{background:red;left:-100px;position:fixed;top:-100px}.treb-main.treb-main .treb-grid .tile-cover{background:transparent;position:relative;z-index:14}.treb-main.treb-main .treb-grid .tile-cover.column-header-cover{z-index:22}.treb-main.treb-main .treb-grid .tile-cover.column-header-cover.resize{cursor:col-resize}.treb-main.treb-main .treb-grid .tile-cover.row-header-cover{z-index:22}.treb-main.treb-main .treb-grid .tile-cover.row-header-cover.resize{cursor:row-resize}.treb-main.treb-main .treb-grid .frozen-annotation-container,.treb-main.treb-main .treb-grid .treb-annotation-container{left:0;pointer-events:none;position:absolute;top:0;z-index:16}.treb-main.treb-main .treb-grid .frozen-annotation-container .annotation,.treb-main.treb-main .treb-grid .treb-annotation-container .annotation{background:hsla(0,0%,100%,.5);border:1px solid #999;overflow:hidden;pointer-events:auto;position:absolute;z-index:1}.treb-main.treb-main .treb-grid .frozen-annotation-container .annotation .annotation-content,.treb-main.treb-main .treb-grid .treb-annotation-container .annotation .annotation-content{font-family:inherit;font-size:inherit;height:100%;left:0;position:absolute;top:0;width:100%;z-index:1}.treb-main.treb-main .treb-grid .frozen-annotation-container .annotation .annotation-move-target,.treb-main.treb-main .treb-grid .treb-annotation-container .annotation .annotation-move-target{cursor:move;height:10%;left:0;min-height:14px;position:absolute;top:0;width:100%;z-index:2}.treb-main.treb-main .treb-grid .frozen-annotation-container .annotation .annotation-resize-target,.treb-main.treb-main .treb-grid .treb-annotation-container .annotation .annotation-resize-target{bottom:0;cursor:nwse-resize;height:10%;min-height:14px;min-width:14px;position:absolute;right:0;width:10%;z-index:3}.treb-main.treb-main .treb-grid .frozen-annotation-container .annotation.clone-focus,.treb-main.treb-main .treb-grid .frozen-annotation-container .annotation.retain-focus,.treb-main.treb-main .treb-grid .frozen-annotation-container .annotation:focus,.treb-main.treb-main .treb-grid .treb-annotation-container .annotation.clone-focus,.treb-main.treb-main .treb-grid .treb-annotation-container .annotation.retain-focus,.treb-main.treb-main .treb-grid .treb-annotation-container .annotation:focus{box-shadow:0 0 0 3px rgba(14,165,233,.33)}.treb-main.treb-main .treb-grid .frozen-annotation-container .move-buffer,.treb-main.treb-main .treb-grid .treb-annotation-container .move-buffer{border:1px solid red;cursor:move;height:10%;left:0;position:absolute;top:0;width:100%}.treb-main.treb-main .treb-grid .treb-grid-selection{background:transparent;position:absolute;transform:translateZ(0);-moz-transform:scale(1);z-index:10}.treb-main.treb-main .treb-grid .frozen-selection{overflow:hidden;pointer-events:none;position:absolute;transform:translateZ(0);-moz-transform:scale(1);transition:background .33s;z-index:12}.treb-main.treb-main .treb-grid .frozen-selection.frozen-selection-rows{border-bottom:1px solid transparent}.treb-main.treb-main .treb-grid .frozen-selection.frozen-selection-columns{border-right:1px solid transparent}.treb-main.treb-main .treb-grid .frozen-annotation-container{height:100%;left:0;overflow:hidden;position:absolute;top:0;width:100%}.treb-main.treb-main .treb-grid .treb-corner{left:0;top:0;z-index:20}.treb-main.treb-main .treb-grid .treb-corner canvas{left:0;pointer-events:none;position:absolute;top:0}.treb-main.treb-main .treb-grid .treb-left-header{left:0;pointer-events:none;z-index:18}.treb-main.treb-main .treb-grid .treb-top-header{pointer-events:none;top:0;z-index:18}.treb-main.treb-main .treb-grid .treb-contents{height:2000px;width:2000px}.treb-main.treb-main{--alternate-selection-color-1:#fbb13c;--alternate-selection-color-2:#40c040;--alternate-selection-color-3:#b66d0d;--alternate-selection-color-4:#2176ae;--alternate-selection-color-5:#fe6847;--text-reference-color-1:#e08a00;--text-reference-color-2:#3aad3a;--text-reference-color-3:#b66d0d;--text-reference-color-4:#2176ae;--text-reference-color-5:#fe2f01}.treb-main.treb-main:focus-within .treb-grid-selection .primary-selection,.treb-main.treb-main:focus-within .treb-header-overlay{color:var(--treb-selection-color,#4caaf1)}.treb-main.treb-main .theme-color-1{color:var(--treb-theme-color-1,#e7e6e6)}.treb-main.treb-main .theme-color-2{color:var(--treb-theme-color-2,#44546a)}.treb-main.treb-main .theme-color-3{color:var(--treb-theme-color-3,#4472c4)}.treb-main.treb-main .theme-color-4{color:var(--treb-theme-color-4,#ed7d31)}.treb-main.treb-main .theme-color-5{color:var(--treb-theme-color-5,#a5a5a5)}.treb-main.treb-main .theme-color-6{color:var(--treb-theme-color-6,#ffc000)}.treb-main.treb-main .theme-color-7{color:var(--treb-theme-color-7,#5b9bd5)}.treb-main.treb-main .theme-color-8{color:var(--treb-theme-color-8,#70ad47)}.treb-main.treb-main .theme-color-9{color:var(--treb-theme-color-9,#0563c1)}.treb-main.treb-main .theme-color-10{color:var(--treb-theme-color-10,#954f72)}.treb-main.treb-main .treb-offset-dark{color:#000}.treb-main.treb-main .treb-offset-light{color:#fff}.treb-main.treb-main .note-marker{background:var(--treb-note-marker-color,#6fab20)}.treb-main.treb-main .grid-headers{background:var(--treb-grid-header-background,#eeeef2);color:var(--treb-grid-header-color,var(--treb-grid-default-color,#666));font-family:var(--treb-grid-header-font-family,inherit);font-size:var(--treb-grid-header-font-size,10pt);font-style:var(--treb-grid-header-font-style,normal);font-weight:var(--treb-grid-header-font-weight,normal);stroke:var(--treb-grid-header-grid-color,var(--treb-grid-grid-color,#ccccd4))}.treb-main.treb-main .grid-cells{color:var(--treb-grid-default-color,inherit);font-family:var(--treb-grid-font-family,inherit);font-size:var(--treb-grid-font-size,14px);stroke:var(--treb-grid-grid-color,#ccccd4);background:var(--treb-grid-background,#fff)}.treb-main.treb-main .frozen-selection.highlight-area{background:rgba(87,184,255,.25);border-bottom-color:#2176ae;border-left-color:#2176ae}.treb-main.treb-main .treb-autocomplete-tooltip{background:var(--treb-autocomplete-tooltip-background,#fffbb5);border:1px solid var(--treb-autocomplete-tooltip-border-color,unset);border-radius:2px;color:var(--treb-autocomplete-tooltip-color,inherit);font-size:14px;line-height:normal;margin:4px 0;padding:3px 8px}.treb-main.treb-main .treb-autocomplete-tooltip .active-argument{font-weight:700}.treb-main.treb-main .treb-autocomplete-tooltip .function-description{font-style:italic}.treb-main.treb-main .treb-autocomplete{background:var(--treb-autocomplete-background,#fff);border:1px solid var(--treb-autocomplete-border-color,var(--treb-ui-border-color,#ccc));border-radius:2px;box-shadow:0 1px 4px 2px hsla(0,0%,43%,.2);font-size:14px}.treb-main.treb-main .treb-autocomplete li{color:var(--treb-autocomplete-entry-color,#333)}.treb-main.treb-main .treb-autocomplete li a.selected{background:var(--treb-autocomplete-selected-entry-background,#2e8dd6);color:var(--treb-autocomplete-selected-entry-color,#fff)}.treb-main.treb-main .treb-header-overlay{stroke:none;color:var(--treb-selection-color-unfocused,var(--treb-selection-color,#4caaf1))}.treb-main.treb-main .treb-header-overlay .treb-overlay{fill:#000;stroke:none;opacity:.05}.treb-main.treb-main .treb-header-overlay .treb-highlight{fill:currentColor}.treb-main.treb-main .treb-editor-container>div [data-highlight-index="1"],.treb-main.treb-main .treb-overlay-editor [data-highlight-index="1"]{color:var(--text-reference-color-1)}.treb-main.treb-main .treb-editor-container>div [data-highlight-index="2"],.treb-main.treb-main .treb-overlay-editor [data-highlight-index="2"]{color:var(--text-reference-color-2)}.treb-main.treb-main .treb-editor-container>div [data-highlight-index="3"],.treb-main.treb-main .treb-overlay-editor [data-highlight-index="3"]{color:var(--text-reference-color-3)}.treb-main.treb-main .treb-editor-container>div [data-highlight-index="4"],.treb-main.treb-main .treb-overlay-editor [data-highlight-index="4"]{color:var(--text-reference-color-4)}.treb-main.treb-main .treb-editor-container>div [data-highlight-index="5"],.treb-main.treb-main .treb-overlay-editor [data-highlight-index="5"]{color:var(--text-reference-color-5)}.treb-main.treb-main .treb-editor-container>div span.highlight-1,.treb-main.treb-main .treb-overlay-editor span.highlight-1{color:var(--text-reference-color-1)}.treb-main.treb-main .treb-editor-container>div span.highlight-2,.treb-main.treb-main .treb-overlay-editor span.highlight-2{color:var(--text-reference-color-2)}.treb-main.treb-main .treb-editor-container>div span.highlight-3,.treb-main.treb-main .treb-overlay-editor span.highlight-3{color:var(--text-reference-color-3)}.treb-main.treb-main .treb-editor-container>div span.highlight-4,.treb-main.treb-main .treb-overlay-editor span.highlight-4{color:var(--text-reference-color-4)}.treb-main.treb-main .treb-editor-container>div span.highlight-5,.treb-main.treb-main .treb-overlay-editor span.highlight-5{color:var(--text-reference-color-5)}.treb-main.treb-main .frozen-selection .selection,.treb-main.treb-main .treb-grid-selection .selection{stroke-width:var(--treb-selection-stroke-width,2px)}.treb-main.treb-main .frozen-selection .selection .treb-selection-outline,.treb-main.treb-main .treb-grid-selection .selection .treb-selection-outline{stroke:currentColor;fill:none}.treb-main.treb-main .frozen-selection .selection .treb-selection-fill,.treb-main.treb-main .treb-grid-selection .selection .treb-selection-fill{stroke:none;fill:currentColor;opacity:var(--treb-selection-fill-opacity,.1)}.treb-main.treb-main .frozen-selection .alternate-selection,.treb-main.treb-main .treb-grid-selection .alternate-selection{stroke-dasharray:var(--treb-alternate-selection-dasharray,3 2)}.treb-main.treb-main .frozen-selection .alternate-selection:nth-of-type(1n),.treb-main.treb-main .treb-grid-selection .alternate-selection:nth-of-type(1n){color:var(--alternate-selection-color-1)}.treb-main.treb-main .frozen-selection .alternate-selection:nth-of-type(2n),.treb-main.treb-main .treb-grid-selection .alternate-selection:nth-of-type(2n){color:var(--alternate-selection-color-2)}.treb-main.treb-main .frozen-selection .alternate-selection:nth-of-type(3n),.treb-main.treb-main .treb-grid-selection .alternate-selection:nth-of-type(3n){color:var(--alternate-selection-color-3)}.treb-main.treb-main .frozen-selection .alternate-selection:nth-of-type(4n),.treb-main.treb-main .treb-grid-selection .alternate-selection:nth-of-type(4n){color:var(--alternate-selection-color-4)}.treb-main.treb-main .frozen-selection .alternate-selection:nth-of-type(5n),.treb-main.treb-main .treb-grid-selection .alternate-selection:nth-of-type(5n){color:var(--alternate-selection-color-5)}.treb-main.treb-main .frozen-selection .primary-selection,.treb-main.treb-main .treb-grid-selection .primary-selection{color:var(--treb-selection-color-unfocused,var(--treb-selection-color,#4caaf1))}.treb-main.treb-main .frozen-selection .primary-selection .treb-selection-nub,.treb-main.treb-main .treb-grid-selection .primary-selection .treb-selection-nub{stroke:#fff;fill:currentColor;stroke-width:1px}.treb-main.treb-main .treb-tooltip{background:var(--treb-resize-tooltip-background,rgba(0,0,0,.8));border-color:var(--treb-resize-tooltip-background,rgba(0,0,0,.8));color:var(--treb-resize-tooltip-color,#fff);font-size:11pt}.treb-main.treb-main .treb-spreadsheet-footer .treb-add-tab,.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li{background:var(--treb-tab-bar-tab-background,#eeeef2);color:var(--treb-tab-bar-tab-color,var(--treb-ui-color,inherit))}.treb-main.treb-main .treb-spreadsheet-footer .treb-add-tab[selected],.treb-main.treb-main .treb-spreadsheet-footer .treb-spreadsheet-tabs>li[selected]{background:var(--treb-tab-bar-active-tab-background,#fff);border-bottom-color:var(--treb-tab-bar-active-tab-border-color,currentColor);color:var(--treb-tab-bar-active-tab-color,var(--treb-ui-color,inherit))}.treb-main.treb-main .treb-formula-bar .treb-address-label,.treb-main.treb-main .treb-formula-bar .treb-editor-container{background:var(--treb-formula-bar-background,transparent);color:var(--treb-formula-bar-color,var(--treb-ui-color,inherit))}.treb-main.treb-main .treb-formula-bar .treb-address-label[locked],.treb-main.treb-main .treb-formula-bar .treb-editor-container[locked]{background:var(--treb-formula-bar-locked-background,#eef4fc);position:relative}.treb-main.treb-main .treb-formula-bar .treb-address-label[locked]:after,.treb-main.treb-main .treb-formula-bar .treb-editor-container[locked]:after{content:"";height:12px;opacity:.4;position:absolute;right:2px;top:2px;width:12px;--icon:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'%3E%3Cpath fill='currentColor' d='M416 224h-16v-80C400 65 335 0 256 0S112 65 112 144v80H96c-35 0-64 29-64 64v160c0 35 29 64 64 64h320c35 0 64-29 64-64V288c0-35-29-64-64-64m-240-80c0-44 36-80 80-80s80 36 80 80v80H176z'/%3E%3C/svg%3E");background:var(--treb-formula-bar-lock-icon-color,currentColor);mask-image:var(--icon);-webkit-mask-image:var(--icon);mask-position:center;-webkit-mask-position:center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;mask-size:12px 12px;-webkit-mask-size:12px 12px}.treb-main.treb-main .treb-annotation-textbox{background:Canvas;height:100%;left:0;overflow:hidden;padding:.5em;position:relative;top:0;width:100%}.treb-main.treb-main .treb-annotation-textbox p{margin-block-end:0;margin-block-start:0}.treb-dark-theme{--treb-autocomplete-background:#333;--treb-autocomplete-border-color:#fff;--treb-autocomplete-entry-color:#fff;--treb-autocomplete-selected-entry-background:darkred;--treb-autocomplete-tooltip-background:darkred;--treb-autocomplete-tooltip-border-color:#fff;--treb-autocomplete-tooltip-color:#fff;--treb-chart-background:#000;--treb-chart-grid-color:#976;--treb-chart-grid-zero-color:#fdd;--treb-chart-text-color:#fff;--treb-dialog-background:#000;--treb-dialog-color:#fff;--treb-dropdown-background:#000;--treb-dropdown-border-color:#fff;--treb-dropdown-caret-active-background:darkred;--treb-dropdown-caret-background:#444;--treb-dropdown-caret-border-color:#fff;--treb-dropdown-caret-color:#fff;--treb-dropdown-color:#fff;--treb-dropdown-selected-background:darkred;--treb-grid-background:#000;--treb-grid-default-color:#fff;--treb-grid-grid-color:#444;--treb-grid-header-background:#444;--treb-grid-header-grid-color:#000;--treb-note-background:#333;--treb-note-border-color:#aaa;--treb-note-color:#fff;--treb-note-marker-color:pink;--treb-resize-tooltip-background:#fff;--treb-resize-tooltip-color:#000;--treb-scale-slider-accent-color:#fff;--treb-scale-slider-background:#333;--treb-scale-slider-border-color:#aaa;--treb-selection-color:#ff0;--treb-selection-fill-opacity:.2;--treb-sidebar-button-background:#000;--treb-sidebar-button-border-color:#888;--treb-stats-value-background:#223;--treb-tab-bar-tab-background:#000;--treb-tab-bar-tab-color:#fff;--treb-theme-color-1:#222;--treb-theme-color-2:#ddd;--treb-toolbar-active-button-background:#555;--treb-toolbar-button-background:#000;--treb-toolbar-hover-button-background:#444;--treb-ui-color:#fff;--treb-table-header-background:#334;--treb-table-odd-background:#122;--treb-table-header-font-weight:700;--treb-table-header-border-top:#889;--treb-table-header-border-bottom:#889;--treb-table-footer-border-bottom:#889;--treb-table-odd-border-top:#889;--treb-table-odd-border-bottom:#889;--treb-table-even-border-top:#889;--treb-table-even-border-bottom:#889;--treb-table-total-border-top:#889;--treb-table-total-border-bottom:#889;--treb-table-total-background:#334;--treb-table-total-font-weight:700;--treb-color-scheme:dark;--treb-resize-handle-color:#add8e6;--treb-resize-frame-color:#add8e6;--treb-formula-bar-locked-background:#234;--treb-grid-background:#1e1e1e;--treb-grid-header-background:#565656;--treb-grid-header-color:#ddd;--treb-tab-bar-active-tab-background:#444;--treb-tab-bar-tab-background:transparent;--treb-tab-bar-tab-border-color:#444;--treb-ui-border-color:#aaa;--treb-toolbar-button-background:#565656;--treb-toolbar-button-background:#212121;--treb-toolbar-border-color:#434343;--treb-toolbar-color:#ddd;--treb-spill-border-color:pink;--treb-spill-border-filter:drop-shadow(3px 3px 2px hsla(0,0%,100%,.95))}@media (prefers-color-scheme:dark){.treb-light-dark-theme{--treb-autocomplete-background:#333;--treb-autocomplete-border-color:#fff;--treb-autocomplete-entry-color:#fff;--treb-autocomplete-selected-entry-background:darkred;--treb-autocomplete-tooltip-background:darkred;--treb-autocomplete-tooltip-border-color:#fff;--treb-autocomplete-tooltip-color:#fff;--treb-chart-background:#000;--treb-chart-grid-color:#976;--treb-chart-grid-zero-color:#fdd;--treb-chart-text-color:#fff;--treb-dialog-background:#000;--treb-dialog-color:#fff;--treb-dropdown-background:#000;--treb-dropdown-border-color:#fff;--treb-dropdown-caret-active-background:darkred;--treb-dropdown-caret-background:#444;--treb-dropdown-caret-border-color:#fff;--treb-dropdown-caret-color:#fff;--treb-dropdown-color:#fff;--treb-dropdown-selected-background:darkred;--treb-grid-background:#000;--treb-grid-default-color:#fff;--treb-grid-grid-color:#444;--treb-grid-header-background:#444;--treb-grid-header-grid-color:#000;--treb-note-background:#333;--treb-note-border-color:#aaa;--treb-note-color:#fff;--treb-note-marker-color:pink;--treb-resize-tooltip-background:#fff;--treb-resize-tooltip-color:#000;--treb-scale-slider-accent-color:#fff;--treb-scale-slider-background:#333;--treb-scale-slider-border-color:#aaa;--treb-selection-color:#ff0;--treb-selection-fill-opacity:.2;--treb-sidebar-button-background:#000;--treb-sidebar-button-border-color:#888;--treb-stats-value-background:#223;--treb-tab-bar-tab-background:#000;--treb-tab-bar-tab-color:#fff;--treb-theme-color-1:#222;--treb-theme-color-2:#ddd;--treb-toolbar-active-button-background:#555;--treb-toolbar-button-background:#000;--treb-toolbar-hover-button-background:#444;--treb-ui-color:#fff;--treb-table-header-background:#334;--treb-table-odd-background:#122;--treb-table-header-font-weight:700;--treb-table-header-border-top:#889;--treb-table-header-border-bottom:#889;--treb-table-footer-border-bottom:#889;--treb-table-odd-border-top:#889;--treb-table-odd-border-bottom:#889;--treb-table-even-border-top:#889;--treb-table-even-border-bottom:#889;--treb-table-total-border-top:#889;--treb-table-total-border-bottom:#889;--treb-table-total-background:#334;--treb-table-total-font-weight:700;--treb-color-scheme:dark;--treb-resize-handle-color:#add8e6;--treb-resize-frame-color:#add8e6;--treb-formula-bar-locked-background:#234;--treb-grid-background:#1e1e1e;--treb-grid-header-background:#565656;--treb-grid-header-color:#ddd;--treb-tab-bar-active-tab-background:#444;--treb-tab-bar-tab-background:transparent;--treb-tab-bar-tab-border-color:#444;--treb-ui-border-color:#aaa;--treb-toolbar-button-background:#565656;--treb-toolbar-button-background:#212121;--treb-toolbar-border-color:#434343;--treb-toolbar-color:#ddd;--treb-spill-border-color:pink;--treb-spill-border-filter:drop-shadow(3px 3px 2px hsla(0,0%,100%,.95))}}.treb-chart,.treb-main.treb-main .treb-chart{background:var(--treb-chart-background,#fff)}.treb-main.treb-main .treb-inherit-font .treb-chart{font-family:inherit}.treb-chart{--segment-2-offset:-20;--segment-3-offset:10;--segment-4-offset:-10;--segment-5-offset:20;--segment-6-offset:-25}.treb-chart .series-1{color:var(--treb-applied-theme-color-1)}.treb-chart .series-2{color:var(--treb-applied-theme-color-2)}.treb-chart .series-3{color:var(--treb-applied-theme-color-3)}.treb-chart .series-4{color:var(--treb-applied-theme-color-4)}.treb-chart .series-5{color:var(--treb-applied-theme-color-5)}.treb-chart .series-6{color:var(--treb-applied-theme-color-6)}.treb-chart .series-7{color:lch(from var(--treb-applied-theme-color-1) calc(l + var(--segment-2-offset)) c h)}.treb-chart .series-8{color:lch(from var(--treb-applied-theme-color-2) calc(l + var(--segment-2-offset)) c h)}.treb-chart .series-9{color:lch(from var(--treb-applied-theme-color-3) calc(l + var(--segment-2-offset)) c h)}.treb-chart .series-10{color:lch(from var(--treb-applied-theme-color-4) calc(l + var(--segment-2-offset)) c h)}.treb-chart .series-11{color:lch(from var(--treb-applied-theme-color-5) calc(l + var(--segment-2-offset)) c h)}.treb-chart .series-12{color:lch(from var(--treb-applied-theme-color-6) calc(l + var(--segment-2-offset)) c h)}.treb-chart .series-13{color:lch(from var(--treb-applied-theme-color-1) calc(l + var(--segment-3-offset)) c h)}.treb-chart .series-14{color:lch(from var(--treb-applied-theme-color-2) calc(l + var(--segment-3-offset)) c h)}.treb-chart .series-15{color:lch(from var(--treb-applied-theme-color-3) calc(l + var(--segment-3-offset)) c h)}.treb-chart .series-16{color:lch(from var(--treb-applied-theme-color-4) calc(l + var(--segment-3-offset)) c h)}.treb-chart .series-17{color:lch(from var(--treb-applied-theme-color-5) calc(l + var(--segment-3-offset)) c h)}.treb-chart .series-18{color:lch(from var(--treb-applied-theme-color-6) calc(l + var(--segment-3-offset)) c h)}.treb-chart .series-19{color:lch(from var(--treb-applied-theme-color-1) calc(l + var(--segment-4-offset)) c h)}.treb-chart .series-20{color:lch(from var(--treb-applied-theme-color-2) calc(l + var(--segment-4-offset)) c h)}.treb-chart .series-21{color:lch(from var(--treb-applied-theme-color-3) calc(l + var(--segment-4-offset)) c h)}.treb-chart .series-22{color:lch(from var(--treb-applied-theme-color-4) calc(l + var(--segment-4-offset)) c h)}.treb-chart .series-23{color:lch(from var(--treb-applied-theme-color-5) calc(l + var(--segment-4-offset)) c h)}.treb-chart .series-24{color:lch(from var(--treb-applied-theme-color-6) calc(l + var(--segment-4-offset)) c h)}.treb-chart .series-25{color:lch(from var(--treb-applied-theme-color-1) calc(l + var(--segment-5-offset)) c h)}.treb-chart .series-26{color:lch(from var(--treb-applied-theme-color-2) calc(l + var(--segment-5-offset)) c h)}.treb-chart .series-27{color:lch(from var(--treb-applied-theme-color-3) calc(l + var(--segment-5-offset)) c h)}.treb-chart .series-28{color:lch(from var(--treb-applied-theme-color-4) calc(l + var(--segment-5-offset)) c h)}.treb-chart .series-29{color:lch(from var(--treb-applied-theme-color-5) calc(l + var(--segment-5-offset)) c h)}.treb-chart .series-30{color:lch(from var(--treb-applied-theme-color-6) calc(l + var(--segment-5-offset)) c h)}.treb-chart .series-31{color:lch(from var(--treb-applied-theme-color-1) calc(l + var(--segment-6-offset)) c h)}.treb-chart .series-32{color:lch(from var(--treb-applied-theme-color-2) calc(l + var(--segment-6-offset)) c h)}.treb-chart .series-33{color:lch(from var(--treb-applied-theme-color-3) calc(l + var(--segment-6-offset)) c h)}.treb-chart .series-34{color:lch(from var(--treb-applied-theme-color-4) calc(l + var(--segment-6-offset)) c h)}.treb-chart .series-35{color:lch(from var(--treb-applied-theme-color-5) calc(l + var(--segment-6-offset)) c h)}.treb-chart .series-36{color:lch(from var(--treb-applied-theme-color-6) calc(l + var(--segment-6-offset)) c h)}.treb-chart .chart-title{font-size:1.4em}.treb-chart .axis-group{font-size:.9em}.treb-chart .axis-group .series-name{font-size:1.3em}.treb-chart text{fill:var(--treb-chart-text-color,#000);stroke:none}.treb-chart .legend{font-size:1.05em}.treb-chart .legend rect{fill:currentColor}.treb-chart .legend circle{fill:currentColor;fill-opacity:.5;stroke:currentColor;stroke-width:2px;r:.25em}.treb-chart .chart-grid,.treb-chart .chart-ticks{stroke:var(--treb-chart-grid-color,#ddd)}.treb-chart .chart-grid.zero,.treb-chart .chart-ticks.zero{stroke:var(--treb-chart-grid-zero-color,var(--treb-chart-grid-color,#999))}.treb-chart .label-target{stroke:none;fill:transparent}.treb-chart path.label-target{transition:fill .2s}.treb-chart path.label-target:hover{fill:rgba(0,0,0,.15)}.treb-chart .data-label{opacity:0;pointer-events:none;transition:opacity .2s ease-in-out}.treb-chart .data-label text{fill:#fff}.treb-chart .data-label path{fill:#000}.treb-chart .data-label .marker-highlight{fill:currentColor;stroke:none}.treb-chart .label-target:hover+.data-label{opacity:1}.treb-chart .chart-line{stroke:currentColor;fill:none;stroke-width:2}.treb-chart .chart-area .line{stroke:currentColor;stroke-width:2px;fill:none}.treb-chart .chart-area .fill{fill:currentColor;opacity:.5}.treb-chart .box-plot .iqr{fill:none;stroke:CanvasText;stroke-width:1px}.treb-chart .box-plot .median{stroke-width:3px;stroke:CanvasText;fill:none}.treb-chart .box-plot .outlier{r:3}.treb-chart .box-plot .outlier,.treb-chart .box-plot .whisker,.treb-chart .box-plot .whisker-extent{stroke-width:1px;stroke:CanvasText;fill:none}.treb-chart .box-plot .whisker-extent{stroke-dasharray:3 3}.treb-chart .bubble-chart{stroke-width:3;fill:color-mix(in srgb,currentColor 75%,transparent);stroke:currentColor}.treb-chart .bubble-label .label-background{stroke:none;fill:none}.treb-chart .bubble-label .label-text{transform:translate(var(--translate-offset),var(--translate-offset))}.treb-chart .scatter-plot{stroke-width:3;fill:none;stroke:currentColor}.treb-chart .scatter-plot .fill{fill:currentColor;opacity:.5;stroke:none}.treb-chart .scatter-plot .marker{stroke-width:2.5px;fill:#fff;transition:stroke-width .15s ease-in}.treb-chart .scatter-plot .marker:hover{stroke-width:5px}.treb-chart .donut path{fill:currentColor}.treb-chart .donut path.callout{fill:none;stroke:#999;stroke-dasharray:2 2}.treb-chart .donut text.callout-label{font-size:1em}.treb-chart .chart-column{fill:currentColor;stroke:none}.treb-chart .mc-correlation{stroke:currentColor;stroke-width:1}.treb-main.treb-main{--treb-icon-svg:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='153.073' height='133.742' viewBox='0.673 4.629 153.073 133.742'%3E%3ClinearGradient id='a' x1='.673' x2='153.746' y1='71.5' y2='71.5' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0' style='stop-color:%235cb5ff'/%3E%3Cstop offset='1' style='stop-color:%230059b9'/%3E%3C/linearGradient%3E%3Cpath fill='url(%23a)' d='M91.656 28.313c-4.989 0-17.266 6.249-21.305 8.504-2.344-2.473-2.603-6.162-3.036-10.933-2.344 2.429-.824 9.806 0 12.496-10.238 7.635-18.83 15.531-27.597 24.471-2.992-4.729-5.031-8.593-5.726-17.183-3.038 6.509.867 15.057 3.121 19.784-9.674 12.193-19.263 25.297-27.03 37.834-35.488-74.973 72.853-119.534 143.663-88.855-43.867 29.199-55.192 121.353-132.248 96.843-5.423 7.809-9.069 18.006-13.538 27.072-3.73.263-6.334-1.646-7.288-3.12 7.506-18.181 17.183-34.192 27.075-49.984 10.718.306 21.346.478 30.198-1.04-7.681-2.038-16.877-.78-26.032-3.123C37.51 70.361 45.667 62.203 53.78 54.004c8.808.782 17.746 3.21 27.074 1.041-8.111-1.431-15.966-1.952-22.909-4.165 7.594-8.378 22.777-17.491 33.711-22.567'/%3E%3C/svg%3E")}.treb-main.treb-main .treb-icon-64{background:no-repeat 50%/100% var(--treb-icon-svg);height:64px;width:64px}.treb-main.treb-main .treb-dialog-mask{align-items:center;display:flex;height:100%;justify-content:center;left:0;opacity:0;pointer-events:none;position:absolute;top:0;transition:opacity .2s;width:100%;z-index:1000}.treb-main.treb-main .treb-embed-dialog{align-items:center;background:var(--treb-dialog-background,#fff);border:1px solid var(--treb-dialog-border-color,var(--treb-ui-border-color,#999));border-radius:3px;border-top:3px solid #999;box-shadow:0 4px 6px -4px rgba(0,0,0,.3);color:var(--treb-dialog-color,#000);display:flex;flex-direction:row;font-size:var(--treb-dialog-font-size,16px);line-height:1.6em;padding:1rem;position:relative;text-align:left}.treb-main.treb-main .treb-embed-dialog>*{display:none}.treb-main.treb-main .treb-embed-dialog>div{position:relative}.treb-main.treb-main .treb-embed-dialog>:nth-child(2){display:block;flex-grow:1;padding:2px 20px 2px 12px}.treb-main.treb-main .treb-embed-dialog>.treb-close-box{background:transparent;border:0;padding:4px;position:absolute;right:0;top:0}.treb-main.treb-main .treb-embed-dialog>.treb-close-box>svg{fill:#73828c;cursor:default;height:20px;width:20px}.treb-main.treb-main .treb-embed-dialog>.treb-close-box>svg:active,.treb-main.treb-main .treb-embed-dialog>.treb-close-box>svg:hover{fill:#049cfb}.treb-main.treb-main .treb-embed-dialog small{display:block;font-size:.9em}.treb-main.treb-main .treb-embed-dialog a{color:inherit;text-decoration:none}.treb-main.treb-main .treb-embed-dialog a:active,.treb-main.treb-main .treb-embed-dialog a:hover{color:#049cfb}.treb-main.treb-main .treb-embed-dialog.dialog-type-success{border-top-color:#44d926;border-top-width:3px}.treb-main.treb-main .treb-embed-dialog.dialog-type-about{border-top-color:#009dff;border-top-width:3px}.treb-main.treb-main .treb-embed-dialog.dialog-type-error{border-top-color:#f92f06;border-top-width:3px}.treb-main.treb-main .treb-embed-dialog.dialog-type-info{border-top-color:#009dff;border-top-width:3px}.treb-main.treb-main .treb-embed-dialog .treb-embed-dialog-message,.treb-main.treb-main .treb-embed-dialog .treb-embed-dialog-title{white-space:pre}.treb-main.treb-main .treb-embed-dialog .treb-embed-progress-container{border:1px solid #ddd;height:6px;margin:1rem auto .5rem;position:relative;width:100%}.treb-main.treb-main .treb-embed-dialog .treb-embed-progress-bar{background:#52880b;height:100%;left:0;position:relative;top:0}.treb-main.treb-main .treb-spinner{align-items:center;background:transparent;display:flex;height:100%;justify-content:center;left:0;opacity:0;position:absolute;top:0;transition:visibility .25s,opacity .25s ease;visibility:collapse;width:100%;z-index:1000}.treb-main.treb-main .treb-spinner.visible{opacity:1;transition:visibility 0s,opacity 1s ease;visibility:visible}.treb-main.treb-main .treb-spinner>div{display:inline-block;height:80px;position:relative;width:80px}.treb-main.treb-main .treb-spinner>div div{animation:treb-spinner 1.2s cubic-bezier(.5,0,.5,1) infinite;border:8px solid #fff;border-color:var(--treb-spinner-color,currentColor) transparent transparent transparent;border-radius:50%;box-sizing:border-box;display:block;height:64px;margin:8px;position:absolute;width:64px}.treb-main.treb-main .treb-spinner>div div:first-child{animation-delay:-.45s}.treb-main.treb-main .treb-spinner>div div:nth-child(2){animation-delay:-.3s}.treb-main.treb-main .treb-spinner>div div:nth-child(3){animation-delay:-.15s}@keyframes treb-spinner{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}.treb-main.treb-main{--icon-x:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708"/></svg>');--icon-popout:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 28 28"><path fill="currentColor" d="M22 14.5v5c0 2.484-2.016 4.5-4.5 4.5h-13A4.5 4.5 0 0 1 0 19.5v-13C0 4.016 2.016 2 4.5 2h11c.281 0 .5.219.5.5v1c0 .281-.219.5-.5.5h-11A2.507 2.507 0 0 0 2 6.5v13C2 20.875 3.125 22 4.5 22h13c1.375 0 2.5-1.125 2.5-2.5v-5c0-.281.219-.5.5-.5h1c.281 0 .5.219.5.5M28 1v8c0 .547-.453 1-1 1a1 1 0 0 1-.703-.297l-2.75-2.75L13.36 17.14c-.094.094-.234.156-.359.156s-.266-.063-.359-.156l-1.781-1.781c-.094-.094-.156-.234-.156-.359s.063-.266.156-.359L21.048 4.454l-2.75-2.75a1 1 0 0 1-.297-.703c0-.547.453-1 1-1h8c.547 0 1 .453 1 1z"/></svg>');--icon-toolbar:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 28"><path fill="currentColor" d="M5.5 22v2H0v-2zm5.5-2c.547 0 1 .453 1 1v4c0 .547-.453 1-1 1H7c-.547 0-1-.453-1-1v-4c0-.547.453-1 1-1zm2.5-6v2H0v-2zm-10-8v2H0V6zM24 22v2H12.5v-2zM9 4c.547 0 1 .453 1 1v4c0 .547-.453 1-1 1H5c-.547 0-1-.453-1-1V5c0-.547.453-1 1-1zm10 8c.547 0 1 .453 1 1v4c0 .547-.453 1-1 1h-4c-.547 0-1-.453-1-1v-4c0-.547.453-1 1-1zm5 2v2h-3.5v-2zm0-8v2H10.5V6z"/></svg>');--icon-export:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 26 28"><path fill="currentColor" d="M20 21c0-.547-.453-1-1-1s-1 .453-1 1 .453 1 1 1 1-.453 1-1m4 0c0-.547-.453-1-1-1s-1 .453-1 1 .453 1 1 1 1-.453 1-1m2-3.5v5a1.5 1.5 0 0 1-1.5 1.5h-23A1.5 1.5 0 0 1 0 22.5v-5A1.5 1.5 0 0 1 1.5 16h7.266l2.109 2.125c.578.562 1.328.875 2.125.875s1.547-.313 2.125-.875L17.25 16h7.25a1.5 1.5 0 0 1 1.5 1.5m-5.078-8.891a.98.98 0 0 1-.219 1.094l-7 7c-.187.203-.453.297-.703.297s-.516-.094-.703-.297l-7-7a.98.98 0 0 1-.219-1.094C5.234 8.25 5.594 8 6 8h4V1c0-.547.453-1 1-1h4c.547 0 1 .453 1 1v7h4c.406 0 .766.25.922.609"/></svg>');--icon-reset:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 28"><path fill="currentColor" d="M23.609 16.5c0 .031 0 .078-.016.109C22.265 22.14 17.702 26 11.937 26c-3.047 0-6-1.203-8.219-3.313l-2.016 2.016A1 1 0 0 1 .999 25c-.547 0-1-.453-1-1v-7c0-.547.453-1 1-1h7c.547 0 1 .453 1 1a1 1 0 0 1-.297.703l-2.141 2.141A7.99 7.99 0 0 0 11.998 22a7.98 7.98 0 0 0 6.813-3.813c.375-.609.562-1.203.828-1.828.078-.219.234-.359.469-.359h3c.281 0 .5.234.5.5zM24 4v7c0 .547-.453 1-1 1h-7c-.547 0-1-.453-1-1a1 1 0 0 1 .297-.703l2.156-2.156A8.04 8.04 0 0 0 12 6a7.98 7.98 0 0 0-6.813 3.813c-.375.609-.562 1.203-.828 1.828-.078.219-.234.359-.469.359H.781a.503.503 0 0 1-.5-.5v-.109C1.625 5.844 6.234 2 12 2c3.063 0 6.047 1.219 8.266 3.313l2.031-2.016A1 1 0 0 1 23 3c.547 0 1 .453 1 1"/></svg>');--icon-about:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 28"><path fill="currentColor" d="M14 21.5v-3c0-.281-.219-.5-.5-.5h-3c-.281 0-.5.219-.5.5v3c0 .281.219.5.5.5h3c.281 0 .5-.219.5-.5M18 11c0-2.859-3-5-5.688-5-2.547 0-4.453 1.094-5.797 3.328a.49.49 0 0 0 .125.656l2.063 1.563a.48.48 0 0 0 .297.094.5.5 0 0 0 .391-.187c.734-.938 1.047-1.219 1.344-1.437.266-.187.781-.375 1.344-.375 1 0 1.922.641 1.922 1.328 0 .812-.422 1.219-1.375 1.656-1.109.5-2.625 1.797-2.625 3.313v.562c0 .281.219.5.5.5h3c.281 0 .5-.219.5-.5 0-.359.453-1.125 1.188-1.547 1.188-.672 2.812-1.578 2.812-3.953zm6 3c0 6.625-5.375 12-12 12S0 20.625 0 14 5.375 2 12 2s12 5.375 12 12"/></svg>');--icon-chevron-left:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 21 28"><path fill="currentColor" d="M18.297 4.703 10 13l8.297 8.297a.99.99 0 0 1 0 1.406l-2.594 2.594a.99.99 0 0 1-1.406 0L2.703 13.703a.99.99 0 0 1 0-1.406L14.297.703a.99.99 0 0 1 1.406 0l2.594 2.594a.99.99 0 0 1 0 1.406"/></svg>');--icon-chevron-right:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 19 28"><path fill="currentColor" d="M17.297 13.703 5.703 25.297a.99.99 0 0 1-1.406 0l-2.594-2.594a.99.99 0 0 1 0-1.406L10 13 1.703 4.703a.99.99 0 0 1 0-1.406L4.297.703a.99.99 0 0 1 1.406 0l11.594 11.594a.99.99 0 0 1 0 1.406"/></svg>');--icon-revert:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 28"><path fill="currentColor" d="M24 14c0 6.609-5.391 12-12 12a11.97 11.97 0 0 1-9.234-4.328.52.52 0 0 1 .031-.672l2.141-2.156a.6.6 0 0 1 .391-.141.5.5 0 0 1 .359.187A7.91 7.91 0 0 0 12 21.999c4.406 0 8-3.594 8-8s-3.594-8-8-8A7.95 7.95 0 0 0 6.563 8.14l2.141 2.156a.96.96 0 0 1 .219 1.078 1 1 0 0 1-.922.625h-7c-.547 0-1-.453-1-1v-7c0-.406.25-.766.625-.922a.96.96 0 0 1 1.078.219l2.031 2.016c2.203-2.078 5.187-3.313 8.266-3.313 6.609 0 12 5.391 12 12zM14 9.5v7c0 .281-.219.5-.5.5h-5a.494.494 0 0 1-.5-.5v-1c0-.281.219-.5.5-.5H12V9.5c0-.281.219-.5.5-.5h1c.281 0 .5.219.5.5"/></svg>');--icon-text-indent:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-text-indent-left" viewBox="0 0 16 16"><path d="M2 3.5a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5m.646 2.146a.5.5 0 0 1 .708 0l2 2a.5.5 0 0 1 0 .708l-2 2a.5.5 0 0 1-.708-.708L4.293 8 2.646 6.354a.5.5 0 0 1 0-.708M7 6.5a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1h-6a.5.5 0 0 1-.5-.5m0 3a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1h-6a.5.5 0 0 1-.5-.5m-5 3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5"/></svg>');--icon-text-outdent:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-text-indent-right" viewBox="0 0 16 16"><path d="M2 3.5a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5m10.646 2.146a.5.5 0 0 1 .708.708L11.707 8l1.647 1.646a.5.5 0 0 1-.708.708l-2-2a.5.5 0 0 1 0-.708zM2 6.5a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1h-6a.5.5 0 0 1-.5-.5m0 3a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1h-6a.5.5 0 0 1-.5-.5m0 3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5"/></svg>');--icon-text-align-left:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M2 12.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5m0-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5m0-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5m0-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5"/></svg>');--icon-text-align-center:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M4 12.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5m-2-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5m2-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5m-2-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5"/></svg>');--icon-text-align-right:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M6 12.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5m-4-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5m4-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5m-4-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5"/></svg>');--icon-text-align-top:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='16' height='16' viewBox='0 0 16 16'%3E%3Cpath d='M8 15a.5.5 0 0 0 .5-.5V5.707l3.146 3.146a.5.5 0 0 0 .707-.707l-4-4a.5.5 0 0 0-.706-.001l-.001.001-4 4a.5.5 0 0 0 .708.707L7.5 5.707V14.5a.5.5 0 0 0 .5.5'/%3E%3Cpath fill='none' stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-miterlimit='10' d='M3 1.5h10'/%3E%3C/svg%3E");--icon-text-align-middle:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M1 8a.5.5 0 0 1 .5-.5h13a.5.5 0 0 1 0 1h-13A.5.5 0 0 1 1 8m7-8a.5.5 0 0 1 .5.5v3.793l1.146-1.147a.5.5 0 0 1 .708.708l-2 2a.5.5 0 0 1-.708 0l-2-2a.5.5 0 1 1 .708-.708L7.5 4.293V.5A.5.5 0 0 1 8 0m-.5 11.707-1.146 1.147a.5.5 0 0 1-.708-.708l2-2a.5.5 0 0 1 .708 0l2 2a.5.5 0 0 1-.708.708L8.5 11.707V15.5a.5.5 0 0 1-1 0z"/></svg>');--icon-text-align-bottom:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='16' height='16' viewBox='0 0 16 16'%3E%3Cpath d='M8 1a.5.5 0 0 0-.5.5v8.793L4.354 7.146a.5.5 0 0 0-.707.707l4 4a.5.5 0 0 0 .707.001l.001-.001 4-4a.5.5 0 0 0-.708-.707L8.5 10.293V1.5A.5.5 0 0 0 8 1'/%3E%3Cpath fill='none' stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-miterlimit='10' d='M13 14.5H3'/%3E%3C/svg%3E");--icon-file-menu:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M.54 3.87.5 3a2 2 0 0 1 2-2h3.672a2 2 0 0 1 1.414.586l.828.828A2 2 0 0 0 9.828 3h3.982a2 2 0 0 1 1.992 2.181l-.637 7A2 2 0 0 1 13.174 14H2.826a2 2 0 0 1-1.991-1.819l-.637-7a2 2 0 0 1 .342-1.31zM2.19 4a1 1 0 0 0-.996 1.09l.637 7a1 1 0 0 0 .995.91h10.348a1 1 0 0 0 .995-.91l.637-7A1 1 0 0 0 13.81 4zm4.69-1.707A1 1 0 0 0 6.172 2H2.5a1 1 0 0 0-1 .981l.006.139q.323-.119.684-.12h5.396z"/></svg>');--icon-wrap-text:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M4 5h8a.5.5 0 0 0 0-1H4a.5.5 0 0 0 0 1M10 8H4a.5.5 0 0 0 0 1h6a1.5 1.5 0 0 1 0 3v-1.203l-2.953 1.707L10 14.203V13a2.5 2.5 0 1 0 0-5M3.75 12.5a.5.5 0 0 0 .5.5H6v-1H4.25a.5.5 0 0 0-.5.5"/></svg>');--icon-unmerge-cells:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M1.5 1a.5.5 0 0 0-.5.5v4a.5.5 0 0 1-1 0v-4A1.5 1.5 0 0 1 1.5 0h4a.5.5 0 0 1 0 1zM10 .5a.5.5 0 0 1 .5-.5h4A1.5 1.5 0 0 1 16 1.5v4a.5.5 0 0 1-1 0v-4a.5.5 0 0 0-.5-.5h-4a.5.5 0 0 1-.5-.5M.5 10a.5.5 0 0 1 .5.5v4a.5.5 0 0 0 .5.5h4a.5.5 0 0 1 0 1h-4A1.5 1.5 0 0 1 0 14.5v-4a.5.5 0 0 1 .5-.5m15 0a.5.5 0 0 1 .5.5v4a1.5 1.5 0 0 1-1.5 1.5h-4a.5.5 0 0 1 0-1h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 1 .5-.5"/></svg>');--icon-merge-cells:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M5.5 0a.5.5 0 0 1 .5.5v4A1.5 1.5 0 0 1 4.5 6h-4a.5.5 0 0 1 0-1h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 1 .5-.5m5 0a.5.5 0 0 1 .5.5v4a.5.5 0 0 0 .5.5h4a.5.5 0 0 1 0 1h-4A1.5 1.5 0 0 1 10 4.5v-4a.5.5 0 0 1 .5-.5M0 10.5a.5.5 0 0 1 .5-.5h4A1.5 1.5 0 0 1 6 11.5v4a.5.5 0 0 1-1 0v-4a.5.5 0 0 0-.5-.5h-4a.5.5 0 0 1-.5-.5m10 1a1.5 1.5 0 0 1 1.5-1.5h4a.5.5 0 0 1 0 1h-4a.5.5 0 0 0-.5.5v4a.5.5 0 0 1-1 0z"/></svg>');--icon-lock:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M8 1a2 2 0 0 1 2 2v4H6V3a2 2 0 0 1 2-2m3 6V3a3 3 0 0 0-6 0v4a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2M5 8h6a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1"/></svg>');--icon-comment:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M14 1a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1h-2.5a2 2 0 0 0-1.6.8L8 14.333 6.1 11.8a2 2 0 0 0-1.6-.8H2a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1zM2 0a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2.5a1 1 0 0 1 .8.4l1.9 2.533a1 1 0 0 0 1.6 0l1.9-2.533a1 1 0 0 1 .8-.4H14a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2z"/></svg>');--icon-fill-color:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M6.192 2.78c-.458-.677-.927-1.248-1.35-1.643a3 3 0 0 0-.71-.515c-.217-.104-.56-.205-.882-.02-.367.213-.427.63-.43.896-.003.304.064.664.173 1.044.196.687.556 1.528 1.035 2.402L.752 8.22c-.277.277-.269.656-.218.918.055.283.187.593.36.903.348.627.92 1.361 1.626 2.068.707.707 1.441 1.278 2.068 1.626.31.173.62.305.903.36.262.05.64.059.918-.218l5.615-5.615c.118.257.092.512.05.939-.03.292-.068.665-.073 1.176v.123h.003a1 1 0 0 0 1.993 0H14v-.057a1 1 0 0 0-.004-.117c-.055-1.25-.7-2.738-1.86-3.494a4 4 0 0 0-.211-.434c-.349-.626-.92-1.36-1.627-2.067S8.857 3.052 8.23 2.704c-.31-.172-.62-.304-.903-.36-.262-.05-.64-.058-.918.219l-.217.216zM4.16 1.867c.381.356.844.922 1.311 1.632l-.704.705c-.382-.727-.66-1.402-.813-1.938a3.3 3.3 0 0 1-.131-.673q.137.09.337.274m.394 3.965c.54.852 1.107 1.567 1.607 2.033a.5.5 0 1 0 .682-.732c-.453-.422-1.017-1.136-1.564-2.027l1.088-1.088q.081.181.183.365c.349.627.92 1.361 1.627 2.068.706.707 1.44 1.278 2.068 1.626q.183.103.365.183l-4.861 4.862a1 1 0 0 1-.068-.01c-.137-.027-.342-.104-.608-.252-.524-.292-1.186-.8-1.846-1.46s-1.168-1.32-1.46-1.846c-.147-.265-.225-.47-.251-.607a1 1 0 0 1-.01-.068zm2.87-1.935a2.4 2.4 0 0 1-.241-.561c.135.033.324.11.562.241.524.292 1.186.8 1.846 1.46.45.45.83.901 1.118 1.31a3.5 3.5 0 0 0-1.066.091 11 11 0 0 1-.76-.694c-.66-.66-1.167-1.322-1.458-1.847z"/></svg>');--icon-text-color:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="16" height="16" viewBox="0 0 16 16"><path d="m12.259 14.001-1.389-3.727H5.465l-1.354 3.727h-1.3L7.609 1.397h1.178l4.772 12.604zM8.418 3.604a6 6 0 0 1-.127-.387 4 4 0 0 1-.11-.501h-.035a5.5 5.5 0 0 1-.247.888L5.86 9.211h4.614z"/></svg>');--icon-border-bottom:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M.969 0H0v.969h.5V1h.469V.969H1V.5H.969zm.937 1h.938V0h-.938zm1.875 0h.938V0H3.78v1zm1.875 0h.938V0h-.938zM7.531.969V1h.938V.969H8.5V.5h-.031V0H7.53v.5H7.5v.469zM9.406 1h.938V0h-.938zm1.875 0h.938V0h-.938zm1.875 0h.938V0h-.938zm1.875 0h.469V.969h.5V0h-.969v.5H15v.469h.031zM1 2.844v-.938H0v.938zm6.5-.938v.938h1v-.938zm7.5 0v.938h1v-.938zM1 4.719V3.78H0v.938h1zm6.5-.938v.938h1V3.78h-1zm7.5 0v.938h1V3.78h-1zM1 6.594v-.938H0v.938zm6.5-.938v.938h1v-.938zm7.5 0v.938h1v-.938zM.5 8.5h.469v-.031H1V7.53H.969V7.5H.5v.031H0v.938h.5zm1.406 0h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm2.813 0v-.031H8.5V7.53h-.031V7.5H7.53v.031H7.5v.938h.031V8.5zm.937 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.469v-.031h.5V7.53h-.5V7.5h-.469v.031H15v.938h.031zM0 9.406v.938h1v-.938zm7.5 0v.938h1v-.938zm8.5.938v-.938h-1v.938zm-16 .937v.938h1v-.938zm7.5 0v.938h1v-.938zm8.5.938v-.938h-1v.938zm-16 .937v.938h1v-.938zm7.5 0v.938h1v-.938zm8.5.938v-.938h-1v.938zM0 15h16v1H0z"/></svg>');--icon-border-top:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M0 0v1h16V0zm1 2.844v-.938H0v.938zm6.5-.938v.938h1v-.938zm7.5 0v.938h1v-.938zM1 4.719V3.78H0v.938h1zm6.5-.938v.938h1V3.78h-1zm7.5 0v.938h1V3.78h-1zM1 6.594v-.938H0v.938zm6.5-.938v.938h1v-.938zm7.5 0v.938h1v-.938zM.5 8.5h.469v-.031H1V7.53H.969V7.5H.5v.031H0v.938h.5zm1.406 0h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm2.813 0v-.031H8.5V7.53h-.031V7.5H7.53v.031H7.5v.938h.031V8.5zm.937 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.469v-.031h.5V7.53h-.5V7.5h-.469v.031H15v.938h.031zM0 9.406v.938h1v-.938zm7.5 0v.938h1v-.938zm8.5.938v-.938h-1v.938zm-16 .937v.938h1v-.938zm7.5 0v.938h1v-.938zm8.5.938v-.938h-1v.938zm-16 .937v.938h1v-.938zm7.5 0v.938h1v-.938zm8.5.938v-.938h-1v.938zM0 16h.969v-.5H1v-.469H.969V15H.5v.031H0zm1.906 0h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm1.875-.5v.5h.938v-.5H8.5v-.469h-.031V15H7.53v.031H7.5v.469zm1.875.5h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875-.5v.5H16v-.969h-.5V15h-.469v.031H15v.469z"/></svg>');--icon-border-left:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M0 0v16h1V0zm1.906 1h.938V0h-.938zm1.875 0h.938V0H3.78v1zm1.875 0h.938V0h-.938zM7.531.969V1h.938V.969H8.5V.5h-.031V0H7.53v.5H7.5v.469zM9.406 1h.938V0h-.938zm1.875 0h.938V0h-.938zm1.875 0h.938V0h-.938zm1.875 0h.469V.969h.5V0h-.969v.5H15v.469h.031zM7.5 1.906v.938h1v-.938zm7.5 0v.938h1v-.938zM7.5 3.781v.938h1V3.78h-1zm7.5 0v.938h1V3.78h-1zM7.5 5.656v.938h1v-.938zm7.5 0v.938h1v-.938zM1.906 8.5h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm2.813 0v-.031H8.5V7.53h-.031V7.5H7.53v.031H7.5v.938h.031V8.5zm.937 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.469v-.031h.5V7.53h-.5V7.5h-.469v.031H15v.938h.031zM7.5 9.406v.938h1v-.938zm8.5.938v-.938h-1v.938zm-8.5.937v.938h1v-.938zm8.5.938v-.938h-1v.938zm-8.5.937v.938h1v-.938zm8.5.938v-.938h-1v.938zM1.906 16h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm1.875-.5v.5h.938v-.5H8.5v-.469h-.031V15H7.53v.031H7.5v.469zm1.875.5h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875-.5v.5H16v-.969h-.5V15h-.469v.031H15v.469z"/></svg>');--icon-border-right:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M.969 0H0v.969h.5V1h.469V.969H1V.5H.969zm.937 1h.938V0h-.938zm1.875 0h.938V0H3.78v1zm1.875 0h.938V0h-.938zM7.531.969V1h.938V.969H8.5V.5h-.031V0H7.53v.5H7.5v.469zM9.406 1h.938V0h-.938zm1.875 0h.938V0h-.938zm1.875 0h.938V0h-.938zM16 0h-1v16h1zM1 2.844v-.938H0v.938zm6.5-.938v.938h1v-.938zM1 4.719V3.78H0v.938h1zm6.5-.938v.938h1V3.78h-1zM1 6.594v-.938H0v.938zm6.5-.938v.938h1v-.938zM.5 8.5h.469v-.031H1V7.53H.969V7.5H.5v.031H0v.938h.5zm1.406 0h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm2.813 0v-.031H8.5V7.53h-.031V7.5H7.53v.031H7.5v.938h.031V8.5zm.937 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zM0 9.406v.938h1v-.938zm7.5 0v.938h1v-.938zM0 11.281v.938h1v-.938zm7.5 0v.938h1v-.938zM0 13.156v.938h1v-.938zm7.5 0v.938h1v-.938zM0 16h.969v-.5H1v-.469H.969V15H.5v.031H0zm1.906 0h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm1.875-.5v.5h.938v-.5H8.5v-.469h-.031V15H7.53v.031H7.5v.469zm1.875.5h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938z"/></svg>');--icon-border-double-bottom:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M.969 0H0v.969h.5V1h.469V.969H1V.5H.969zm.937 1h.938V0h-.938zm1.875 0h.938V0H3.78v1zm1.875 0h.938V0h-.938zM7.531.969V1h.938V.969H8.5V.5h-.031V0H7.53v.5H7.5v.469zM9.406 1h.938V0h-.938zm1.875 0h.938V0h-.938zm1.875 0h.938V0h-.938zm1.875 0h.469V.969h.5V0h-.969v.5H15v.469h.031zM1 2.844v-.938H0v.938zm6.5-.938v.938h1v-.938zm7.5 0v.938h1v-.938zM1 4.719V3.78H0v.938zm6.5-.938v.938h1V3.78h-1zm7.5 0v.938h1V3.78h-1zM1 6.594v-.938H0v.938zm6.5-.938v.938h1v-.938zm7.5 0v.938h1v-.938zM.5 8.5h.469v-.031H1V7.53H.969V7.5H.5v.031H0v.938h.5zm1.406 0h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm2.813 0v-.031H8.5V7.53h-.031V7.5H7.53v.031H7.5v.938h.031V8.5zm.937 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.469v-.031h.5V7.53h-.5V7.5h-.469v.031H15v.938h.031zM0 9.406v.938h1v-.938zm7.5 0v.938h1v-.938zm8.5.938v-.938h-1v.938zm-16 .937v.938h1v-.938zm7.5 0v.938h1v-.938zm8.5.938v-.938h-1v.938zM0 15h16v1H0zm0-2h16v1H0z"/></svg>');--icon-border-all:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M0 0h16v16H0zm1 1v6.5h6.5V1zm7.5 0v6.5H15V1zM15 8.5H8.5V15H15zM7.5 15V8.5H1V15z"/></svg>');--icon-border-outer:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M7.5 1.906v.938h1v-.938zm0 1.875v.938h1V3.78h-1zm0 1.875v.938h1v-.938zM1.906 8.5h.938v-1h-.938zm1.875 0h.938v-1H3.78v1zm1.875 0h.938v-1h-.938zm2.813 0v-.031H8.5V7.53h-.031V7.5H7.53v.031H7.5v.938h.031V8.5zm.937 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zm1.875 0h.938v-1h-.938zM7.5 9.406v.938h1v-.938zm0 1.875v.938h1v-.938zm0 1.875v.938h1v-.938z"/><path d="M0 0v16h16V0zm1 1h14v14H1z"/></svg>');--icon-border-none:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M0 0h.969v.5H1v.469H.969V1H.5V.969H0zm2.844 1h-.938V0h.938zm1.875 0H3.78V0h.938v1zm1.875 0h-.938V0h.938zm.937 0V.969H7.5V.5h.031V0h.938v.5H8.5v.469h-.031V1zm2.813 0h-.938V0h.938zm1.875 0h-.938V0h.938zm1.875 0h-.938V0h.938zM15.5 1h-.469V.969H15V.5h.031V0H16v.969h-.5zM1 1.906v.938H0v-.938zm6.5.938v-.938h1v.938zm7.5 0v-.938h1v.938zM1 3.78v.938H0V3.78zm6.5.938V3.78h1v.938zm7.5 0V3.78h1v.938zM1 5.656v.938H0v-.938zm6.5.938v-.938h1v.938zm7.5 0v-.938h1v.938zM.969 8.5H.5v-.031H0V7.53h.5V7.5h.469v.031H1v.938H.969zm1.875 0h-.938v-1h.938zm1.875 0H3.78v-1h.938v1zm1.875 0h-.938v-1h.938zm1.875-.031V8.5H7.53v-.031H7.5V7.53h.031V7.5h.938v.031H8.5v.938zm1.875.031h-.938v-1h.938zm1.875 0h-.938v-1h.938zm1.875 0h-.938v-1h.938zm1.406 0h-.469v-.031H15V7.53h.031V7.5h.469v.031h.5v.938h-.5zM0 10.344v-.938h1v.938zm7.5 0v-.938h1v.938zm8.5-.938v.938h-1v-.938zM0 12.22v-.938h1v.938zm7.5 0v-.938h1v.938zm8.5-.938v.938h-1v-.938zM0 14.094v-.938h1v.938zm7.5 0v-.938h1v.938zm8.5-.938v.938h-1v-.938zM.969 16H0v-.969h.5V15h.469v.031H1v.469H.969zm1.875 0h-.938v-1h.938zm1.875 0H3.78v-1h.938v1zm1.875 0h-.938v-1h.938zm.937 0v-.5H7.5v-.469h.031V15h.938v.031H8.5v.469h-.031v.5zm2.813 0h-.938v-1h.938zm1.875 0h-.938v-1h.938zm1.875 0h-.938v-1h.938zm.937 0v-.5H15v-.469h.031V15h.469v.031h.5V16z"/></svg>');--icon-palette:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M0 .5A.5.5 0 0 1 .5 0h5a.5.5 0 0 1 .5.5v5.277l4.147-4.131a.5.5 0 0 1 .707 0l3.535 3.536a.5.5 0 0 1 0 .708L10.261 10H15.5a.5.5 0 0 1 .5.5v5a.5.5 0 0 1-.5.5H3a3 3 0 0 1-2.121-.879A3 3 0 0 1 0 13.044m6-.21 7.328-7.3-2.829-2.828L6 7.188zM4.5 13a1.5 1.5 0 1 0-3 0 1.5 1.5 0 0 0 3 0M15 15v-4H9.258l-4.015 4zM0 .5v12.495zM0 12.995V13z"/></svg>');--icon-layout:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="20" height="20" viewBox="0 0 20 20"><path d="m3 0 17 17.156v-.114z"/><path d="M3 0H0v16h1V1h1.585L19 17.455V19H4v1h16v-2.844z"/><path d="M6.886 3.922 5.343 5.465a.5.5 0 0 0 .708.707l1.539-1.54zM9.702 6.763l-1.53 1.53A.5.5 0 0 0 8.879 9l1.526-1.526zM12.517 9.604 11 11.121a.5.5 0 0 0 .707.707l1.514-1.514zM15.332 12.445l-1.504 1.504a.5.5 0 0 0 .707.707l1.501-1.5zM1 16H0a4 4 0 0 0 4 4v-1c-1.654 0-3-1.346-3-3M5 9v6h6zm1 2.414L8.586 14H6z"/></svg>');--icon-freeze:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M8 16a.5.5 0 0 1-.5-.5v-1.293l-.646.647a.5.5 0 0 1-.707-.708L7.5 12.793V8.866l-3.4 1.963-.496 1.85a.5.5 0 1 1-.966-.26l.237-.882-1.12.646a.5.5 0 0 1-.5-.866l1.12-.646-.884-.237a.5.5 0 1 1 .26-.966l1.848.495L7 8 3.6 6.037l-1.85.495a.5.5 0 0 1-.258-.966l.883-.237-1.12-.646a.5.5 0 1 1 .5-.866l1.12.646-.237-.883a.5.5 0 1 1 .966-.258l.495 1.849L7.5 7.134V3.207L6.147 1.854a.5.5 0 1 1 .707-.708l.646.647V.5a.5.5 0 1 1 1 0v1.293l.647-.647a.5.5 0 1 1 .707.708L8.5 3.207v3.927l3.4-1.963.496-1.85a.5.5 0 1 1 .966.26l-.236.882 1.12-.646a.5.5 0 0 1 .5.866l-1.12.646.883.237a.5.5 0 1 1-.26.966l-1.848-.495L9 8l3.4 1.963 1.849-.495a.5.5 0 0 1 .259.966l-.883.237 1.12.646a.5.5 0 0 1-.5.866l-1.12-.646.236.883a.5.5 0 1 1-.966.258l-.495-1.849-3.4-1.963v3.927l1.353 1.353a.5.5 0 0 1-.707.708l-.647-.647V15.5a.5.5 0 0 1-.5.5z"/></svg>');--icon-column-chart:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="20" height="20" viewBox="0 0 20 20"><path d="M4.5 17.5a.5.5 0 0 1-1 0v-5a.5.5 0 0 1 1 0zM12.5 17.5a.5.5 0 0 1-1 0v-9a.5.5 0 0 1 1 0zM16.5 17.5a.5.5 0 0 1-1 0v-13a.5.5 0 0 1 1 0zM8.5 17.5a.5.5 0 0 1-1 0v-14a.5.5 0 0 1 1 0z"/></svg>');--icon-donut-chart:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="20" height="20" viewBox="0 0 20 20"><path d="M12 1.23v1.548c2.526.701 4.5 2.699 5.203 5.222h1.565A9.01 9.01 0 0 0 12 1.23M2.5 10c0-3.51 2.426-6.456 5.688-7.27V1.183A9 9 0 0 0 1 10c0 1.761.513 3.397 1.387 4.784l1.093-1.093A7.43 7.43 0 0 1 2.5 10M17.221 12c-.878 3.166-3.778 5.5-7.221 5.5a7.45 7.45 0 0 1-3.692-.979l-1.093 1.093A8.96 8.96 0 0 0 10 19c4.282 0 7.859-2.993 8.77-7z"/></svg>');--icon-bar-chart:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="20" height="20" viewBox="0 0 20 20"><path d="M2.5 4.5a.5.5 0 0 1 0-1h5a.5.5 0 0 1 0 1zM2.5 12.5a.5.5 0 0 1 0-1h9a.5.5 0 0 1 0 1zM2.5 16.5a.5.5 0 0 1 0-1h13a.5.5 0 0 1 0 1zM2.5 8.5a.5.5 0 0 1 0-1h14a.5.5 0 0 1 0 1z"/></svg>');--icon-line-chart:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="20" height="20" viewBox="0 0 20 20"><path d="m1 8 3-3 7 5 8-8v2l-8 8-7-5-3 3z"/></svg>');--icon-image:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M6.002 5.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0"/><path d="M2.002 1a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2zm12 1a1 1 0 0 1 1 1v6.5l-3.777-1.947a.5.5 0 0 0-.577.093l-3.71 3.71-2.66-1.772a.5.5 0 0 0-.63.062L1.002 12V3a1 1 0 0 1 1-1z"/></svg>');--icon-recalculate:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="20" height="20" viewBox="0 0 20 20"><path d="M9.478 4.022c2.402-.209 4.583 1.047 5.711 3.014l1.083-.095c-1.233-2.528-3.912-4.175-6.881-3.916-2.97.26-5.321 2.347-6.098 5.051l1.083-.095c.768-2.132 2.698-3.748 5.102-3.959M10.523 15.977c-2.403.211-4.585-1.047-5.712-3.013l-1.08.095c1.234 2.527 3.91 4.175 6.879 3.914 2.971-.259 5.32-2.347 6.095-5.05l-1.08.095c-.769 2.132-2.699 3.749-5.102 3.959"/><path d="m2.272 15.616 5.197-3-4.098-1.097zM17.728 4.384l-5.197 3 4.098 1.098z"/></svg>');--icon-check:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M13.854 3.646a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708 0l-3.5-3.5a.5.5 0 1 1 .708-.708L6.5 10.293l6.646-6.647a.5.5 0 0 1 .708 0"/></svg>');--icon-table:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M0 2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2zm15 2h-4v3h4zm0 4h-4v3h4zm0 4h-4v3h3a1 1 0 0 0 1-1zm-5 3v-3H6v3zm-5 0v-3H1v2a1 1 0 0 0 1 1zm-4-4h4V8H1zm0-4h4V4H1zm5-3v3h4V4zm4 4H6v3h4z"/></svg>')}.treb-main.treb-main .treb-layout-header{overflow:hidden;overflow-x:scroll;position:relative;-ms-overflow-style:none;scrollbar-width:none}.treb-main.treb-main .treb-layout-header::-webkit-scrollbar{display:none}.treb-main.treb-main .treb-toolbar{color:var(--treb-toolbar-color,var(--treb-ui-color,#333));display:flex;flex-direction:row;font-size:var(--treb-toolbar-font-size,inherit);gap:.5rem}.treb-main.treb-main .treb-toolbar>div{display:flex;flex-direction:row}.treb-main.treb-main .treb-toolbar>div>input,.treb-main.treb-main .treb-toolbar>input{background-color:var(--treb-toolbar-button-background,transparent);border:1px solid var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));height:32px;overflow:hidden;padding-left:.5em;padding-right:.5em;text-overflow:ellipsis}.treb-main.treb-main .treb-toolbar>.treb-menu>button{border-radius:3px}.treb-main.treb-main .treb-toolbar>.group>.treb-menu+button,.treb-main.treb-main .treb-toolbar>.group>button+.treb-menu>button,.treb-main.treb-main .treb-toolbar>.group>button+button,.treb-main.treb-main .treb-toolbar>.group>input+.treb-menu>button,.treb-main.treb-main .treb-toolbar>.group>input+button,.treb-main.treb-main .treb-toolbar>[composite]>.treb-menu+button,.treb-main.treb-main .treb-toolbar>[composite]>button+.treb-menu>button,.treb-main.treb-main .treb-toolbar>[composite]>button+button,.treb-main.treb-main .treb-toolbar>[composite]>input+.treb-menu>button,.treb-main.treb-main .treb-toolbar>[composite]>input+button{border-left-width:0}.treb-main.treb-main .treb-toolbar>.group>button:first-child,.treb-main.treb-main .treb-toolbar>.group>input:first-child,.treb-main.treb-main .treb-toolbar>[composite]>button:first-child,.treb-main.treb-main .treb-toolbar>[composite]>input:first-child{border-bottom-left-radius:3px;border-top-left-radius:3px}.treb-main.treb-main .treb-toolbar>.group>.treb-menu:last-child>button,.treb-main.treb-main .treb-toolbar>.group>button:last-child,.treb-main.treb-main .treb-toolbar>[composite]>.treb-menu:last-child>button,.treb-main.treb-main .treb-toolbar>[composite]>button:last-child{border-bottom-right-radius:3px;border-top-right-radius:3px}.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button,.treb-main.treb-main .treb-toolbar .treb-menu>button,.treb-main.treb-main .treb-toolbar button[data-icon],.treb-main.treb-main .treb-toolbar>button,.treb-main.treb-main .treb-toolbar>div>button{align-items:center;background-color:var(--treb-toolbar-button-background,transparent);border:1px solid var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));display:flex;flex-direction:column;height:32px;justify-content:center;position:relative;width:32px}.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button[dropdown],.treb-main.treb-main .treb-toolbar .treb-menu>button[dropdown],.treb-main.treb-main .treb-toolbar button[data-icon][dropdown],.treb-main.treb-main .treb-toolbar>button[dropdown],.treb-main.treb-main .treb-toolbar>div>button[dropdown]{width:16px}.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button[dropdown]:after,.treb-main.treb-main .treb-toolbar .treb-menu>button[dropdown]:after,.treb-main.treb-main .treb-toolbar button[data-icon][dropdown]:after,.treb-main.treb-main .treb-toolbar>button[dropdown]:after,.treb-main.treb-main .treb-toolbar>div>button[dropdown]:after{border:5px solid transparent;border-top-color:currentcolor;box-sizing:content-box;content:"";height:0;left:50%;position:absolute;top:18px;transform:translate(-50%,-50%);width:0}.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button:hover,.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button[active],.treb-main.treb-main .treb-toolbar .treb-menu>button:hover,.treb-main.treb-main .treb-toolbar .treb-menu>button[active],.treb-main.treb-main .treb-toolbar button[data-icon]:hover,.treb-main.treb-main .treb-toolbar button[data-icon][active],.treb-main.treb-main .treb-toolbar>button:hover,.treb-main.treb-main .treb-toolbar>button[active],.treb-main.treb-main .treb-toolbar>div>button:hover,.treb-main.treb-main .treb-toolbar>div>button[active]{background-color:var(--treb-toolbar-hover-button-background,#f3f4f6)}.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button[data-color-bar]:after,.treb-main.treb-main .treb-toolbar .treb-menu>button[data-color-bar]:after,.treb-main.treb-main .treb-toolbar button[data-icon][data-color-bar]:after,.treb-main.treb-main .treb-toolbar>button[data-color-bar]:after,.treb-main.treb-main .treb-toolbar>div>button[data-color-bar]:after{background:var(--treb-color-bar-color,var(--treb-default-color,unset));border:1px solid var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));box-sizing:border-box;content:"";display:block;height:6px;position:relative;width:20px}.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button[data-command]:before,.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button[data-icon]:before,.treb-main.treb-main .treb-toolbar .treb-menu>button[data-command]:before,.treb-main.treb-main .treb-toolbar .treb-menu>button[data-icon]:before,.treb-main.treb-main .treb-toolbar button[data-icon][data-command]:before,.treb-main.treb-main .treb-toolbar button[data-icon][data-icon]:before,.treb-main.treb-main .treb-toolbar>button[data-command]:before,.treb-main.treb-main .treb-toolbar>button[data-icon]:before,.treb-main.treb-main .treb-toolbar>div>button[data-command]:before,.treb-main.treb-main .treb-toolbar>div>button[data-icon]:before{background:currentColor;content:"";display:block;height:20px;mask-image:var(--icon);-webkit-mask-image:var(--icon);mask-position:center;-webkit-mask-position:center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;mask-size:var(--icon-size,16px 16px);-webkit-mask-size:var(--icon-size,16px 16px);position:relative;width:20px}.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button[data-command].treb-font-stack:before,.treb-main.treb-main .treb-toolbar .treb-icon-buttons>button[data-icon].treb-font-stack:before,.treb-main.treb-main .treb-toolbar .treb-menu>button[data-command].treb-font-stack:before,.treb-main.treb-main .treb-toolbar .treb-menu>button[data-icon].treb-font-stack:before,.treb-main.treb-main .treb-toolbar button[data-icon][data-command].treb-font-stack:before,.treb-main.treb-main .treb-toolbar button[data-icon][data-icon].treb-font-stack:before,.treb-main.treb-main .treb-toolbar>button[data-command].treb-font-stack:before,.treb-main.treb-main .treb-toolbar>button[data-icon].treb-font-stack:before,.treb-main.treb-main .treb-toolbar>div>button[data-command].treb-font-stack:before,.treb-main.treb-main .treb-toolbar>div>button[data-icon].treb-font-stack:before{display:none}.treb-main.treb-main .treb-toolbar .treb-split{display:flex;flex-direction:column;gap:0}.treb-main.treb-main .treb-toolbar .treb-split button[data-command]{font-size:10px}.treb-main.treb-main .treb-toolbar .treb-split button[data-command]:before{display:none}.treb-main.treb-main .treb-toolbar .treb-split>button{align-items:center;display:flex;height:16px;justify-content:center}.treb-main.treb-main .treb-toolbar .treb-split>button:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.treb-main.treb-main .treb-toolbar .treb-split>button:last-child{border-bottom-left-radius:3px;border-bottom-right-radius:3px;border-top:0}.treb-main.treb-main .treb-toolbar .treb-font-stack{align-items:flex-start;overflow:hidden;width:8em}.treb-main.treb-main .treb-toolbar .treb-font-stack:before{display:none}.treb-main.treb-main .treb-toolbar .treb-menu{outline:none}.treb-main.treb-main .treb-toolbar .treb-menu>div{background:var(--treb-toolbar-button-background,#fff);border:1px solid var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));border-radius:3px;box-shadow:0 4px 6px -4px rgba(0,0,0,.4);display:none;flex-direction:column;margin-top:.5rem;position:fixed;top:48px;z-index:20}.treb-main.treb-main .treb-toolbar .treb-menu>div button{background:transparent;border:0;margin:3px 0;padding:.4rem 1rem;text-align:left;transition:background-color .125s ease;white-space:nowrap}.treb-main.treb-main .treb-toolbar .treb-menu>div button:hover{background:var(--treb-toolbar-hover-button-background,#f3f4f6)}.treb-main.treb-main .treb-toolbar .treb-menu>div.treb-icon-buttons>.treb-menu>button,.treb-main.treb-main .treb-toolbar .treb-menu>div.treb-icon-buttons>button{padding:0}.treb-main.treb-main .treb-toolbar .treb-menu>div>[separator]{background:var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));height:1px;margin:2px 0}.treb-main.treb-main .treb-toolbar .treb-menu.visible>div,.treb-main.treb-main .treb-toolbar .treb-menu:focus-within>div{display:flex}.treb-main.treb-main .treb-toolbar [data-icon=file-menu]{--icon:var(--icon-file-menu)}.treb-main.treb-main .treb-toolbar [data-command=justify-left]{--icon:var(--icon-text-align-left)}.treb-main.treb-main .treb-toolbar [data-command=justify-right]{--icon:var(--icon-text-align-right)}.treb-main.treb-main .treb-toolbar [data-command=justify-center]{--icon:var(--icon-text-align-center)}.treb-main.treb-main .treb-toolbar [data-command=indent]{--icon:var(--icon-text-indent)}.treb-main.treb-main .treb-toolbar [data-command=outdent]{--icon:var(--icon-text-outdent)}.treb-main.treb-main .treb-toolbar [data-command=align-top]{--icon:var(--icon-text-align-top)}.treb-main.treb-main .treb-toolbar [data-command=align-middle]{--icon:var(--icon-text-align-middle)}.treb-main.treb-main .treb-toolbar [data-command=align-bottom]{--icon:var(--icon-text-align-bottom)}.treb-main.treb-main .treb-toolbar [data-command=merge-cells]{--icon:var(--icon-merge-cells)}.treb-main.treb-main .treb-toolbar [data-command=unmerge-cells]{--icon:var(--icon-unmerge-cells)}.treb-main.treb-main .treb-toolbar [data-command=fill-color]{--icon:var(--icon-fill-color)}.treb-main.treb-main .treb-toolbar [data-command=text-color]{--icon:var(--icon-text-color)}.treb-main.treb-main .treb-toolbar [data-command=lock-cells]{--icon:var(--icon-lock)}.treb-main.treb-main .treb-toolbar [data-command=wrap-text]{--icon:var(--icon-wrap-text)}.treb-main.treb-main .treb-toolbar [data-icon=comment]{--icon:var(--icon-comment)}.treb-main.treb-main .treb-toolbar [data-icon=table]{--icon:var(--icon-table)}.treb-main.treb-main .treb-toolbar [data-icon=layout]{--icon:var(--icon-layout)}.treb-main.treb-main .treb-toolbar [data-command=freeze-panes]{--icon:var(--icon-freeze)}.treb-main.treb-main .treb-toolbar [data-command=insert-column-chart]{--icon:var(--icon-column-chart)}.treb-main.treb-main .treb-toolbar [data-command=insert-donut-chart]{--icon:var(--icon-donut-chart)}.treb-main.treb-main .treb-toolbar [data-command=insert-bar-chart]{--icon:var(--icon-bar-chart)}.treb-main.treb-main .treb-toolbar [data-command=insert-line-chart]{--icon:var(--icon-line-chart)}.treb-main.treb-main .treb-toolbar [data-command=insert-image]{--icon:var(--icon-image)}.treb-main.treb-main .treb-toolbar [data-command=border-bottom]{--icon:var(--icon-border-bottom)}.treb-main.treb-main .treb-toolbar [data-command=border-left]{--icon:var(--icon-border-left)}.treb-main.treb-main .treb-toolbar [data-command=border-right]{--icon:var(--icon-border-right)}.treb-main.treb-main .treb-toolbar [data-command=border-top]{--icon:var(--icon-border-top)}.treb-main.treb-main .treb-toolbar [data-command=border-outside]{--icon:var(--icon-border-outer)}.treb-main.treb-main .treb-toolbar [data-command=border-all]{--icon:var(--icon-border-all)}.treb-main.treb-main .treb-toolbar [data-command=border-none]{--icon:var(--icon-border-none)}.treb-main.treb-main .treb-toolbar [data-command=border-double-bottom]{--icon:var(--icon-border-double-bottom)}.treb-main.treb-main .treb-toolbar [data-icon=palette]{--icon:var(--icon-palette)}.treb-main.treb-main .treb-toolbar [data-command=recalculate]{--icon:var(--icon-recalculate);--icon-size:20px 20px}.treb-main.treb-main .treb-toolbar .treb-font-scale{width:4em}.treb-main.treb-main .treb-toolbar .treb-number-format{width:8em}.treb-main.treb-main .treb-toolbar .treb-color-chooser button[data-command=set-color]{align-items:center;display:flex;justify-content:center;padding:0;width:32px}.treb-main.treb-main .treb-toolbar .treb-color-chooser button[data-command=set-color]>svg{pointer-events:none}.treb-main.treb-main .treb-toolbar .treb-color-chooser>div{padding:.75rem}.treb-main.treb-main .treb-toolbar .treb-color-chooser>div+div{padding-top:0}.treb-main.treb-main .treb-toolbar .treb-color-chooser>div:last-child{align-items:center;display:flex;flex-direction:row;gap:.5rem}.treb-main.treb-main .treb-toolbar .treb-color-chooser>div:last-child input{flex-grow:1;padding:0 .5rem}.treb-main.treb-main .treb-toolbar .treb-color-chooser>div:last-child button,.treb-main.treb-main .treb-toolbar .treb-color-chooser>div:last-child input{border:1px solid var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));border-radius:3px;height:32px}.treb-main.treb-main .treb-toolbar .treb-color-chooser .treb-default-swatch button,.treb-main.treb-main .treb-toolbar .treb-color-chooser .treb-swatches button{border:1px solid var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));border-radius:2px;height:18px;margin:0;padding:0;width:18px}.treb-main.treb-main .treb-toolbar .treb-color-chooser .treb-default-swatch .treb-default-color:before,.treb-main.treb-main .treb-toolbar .treb-color-chooser .treb-swatches .treb-default-color:before{background:currentColor;content:"";display:block;height:100%;mask-image:var(--icon-x);-webkit-mask-image:var(--icon-x);mask-position:center;-webkit-mask-position:center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;mask-size:24px 24px;-webkit-mask-size:24px 24px;opacity:.7;position:relative;width:100%}.treb-main.treb-main .treb-toolbar .treb-color-chooser .treb-default-swatch{align-items:center;display:grid;gap:.5rem;grid-template-columns:auto 1fr}.treb-main.treb-main .treb-toolbar .treb-color-chooser .treb-swatches{display:grid;gap:.5rem;grid-template-columns:repeat(10,1fr)}.treb-main.treb-main .treb-toolbar .treb-comment-box textarea{border:1px solid var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));font:inherit;height:10rem;line-height:1.5;margin:.5rem;padding:.25rem;resize:both}.treb-main.treb-main .treb-toolbar .treb-comment-box textarea+div{align-items:center;display:flex;flex-direction:row;gap:.5rem;justify-content:center;padding:0 0 .5rem}.treb-main.treb-main .treb-toolbar .treb-comment-box textarea+div button{border:1px solid var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));border-radius:3px}.treb-main.treb-main .treb-toolbar .treb-font-scale{padding-left:2em;text-align:right;width:5em}.treb-main.treb-main .treb-toolbar [composite][font-scale]{position:relative}.treb-main.treb-main .treb-toolbar .treb-font-scale-icon{border-radius:3px;left:.5em;line-height:1;opacity:.9;pointer-events:none;position:absolute;top:50%;transform:translateY(-50%)}.treb-main.treb-main .treb-toolbar .treb-font-scale-icon:after,.treb-main.treb-main .treb-toolbar .treb-font-scale-icon:before{content:"A";position:relative}.treb-main.treb-main .treb-toolbar .treb-font-scale-icon:before{font-size:1.2em}.treb-main.treb-main .treb-toolbar .treb-font-scale-icon:after{font-size:.9em;left:-.125em}.treb-main.treb-main{--treb-font-stack-default-size:14px;--treb-font-stack-calibri-size:16px;--treb-font-stack-tscu-comic-size:16px;--treb-font-stack-helvetica-neue-size:13px;--treb-font-stack-cambria-size:16px;--treb-font-stack-sitka-text-variant:lining-nums tabular-nums}.treb-main.treb-main.treb-ua-osx{--treb-font-stack-system-ui-size:10pt}.treb-main.treb-main .treb-font-stack-default{font-family:calibri,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen-Sans,Ubuntu,Cantarell,Helvetica Neue,"sans-serif"}.treb-main.treb-main .treb-font-stack-transitional{font-family:Charter,Bitstream Charter,Cambria,serif}.treb-main.treb-main .treb-font-stack-old-style{font-family:Iowan Old Style,Palatino Linotype,URW Palladio L,P052,serif}.treb-main.treb-main .treb-font-stack-handwritten{font-family:Segoe Print,Bradley Hand,Chilanka,TSCu_Comic,casual,cursive}.treb-main.treb-main .treb-font-stack-industrial{font-family:Bahnschrift,DIN Alternate,Franklin Gothic Medium,Nimbus Sans Narrow,sans-serif-condensed,sans-serif}.treb-main.treb-main .treb-font-stack-monospace{font-family:ui-monospace,Cascadia Code,Source Code Pro,Menlo,Consolas,DejaVu Sans Mono,monospace}.treb-main.treb-main .treb-font-stack-ui{font-family:system-ui,sans-serif}.treb-main.treb-main{all:revert;box-sizing:border-box;color:inherit;color-scheme:var(--treb-color-scheme,unset);display:grid;font-family:var(--treb-default-font,system-ui,"BlinkMacSystemFont","Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue","sans-serif");font-family:BlinkMacSystemFont,Segoe UI,Roboto,Oxygen-Sans,Ubuntu,Cantarell,Helvetica Neue,"sans-serif";font-size:14px;font-style:normal;font-weight:400;grid-template-columns:minmax(0,1fr) auto;grid-template-rows:auto minmax(0,1fr);height:100%;line-height:normal;position:relative;text-align:start;width:100%}.treb-main.treb-main a,.treb-main.treb-main button,.treb-main.treb-main div,.treb-main.treb-main input,.treb-main.treb-main li,.treb-main.treb-main ol,.treb-main.treb-main svg,.treb-main.treb-main textarea,.treb-main.treb-main ul{all:revert;box-sizing:border-box;font-family:var(--treb-default-font,system-ui,"BlinkMacSystemFont","Segoe UI","Roboto","Oxygen-Sans","Ubuntu","Cantarell","Helvetica Neue","sans-serif")}.treb-main.treb-main button,.treb-main.treb-main input{color:inherit;font:inherit}.treb-main.treb-main *{box-sizing:border-box}.treb-main.treb-main [contenteditable]{-webkit-user-modify:read-write;-moz-user-modify:read-write}.treb-main.treb-main[animate] .treb-layout-header{transition:height var(--treb-sidebar-transition,.2s ease),opacity var(--treb-sidebar-transition,.2s ease)}.treb-main.treb-main .treb-layout-header{grid-column:1/3;grid-row:1;height:1px;opacity:0}.treb-main.treb-main[toolbar] .treb-layout-header{height:42px;opacity:1}.treb-main.treb-main[dialog] .treb-layout-header,.treb-main.treb-main[dialog]>*{opacity:.6}.treb-main.treb-main[dialog] .treb-dialog-mask{opacity:1;pointer-events:auto}.treb-main.treb-main .treb-layout-spreadsheet{display:flex;flex-direction:row;gap:1em;grid-column:1;grid-row:2;position:relative;transition:opacity .2s ease;z-index:5}.treb-main.treb-main .treb-views.treb-can-revert .treb-view .treb-revert-indicator{opacity:1;pointer-events:auto}.treb-main.treb-main .treb-view{display:grid;flex:1 1 0px;grid-template-columns:minmax(0,1fr);grid-template-rows:auto minmax(0,1fr) auto;position:relative}.treb-main.treb-main .treb-view .treb-spreadsheet-backdrop{box-shadow:0 4px 6px -4px rgba(0,0,0,.4);grid-column:1;grid-row:2;z-index:2}.treb-main.treb-main .treb-view .treb-spreadsheet-body{position:relative;z-index:4}.treb-main.treb-main .treb-view .treb-spreadsheet-footer{position:relative;z-index:5}.treb-main.treb-main .treb-view .treb-layout-resize-handle,.treb-main.treb-main .treb-view .treb-revert-indicator{display:none}.treb-main.treb-main .treb-view:first-of-type .treb-revert-indicator{align-self:start;border-color:orange transparent transparent orange;border-style:solid;border-width:.5em;display:block;grid-area:2/1/3/2;height:1rem;justify-self:start;opacity:0;overflow:hidden;pointer-events:none;position:relative;transition:opacity .125s ease;width:1rem;z-index:20}.treb-main.treb-main .treb-view:last-of-type .treb-layout-resize-handle{align-self:end;border-bottom:.5rem solid var(--treb-resize-handle-color,#0059b9);border-left:.5rem solid transparent;border-right:.5rem solid var(--treb-resize-handle-color,#0059b9);border-top:.5rem solid transparent;cursor:nw-resize;display:block;grid-area:2/1/3/2;height:1rem;justify-self:end;width:1rem;z-index:20}.treb-main.treb-main[animate] .treb-layout-sidebar{transition:width var(--treb-sidebar-transition,.2s ease),opacity var(--treb-sidebar-transition,.2s ease)}.treb-main.treb-main .treb-layout-sidebar{align-items:center;display:flex;flex-direction:column;gap:.75rem;grid-column:2;grid-row:2;justify-content:flex-start;overflow:hidden;padding-top:3rem;width:2.5rem;width:3rem}.treb-main.treb-main[collapsed] .treb-layout-sidebar{opacity:0;width:0}.treb-main.treb-main[collapsed] .treb-toggle-sidebar-button{background:var(--treb-toolbar-button-background,#fff);border-bottom-right-radius:0;border-color:var(--treb-toolbar-border-color,var(--treb-ui-border-color,#d1d5db));border-right-color:var(--treb-toolbar-button-background,transparent);border-top-right-radius:0;right:0}.treb-main.treb-main[collapsed] .treb-toggle-sidebar-button:after{mask-image:var(--icon-chevron-left);-webkit-mask-image:var(--icon-chevron-left)}.treb-main.treb-main .treb-layout-sidebar>button,.treb-main.treb-main .treb-toggle-sidebar-button{background:transparent;border:0;margin:0;padding:0}.treb-main.treb-main .treb-layout-sidebar>button:after,.treb-main.treb-main .treb-toggle-sidebar-button:after{background:#ccc;content:"";display:block;height:24px;mask-image:var(--icon);-webkit-mask-image:var(--icon);mask-position:center;-webkit-mask-position:center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;transition:background-color .1s ease;width:24px}.treb-main.treb-main .treb-layout-sidebar>button[data-can-revert=false],.treb-main.treb-main .treb-toggle-sidebar-button[data-can-revert=false]{display:none}.treb-main.treb-main .treb-layout-sidebar>button:hover:after,.treb-main.treb-main .treb-toggle-sidebar-button:hover:after{background:#666}.treb-main.treb-main .treb-layout-sidebar>button[data-command=recalculate],.treb-main.treb-main .treb-toggle-sidebar-button[data-command=recalculate]{--icon:var(--icon-reset)}.treb-main.treb-main .treb-layout-sidebar>button[data-command=toggle-toolbar],.treb-main.treb-main .treb-toggle-sidebar-button[data-command=toggle-toolbar]{--icon:var(--icon-toolbar)}.treb-main.treb-main .treb-layout-sidebar>button[data-command=revert],.treb-main.treb-main .treb-toggle-sidebar-button[data-command=revert]{--icon:var(--icon-revert)}.treb-main.treb-main .treb-layout-sidebar>button[data-command=export-xlsx],.treb-main.treb-main .treb-toggle-sidebar-button[data-command=export-xlsx]{--icon:var(--icon-export)}.treb-main.treb-main .treb-layout-sidebar>button[data-command=about],.treb-main.treb-main .treb-toggle-sidebar-button[data-command=about]{--icon:var(--icon-about)}.treb-main.treb-main .treb-toggle-sidebar-button{align-items:center;background:transparent;border:1px solid transparent;border-radius:12px;bottom:6rem;display:flex;height:24px;justify-content:center;margin:0;padding:0;position:absolute;right:.5rem;right:calc(1.5rem - 12px);width:24px;z-index:39}.treb-main.treb-main .treb-toggle-sidebar-button:after{height:12px;mask-image:var(--icon-chevron-right);-webkit-mask-image:var(--icon-chevron-right);width:12px}.treb-main.treb-main .treb-resize-rect{border:1px dotted var(--treb-resize-frame-color,blue);display:block;height:100%;left:0;position:fixed;top:0;width:100%;z-index:9998}.treb-main.treb-main .treb-resize-mask{height:100vh;left:0;position:fixed;top:0;width:100vw;z-index:9999}treb-spreadsheet{display:block;overflow:hidden;position:relative}.treb-default-size{height:550px;width:800px}`;var co='<div class="treb-main treb-theme"><div class="treb-layout-header treb-animate"><div class="treb-toolbar"></div></div><div class="treb-dialog-mask"><div data-bind="dialog" class="treb-embed-dialog"><div data-bind="left"><a href="https://treb.app" target="_blank"><div class="treb-icon-64"></div></a></div><div data-bind="middle"><div data-bind="title" class="treb-embed-dialog-title"></div><div data-bind="message" class="treb-embed-dialog-message"></div><div data-bind="about" class="treb-embed-dialog-body"></div></div><button type="button" data-title="close_dialog" data-bind="close" class="treb-close-box"><svg viewBox="0 0 16 16"><path d="M11.854 4.146a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708-.708l7-7a.5.5 0 0 1 .708 0z"/><path d="M4.146 4.146a.5.5 0 0 0 0 .708l7 7a.5.5 0 0 0 .708-.708l-7-7a.5.5 0 0 0-.708 0z"/></svg></button></div></div><div class="treb-layout-spreadsheet treb-views"><template class="treb-view-template"><div class="treb-view"><div class="treb-formula-bar notranslate" hidden><div class="treb-address-label"><div></div></div><button class="treb-insert-function-button" data-title="insert_function" data-conditional="insert-function">\u{1D453}<small>(x)</small></button><div class="treb-editor-container"><div contenteditable="true"></div></div></div><div class="treb-spreadsheet-backdrop"></div><div class="treb-spreadsheet-body" role="grid"><div class="treb-grid" tabindex="-1"><div class="treb-overlay-container notranslate" translate="no"><div class="treb-overlay-inset"><div class="treb-overlay-editor" contenteditable tabindex="-1" spellcheck="true" role="gridcell"></div></div></div></div></div><div class="treb-spreadsheet-footer" hidden><button class="treb-delete-tab" data-title="delete_sheet" data-command="delete-tab" data-conditional="delete-tab"><svg tabindex="-1" viewbox="0 0 16 16"><path d="M4,4 L12,12 M12,4 L4,12"/></svg></button><div class="treb-spreadsheet-tab-container"><ol class="treb-spreadsheet-tabs" role="tablist"></ol></div><button class="treb-add-tab" data-command="add-tab" data-conditional="add-tab" data-title="add_sheet">+</button><div class="treb-stats-panel"></div><div class="treb-scale-control" data-conditional="scale-control"></div></div><div class="treb-layout-resize-handle" data-conditional="resize"></div><div class="treb-revert-indicator" data-command="revert-indicator" data-title="document_modified"></div></div></template></div><div class="treb-layout-sidebar treb-animate"><button data-command="recalculate" data-title="recalculate"></button> <button data-command="toggle-toolbar" data-conditional="toolbar" data-title="toggle_toolbar"></button> <button data-command="export-xlsx" data-conditional="export" data-title="export"></button> <button data-command="revert" data-conditional="revert" data-title="revert"></button> <button data-command="about" data-title="about"></button></div><button class="treb-toggle-sidebar-button" data-title="toggle_sidebar"></button></div>';var uo='<div class="treb-menu" title="File menu" file-menu><button data-icon="file-menu" menu-target></button><div><button data-command="reset">New document</button><div separator></div><button data-command="import-file">Open file...</button> <button data-command="save-json">Save JSON</button><div separator xlsx-support></div><button data-command="export-xlsx" xlsx-support>Export XLSX</button></div></div><div composite narrow><button data-command="justify-left" data-target="justify" title="Left-align text"></button><div class="treb-menu"><button dropdown title="Text justify options"></button><div class="treb-icon-buttons" data-replace="justify"><button data-command="justify-left" title="Left-align text"></button> <button data-command="justify-center" title="Center-align text"></button> <button data-command="justify-right" title="Right-align text"></button></div></div></div><div composite narrow><button data-command="align-top" data-target="align" title="Align to top"></button><div class="treb-menu"><button dropdown title="Text align options"></button><div class="treb-icon-buttons" data-replace="align"><button data-command="align-top" title="Align to top"></button> <button data-command="align-middle" title="Align to middle"></button> <button data-command="align-bottom" title="Align to bottom"></button></div></div></div><div class="group" wide><button data-command="justify-left" title="Left-align text"></button> <button data-command="justify-center" title="Center-align text"></button> <button data-command="justify-right" title="Right-align text"></button></div><div class="group" wide><button data-command="align-top" title="Align to top"></button> <button data-command="align-middle" title="Align to middle"></button> <button data-command="align-bottom" title="Align to bottom"></button></div><div class="group" wide indent-group><button data-command="outdent" title="Decrease indent"></button> <button data-command="indent" title="Incrase indent"></button></div><div class="group"><button data-command="wrap-text" title="Wrap text"></button> <button data-command="merge-cells" data-id="merge" data-inactive-title="Merge cells" data-active-title="Unmerge cells"></button> <button data-command="lock-cells" data-inactive-title="Lock cells" data-active-title="Unlock cells"></button> <button data-command="freeze-panes" data-inactive-title="Freeze panes" data-active-title="Unfreeze panes" freeze-button></button> <button data-command="insert-table" data-icon="table" data-inactive-title="Insert table" data-active-title="Remove table" table-button></button><div class="treb-menu"><button data-icon="comment" data-inactive-title="Comment" data-active-title="Update comment"></button><div class="treb-comment-box"><textarea></textarea><div><button data-command="clear-comment">Clear</button> <button data-command="update-comment">Save</button></div></div></div></div><div composite><button data-command="border-bottom" data-target="border" title="Bottom border"></button><div class="treb-menu"><button dropdown title="Border options"></button><div class="treb-icon-buttons" data-replace="border"><button data-command="border-top" title="Top border"></button> <button data-command="border-left" title="Left border"></button> <button data-command="border-right" title="Right border"></button> <button data-command="border-bottom" title="Bottom border"></button> <button data-command="border-double-bottom" title="Double bottom border"></button> <button data-command="border-outside" title="Outside borders"></button> <button data-command="border-all" title="All borders"></button> <button data-command="border-none" title="Clear borders"></button><div separator></div><div class="treb-menu treb-color-menu treb-submenu" data-color-command="border-color" data-replace-color="border" title="Border color" data-default-color-text="Default border color"><button data-icon="palette" data-color-bar="border" data-color="{}"></button></div></div></div></div><div composite><button data-command="fill-color" data-color-bar="fill" data-color="{}" title="Fill color"></button><div class="treb-menu treb-color-menu" data-color-command="fill-color" data-replace-color="fill" data-default-color-text="No fill"><button dropdown title="Color options"></button><div class="treb-color-chooser"><div class="treb-caption">Theme colors</div><div class="treb-swatches"></div><div class="treb-caption">No color</div><div class="treb-default-swatch"><button class="treb-default-color" data-command="set-color" data-color="{}"></button> <span class="treb-default-color-label" data-command="set-color" data-color="{}">...</span></div><div class="treb-caption">Other colors</div><div class="treb-swatches"></div><div><input placeholder="New color" class="treb-color-input"> <button data-command="set-color" data-color=""><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 16 16"><path d="M13.854 3.646a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708 0l-3.5-3.5a.5.5 0 1 1 .708-.708L6.5 10.293l6.646-6.647a.5.5 0 0 1 .708 0z"/></svg></button></div></div></div></div><div composite><button data-command="text-color" data-color-bar="text" data-color="{}" title="Text color"></button><div class="treb-menu treb-color-menu" data-color-command="text-color" data-replace-color="text" data-default-color-text="Default text color"><button dropdown title="Color options"></button></div></div><div composite font-scale><div class="treb-font-scale-icon"></div><input class="treb-font-scale" title="Font scale"><div class="treb-menu"><button dropdown title="Font scale options"></button><div><button data-command="font-scale" data-scale="0.8">0.80</button> <button data-command="font-scale" data-scale="0.9">0.90</button> <button data-command="font-scale" data-scale="1.0">1.00</button> <button data-command="font-scale" data-scale="1.1">1.10</button> <button data-command="font-scale" data-scale="1.25">1.25</button> <button data-command="font-scale" data-scale="1.5">1.50</button> <button data-command="font-scale" data-scale="2.0">2.00</button></div></div></div><div composite font-stack><button class="treb-font-stack" data-command="font-stack" data-font-stack="" title="Font stack"></button><div class="treb-menu"><button dropdown title="Font stack options"></button><div><button data-command="font-stack" data-font-stack="default"></button> <button data-command="font-stack" data-font-stack="transitional"></button> <button data-command="font-stack" data-font-stack="monospace"></button> <button data-command="font-stack" data-font-stack="handwritten"></button> <button data-command="font-stack" data-font-stack="ui"></button></div></div></div><div composite><input class="treb-number-format" title="Number format"><div class="treb-menu"><button dropdown title="Number formats"></button><div class="treb-number-format-menu"></div></div></div><div class="treb-split"><button data-command="decrease-precision" title="Decrease precision"></button> <button data-command="increase-precision" title="Increase precision"></button></div><div class="treb-menu"><button data-icon="layout" title="Rows & columns"></button><div><button data-command="insert-row">Insert row</button> <button data-command="insert-column">Insert column</button> <button data-command="delete-row">Delete row</button> <button data-command="delete-column">Delete column</button><div separator add-remove-sheet></div><button data-command="insert-sheet" add-remove-sheet>Add sheet</button> <button data-command="delete-sheet" add-remove-sheet>Delete sheet</button></div></div><div composite chart-menu><button data-command="insert-column-chart" data-target="annotation" title="Insert column chart"></button><div class="treb-menu"><button dropdown title="Chart options"></button><div class="treb-icon-buttons" data-replace="annotation"><button data-command="insert-column-chart" title="Insert column chart"></button> <button data-command="insert-donut-chart" title="Insert donut chart"></button> <button data-command="insert-bar-chart" title="Insert bar chart"></button> <button data-command="insert-line-chart" title="Insert line chart"></button><div separator></div><button data-command="insert-image" title="Insert image"></button></div></div></div><button data-command="recalculate" title="Recalculate" recalculate-button></button>';var ho={close_dialog:"Close dialog",insert_function:"Insert function...",delete_sheet:"Delete current sheet",add_sheet:"Add sheet",document_modified:"This document has been modified from the original version.",recalculate:"Recalculate",toggle_toolbar:"Toggle toolbar",export:"Export as XLSX",revert:"Revert to original version",about:"What's this?",toggle_sidebar:"Toggle sidebar"},nt=class{root;sheet;border_color;color_bar_elements={};replace_targets={};layout_element;views;revert_button;revert_state=!1;toolbar_controls={};swatch_lists={};DOM;constructor(e){typeof e=="string"&&(e=document.querySelector(e)),this.DOM=O.GetInstance(e?.ownerDocument),this.DOM.view&&e instanceof this.DOM.view.HTMLElement&&(this.root=e,this.DOM.doc?.head.querySelector("style[treb-stylesheet]")||this.DOM.doc?.head.prepend(this.DOM.Create("style",void 0,void 0,{text:lo,attrs:{"treb-stylesheet":""}})))}CoerceAttributeValue(e){if(e===null||e.toString().toLowerCase()==="true"||e==="")return!0;if(e.toLowerCase()==="false")return!1;{let t=Number(e);if(!isNaN(t))return t}return e||""}ParseOptionAttributes(){let e={};if(this.root){let t=this.root.getAttributeNames();for(let r of t){switch(r){case"class":case"style":case"id":continue;case"data-options":case"options":{let n=(this.root.getAttribute(r)||"").split(",");for(let o of n){let a=o.split(/=/);a.length===1?e[a[0]]=!0:e[a[0]]=this.CoerceAttributeValue(a[1])}}continue;case"data-treb":continue;case"inline-document":continue;case"src":e.document=this.root.getAttribute("src")||void 0;continue}e[r.replace(/-/g,"_")]=this.CoerceAttributeValue(this.root.getAttribute(r))}}return{...e}}AttachElement(e={}){if(e={...this.ParseOptionAttributes(),...e},this.root){if(!e.headless){let t=this.root.getBoundingClientRect();(!t.width||!t.height)&&this.root.classList.add("treb-default-size")}if(this.root.hasAttribute("inline-document")){let t=this.root.getAttribute("inline-document")||"";for(let r of Array.from(this.root.children))if(this.DOM.view&&r instanceof this.DOM.view.HTMLScriptElement&&r.type==="application/json"){let i=r.getAttribute("name")||"";if(i===t||!i&&t==="true"){let n=r.textContent;if(n)try{e.inline_document=JSON.parse(n)}catch(o){console.error(o)}break}}e.inline_document||console.warn("inline document failed")}this.root.innerHTML=co,e.container=this.root.querySelector(".treb-layout-spreadsheet")}this.sheet=new Sr(e),this.root&&this.CreateLayout(this.sheet,this.root)}CreateLayout(e,t){new ResizeObserver(()=>e.Resize()).observe(t),this.layout_element=t.querySelector(".treb-main");let i=t.querySelector(".treb-toggle-sidebar-button");if(i&&this.layout_element){let c=this.layout_element;i.addEventListener("click",()=>{let d=c.getAttribute("collapsed");typeof d=="string"&&(d===""||d==="true")?c.removeAttribute("collapsed"):c.setAttribute("collapsed","")})}(e.options.toolbar==="show"||e.options.toolbar==="show-narrow")&&this.layout_element?.setAttribute("toolbar",""),e.options.collapsed&&this.layout_element?.setAttribute("collapsed","");let n=t.querySelector("[data-command=revert-indicator]");this.DOM.view&&n instanceof this.DOM.view.HTMLElement&&(e.options.revert_indicator?n.addEventListener("click",()=>{e.HandleToolbarMessage({command:"revert-indicator"})}):n.style.display="none"),t.querySelector(".treb-layout-sidebar")?.addEventListener("click",c=>{let d=c.target;if(d.dataset.command)switch(d.dataset.command){case"toggle-toolbar":this.ToggleToolbar();break;default:e.HandleToolbarMessage({command:d.dataset.command});break}}),e.options.toolbar&&this.AttachToolbar(e,t);let a={"table-button":!!e.options.table_button,revert:!!e.options.revert_button,toolbar:!!e.options.toolbar,export:!!e.options.export,"insert-function":!!e.options.insert_function_button,resize:!!e.options.resizable,"add-tab":!!e.options.add_tab,"delete-tab":!!e.options.delete_tab||!!e.options.add_tab};for(let[c,d]of Object.entries(a))if(!d){let u=this.layout_element.querySelectorAll(`[data-conditional=${c}]`);for(let h of Array.from(u))h.style.display="none"}if(e.options.revert_button&&(this.revert_button=this.layout_element.querySelector("[data-command=revert]")||void 0),e.options.resizable){let c={width:0,height:0},d={x:0,y:0},u={x:0,y:0};this.views=t.querySelector(".treb-views")||void 0;let h,m,f=t.querySelector(".treb-layout-resize-handle"),p=()=>g(),b=x=>{x.buttons===0?g():(u.x=x.screenX-d.x,u.y=x.screenY-d.y,m&&(m.style.width=c.width+u.x+"px",m.style.height=c.height+u.y+"px"))},g=()=>{if(u.x||u.y){let x=t.getBoundingClientRect();e.options.constrain_width||(t.style.width=x.width+u.x+"px"),t.style.height=x.height+u.y+"px"}h&&(h.removeEventListener("mouseup",p),h.removeEventListener("mousemove",b),h.parentElement?.removeChild(h),h=void 0),m?.parentElement?.removeChild(m),m=void 0};f.addEventListener("mousedown",x=>{x.stopPropagation(),x.preventDefault();let y=t.querySelector(".treb-main");m=this.DOM.Div("treb-resize-rect",y),h=this.DOM.Div("treb-resize-mask",y,{attrs:{style:"cursor: nw-resize;"},events:{mouseup:p,mousemove:b}}),d.x=x.screenX,d.y=x.screenY,u.x=0,u.y=0;let w=this.views?.querySelectorAll(".treb-spreadsheet-body"),_=Array.from(w||[]).map(C=>C.getBoundingClientRect());if(_.length){let C=JSON.parse(JSON.stringify(_.shift()));for(let E of _)C.top=Math.min(E.top,C.top),C.left=Math.min(E.left,C.left),C.right=Math.max(E.right,C.right),C.bottom=Math.max(E.bottom,C.bottom);let S=C.right-C.left,A=C.bottom-C.top;m.style.top=C.top+"px",m.style.left=C.left+"px",m.style.width=S+"px",m.style.height=A+"px",c.width=S,c.height=A}})}let s=Array.from(this.layout_element.querySelectorAll("[data-title]"));for(let c of s)if(c instanceof HTMLElement){if(c.dataset.activeTitle)continue;c.dataset.title&&ho[c.dataset.title]&&(c.title=ho[c.dataset.title])}setTimeout(()=>this.layout_element?.setAttribute("animate",""),250)}ToggleToolbar(){if(this.layout_element){let e=this.layout_element.getAttribute("toolbar");typeof e=="string"&&(e===""||e==="true")?this.layout_element.removeAttribute("toolbar"):this.layout_element.setAttribute("toolbar","")}}UpdateSelectionStyle(e,t,r){let i=e.selection_state;r.value="";for(let s of Object.values(this.toolbar_controls))s&&(s.removeAttribute("active"),s.dataset.inactiveTitle&&(s.title=s.dataset.inactiveTitle));let n=s=>{s&&(s.setAttribute("active",""),s.dataset.activeTitle&&(s.title=s.dataset.activeTitle))};if(i.comment&&(n(this.toolbar_controls.comment),r.value=i.comment),i.style?.locked&&n(this.toolbar_controls.locked),i.frozen&&n(this.toolbar_controls.freeze),i.style?.wrap&&n(this.toolbar_controls.wrap),this.toolbar_controls.table&&(i.table?(n(this.toolbar_controls.table),this.toolbar_controls.table.dataset.command="remove-table"):this.toolbar_controls.table.dataset.command="insert-table"),this.toolbar_controls.merge&&(i.merge?(n(this.toolbar_controls.merge),this.toolbar_controls.merge.dataset.command="unmerge-cells"):this.toolbar_controls.merge.dataset.command="merge-cells"),this.toolbar_controls.stack)if(i.style?.font_face)if(i.style.font_face.startsWith("stack:")){let s=i.style.font_face.substring(6);this.toolbar_controls.stack.textContent=Jt[s]||"",this.toolbar_controls.stack.dataset.fontStack=s}else this.toolbar_controls.stack.textContent="",this.toolbar_controls.stack.dataset.fontStack="";else this.toolbar_controls.stack.textContent=Jt.default||"",this.toolbar_controls.stack.dataset.fontStack="default";let o=this.toolbar_controls.format;o&&(i.style?.number_format?o.value=L.SymbolicName(i.style.number_format)||i.style.number_format:o.value="General");let a=this.toolbar_controls.scale;switch(a&&(a.value=e.FormatNumber(i.relative_font_size||1,"0.00")),i.style?.horizontal_align){case"left":n(this.toolbar_controls.left);break;case"center":n(this.toolbar_controls.center);break;case"right":n(this.toolbar_controls.right);break}switch(i.style?.vertical_align){case"top":n(this.toolbar_controls.top);break;case"middle":n(this.toolbar_controls.middle);break;case"bottom":n(this.toolbar_controls.bottom);break}}UpdateDocumentStyles(e,t){{let a=this.DOM.Fragment(),s=e.document_styles.theme_colors.length,c=["Background","Text","Background","Text","Accent"];if(s){let m=e.document_styles.theme_colors[0].length;for(let f=0;f<m;f++)for(let p=0;p<s;p++){let b=e.document_styles.theme_colors[p][f],g=`background: ${b.resolved};`,x=c[p]||c[4];Ke(b.color)&&b.color.tint?x+=` (${(b.color.tint>0?"+":"")+b.color.tint*100}%)`:p===0?this.color_bar_elements.fill?.style.setProperty("--treb-default-color",b.resolved):p===1&&(this.color_bar_elements.text?.style.setProperty("--treb-default-color",b.resolved),this.color_bar_elements.border?.style.setProperty("--treb-default-color",b.resolved)),this.DOM.Create("button",void 0,a,{attrs:{style:g,title:x},data:{command:"set-color",color:JSON.stringify(b.color)}})}}this.swatch_lists.theme?.replaceChildren(a),a=this.DOM.Fragment();let d=["Black","White","Gray","Red","Orange","Yellow","Green","Blue","Indigo","Violet"],u=d.map(m=>m.toLowerCase()),h=e.document_styles.colors.filter(m=>!u.includes(m.toLowerCase()));for(let m of[...d,...h]){let f=`background: ${m.toLowerCase()};`;this.DOM.Create("button",void 0,a,{attrs:{style:f,title:m},data:{command:"set-color",color:JSON.stringify({text:m.toLowerCase()})}})}this.swatch_lists.other?.replaceChildren(a)}let r=["General","Number","Integer","Percent","Fraction","Accounting","Currency","Scientific"],i=["Timestamp","Long Date","Short Date"];for(let a of e.document_styles.number_formats){if(L.SymbolicName(L.Translate(a)))continue;L.Get(a).date_format?i.push(a):r.push(a)}let n=a=>this.DOM.Create("button",void 0,void 0,{text:a,data:{format:a,command:"number-format"}}),o=this.DOM.Fragment();o.append(...r.map(a=>n(a))),o.append(this.DOM.Div(void 0,void 0,{attrs:{separator:""}})),o.append(...i.map(a=>n(a))),t.textContent="",t.append(o)}UpdateRevertState(e){let t=e.can_revert;this.revert_state!==t&&(this.revert_state=t,(this.revert_button||e.options.revert_indicator)&&(this.revert_state?this.views?.classList.add("treb-can-revert"):this.views?.classList.remove("treb-can-revert"),this.revert_button&&(this.revert_button.dataset.canRevert=t?"true":"false",t?(this.revert_button.classList.remove("sidebar-disabled"),this.revert_button.title="Revert to original version"):(this.revert_button.classList.add("sidebar-disabled"),this.revert_button.title="This is the original version of the document"))))}ReplaceTemplate(e,t,r=!0){let i=e.querySelector(t);if(i&&i.parentElement){for(let n of Array.from(i.content.children))i.parentElement.insertBefore(n,i);r&&i.parentElement.removeChild(i)}else console.warn("template not found",t)}AttachToolbar(e,t){let r=t.querySelector(".treb-layout-header"),i=t.querySelector(".treb-toolbar");i.innerHTML=uo;let n=[];if(e.options.toolbar==="narrow"||e.options.toolbar==="show-narrow"?n.push(...Array.from(i.querySelectorAll("[wide]"))):n.push(...Array.from(i.querySelectorAll("[narrow]"))),e.options.file_menu||n.push(i.querySelector("[file-menu]")),e.options.indent_buttons||n.push(i.querySelector("[indent-group]")),e.options.font_scale||n.push(i.querySelector("[font-scale]")),!e.options.font_stack)n.push(i.querySelector("[font-stack]"));else{let y=i.querySelectorAll("[font-stack] button[data-font-stack]");for(let w of y)if(w.dataset.fontStack){let _=Jt[w.dataset.fontStack];w.textContent=_||""}}e.options.chart_menu||n.push(i.querySelector("[chart-menu]")),e.options.freeze_button||n.push(i.querySelector("[freeze-button]")),e.options.table_button||n.push(i.querySelector("[table-button]")),!e.options.add_tab&&!e.options.delete_tab&&n.push(...Array.from(i.querySelectorAll("[add-remove-sheet]"))),e.options.toolbar_recalculate_button||n.push(i.querySelector("[recalculate-button]"));for(let y of n)y&&y.parentElement?.removeChild(y);let o=i.querySelector(".treb-color-chooser"),a=i.querySelector(".treb-comment-box textarea");for(let[y,w]of Object.entries({top:"[wide] [data-command=align-top]",middle:"[wide] [data-command=align-middle]",bottom:"[wide] [data-command=align-bottom]",left:"[wide] [data-command=justify-left]",right:"[wide] [data-command=justify-right]",center:"[wide] [data-command=justify-center]",wrap:"[data-command=wrap-text]",merge:"[data-id=merge]",comment:"[data-icon=comment]",locked:"[data-command=lock-cells]",freeze:"[data-command=freeze-panes]",table:"[data-icon=table]",format:"input.treb-number-format",scale:"input.treb-font-scale",stack:"button.treb-font-stack"})){let _=i.querySelector(w);_&&(this.toolbar_controls[y]=_)}let s=o.querySelectorAll(".treb-swatches");this.swatch_lists={theme:s[0],other:s[1]};let c=t.querySelector("[data-command=increase-precision");c&&(c.textContent=this.sheet?.FormatNumber(0,"0.00")||""),c=t.querySelector("[data-command=decrease-precision"),c&&(c.textContent=this.sheet?.FormatNumber(0,"0.0")||""),c=i.querySelector("[data-command=update-comment]"),a.addEventListener("keydown",y=>{y.key==="Enter"&&(y.shiftKey||y.ctrlKey)&&c.click()});for(let y of["border","annotation","align","justify"])this.replace_targets[y]=i.querySelector(`[data-target=${y}`);for(let y of["fill","text","border"])this.color_bar_elements[y]=i.querySelector(`[data-color-bar=${y}]`);i.addEventListener("click",y=>{let w=y.target,_={format:w.dataset.format,scale:w.dataset.scale,font_stack:w.dataset.fontStack},C=w?.dataset.command;if(C){let S=w.parentElement?.dataset.replace;if(S){let A=this.replace_targets[S];A&&(A.dataset.command=C,A.title=w.title||"")}switch(/^border-/.test(C)&&(_.color=this.border_color||{}),C){case"text-color":case"fill-color":_.color={};try{_.color=JSON.parse(w.dataset.color||"{}")}catch(A){console.error(A)}break;case"set-color":C=o.dataset.colorCommand||"",_.color={};try{_.color=JSON.parse(w.dataset.color||"{}")}catch(A){console.error(A)}if(C==="border-color"&&(this.border_color=_.color),o.dataset.target){let A=this.color_bar_elements[o.dataset.target];A&&(A.style.setProperty("--treb-color-bar-color",w.style.backgroundColor),A.dataset.color=w.dataset.color||"{}")}break;case"update-comment":_.comment=a.value;break}e.HandleToolbarMessage({command:C,..._})}});let d=(y,w)=>{let _=i.querySelector(y);if(_){let C="";_.addEventListener("focusin",()=>C=_.value),_.addEventListener("keydown",S=>{switch(S.key){case"Escape":_.value=C,e.Focus();break;case"Enter":w(_.value)||(_.value=C,e.Focus());break;default:return}S.stopPropagation(),S.preventDefault()})}};d("input.treb-number-format",y=>y?(e.HandleToolbarMessage({command:"number-format",format:y}),!0):!1),d("input.treb-font-scale",y=>{let w=Number(y);return!w||isNaN(w)?(console.warn("invalid scale value"),!1):(e.HandleToolbarMessage({command:"font-scale",scale:w}),!0)});let u=o.querySelector("input"),h=o.querySelector("input + button");u.addEventListener("input",y=>{if(y instanceof InputEvent&&y.isComposing)return;h.style.background=u.value||"";let w=h.style.backgroundColor||"#fff",_=se.MeasureColor(w),C=W.RGBToHSL(_[0],_[1],_[2]);h.style.color=C.l>.5?"#000":"#fff",h.dataset.color=JSON.stringify(h.style.backgroundColor?{text:h.style.backgroundColor}:{})}),u.addEventListener("keydown",y=>{y.key==="Enter"&&(y.stopPropagation(),y.preventDefault(),h.click())}),/firefox/i.test(navigator.userAgent)?r.addEventListener("scroll",()=>{this.DOM.view&&this.DOM.doc?.activeElement instanceof this.DOM.view.HTMLElement&&this.DOM.doc.activeElement?.blur()}):r.addEventListener("scroll",()=>e.Focus());let m=!1,f=y=>{y.key==="Escape"&&(y.stopPropagation(),y.preventDefault(),Promise.resolve().then(()=>e.Focus()))},p=y=>{if(m){if(y.relatedTarget instanceof Node&&i.contains(y.relatedTarget))return;i.removeEventListener("keydown",f),i.removeEventListener("focusout",p),m=!1}},b=y=>{let w=y.target,_=w?.parentElement;if(w?.classList.contains("treb-menu")){_=w;for(let C of Array.from(_.children))if(C.tagName==="BUTTON"){w=C;break}}else if(!_?.classList.contains("treb-menu"))return;if(w&&_){if(m||(i.addEventListener("focusout",p),i.addEventListener("keydown",f),m=!0),_.dataset.colorCommand){o.querySelector(".treb-default-color")?.setAttribute("title",_.dataset.defaultColorText||"Default color");let ie=o.querySelector(".treb-default-color-label");ie&&(ie.textContent=_.dataset.defaultColorText||"Default color"),_.appendChild(o),o.dataset.colorCommand=_.dataset.colorCommand,o.dataset.target=_.dataset.replaceColor||""}let C=_.querySelector("div"),S=r.getBoundingClientRect(),A=w.getBoundingClientRect(),{left:E}=A,R=_.parentElement;R?.hasAttribute("composite")&&(E=R.firstElementChild.getBoundingClientRect().left);let z=C.getBoundingClientRect();_.classList.contains("treb-submenu")?(C.style.top=A.top-z.height/2+"px",E+A.width+6+z.width>S.right?C.style.left=E-6-z.width+"px":C.style.left=E+A.width+6+"px"):(C.style.top=A.bottom+"px",E+z.width>S.right-6?C.style.left=A.right-z.width+"px":C.style.left=E+"px");let K=C.querySelector("textarea");K&&requestAnimationFrame(()=>K.focus())}},g=this.root?.querySelector(".treb-number-format-menu");g&&(this.UpdateDocumentStyles(e,g),this.UpdateSelectionStyle(e,i,a),e.Subscribe(y=>{switch(y.type){case"focus-view":break;case"data":case"document-change":case"load":case"reset":this.UpdateDocumentStyles(e,g),this.UpdateSelectionStyle(e,i,a),this.UpdateRevertState(e);break;case"theme-change":this.UpdateDocumentStyles(e,g),this.UpdateSelectionStyle(e,i,a);break;case"annotation-selection":case"selection":this.UpdateSelectionStyle(e,i,a);break}}));let x=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);if(i.addEventListener("focusin",y=>{b(y)}),x){let y=Array.from(i.querySelectorAll(".treb-menu"));for(let w of y)w.tabIndex=0;i.addEventListener("mousedown",w=>{b(w)})}}};var Ar=class{version="32.9.3";CreateSpreadsheet(e){let t=e.container,r=new nt(t);if(r.AttachElement(e),!r.sheet)throw new Error("construction failed");return r.sheet}},$a=new Ar;if(typeof HTMLElement<"u"){class l extends HTMLElement{get sheet(){return this.instance.sheet}instance;constructor(){super(),this.instance=new nt(this)}connectedCallback(){this.instance.AttachElement()}}typeof customElements<"u"&&(customElements.get("treb-spreadsheet")?console.info("custom element treb-spreadsheet is already defined."):customElements.define("treb-spreadsheet",l))}export{$a as TREB,Ar as TREBGlobal};